ccdserver.cpp 1008 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jmisc.hpp"
  14. #include "jdebug.hpp"
  15. #include "jptree.hpp"
  16. #include "rtlkey.hpp"
  17. #include "jsort.hpp"
  18. #include "jhtree.hpp"
  19. #include "jqueue.tpp"
  20. #include "jisem.hpp"
  21. #include "thorxmlread.hpp"
  22. #include "thorrparse.ipp"
  23. #include "thorxmlwrite.hpp"
  24. #include "thorsoapcall.hpp"
  25. #include "thorcommon.ipp"
  26. #include "thorsort.hpp"
  27. #include "thorstats.hpp"
  28. #include "jlzw.hpp"
  29. #include "javahash.hpp"
  30. #include "javahash.tpp"
  31. #include "thorstep.ipp"
  32. #include "thorpipe.hpp"
  33. #include "thorfile.hpp"
  34. #include "eclhelper.hpp"
  35. #include "eclrtl_imp.hpp"
  36. #include "rtlfield.hpp"
  37. #include "rtlds_imp.hpp"
  38. #include "rtlread_imp.hpp"
  39. #include "rtlcommon.hpp"
  40. #include <algorithm>
  41. #include "dafdesc.hpp"
  42. #include "dautils.hpp"
  43. #include "ftbase.ipp"
  44. #include "eclhelper_base.hpp"
  45. #include "ccd.hpp"
  46. #include "ccdserver.hpp"
  47. #include "ccdcontext.hpp"
  48. #include "ccdactivities.hpp"
  49. #include "ccdquery.hpp"
  50. #include "ccdstate.hpp"
  51. #include "ccdqueue.ipp"
  52. #include "ccdsnmp.hpp"
  53. #include "ccddali.hpp"
  54. #include "jsmartsock.hpp"
  55. #include "dllserver.hpp"
  56. #include "workflow.hpp"
  57. #include "roxiemem.hpp"
  58. #include "roxierowbuff.hpp"
  59. #include "roxiehelper.hpp"
  60. #include "roxielmj.hpp"
  61. #include "roxierow.hpp"
  62. #include "thorplugin.hpp"
  63. #include "keybuild.hpp"
  64. #include "thorstrand.hpp"
  65. #include "rtldynfield.hpp"
  66. #define MAX_HTTP_HEADERSIZE 8000
  67. #define MIN_PAYLOAD_SIZE 800
  68. #ifdef _WIN32
  69. #pragma warning(disable : 4355)
  70. #endif
  71. #define DEFAULT_PARALLEL_LOOP_THREADS 1
  72. #define PROBE
  73. #ifdef _DEBUG
  74. //#define FAKE_EXCEPTIONS
  75. //#define TRACE_JOINGROUPS
  76. //#define TRACE_SPLIT
  77. //#define _CHECK_HEAPSORT
  78. //#undef PARALLEL_EXECUTE
  79. //#define TRACE_SEEK_REQUESTS
  80. #endif
  81. using roxiemem::OwnedRoxieRow;
  82. using roxiemem::OwnedRoxieString;
  83. using roxiemem::OwnedConstRoxieRow;
  84. using roxiemem::IRowManager;
  85. using roxiemem::ReleaseRoxieRows;
  86. // There is a bug in VC6 implemetation of protected which prevents nested classes from accessing owner's data. It can be tricky to work around - hence...
  87. #if _MSC_VER==1200
  88. #define protected public
  89. #endif
  90. #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
  91. #define TRACE_STRANDS
  92. #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
  93. static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
  94. //=================================================================================
  95. class RestartableThread : public CInterface
  96. {
  97. class MyThread : public Thread
  98. {
  99. Linked<RestartableThread> owner;
  100. public:
  101. MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
  102. {
  103. }
  104. virtual int run()
  105. {
  106. owner->started.signal();
  107. return owner->run();
  108. }
  109. };
  110. friend class MyThread;
  111. Semaphore started;
  112. Owned<MyThread> thread;
  113. CriticalSection crit;
  114. StringAttr name;
  115. public:
  116. RestartableThread(const char *_name) : name(_name)
  117. {
  118. }
  119. virtual void start(const char *namePrefix)
  120. {
  121. StringBuffer s(namePrefix);
  122. s.append(name);
  123. {
  124. CriticalBlock b(crit);
  125. assertex(!thread);
  126. thread.setown(new MyThread(this, s));
  127. thread->start();
  128. }
  129. started.wait();
  130. }
  131. virtual void join()
  132. {
  133. {
  134. Owned<Thread> tthread;
  135. {
  136. CriticalBlock b(crit);
  137. tthread.setown(thread.getClear());
  138. }
  139. if (tthread)
  140. tthread->join();
  141. }
  142. }
  143. virtual int run() = 0;
  144. };
  145. //================================================================================
  146. //The following don't link their arguments because that creates a circular reference
  147. //But I wish there was a better way
  148. class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
  149. {
  150. public:
  151. IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
  152. IMPLEMENT_IINTERFACE
  153. // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
  154. virtual ICodeContext *queryCodeContext()
  155. {
  156. return ctx->queryCodeContext();
  157. }
  158. virtual void checkAbort()
  159. {
  160. ctx->checkAbort();
  161. }
  162. virtual void notifyAbort(IException *E)
  163. {
  164. ctx->notifyAbort(E);
  165. }
  166. virtual IActivityGraph * queryChildGraph(unsigned id)
  167. {
  168. return ctx->queryChildGraph(id);
  169. }
  170. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  171. {
  172. ctx->noteChildGraph(id, childGraph) ;
  173. }
  174. virtual IRowManager &queryRowManager()
  175. {
  176. return ctx->queryRowManager();
  177. }
  178. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  179. {
  180. ctx->noteStatistic(kind, value);
  181. }
  182. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  183. {
  184. ctx->mergeStats(from);
  185. }
  186. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  187. {
  188. ctx->gatherStats(merged);
  189. }
  190. virtual bool collectingDetailedStatistics() const
  191. {
  192. return ctx->collectingDetailedStatistics();
  193. }
  194. virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
  195. {
  196. ctx->CTXLOGva(format, args);
  197. }
  198. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  199. {
  200. ctx->CTXLOGa(category, prefix, text);
  201. }
  202. virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
  203. {
  204. ctx->logOperatorExceptionVA(E, file, line, format, args);
  205. }
  206. virtual void CTXLOGaeva(IException *E, const char *file, unsigned line, const char *prefix, const char *format, va_list args) const __attribute__((format(printf,6,0)))
  207. {
  208. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  209. }
  210. virtual void CTXLOGl(LogItem *log) const
  211. {
  212. ctx->CTXLOGl(log);
  213. }
  214. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  215. {
  216. return ctx->getLogPrefix(ret);
  217. }
  218. virtual unsigned queryTraceLevel() const
  219. {
  220. return ctx->queryTraceLevel();
  221. }
  222. virtual bool isIntercepted() const
  223. {
  224. return ctx->isIntercepted();
  225. }
  226. virtual bool isBlind() const
  227. {
  228. return ctx->isBlind();
  229. }
  230. virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid) override
  231. {
  232. ctx->setGlobalId(id, ep, pid);
  233. }
  234. virtual void setCallerId(const char *id) override
  235. {
  236. ctx->setCallerId(id);
  237. }
  238. virtual const char *queryGlobalId() const
  239. {
  240. return ctx->queryGlobalId();
  241. }
  242. virtual const char *queryCallerId() const override
  243. {
  244. return ctx->queryCallerId();
  245. }
  246. virtual const char *queryLocalId() const
  247. {
  248. return ctx->queryLocalId();
  249. }
  250. virtual void setHttpIdHeaders(const char *global, const char *caller)
  251. {
  252. ctx->setHttpIdHeaders(global, caller);
  253. }
  254. virtual const char *queryGlobalIdHttpHeader() const
  255. {
  256. return ctx->queryGlobalIdHttpHeader();
  257. }
  258. virtual const char *queryCallerIdHttpHeader() const
  259. {
  260. return ctx->queryCallerIdHttpHeader();
  261. }
  262. virtual const QueryOptions &queryOptions() const
  263. {
  264. return ctx->queryOptions();
  265. }
  266. virtual void addSlavesReplyLen(unsigned len)
  267. {
  268. ctx->addSlavesReplyLen(len);
  269. }
  270. virtual const char *queryAuthToken()
  271. {
  272. return ctx->queryAuthToken();
  273. }
  274. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  275. {
  276. return ctx->resolveLFN(filename, isOpt);
  277. }
  278. virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
  279. {
  280. return ctx->createLFN(filename, overwrite, extend, clusters);
  281. }
  282. virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
  283. {
  284. ctx->onFileCallback(header, lfn, isOpt, isLocal);
  285. }
  286. virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
  287. {
  288. return ctx->getLibraryGraph(extra, parentActivity);
  289. }
  290. virtual IProbeManager *queryProbeManager() const
  291. {
  292. return ctx->queryProbeManager();
  293. }
  294. virtual IDebuggableContext *queryDebugContext() const
  295. {
  296. return ctx->queryDebugContext();
  297. }
  298. virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
  299. {
  300. ctx->printResults(output, name, sequence);
  301. }
  302. virtual void setWUState(WUState state)
  303. {
  304. ctx->setWUState(state);
  305. }
  306. virtual bool checkWuAborted()
  307. {
  308. return ctx->checkWuAborted();
  309. }
  310. virtual IWorkUnit *updateWorkUnit() const
  311. {
  312. return ctx->updateWorkUnit();
  313. }
  314. virtual IConstWorkUnit *queryWorkUnit() const
  315. {
  316. return ctx->queryWorkUnit();
  317. }
  318. virtual IRoxieServerContext *queryServerContext()
  319. {
  320. return ctx->queryServerContext();
  321. }
  322. virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
  323. {
  324. return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
  325. }
  326. virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
  327. {
  328. return ctx->getRowAllocatorEx(meta, activityId, flags);
  329. }
  330. protected:
  331. IRoxieSlaveContext * ctx;
  332. };
  333. //=================================================================================
  334. #define RESULT_FLUSH_THRESHOLD 10000u
  335. #ifdef _DEBUG
  336. #define SOAP_SPLIT_THRESHOLD 100u
  337. #define SOAP_SPLIT_RESERVE 200u
  338. #else
  339. #define SOAP_SPLIT_THRESHOLD 64000u
  340. #define SOAP_SPLIT_RESERVE 65535u
  341. #endif
  342. //=================================================================================
  343. // General activity statistics
  344. static const StatisticsMapping actStatistics({StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
  345. StNumRowsProcessed, StNumSlaves, StNumStarts, StNumStops, StNumStrands,
  346. StNumScansPerRow, StNumAllocations, StNumAllocationScans,
  347. StTimeFirstExecute, StCycleLocalExecuteCycles, StCycleTotalExecuteCycles});
  348. static const StatisticsMapping joinStatistics(&actStatistics, {StNumAtmostTriggered});
  349. static const StatisticsMapping keyedJoinStatistics(&joinStatistics, { StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  350. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  351. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  352. StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  353. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  354. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  355. StNumDiskRejected});
  356. static const StatisticsMapping indexStatistics(&actStatistics, {StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
  357. StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
  358. StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
  359. StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
  360. StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
  361. StNumIndexRowsRead});
  362. static const StatisticsMapping diskStatistics(&actStatistics, {StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
  363. StNumDiskRejected });
  364. static const StatisticsMapping soapStatistics(&actStatistics, { StTimeSoapcall });
  365. static const StatisticsMapping groupStatistics(&actStatistics, { StNumGroups, StNumGroupMax });
  366. static const StatisticsMapping sortStatistics(&actStatistics, { StTimeSortElapsed });
  367. static const StatisticsMapping indexWriteStatistics(&actStatistics, { StNumDuplicateKeys });
  368. //=================================================================================
  369. const static unsigned minus1U = (0U-1U);
  370. class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
  371. {
  372. protected:
  373. IntArray dependencies; // things I am dependent on
  374. IntArray dependencyIndexes; // things I am dependent on
  375. IntArray dependencyControlIds; // things I am dependent on
  376. StringArray dependencyEdgeIds; // How to describe them to the debugger
  377. unsigned dependentCount; // things dependent on me
  378. unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
  379. bool optStableInput = true; // is the input forced to ordered?
  380. bool optUnstableInput = false; // is the input forced to unordered?
  381. bool optUnordered = false; // is the output specified as unordered?
  382. unsigned heapFlags;
  383. mutable RelaxedAtomic<__int64> processed = {0};
  384. mutable RelaxedAtomic<__int64> started = {0};
  385. public:
  386. IMPLEMENT_IINTERFACE;
  387. CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  388. : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  389. {
  390. dependentCount = 0;
  391. optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  392. optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
  393. heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
  394. }
  395. ~CRoxieServerActivityFactoryBase()
  396. {
  397. }
  398. StringBuffer &toString(StringBuffer &ret) const
  399. {
  400. return ret.appendf("%p", this);
  401. }
  402. virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
  403. {
  404. dependencies.append(_source);
  405. dependencyIndexes.append(_sourceIdx);
  406. dependencyControlIds.append(controlId);
  407. dependencyEdgeIds.append(edgeId);
  408. }
  409. virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  410. {
  411. if (optStableInput)
  412. return true;
  413. if (optUnstableInput)
  414. return false;
  415. if (optUnordered)
  416. return false;
  417. return consumerOrdered;
  418. }
  419. virtual void noteDependent(unsigned target)
  420. {
  421. dependentCount++;
  422. }
  423. virtual IntArray &queryDependencies() { return dependencies; }
  424. virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
  425. virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
  426. virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
  427. virtual unsigned queryId() const { return id; }
  428. virtual unsigned querySubgraphId() const { return subgraphId; }
  429. virtual ThorActivityKind getKind() const { return kind; }
  430. virtual IOutputMetaData * queryOutputMeta() const
  431. {
  432. return meta;
  433. }
  434. virtual bool isSink() const
  435. {
  436. return false;
  437. }
  438. virtual bool isFunction() const
  439. {
  440. return false;
  441. }
  442. virtual bool isGraphInvariant() const
  443. {
  444. return false;
  445. }
  446. virtual IHThorArg &getHelper() const
  447. {
  448. return *helperFactory();
  449. }
  450. virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
  451. {
  452. arg.Release();
  453. throwUnexpected();
  454. }
  455. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  456. {
  457. CActivityFactory::mergeStats(from);
  458. }
  459. virtual void noteProcessed(unsigned _idx, unsigned _processed) const
  460. {
  461. dbgassertex(!_idx);
  462. if (likely(_processed))
  463. processed += _processed;
  464. }
  465. virtual void noteStarted() const
  466. {
  467. started++;
  468. }
  469. virtual void noteStarted(unsigned idx) const
  470. {
  471. throwUnexpected(); // should be implemented/required by multiOutput cases only
  472. }
  473. virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
  474. {
  475. if (output == 0)
  476. {
  477. putStatsValue(&edge, "NumRowsProcessed", "sum", processed);
  478. auto _started = started.load();
  479. if (_started)
  480. putStatsValue(&edge, "NumStarts", "sum", _started);
  481. }
  482. else
  483. IERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
  484. }
  485. virtual void getNodeProgressInfo(IPropertyTree &node) const
  486. {
  487. CActivityFactory::getNodeProgressInfo(node);
  488. auto _started = started.load();
  489. if (_started)
  490. putStatsValue(&node, "_roxieStarted", "sum", _started);
  491. }
  492. virtual void resetNodeProgressInfo()
  493. {
  494. CActivityFactory::resetNodeProgressInfo();
  495. processed = 0;
  496. started = 0;
  497. }
  498. virtual void getActivityMetrics(StringBuffer &reply) const
  499. {
  500. CActivityFactory::getActivityMetrics(reply);
  501. putStatsValue(reply, "NumStarts", "sum", started);
  502. CriticalBlock b(statsCrit);
  503. putStatsValue(reply, "TimeTotalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeTotalExecute)/1000));
  504. putStatsValue(reply, "TimeLocalExecute", "sum", (unsigned) (mystats.getSerialStatisticValue(StTimeLocalExecute)/1000));
  505. }
  506. virtual unsigned __int64 queryLocalTimeNs() const
  507. {
  508. return mystats.getSerialStatisticValue(StTimeLocalExecute);
  509. }
  510. virtual IQueryFactory &queryQueryFactory() const
  511. {
  512. return CActivityFactory::queryQueryFactory();
  513. }
  514. virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
  515. {
  516. return CActivityFactory::queryChildQuery(idx, id);
  517. }
  518. virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
  519. {
  520. CActivityFactory::addChildQuery(id, childQuery);
  521. }
  522. virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
  523. {
  524. ForEachItemIn(idx, childQueries)
  525. {
  526. childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
  527. ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
  528. childGraphs.item(idx).onCreate(colocalArg);
  529. }
  530. }
  531. IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
  532. {
  533. unsigned match = childQueryIndexes.find(childId);
  534. assertex(match != NotFound);
  535. Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
  536. graph->onCreate(colocalArg);
  537. return graph.getClear();
  538. }
  539. virtual IRoxieServerSideCache *queryServerSideCache() const
  540. {
  541. return NULL; // Activities that wish to support server-side caching will need to do better....
  542. }
  543. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  544. {
  545. // Most activities have nothing to say...
  546. }
  547. virtual const StatisticsMapping &queryStatsMapping() const
  548. {
  549. return actStatistics; // Overridden by anyone that needs more
  550. }
  551. virtual roxiemem::RoxieHeapFlags getHeapFlags() const
  552. {
  553. return (roxiemem::RoxieHeapFlags)heapFlags;
  554. }
  555. };
  556. class CRoxieServerMultiInputInfo
  557. {
  558. private:
  559. UnsignedArray inputs;
  560. UnsignedArray inputIndexes;
  561. public:
  562. void set(unsigned idx, unsigned source, unsigned sourceidx)
  563. {
  564. if (idx==inputs.length())
  565. {
  566. inputs.append(source);
  567. inputIndexes.append(sourceidx);
  568. }
  569. else
  570. {
  571. while (!inputs.isItem(idx))
  572. {
  573. inputs.append(0);
  574. inputIndexes.append(0);
  575. }
  576. inputs.replace(source, idx);
  577. inputIndexes.replace(sourceidx, idx);
  578. }
  579. }
  580. unsigned get(unsigned idx, unsigned &sourceidx) const
  581. {
  582. if (inputs.isItem(idx))
  583. {
  584. sourceidx = inputIndexes.item(idx);
  585. return inputs.item(idx);
  586. }
  587. else
  588. return (unsigned) -1;
  589. }
  590. inline unsigned ordinality() const { return inputs.ordinality(); }
  591. };
  592. class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
  593. {
  594. private:
  595. CRoxieServerMultiInputInfo inputs;
  596. public:
  597. CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  598. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  599. {
  600. }
  601. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  602. {
  603. inputs.set(idx, source, sourceidx);
  604. }
  605. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  606. {
  607. return inputs.get(idx, sourceidx);
  608. }
  609. virtual unsigned numInputs() const { return inputs.ordinality(); }
  610. };
  611. class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
  612. {
  613. Owned<IException> wrapped;
  614. ThorActivityKind kind;
  615. unsigned queryId;
  616. public:
  617. IMPLEMENT_IINTERFACE;
  618. CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
  619. : wrapped(_wrapped), kind(_kind), queryId(_queryId)
  620. {
  621. }
  622. virtual int errorCode() const { return wrapped->errorCode(); }
  623. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
  624. virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
  625. };
  626. class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
  627. {
  628. protected:
  629. unsigned input;
  630. unsigned inputidx;
  631. public:
  632. CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  633. : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  634. {
  635. input = (unsigned) -1;
  636. inputidx = 0;
  637. }
  638. inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  639. {
  640. if (idx != 0)
  641. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
  642. if (input != (unsigned) -1)
  643. 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__);
  644. input = source;
  645. inputidx = sourceidx;
  646. }
  647. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  648. {
  649. if (!idx)
  650. {
  651. sourceidx = inputidx;
  652. return input;
  653. }
  654. return (unsigned) -1;
  655. }
  656. virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
  657. };
  658. class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
  659. {
  660. protected:
  661. unsigned numOutputs = 0;
  662. RelaxedAtomic<__int64> *processedArray = nullptr;
  663. RelaxedAtomic<__int64> *startedArray = nullptr;
  664. CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  665. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  666. {
  667. }
  668. ~CRoxieServerMultiOutputFactory()
  669. {
  670. delete [] processedArray;
  671. delete [] startedArray;
  672. }
  673. void setNumOutputs(unsigned num)
  674. {
  675. numOutputs = num;
  676. if (!num)
  677. num = 1; // Even sink activities like to track how many records they process
  678. processedArray = new RelaxedAtomic<__int64>[num];
  679. startedArray = new RelaxedAtomic<__int64>[num];
  680. for (unsigned i = 0; i < num; i++)
  681. {
  682. processedArray[i] = 0;
  683. startedArray[i] = 0;
  684. }
  685. }
  686. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  687. {
  688. assertex(numOutputs ? idx < numOutputs : idx==0);
  689. putStatsValue(&edge, "NumRowsProcessed", "sum", processedArray[idx]);
  690. putStatsValue(&edge, "NumStarts", "sum", startedArray[idx]);
  691. }
  692. virtual void resetNodeProgressInfo()
  693. {
  694. CRoxieServerActivityFactory::resetNodeProgressInfo();
  695. for (unsigned i = 0; i < numOutputs; i++)
  696. {
  697. processedArray[i] = 0;
  698. startedArray[i] = 0;
  699. }
  700. }
  701. virtual void noteProcessed(unsigned idx, unsigned _processed) const
  702. {
  703. assertex(numOutputs ? idx < numOutputs : idx==0);
  704. processedArray[idx] += _processed;
  705. }
  706. virtual void noteStarted(unsigned idx) const
  707. {
  708. assertex(numOutputs ? idx < numOutputs : idx==0);
  709. startedArray[idx]++;
  710. }
  711. };
  712. class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
  713. {
  714. protected:
  715. bool isInternal;
  716. bool isRoot;
  717. unsigned usageCount;
  718. public:
  719. CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  720. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  721. {
  722. usageCount = _usageCount;
  723. isRoot = _isRoot;
  724. isInternal = false; // filled in by derived class constructor
  725. }
  726. virtual bool isSink() const
  727. {
  728. //only a sink if a root activity
  729. 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?
  730. }
  731. virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
  732. {
  733. // 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
  734. // Just leave it blank is safest.
  735. }
  736. };
  737. typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
  738. const char *queryStateText(activityState state)
  739. {
  740. switch (state)
  741. {
  742. case STATEreset: return "reset";
  743. case STATEstarted: return "started";
  744. case STATEstopped: return "stopped";
  745. case STATEstarting: return "starting";
  746. default: return "unknown";
  747. }
  748. }
  749. typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
  750. class CParallelActivityExecutor : public CAsyncFor
  751. {
  752. public:
  753. unsigned parentExtractSize;
  754. const byte * parentExtract;
  755. CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
  756. parentExtractSize(_parentExtractSize), parentExtract(_parentExtract), activities(_activities) { }
  757. void Do(unsigned i)
  758. {
  759. activities.item(i).execute(parentExtractSize, parentExtract);
  760. }
  761. private:
  762. IRoxieServerActivityCopyArray & activities;
  763. };
  764. extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
  765. {
  766. if (instreams.length() != 1)
  767. {
  768. assertex(instreams.length());
  769. if (!junction)
  770. junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
  771. ForEachItemIn(stream, instreams)
  772. {
  773. junction->setInput(stream, instreams.item(stream));
  774. }
  775. return junction->queryOutput(0);
  776. }
  777. else
  778. return instreams.item(0);
  779. }
  780. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
  781. {
  782. if (input)
  783. {
  784. PointerArrayOf<IEngineRowStream> instreams;
  785. junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
  786. return ensureSingleStream(ctx, instreams, junction);
  787. }
  788. else
  789. return NULL;
  790. }
  791. extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
  792. {
  793. Owned<IStrandJunction> junction;
  794. IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
  795. assertex(!junction);
  796. return result;
  797. }
  798. class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
  799. {
  800. friend class StrandProcessor;
  801. protected:
  802. IFinalRoxieInput *input;
  803. unsigned sourceIdx;
  804. IEngineRowStream *inputStream;
  805. Owned<IStrandJunction> junction;
  806. IHThorArg &basehelper;
  807. IRoxieSlaveContext *ctx;
  808. class InterceptRegisterTimer : public IndirectCodeContext
  809. {
  810. public:
  811. InterceptRegisterTimer(CRoxieServerActivity &_activity) : activity(_activity) {}
  812. virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
  813. {
  814. if (activityId == activity.queryId())
  815. return activity.registerTimer(activityId, name);
  816. else
  817. return ctx->registerTimer(activityId, name);
  818. }
  819. private:
  820. CRoxieServerActivity &activity;
  821. } interceptedCtx;
  822. const IRoxieServerActivityFactory *factory;
  823. IRoxieServerActivityCopyArray dependencies;
  824. IntArray dependencyIndexes;
  825. IntArray dependencyControlIds;
  826. IArrayOf<IActivityGraph> childGraphs;
  827. CachedOutputMetaData meta;
  828. IHThorArg *colocalParent;
  829. IEngineRowAllocator *rowAllocator;
  830. CriticalSection statecrit;
  831. CriticalSection statscrit;
  832. mutable CRuntimeStatisticCollection stats;
  833. MapStringToMyClass<ThorSectionTimer> functionTimers;
  834. ActivityTimeAccumulator totalCycles;
  835. IProbeManager *probeManager = NULL;
  836. unsigned processed;
  837. unsigned numStarts = 0;
  838. unsigned activityId;
  839. activityState state;
  840. bool createPending;
  841. bool debugging;
  842. bool timeActivities;
  843. bool aborted;
  844. bool connected = false;
  845. bool collectFactoryStatistics = false;
  846. public:
  847. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
  848. CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  849. : basehelper(_factory->getHelper()),
  850. ctx(_ctx),
  851. interceptedCtx(*this),
  852. factory(_factory),
  853. stats(_factory->queryStatsMapping()),
  854. probeManager(_probeManager),
  855. activityId(_factory->queryId())
  856. {
  857. input = NULL;
  858. sourceIdx = 0;
  859. inputStream = NULL;
  860. meta.set(basehelper.queryOutputMeta());
  861. processed = 0;
  862. state=STATEreset;
  863. rowAllocator = NULL;
  864. debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
  865. colocalParent = NULL;
  866. createPending = true;
  867. timeActivities = defaultTimeActivities;
  868. collectFactoryStatistics = defaultCollectFactoryStatistics && !debugging && factory;
  869. aborted = false;
  870. }
  871. CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper)
  872. : basehelper(_helper), ctx(_ctx),
  873. interceptedCtx(*this), factory(NULL), stats(allStatistics)
  874. {
  875. activityId = 0;
  876. input = NULL;
  877. sourceIdx = 0;
  878. inputStream = NULL;
  879. ctx = NULL;
  880. meta.set(basehelper.queryOutputMeta());
  881. processed = 0;
  882. state=STATEreset;
  883. rowAllocator = NULL;
  884. debugging = false;
  885. colocalParent = NULL;
  886. createPending = true;
  887. timeActivities = defaultTimeActivities;
  888. collectFactoryStatistics = false; // since no factory
  889. aborted = false;
  890. }
  891. ~CRoxieServerActivity()
  892. {
  893. basehelper.Release();
  894. ::Release(rowAllocator);
  895. }
  896. virtual void beforeDispose() override
  897. {
  898. if (traceStartStop)
  899. {
  900. // There was an old comment here stating // Note- CTXLOG may not be safe
  901. // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
  902. // was released while activities still referenced it.
  903. // However these should now all be fixed
  904. DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
  905. if (watchActivityId && watchActivityId==activityId)
  906. {
  907. DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
  908. }
  909. }
  910. if (state!=STATEreset)
  911. {
  912. DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
  913. state = STATEreset; // bit pointless but there you go...
  914. }
  915. }
  916. const IResolvedFile *resolveLFNIndex(const char *filename, bool isOpt)
  917. {
  918. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  919. if (ret && !ret->isKey())
  920. throw MakeStringException(0, "Attempting to read flat file as an index: %s", filename);
  921. return ret;
  922. }
  923. const IResolvedFile *resolveLFNFlat(const char *filename, bool isOpt)
  924. {
  925. const IResolvedFile *ret = resolveLFN(filename, isOpt);
  926. if (ret && ret->isKey())
  927. throw MakeStringException(0, "Attempting to read index as a flat file: %s", filename);
  928. return ret;
  929. }
  930. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  931. {
  932. if (!factory)
  933. return;
  934. //Collate the stats for this activity from various different sources.
  935. CRuntimeStatisticCollection mergedStats(stats.queryMapping());
  936. gatherStats(mergedStats);
  937. //Because subgraphs are flattened in roxie the subgraph needs to be selected for each activity
  938. if (statsBuilder)
  939. statsBuilder->beginSubGraphScope(factory->querySubgraphId());
  940. //Still needed even if statsBuilder is null to update values in the factory
  941. updateEdgeStats(statsBuilder);
  942. if (statsBuilder)
  943. {
  944. StatsActivityScope ac(*statsBuilder, activityId);
  945. mergedStats.recordStatistics(*statsBuilder);
  946. //close the subgraph scope from the previous if()
  947. statsBuilder->endScope();
  948. }
  949. //Update the statistics accumulated over all the queries
  950. if (collectFactoryStatistics)
  951. factory->mergeStats(mergedStats);
  952. //Updates the query summary statistics
  953. if (ctx)
  954. ctx->queryCodeContext()->queryContextLogger().mergeStats(mergedStats);
  955. ForEachItemIn(i, childGraphs)
  956. childGraphs.item(i).gatherStatistics(statsBuilder);
  957. }
  958. virtual const IRoxieContextLogger &queryLogCtx()const
  959. {
  960. return *this;
  961. }
  962. inline const StatisticsMapping & queryStatsMapping() const
  963. {
  964. return factory ? factory->queryStatsMapping() : actStatistics;
  965. }
  966. virtual bool collectingDetailedStatistics() const
  967. {
  968. return ctx && ctx->collectingDetailedStatistics();
  969. }
  970. virtual void mergeStats(MemoryBuffer &buf)
  971. {
  972. stats.deserializeMerge(buf);
  973. }
  974. virtual void mergeStats(const CRuntimeStatisticCollection & childStats)
  975. {
  976. CriticalBlock b(statscrit);
  977. stats.merge(childStats);
  978. }
  979. virtual ISectionTimer *registerTimer(unsigned _activityId, const char * name)
  980. {
  981. CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
  982. ISectionTimer *timer = functionTimers.getValue(name);
  983. if (!timer)
  984. {
  985. timer = ThorSectionTimer::createTimer(stats, name);
  986. functionTimers.setValue(name, timer);
  987. timer->Release(); // Value returned is not linked
  988. }
  989. return timer;
  990. }
  991. void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles)
  992. {
  993. CriticalBlock cb(statscrit);
  994. processed += strandProcessed;
  995. totalCycles.merge(strandCycles);
  996. }
  997. inline void ensureRowAllocator()
  998. {
  999. if (!rowAllocator)
  1000. rowAllocator = createRowAllocator(meta.queryOriginal());
  1001. }
  1002. virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
  1003. {
  1004. return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
  1005. }
  1006. virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
  1007. {
  1008. return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
  1009. }
  1010. inline ICodeContext *queryCodeContext()
  1011. {
  1012. return ctx->queryCodeContext();
  1013. }
  1014. // MORE - most of this is copied from ccd.hpp - can't we refactor?
  1015. virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
  1016. {
  1017. if (ctx)
  1018. ctx->CTXLOGa(category, prefix, text);
  1019. else
  1020. DBGLOG("[%s] %s", prefix, text);
  1021. }
  1022. 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)))
  1023. {
  1024. if (ctx)
  1025. ctx->CTXLOGaeva(E, file, line, prefix, format, args);
  1026. else
  1027. {
  1028. StringBuffer ss;
  1029. ss.appendf("[%s] ERROR", prefix);
  1030. if (E)
  1031. ss.append(": ").append(E->errorCode());
  1032. if (file)
  1033. ss.appendf(": %s(%d) ", file, line);
  1034. if (E)
  1035. E->errorMessage(ss.append(": "));
  1036. if (format)
  1037. {
  1038. ss.append(": ").valist_appendf(format, args);
  1039. }
  1040. LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
  1041. }
  1042. }
  1043. virtual void CTXLOGl(LogItem *log) const
  1044. {
  1045. if (ctx)
  1046. ctx->CTXLOGl(log);
  1047. else
  1048. {
  1049. assert(ctx);
  1050. log->Release(); // Should never happen
  1051. }
  1052. }
  1053. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
  1054. {
  1055. stats.addStatistic(kind, value);
  1056. }
  1057. virtual void mergeStats(const CRuntimeStatisticCollection &from) const
  1058. {
  1059. stats.merge(from);
  1060. }
  1061. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1062. {
  1063. merged.merge(stats);
  1064. if (rowAllocator)
  1065. rowAllocator->gatherStats(merged);
  1066. totalCycles.addStatistics(merged);
  1067. merged.mergeStatistic(StCycleLocalExecuteCycles, queryLocalCycles());
  1068. }
  1069. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  1070. {
  1071. if (ctx)
  1072. ctx->getLogPrefix(ret);
  1073. return ret.append('@').append(activityId);
  1074. }
  1075. virtual bool isIntercepted() const
  1076. {
  1077. return ctx ? ctx->isIntercepted() : false;
  1078. }
  1079. virtual bool isBlind() const
  1080. {
  1081. return ctx ? ctx->isBlind() : blindLogging;
  1082. }
  1083. virtual unsigned queryTraceLevel() const
  1084. {
  1085. if (ctx)
  1086. return ctx->queryTraceLevel();
  1087. else
  1088. return traceLevel;
  1089. }
  1090. virtual void setGlobalId(const char *id, SocketEndpoint&ep, unsigned pid) override
  1091. {
  1092. if (ctx)
  1093. ctx->setGlobalId(id, ep, pid);
  1094. }
  1095. virtual void setCallerId(const char *id) override
  1096. {
  1097. if (ctx)
  1098. ctx->setCallerId(id);
  1099. }
  1100. virtual const char *queryGlobalId() const
  1101. {
  1102. return ctx ? ctx->queryGlobalId() : nullptr;
  1103. }
  1104. virtual const char *queryCallerId() const override
  1105. {
  1106. return ctx ? ctx->queryCallerId() : nullptr;
  1107. }
  1108. virtual const char *queryLocalId() const
  1109. {
  1110. return ctx ? ctx->queryLocalId() : nullptr;
  1111. }
  1112. virtual void setHttpIdHeaders(const char *global, const char *caller)
  1113. {
  1114. if (ctx)
  1115. ctx->setHttpIdHeaders(global, caller);
  1116. }
  1117. virtual const char *queryGlobalIdHttpHeader() const
  1118. {
  1119. return ctx ? ctx->queryGlobalIdHttpHeader() : "HPCC-Global-Id";
  1120. }
  1121. virtual const char *queryCallerIdHttpHeader() const
  1122. {
  1123. return ctx ? ctx->queryCallerIdHttpHeader() : "HPCC-Caller-Id";
  1124. }
  1125. virtual bool isPassThrough()
  1126. {
  1127. return false;
  1128. }
  1129. virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
  1130. {
  1131. return ctx->resolveLFN(filename, isOpt);
  1132. }
  1133. virtual const IResolvedFile *queryVarFileInfo() const
  1134. {
  1135. throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
  1136. return NULL;
  1137. }
  1138. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  1139. {
  1140. throwUnexpected(); // should be implemented in more derived class wherever needed
  1141. }
  1142. virtual IRoxieSlaveContext *queryContext()
  1143. {
  1144. return ctx;
  1145. }
  1146. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  1147. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
  1148. virtual IRoxieServerActivity *queryActivity() { return this; }
  1149. virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
  1150. virtual bool needsAllocator() const { return false; }
  1151. void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
  1152. {
  1153. colocalParent = _colocalParent;
  1154. createPending = true;
  1155. if (needsAllocator())
  1156. ensureRowAllocator();
  1157. processed = 0;
  1158. if (factory)
  1159. factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
  1160. if (ctx)
  1161. {
  1162. timeActivities = ctx->queryOptions().timeActivities;
  1163. collectFactoryStatistics = ctx->queryOptions().collectFactoryStatistics && !debugging && factory;
  1164. }
  1165. }
  1166. virtual void onCreate(IHThorArg *_colocalParent)
  1167. {
  1168. _onCreate(_colocalParent, 1);
  1169. }
  1170. virtual void serializeCreateStartContext(MemoryBuffer &out)
  1171. {
  1172. //This should only be called after onStart has been called on the helper
  1173. assertex(!createPending);
  1174. assertex(state==STATEstarted);
  1175. unsigned startlen = out.length();
  1176. basehelper.serializeCreateContext(out);
  1177. basehelper.serializeStartContext(out);
  1178. if (queryTraceLevel() > 10)
  1179. CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
  1180. }
  1181. virtual void serializeExtra(MemoryBuffer &out) {}
  1182. inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1183. {
  1184. CriticalBlock cb(statecrit);
  1185. if (state != STATEreset && state != STATEstarting)
  1186. {
  1187. CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
  1188. }
  1189. state=STATEstarted;
  1190. numStarts++;
  1191. #ifdef TRACE_STARTSTOP
  1192. if (traceStartStop)
  1193. {
  1194. CTXLOG("start %p %d", this, activityId);
  1195. if (watchActivityId && watchActivityId==activityId)
  1196. {
  1197. CTXLOG("WATCH: start %p %d", this, activityId);
  1198. }
  1199. }
  1200. #endif
  1201. executeDependencies(parentExtractSize, parentExtract, 0);
  1202. if (input)
  1203. input->start(parentExtractSize, parentExtract, paused);
  1204. ensureCreated();
  1205. basehelper.onStart(parentExtract, NULL);
  1206. if (collectFactoryStatistics)
  1207. factory->noteStarted();
  1208. startJunction(junction);
  1209. }
  1210. void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1211. {
  1212. //MORE: Create a filtered list and then use asyncfor
  1213. ForEachItemIn(idx, dependencies)
  1214. {
  1215. if (dependencyControlIds.item(idx) == (int) controlId)
  1216. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  1217. }
  1218. }
  1219. void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
  1220. {
  1221. ForEachItemIn(idx, dependencies)
  1222. {
  1223. if (dependencyControlIds.item(idx) == (int) controlId)
  1224. dependencies.item(idx).stop();
  1225. }
  1226. }
  1227. virtual unsigned __int64 queryTotalCycles() const
  1228. {
  1229. return totalCycles.totalCycles;
  1230. }
  1231. virtual unsigned __int64 queryLocalCycles() const
  1232. {
  1233. __int64 ret = totalCycles.totalCycles;
  1234. if (input) ret -= input->queryTotalCycles();
  1235. if (ret < 0)
  1236. ret = 0;
  1237. return ret;
  1238. }
  1239. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  1240. {
  1241. if (idx==0)
  1242. return input;
  1243. else
  1244. return NULL;
  1245. }
  1246. inline void ensureCreated()
  1247. {
  1248. if (createPending)
  1249. {
  1250. createPending = false;
  1251. interceptedCtx.set(ctx->queryCodeContext());
  1252. basehelper.onCreate(&interceptedCtx, colocalParent, NULL);
  1253. }
  1254. }
  1255. virtual void stop()
  1256. {
  1257. // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
  1258. if (state != STATEstopped)
  1259. {
  1260. CriticalBlock cb(statecrit);
  1261. if (state != STATEstopped)
  1262. {
  1263. #ifdef TRACE_STARTSTOP
  1264. if (traceStartStop)
  1265. {
  1266. CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
  1267. if (watchActivityId && watchActivityId==activityId)
  1268. {
  1269. CTXLOG("WATCH: stop %p %d", this, activityId);
  1270. }
  1271. }
  1272. #endif
  1273. state=STATEstopped;
  1274. // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
  1275. ForEachItemIn(idx, dependencies)
  1276. {
  1277. if (dependencyControlIds.item(idx) == 0)
  1278. dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
  1279. }
  1280. if (inputStream)
  1281. inputStream->stop();
  1282. }
  1283. }
  1284. }
  1285. virtual void abort()
  1286. {
  1287. aborted = true;
  1288. // MORE - should abort dependencies here?
  1289. stop();
  1290. }
  1291. inline void reset()
  1292. {
  1293. if (state != STATEreset)
  1294. {
  1295. CriticalBlock cb(statecrit);
  1296. if (state != STATEreset)
  1297. {
  1298. if (state==STATEstarted || state==STATEstarting)
  1299. {
  1300. if (ctx->queryOptions().failOnLeaks)
  1301. throw makeStringExceptionV(ROXIE_INTERNAL_ERROR, "STATE: activity %d reset without stop", activityId);
  1302. if (traceStartStop || traceLevel > 2)
  1303. CTXLOG("STATE: activity %d reset without stop", activityId);
  1304. stop();
  1305. }
  1306. state = STATEreset;
  1307. #ifdef TRACE_STARTSTOP
  1308. if (traceStartStop)
  1309. {
  1310. CTXLOG("reset %p %d", this, activityId);
  1311. if (watchActivityId && watchActivityId==activityId)
  1312. {
  1313. CTXLOG("WATCH: reset %p %d", this, activityId);
  1314. }
  1315. }
  1316. #endif
  1317. resetJunction(junction);
  1318. ForEachItemIn(idx, dependencies)
  1319. dependencies.item(idx).reset();
  1320. if (input)
  1321. input->reset();
  1322. }
  1323. }
  1324. aborted = false;
  1325. }
  1326. virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
  1327. {
  1328. dependencies.append(source);
  1329. dependencyIndexes.append(sourceIdx);
  1330. dependencyControlIds.append(controlId);
  1331. }
  1332. virtual void resetEOF()
  1333. {
  1334. //would make more sense if the default implementation (and eof member) were in the base class
  1335. }
  1336. // Sink activities should override this....
  1337. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  1338. {
  1339. throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
  1340. }
  1341. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  1342. {
  1343. throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
  1344. }
  1345. virtual void stopSink(unsigned idx)
  1346. {
  1347. throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
  1348. }
  1349. virtual void connectInputStreams(bool consumerOrdered)
  1350. {
  1351. if (input && !inputStream)
  1352. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
  1353. if (!connected)
  1354. {
  1355. connectDependencies();
  1356. connected = true;
  1357. }
  1358. }
  1359. void connectDependencies()
  1360. {
  1361. ForEachItemIn(i, dependencies)
  1362. dependencies.item(i).connectInputStreams(true);
  1363. }
  1364. virtual __int64 evaluate()
  1365. {
  1366. throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
  1367. }
  1368. virtual IFinalRoxieInput * querySelectOutput(unsigned id)
  1369. {
  1370. return NULL;
  1371. }
  1372. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  1373. {
  1374. return false;
  1375. }
  1376. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  1377. {
  1378. assertex(!idx);
  1379. input = _in;
  1380. sourceIdx = _sourceIdx;
  1381. inputStream = NULL;
  1382. }
  1383. bool isInputOrdered(bool consumerOrdered, unsigned idx) const
  1384. {
  1385. if (!factory)
  1386. return true;
  1387. //Grouping implies the stream processing must be ordered - I think this always applies
  1388. IFinalRoxieInput * curInput = queryInput(idx);
  1389. if (curInput && curInput->queryOutputMeta()->isGrouped())
  1390. return true;
  1391. return factory->isInputOrdered(consumerOrdered, idx);
  1392. }
  1393. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  1394. {
  1395. assertex(!idx);
  1396. // By default, activities are assumed NOT to support streams
  1397. bool inputOrdered = isInputOrdered(consumerOrdered, 0);
  1398. connectInputStreams(inputOrdered);
  1399. // Return a single stream
  1400. streams.append(this);
  1401. return NULL;
  1402. }
  1403. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  1404. {
  1405. if (idx == (unsigned) -1)
  1406. idx = 0;
  1407. return idx ? NULL : this;
  1408. }
  1409. virtual IOutputMetaData *queryOutputMeta() const
  1410. {
  1411. return meta.queryOriginal();
  1412. }
  1413. virtual unsigned queryId() const
  1414. {
  1415. return activityId;
  1416. }
  1417. virtual unsigned querySubgraphId() const
  1418. {
  1419. return factory->querySubgraphId();
  1420. }
  1421. virtual void checkAbort()
  1422. {
  1423. ctx->checkAbort();
  1424. }
  1425. IException *makeWrappedException(IException *e)
  1426. {
  1427. StringBuffer msg;
  1428. ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
  1429. CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
  1430. if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
  1431. return e;
  1432. else
  1433. return new CWrappedException(e, activityKind, activityId);
  1434. }
  1435. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  1436. {
  1437. }
  1438. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  1439. {
  1440. }
  1441. virtual void resetOutputsUsed()
  1442. {
  1443. }
  1444. virtual void noteOutputUsed()
  1445. {
  1446. }
  1447. virtual IRoxieServerSideCache *queryServerSideCache() const
  1448. {
  1449. return factory->queryServerSideCache();
  1450. }
  1451. virtual const IRoxieServerActivityFactory *queryFactory() const
  1452. {
  1453. return factory;
  1454. }
  1455. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1456. {
  1457. addEdgeStats(statsBuilder, 0, numStarts, processed, 1);
  1458. }
  1459. inline ThorActivityKind getKind() const
  1460. {
  1461. return factory->getKind();
  1462. }
  1463. inline bool isSink() const
  1464. {
  1465. return (factory != NULL) && factory->isSink();
  1466. }
  1467. void addEdgeStats(IStatisticGatherer * statsBuilder, unsigned oid, unsigned starts, unsigned _processed, unsigned _strands) const
  1468. {
  1469. if (statsBuilder)
  1470. {
  1471. StatsEdgeScope scope(*statsBuilder, activityId, oid);
  1472. if (_strands)
  1473. statsBuilder->addStatistic(StNumStrands, _strands);
  1474. if (starts != 0)
  1475. {
  1476. statsBuilder->addStatistic(StNumRowsProcessed, _processed);
  1477. statsBuilder->addStatistic(StNumStarts, starts);
  1478. // Assume number of starts = number of stops since stats only ever gathered when a query is complete
  1479. statsBuilder->addStatistic(StNumStops, starts);
  1480. statsBuilder->addStatistic(StNumSlaves, 1); // Arguable
  1481. }
  1482. }
  1483. if (collectFactoryStatistics)
  1484. factory->noteProcessed(oid, processed);
  1485. }
  1486. protected:
  1487. RecordTranslationMode getEnableFieldTranslation() const
  1488. {
  1489. return factory->queryQueryFactory().queryOptions().enableFieldTranslation;
  1490. }
  1491. };
  1492. //=====================================================================================================
  1493. class CRoxieServerLateStartActivity : public CRoxieServerActivity
  1494. {
  1495. protected:
  1496. bool prefiltered;
  1497. bool eof;
  1498. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1499. {
  1500. prefiltered = !any;
  1501. eof = prefiltered;
  1502. if (!prefiltered)
  1503. {
  1504. input->start(parentExtractSize, parentExtract, false);
  1505. startJunction(junction);
  1506. }
  1507. else
  1508. {
  1509. if (traceStartStop)
  1510. CTXLOG("lateStart activity stopping input early as prefiltered");
  1511. inputStream->stop();
  1512. }
  1513. }
  1514. public:
  1515. CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  1516. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  1517. {
  1518. prefiltered = false;
  1519. eof = false;
  1520. }
  1521. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1522. {
  1523. IFinalRoxieInput *saveInput = input;
  1524. Owned<IStrandJunction> saveJunction = junction.getClear();
  1525. input = NULL; // Make sure parent does not start the chain yet
  1526. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1527. input = saveInput;
  1528. junction.setown(saveJunction.getClear());
  1529. }
  1530. virtual void stop()
  1531. {
  1532. if (!prefiltered && inputStream)
  1533. {
  1534. inputStream->stop();
  1535. }
  1536. else if (traceStartStop)
  1537. CTXLOG("lateStart activity NOT stopping input late as prefiltered");
  1538. IEngineRowStream *save = inputStream;
  1539. inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
  1540. CRoxieServerActivity::stop();
  1541. inputStream = save;
  1542. }
  1543. virtual void reset()
  1544. {
  1545. CRoxieServerActivity::reset();
  1546. prefiltered = false;
  1547. }
  1548. };
  1549. //=================================================================================
  1550. class StrandOptions
  1551. {
  1552. // Typically set from hints, common to many stranded activities
  1553. public:
  1554. explicit StrandOptions(IPropertyTree &_graphNode)
  1555. {
  1556. //PARALLEL(1) can be used to explicitly disable parallel processing.
  1557. numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
  1558. if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
  1559. numStrands = getAffinityCpus();
  1560. blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
  1561. }
  1562. StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
  1563. {
  1564. numStrands = from.numStrands;
  1565. blockSize = from.blockSize;
  1566. if (!blockSize)
  1567. blockSize = ctx->queryOptions().strandBlockSize;
  1568. if (numStrands == 0)
  1569. numStrands = ctx->queryOptions().forceNumStrands;
  1570. }
  1571. public:
  1572. unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
  1573. unsigned blockSize = 0;
  1574. };
  1575. class StrandProcessor : public CInterfaceOf<IEngineRowStream>
  1576. {
  1577. protected:
  1578. CRoxieServerActivity &parent;
  1579. IEngineRowAllocator *rowAllocator;
  1580. IEngineRowStream *inputStream;
  1581. ActivityTimeAccumulator totalCycles;
  1582. mutable CRuntimeStatisticCollection stats;
  1583. unsigned processed = 0;
  1584. unsigned numProcessedLastGroup = 0;
  1585. const bool timeActivities;
  1586. bool stopped = false;
  1587. std::atomic<bool> abortRequested;
  1588. public:
  1589. explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
  1590. : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
  1591. {
  1592. if (needsAllocator)
  1593. {
  1594. rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
  1595. }
  1596. else
  1597. rowAllocator = NULL;
  1598. }
  1599. ~StrandProcessor()
  1600. {
  1601. ::Release(rowAllocator);
  1602. }
  1603. virtual void start()
  1604. {
  1605. processed = 0;
  1606. numProcessedLastGroup = 0;
  1607. totalCycles.reset();
  1608. }
  1609. virtual void stop()
  1610. {
  1611. if (!stopped)
  1612. {
  1613. if (inputStream)
  1614. inputStream->stop();
  1615. parent.stop();
  1616. //It would be preferrable to move totalCycles (+processed?) to gatherStats(), but because of
  1617. //the way firstRow is associated with startCycles it would require an extra parameter
  1618. //which is not consistent with the other gatherStats() calls, or extra logic in the stats classes.
  1619. parent.mergeStrandStats(processed, totalCycles);
  1620. }
  1621. stopped = true;
  1622. }
  1623. virtual void reset()
  1624. {
  1625. stopped = false;
  1626. abortRequested.store(false, std::memory_order_relaxed);
  1627. }
  1628. virtual void resetEOF()
  1629. {
  1630. inputStream->resetEOF();
  1631. }
  1632. inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
  1633. inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
  1634. void gatherStats(CRuntimeStatisticCollection & mergedStats) const
  1635. {
  1636. mergedStats.merge(stats);
  1637. if (rowAllocator)
  1638. rowAllocator->gatherStats(mergedStats);
  1639. }
  1640. const ActivityTimeAccumulator& queryTimings() const { return totalCycles; }
  1641. };
  1642. class CRoxieServerStrandedActivity : public CRoxieServerActivity
  1643. {
  1644. protected:
  1645. StrandOptions strandOptions;
  1646. IArrayOf<StrandProcessor> strands;
  1647. Owned<IStrandBranch> branch;
  1648. Owned<IStrandJunction> splitter;
  1649. Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
  1650. std::atomic<unsigned> active;
  1651. public:
  1652. CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1653. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  1654. strandOptions(_strandOptions, ctx)
  1655. {
  1656. active = 0;
  1657. }
  1658. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  1659. {
  1660. CRoxieServerActivity::gatherStats(merged);
  1661. ForEachItemIn(i, strands)
  1662. strands.item(i).gatherStats(merged);
  1663. }
  1664. virtual void onCreate(IHThorArg *_colocalArg)
  1665. {
  1666. CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
  1667. }
  1668. //This function is pure (But also implemented out of line) to force the derived classes to implement it.
  1669. //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
  1670. //this must also happen before any rows are read from the strands (e.g., by a source junction)
  1671. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
  1672. virtual void reset()
  1673. {
  1674. assertex(active==0);
  1675. totalCycles.reset();
  1676. ForEachItemIn(idx, strands)
  1677. {
  1678. strands.item(idx).reset();
  1679. totalCycles.merge(strands.item(idx).queryTimings());
  1680. }
  1681. resetJunction(splitter);
  1682. CRoxieServerActivity::reset();
  1683. resetJunction(sourceJunction);
  1684. }
  1685. virtual void stop()
  1686. {
  1687. // Called from the strands... which should ensure that stop is not called more than once per strand
  1688. //The first strand to call
  1689. if (active)
  1690. --active;
  1691. if (!active)
  1692. CRoxieServerActivity::stop();
  1693. }
  1694. void requestAbort()
  1695. {
  1696. ForEachItemIn(idx, strands)
  1697. strands.item(idx).requestAbort();
  1698. }
  1699. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  1700. {
  1701. assertex(idx == 0);
  1702. assertex(strands.empty());
  1703. CRoxieServerActivity::connectDependencies();
  1704. bool inputOrdered = isInputOrdered(consumerOrdered, idx);
  1705. //Note, numStrands == 1 is an explicit request to disable threading
  1706. if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
  1707. {
  1708. //Check to see if the consumer's settings should override
  1709. if (strandOptions.numStrands == 0)
  1710. {
  1711. strandOptions.numStrands = consumerOptions->numStrands;
  1712. strandOptions.blockSize = consumerOptions->blockSize;
  1713. }
  1714. else if (consumerOptions->numStrands > strandOptions.numStrands)
  1715. {
  1716. strandOptions.numStrands = consumerOptions->numStrands;
  1717. }
  1718. }
  1719. Owned <IStrandJunction> recombiner;
  1720. if (input)
  1721. {
  1722. if (strandOptions.numStrands == 1)
  1723. {
  1724. // 1 means explicitly requested single-strand.
  1725. IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
  1726. strands.append(*createStrandProcessor(instream));
  1727. }
  1728. else
  1729. {
  1730. PointerArrayOf<IEngineRowStream> instreams;
  1731. recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
  1732. if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
  1733. {
  1734. assertex(recombiner == NULL);
  1735. // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
  1736. if (inputOrdered)
  1737. {
  1738. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
  1739. splitter.set(branch->queryInputJunction());
  1740. recombiner.set(branch->queryOutputJunction());
  1741. }
  1742. else
  1743. {
  1744. splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
  1745. }
  1746. splitter->setInput(0, instreams.item(0));
  1747. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1748. strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
  1749. }
  1750. else
  1751. {
  1752. // Ignore my hint and just use the width already split into...
  1753. ForEachItemIn(strandNo, instreams)
  1754. strands.append(*createStrandProcessor(instreams.item(strandNo)));
  1755. }
  1756. }
  1757. }
  1758. else
  1759. {
  1760. unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
  1761. for (unsigned i=0; i < numStrands; i++)
  1762. strands.append(*createStrandSourceProcessor(inputOrdered));
  1763. if (inputOrdered && (numStrands > 1))
  1764. {
  1765. if (consumerOptions)
  1766. {
  1767. //If the output activities are also stranded then need to create a version of the branch
  1768. bool isGrouped = queryOutputMeta()->isGrouped();
  1769. branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
  1770. sourceJunction.set(branch->queryInputJunction());
  1771. recombiner.set(branch->queryOutputJunction());
  1772. assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
  1773. //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
  1774. for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
  1775. {
  1776. sourceJunction->setInput(strandNo, &strands.item(strandNo));
  1777. streams.append(sourceJunction->queryOutput(strandNo));
  1778. }
  1779. #ifdef TRACE_STRANDS
  1780. if (traceLevel > 2)
  1781. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1782. #endif
  1783. return recombiner.getClear();
  1784. }
  1785. else
  1786. {
  1787. //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
  1788. recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
  1789. }
  1790. }
  1791. }
  1792. ForEachItemIn(i, strands)
  1793. streams.append(&strands.item(i));
  1794. #ifdef TRACE_STRANDS
  1795. if (traceLevel > 2)
  1796. DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
  1797. #endif
  1798. return recombiner.getClear();
  1799. }
  1800. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
  1801. //MORE: Possibly this class should be split into two for sinks and non sinks...
  1802. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
  1803. virtual const void * nextRow()
  1804. {
  1805. throwUnexpected();
  1806. }
  1807. inline unsigned numStrands() const { return strands.ordinality(); }
  1808. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  1809. {
  1810. addEdgeStats(statsBuilder, 0, numStarts, processed, strands.ordinality());
  1811. }
  1812. protected:
  1813. void onStartStrands()
  1814. {
  1815. ForEachItemIn(idx, strands)
  1816. {
  1817. strands.item(idx).start();
  1818. active++;
  1819. }
  1820. }
  1821. };
  1822. //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
  1823. void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1824. {
  1825. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1826. startJunction(splitter);
  1827. }
  1828. class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
  1829. {
  1830. protected:
  1831. bool prefiltered;
  1832. bool eof;
  1833. void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
  1834. {
  1835. prefiltered = !any;
  1836. eof = prefiltered;
  1837. if (!prefiltered)
  1838. {
  1839. //At this point
  1840. input->start(parentExtractSize, parentExtract, false);
  1841. startJunction(splitter);
  1842. onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
  1843. startJunction(sourceJunction);
  1844. }
  1845. else
  1846. {
  1847. if (traceStartStop)
  1848. CTXLOG("strandedLateStart activity stopping input early as prefiltered");
  1849. ForEachItemIn(idx, strands)
  1850. strands.item(idx).stop();
  1851. }
  1852. }
  1853. public:
  1854. CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  1855. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  1856. {
  1857. prefiltered = false;
  1858. eof = false;
  1859. }
  1860. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  1861. {
  1862. IFinalRoxieInput *save = input;
  1863. 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)
  1864. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  1865. input = save;
  1866. }
  1867. virtual void reset()
  1868. {
  1869. CRoxieServerStrandedActivity::reset();
  1870. prefiltered = false;
  1871. }
  1872. };
  1873. //=====================================================================================================
  1874. atomic_t nextInstanceId;
  1875. extern unsigned getNextInstanceId()
  1876. {
  1877. return atomic_add_exchange(&nextInstanceId, 1)+1;
  1878. }
  1879. atomic_t nextRuid;
  1880. ruid_t getNextRuid()
  1881. {
  1882. ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
  1883. while (ret < RUID_FIRST)
  1884. ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
  1885. return ret;
  1886. }
  1887. void setStartRuid(unsigned restarts)
  1888. {
  1889. atomic_set(&nextRuid, restarts * 0x10000);
  1890. atomic_set(&nextInstanceId, restarts * 10000);
  1891. }
  1892. enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
  1893. class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
  1894. {
  1895. int code;
  1896. public:
  1897. LimitSkipException(int _code) { code = _code; }
  1898. IMPLEMENT_IINTERFACE;
  1899. virtual int errorCode() const { return code; }
  1900. virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
  1901. virtual MessageAudience errorAudience() const { return MSGAUD_programmer; }
  1902. };
  1903. IException *makeLimitSkipException(bool isKeyed)
  1904. {
  1905. // We need to make sure what we throw is IException not something derived from it....
  1906. return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
  1907. }
  1908. //=================================================================================
  1909. interface IRecordPullerCallback : extends IExceptionHandler
  1910. {
  1911. virtual void processRow(const void *row) = 0;
  1912. virtual void processEOG() = 0;
  1913. virtual void processGroup(const ConstPointerArray &rows) = 0;
  1914. virtual void processDone() = 0;
  1915. };
  1916. class RecordPullerThread : public RestartableThread
  1917. {
  1918. protected:
  1919. IFinalRoxieInput *input;
  1920. Owned<IStrandJunction> junction;
  1921. unsigned sourceIdx = 0;
  1922. IEngineRowStream *inputStream;
  1923. IRecordPullerCallback *helper;
  1924. Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
  1925. bool groupAtOnce, eof, eog;
  1926. CriticalSection crit;
  1927. public:
  1928. RecordPullerThread(bool _groupAtOnce)
  1929. : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
  1930. {
  1931. input = NULL;
  1932. inputStream = NULL;
  1933. helper = NULL;
  1934. eof = eog = FALSE;
  1935. }
  1936. inline unsigned __int64 queryTotalCycles() const
  1937. {
  1938. return input->queryTotalCycles();
  1939. }
  1940. void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
  1941. {
  1942. helper = _helper;
  1943. input = _input;
  1944. sourceIdx = _sourceIdx;
  1945. }
  1946. IFinalRoxieInput *queryInput() const
  1947. {
  1948. return input;
  1949. }
  1950. virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  1951. {
  1952. inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  1953. }
  1954. IEngineRowStream *queryStream() const
  1955. {
  1956. return inputStream;
  1957. }
  1958. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
  1959. {
  1960. eof = false;
  1961. eog = false;
  1962. input->start(parentExtractSize, parentExtract, paused);
  1963. startJunction(junction);
  1964. try
  1965. {
  1966. if (preload && !paused)
  1967. {
  1968. if (traceLevel > 4)
  1969. DBGLOG("Preload fetching first %d records", preload);
  1970. if (groupAtOnce)
  1971. pullGroups(preload);
  1972. else
  1973. pullRecords(preload);
  1974. }
  1975. if (eof)
  1976. {
  1977. if (traceLevel > 4)
  1978. DBGLOG("No need to start puller after preload");
  1979. helper->processDone();
  1980. }
  1981. else
  1982. {
  1983. if (!noThread)
  1984. {
  1985. StringBuffer logPrefix("[");
  1986. if (ctx) ctx->getLogPrefix(logPrefix);
  1987. logPrefix.append("] ");
  1988. RestartableThread::start(logPrefix);
  1989. started.wait();
  1990. }
  1991. }
  1992. }
  1993. catch (IException *e)
  1994. {
  1995. helper->fireException(e);
  1996. }
  1997. catch (...)
  1998. {
  1999. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
  2000. }
  2001. }
  2002. void stop()
  2003. {
  2004. if (traceStartStop)
  2005. DBGLOG("RecordPullerThread::stop");
  2006. {
  2007. 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.
  2008. if (inputStream)
  2009. inputStream->stop();
  2010. }
  2011. RestartableThread::join();
  2012. }
  2013. void reset()
  2014. {
  2015. input->reset();
  2016. resetJunction(junction);
  2017. }
  2018. virtual int run()
  2019. {
  2020. started.signal();
  2021. try
  2022. {
  2023. if (groupAtOnce)
  2024. pullGroups((unsigned) -1);
  2025. else
  2026. pullRecords((unsigned) -1);
  2027. helper->processDone();
  2028. }
  2029. catch (IException *e)
  2030. {
  2031. helper->fireException(e);
  2032. }
  2033. catch (...)
  2034. {
  2035. helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
  2036. }
  2037. return 0;
  2038. }
  2039. void done()
  2040. {
  2041. helper->processDone();
  2042. }
  2043. bool pullRecords(unsigned preload)
  2044. {
  2045. if (eof)
  2046. return false;
  2047. while (preload)
  2048. {
  2049. const void * row;
  2050. {
  2051. CriticalBlock c(crit); // See comments in stop for why this is needed
  2052. row = inputStream->nextRow();
  2053. }
  2054. if (row)
  2055. {
  2056. eog = false;
  2057. helper->processRow(row);
  2058. }
  2059. else if (!eog)
  2060. {
  2061. helper->processEOG();
  2062. eog = true;
  2063. }
  2064. else
  2065. {
  2066. eof = true;
  2067. return false;
  2068. }
  2069. if (preload != (unsigned) -1)
  2070. preload--;
  2071. }
  2072. return true;
  2073. }
  2074. void pullGroups(unsigned preload)
  2075. {
  2076. ConstPointerArray thisGroup;
  2077. unsigned rowsDone = 0;
  2078. while (preload && !eof)
  2079. {
  2080. const void *row;
  2081. {
  2082. CriticalBlock c(crit);
  2083. row = inputStream->nextRow();
  2084. }
  2085. if (row)
  2086. {
  2087. thisGroup.append(row);
  2088. rowsDone++;
  2089. }
  2090. else if (thisGroup.length())
  2091. {
  2092. helper->processGroup(thisGroup);
  2093. thisGroup.kill();
  2094. if (preload != (unsigned) -1)
  2095. {
  2096. if (preload > rowsDone)
  2097. preload -= rowsDone;
  2098. else
  2099. break;
  2100. }
  2101. rowsDone = 0;
  2102. }
  2103. else
  2104. {
  2105. eof = true;
  2106. break;
  2107. }
  2108. }
  2109. }
  2110. };
  2111. //=================================================================================
  2112. #define READAHEAD_SIZE 1000
  2113. // MORE - this code copied from ThreadedConcat code - may be able to common up some.
  2114. class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
  2115. {
  2116. QueueOf<const void, true> buffer;
  2117. InterruptableSemaphore ready;
  2118. InterruptableSemaphore space;
  2119. CriticalSection crit;
  2120. bool eof;
  2121. bool disabled;
  2122. IRoxieSlaveContext *ctx;
  2123. RecordPullerThread puller;
  2124. unsigned preload;
  2125. cycle_t totalCycles;
  2126. bool timeActivities;
  2127. public:
  2128. IMPLEMENT_IINTERFACE;
  2129. CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
  2130. {
  2131. eof = false;
  2132. disabled = (ctx->queryDebugContext() != NULL);
  2133. totalCycles = 0;
  2134. timeActivities = ctx->queryOptions().timeActivities;
  2135. }
  2136. virtual IRoxieServerActivity *queryActivity()
  2137. {
  2138. return puller.queryInput()->queryActivity();
  2139. }
  2140. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2141. {
  2142. assertex(!idx);
  2143. puller.connectInputStreams(ctx, consumerOrdered);
  2144. streams.append(this);
  2145. return NULL;
  2146. }
  2147. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  2148. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  2149. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  2150. {
  2151. return puller.queryInput()->queryIndexReadActivity();
  2152. }
  2153. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2154. {
  2155. eof = false;
  2156. if (disabled)
  2157. puller.queryInput()->start(parentExtractSize, parentExtract, paused);
  2158. else
  2159. {
  2160. space.reinit(READAHEAD_SIZE);
  2161. ready.reinit();
  2162. puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
  2163. }
  2164. }
  2165. virtual void stop()
  2166. {
  2167. if (disabled)
  2168. puller.queryStream()->stop();
  2169. else
  2170. {
  2171. space.interrupt();
  2172. ready.interrupt();
  2173. puller.stop();
  2174. }
  2175. }
  2176. virtual void reset()
  2177. {
  2178. if (disabled)
  2179. puller.queryInput()->reset();
  2180. else
  2181. {
  2182. puller.reset();
  2183. ForEachItemIn(idx1, buffer)
  2184. ReleaseRoxieRow(buffer.item(idx1));
  2185. buffer.clear();
  2186. }
  2187. }
  2188. virtual void resetEOF()
  2189. {
  2190. throwUnexpected();
  2191. }
  2192. virtual IOutputMetaData * queryOutputMeta() const
  2193. {
  2194. return puller.queryInput()->queryOutputMeta();
  2195. }
  2196. void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2197. {
  2198. assertex(!idx);
  2199. puller.setInput(this, _sourceIdx, _in);
  2200. }
  2201. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2202. {
  2203. if (idx==0)
  2204. return puller.queryInput();
  2205. else
  2206. return NULL;
  2207. }
  2208. virtual unsigned __int64 queryTotalCycles() const
  2209. {
  2210. return totalCycles;
  2211. }
  2212. virtual const void * nextRow()
  2213. {
  2214. SimpleActivityTimer t(totalCycles, timeActivities);
  2215. if (disabled)
  2216. return puller.queryStream()->nextRow();
  2217. else
  2218. {
  2219. for (;;)
  2220. {
  2221. {
  2222. CriticalBlock b(crit);
  2223. if (eof && !buffer.ordinality())
  2224. return NULL; // eof
  2225. }
  2226. ready.wait();
  2227. const void *ret;
  2228. {
  2229. CriticalBlock b(crit);
  2230. ret = buffer.dequeue();
  2231. }
  2232. space.signal();
  2233. return ret;
  2234. }
  2235. }
  2236. }
  2237. virtual bool fireException(IException *e)
  2238. {
  2239. // called from puller thread on failure
  2240. ready.interrupt(LINK(e));
  2241. space.interrupt(e);
  2242. return true;
  2243. }
  2244. virtual void processRow(const void *row)
  2245. {
  2246. {
  2247. CriticalBlock b(crit);
  2248. buffer.enqueue(row);
  2249. }
  2250. ready.signal();
  2251. space.wait();
  2252. }
  2253. virtual void processGroup(const ConstPointerArray &rows)
  2254. {
  2255. // NOTE - a bit bizarre in that it waits for the space AFTER using it.
  2256. // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
  2257. // if group was larger than max(space)
  2258. {
  2259. CriticalBlock b(crit);
  2260. ForEachItemIn(idx, rows)
  2261. buffer.enqueue(rows.item(idx));
  2262. buffer.enqueue(NULL);
  2263. }
  2264. for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
  2265. {
  2266. ready.signal();
  2267. space.wait();
  2268. }
  2269. }
  2270. virtual void processEOG()
  2271. {
  2272. // Used when output is not grouped - just ignore
  2273. }
  2274. virtual void processDone()
  2275. {
  2276. CriticalBlock b(crit);
  2277. eof = true;
  2278. ready.signal();
  2279. }
  2280. };
  2281. //=================================================================================
  2282. class CRoxieServerTwoInputActivity : public CRoxieServerActivity
  2283. {
  2284. protected:
  2285. IFinalRoxieInput *input1;
  2286. IEngineRowStream *inputStream1;
  2287. Owned<IStrandJunction> junction1;
  2288. unsigned sourceIdx1 = 0;
  2289. Owned<CRoxieServerReadAheadInput> puller;
  2290. public:
  2291. CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  2292. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  2293. {
  2294. input1 = NULL;
  2295. inputStream1 = NULL;
  2296. }
  2297. ~CRoxieServerTwoInputActivity()
  2298. {
  2299. }
  2300. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2301. {
  2302. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  2303. input1->start(parentExtractSize, parentExtract, paused);
  2304. startJunction(junction1);
  2305. }
  2306. virtual void stop()
  2307. {
  2308. inputStream1->stop();
  2309. CRoxieServerActivity::stop();
  2310. }
  2311. virtual unsigned __int64 queryLocalCycles() const
  2312. {
  2313. __int64 ret;
  2314. __int64 inputCycles = input->queryTotalCycles();
  2315. __int64 input1Cycles = input1->queryTotalCycles();
  2316. if (puller)
  2317. ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
  2318. else
  2319. ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
  2320. if (ret < 0)
  2321. ret = 0;
  2322. return ret;
  2323. }
  2324. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2325. {
  2326. switch (idx)
  2327. {
  2328. case 0:
  2329. return input;
  2330. case 1:
  2331. return input1;
  2332. default:
  2333. return NULL;
  2334. }
  2335. }
  2336. virtual void reset()
  2337. {
  2338. CRoxieServerActivity::reset();
  2339. if (input1)
  2340. input1->reset();
  2341. resetJunction(junction1);
  2342. }
  2343. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2344. {
  2345. switch(idx)
  2346. {
  2347. case 0:
  2348. CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
  2349. break;
  2350. case 1:
  2351. input1 = _in;
  2352. sourceIdx1 = _sourceIdx;
  2353. break;
  2354. default:
  2355. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  2356. }
  2357. }
  2358. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2359. {
  2360. inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
  2361. //Assumes input1 will be stranded if any.
  2362. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  2363. }
  2364. };
  2365. //=================================================================================
  2366. class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
  2367. {
  2368. protected:
  2369. unsigned numInputs;
  2370. unsigned numStreams;
  2371. IFinalRoxieInput **inputArray;
  2372. unsigned *sourceIdxArray;
  2373. IEngineRowStream **streamArray;
  2374. Owned<IStrandJunction> *junctionArray;
  2375. public:
  2376. CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2377. : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
  2378. {
  2379. numStreams = numInputs;
  2380. inputArray = new IFinalRoxieInput*[numInputs];
  2381. sourceIdxArray = new unsigned[numInputs];
  2382. streamArray = new IEngineRowStream*[numStreams];
  2383. junctionArray = new Owned<IStrandJunction>[numStreams];
  2384. for (unsigned i1 = 0; i1 < numInputs; i1++)
  2385. {
  2386. inputArray[i1] = NULL;
  2387. sourceIdxArray[i1] = 0;
  2388. }
  2389. for (unsigned i2 = 0; i2 < numStreams; i2++)
  2390. streamArray[i2] = NULL;
  2391. }
  2392. ~CRoxieServerMultiInputBaseActivity()
  2393. {
  2394. delete [] inputArray;
  2395. delete [] sourceIdxArray;
  2396. delete [] streamArray;
  2397. delete [] junctionArray;
  2398. }
  2399. virtual unsigned __int64 queryLocalCycles() const
  2400. {
  2401. __int64 localCycles = totalCycles.totalCycles;
  2402. for (unsigned i = 0; i < numInputs; i++)
  2403. localCycles -= inputArray[i]->queryTotalCycles();
  2404. if (localCycles < 0)
  2405. localCycles = 0;
  2406. return localCycles;
  2407. }
  2408. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  2409. {
  2410. if (idx < numInputs)
  2411. return inputArray[idx];
  2412. else
  2413. return NULL;
  2414. }
  2415. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  2416. {
  2417. return queryInput(idx);
  2418. }
  2419. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  2420. {
  2421. if (whichInput < numInputs)
  2422. return streamArray[whichInput];
  2423. else
  2424. return NULL;
  2425. }
  2426. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  2427. {
  2428. if (idx < numInputs)
  2429. return junctionArray[idx];
  2430. else
  2431. return NULL;
  2432. }
  2433. virtual void reset()
  2434. {
  2435. for (unsigned i = 0; i < numInputs; i++)
  2436. inputArray[i]->reset();
  2437. for (unsigned iS = 0; iS < numStreams; iS++)
  2438. {
  2439. resetJunction(junctionArray[iS]);
  2440. }
  2441. CRoxieServerActivity::reset();
  2442. }
  2443. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  2444. {
  2445. assertex(idx < numInputs && idx < numStreams);
  2446. inputArray[idx] = _in;
  2447. sourceIdxArray[idx] = _sourceIdx;
  2448. }
  2449. virtual void connectInputStreams(bool consumerOrdered)
  2450. {
  2451. //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
  2452. connectSingleInputStreams(consumerOrdered);
  2453. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  2454. }
  2455. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  2456. {
  2457. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
  2458. }
  2459. protected:
  2460. void connectSingleInputStreams(bool consumerOrdered)
  2461. {
  2462. for (unsigned i = 0; i < numInputs; i++)
  2463. streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
  2464. }
  2465. };
  2466. //=================================================================================
  2467. class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
  2468. {
  2469. public:
  2470. CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  2471. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  2472. {
  2473. }
  2474. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  2475. {
  2476. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  2477. for (unsigned i = 0; i < numInputs; i++)
  2478. {
  2479. inputArray[i]->start(parentExtractSize, parentExtract, paused);
  2480. }
  2481. for (unsigned iS = 0; iS < numStreams; iS++)
  2482. {
  2483. startJunction(junctionArray[iS]);
  2484. }
  2485. }
  2486. virtual void stop()
  2487. {
  2488. for (unsigned i = 0; i < numStreams; i++)
  2489. {
  2490. streamArray[i]->stop();
  2491. }
  2492. CRoxieServerMultiInputBaseActivity::stop();
  2493. }
  2494. };
  2495. //=====================================================================================================
  2496. class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
  2497. {
  2498. protected:
  2499. unsigned numOutputs;
  2500. bool executed;
  2501. bool *stopped;
  2502. CriticalSection ecrit;
  2503. Owned<IException> exception;
  2504. public:
  2505. CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  2506. : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
  2507. {
  2508. executed = false;
  2509. stopped = new bool[numOutputs];
  2510. for (unsigned s = 0; s < numOutputs; s++)
  2511. stopped[s] = false;
  2512. }
  2513. ~CRoxieServerInternalSinkActivity()
  2514. {
  2515. delete [] stopped;
  2516. }
  2517. virtual void reset()
  2518. {
  2519. for (unsigned s = 0; s < numOutputs; s++)
  2520. stopped[s] = false;
  2521. executed = false;
  2522. exception.clear();
  2523. CRoxieServerActivity::reset();
  2524. }
  2525. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  2526. {
  2527. return NULL;
  2528. }
  2529. virtual void stopSink(unsigned outputIdx)
  2530. {
  2531. if (outputIdx < numOutputs && !stopped[outputIdx]) // Implicit dependencies on DiskWrite activities do not count as outputs
  2532. {
  2533. stopped[outputIdx] = true;
  2534. for (unsigned s = 0; s < numOutputs; s++)
  2535. if (!stopped[s])
  2536. return;
  2537. stop(); // all outputs stopped - stop parent.
  2538. }
  2539. }
  2540. virtual const void *nextRow()
  2541. {
  2542. throwUnexpected(); // I am nobody's input
  2543. }
  2544. virtual void onExecute() = 0;
  2545. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  2546. {
  2547. CriticalBlock b(ecrit);
  2548. if (exception)
  2549. throw exception.getLink();
  2550. if (!executed)
  2551. {
  2552. try
  2553. {
  2554. start(parentExtractSize, parentExtract, false);
  2555. {
  2556. ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
  2557. onExecute();
  2558. }
  2559. stop();
  2560. executed = true;
  2561. }
  2562. catch (IException *E)
  2563. {
  2564. exception.set(E); // (or maybe makeWrappedException?)
  2565. abort();
  2566. throw;
  2567. }
  2568. catch (...)
  2569. {
  2570. exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
  2571. abort();
  2572. throw;
  2573. }
  2574. }
  2575. }
  2576. };
  2577. //=================================================================================
  2578. class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
  2579. {
  2580. protected:
  2581. Owned<IMessageResult> result;
  2582. Owned<IRoxieQueryPacket> packet;
  2583. Linked<IRoxieServerQueryPacket> continuation;
  2584. unsigned hash;
  2585. unsigned seq;
  2586. unsigned lastDebugSequence;
  2587. Owned<IRoxieQueryPacket> lastDebugResponse;
  2588. ILRUChain *prev;
  2589. ILRUChain *next;
  2590. bool delayed;
  2591. public:
  2592. IMPLEMENT_IINTERFACE;
  2593. CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
  2594. {
  2595. hash = 0;
  2596. seq = 0;
  2597. prev = NULL;
  2598. next = NULL;
  2599. delayed = false;
  2600. lastDebugSequence = 0;
  2601. }
  2602. virtual IRoxieQueryPacket *queryPacket() const
  2603. {
  2604. return packet;
  2605. }
  2606. virtual bool isContinuation() const
  2607. {
  2608. return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
  2609. }
  2610. virtual bool isDelayed() const
  2611. {
  2612. return delayed;
  2613. }
  2614. virtual bool isEnd() const
  2615. {
  2616. return false;
  2617. }
  2618. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2619. {
  2620. return false;
  2621. }
  2622. virtual bool hasResult() const
  2623. {
  2624. return result != NULL;
  2625. }
  2626. virtual bool hasContinuation() const
  2627. {
  2628. return continuation != NULL;
  2629. }
  2630. virtual void setDelayed(bool _delayed)
  2631. {
  2632. delayed = _delayed;
  2633. }
  2634. virtual void setPacket(IRoxieQueryPacket *_packet)
  2635. {
  2636. packet.setown(_packet);
  2637. }
  2638. virtual void setSequence(unsigned _seq)
  2639. {
  2640. assertex(!IsShared());
  2641. seq = _seq;
  2642. }
  2643. virtual unsigned getSequence() const
  2644. {
  2645. return seq;
  2646. }
  2647. IMessageResult *getResult()
  2648. {
  2649. return result.getLink();
  2650. }
  2651. IMessageResult *queryResult()
  2652. {
  2653. return result;
  2654. }
  2655. void setResult(IMessageResult *r)
  2656. {
  2657. result.setown(r);
  2658. }
  2659. IRoxieServerQueryPacket *queryContinuation()
  2660. {
  2661. return continuation;
  2662. }
  2663. void setContinuation(IRoxieServerQueryPacket *c)
  2664. {
  2665. continuation.setown(c);
  2666. }
  2667. virtual unsigned queryHash() const
  2668. {
  2669. return hash;
  2670. }
  2671. virtual void setHash(unsigned _hash)
  2672. {
  2673. hash = _hash;
  2674. }
  2675. virtual ILRUChain *queryPrev() const { return prev; }
  2676. virtual ILRUChain *queryNext() const { return next; }
  2677. virtual void setPrev(ILRUChain *p) { prev = p; }
  2678. virtual void setNext(ILRUChain *n) { next = n; }
  2679. virtual void unchain()
  2680. {
  2681. if (prev && next)
  2682. {
  2683. prev->setNext(next);
  2684. next->setPrev(prev);
  2685. }
  2686. next = NULL;
  2687. prev = NULL;
  2688. }
  2689. virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
  2690. {
  2691. if (sequence == lastDebugSequence)
  2692. return lastDebugResponse.getLink();
  2693. else if (sequence > lastDebugSequence)
  2694. {
  2695. lastDebugResponse.clear();
  2696. return NULL;
  2697. }
  2698. else
  2699. throwUnexpected();
  2700. }
  2701. virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
  2702. {
  2703. lastDebugSequence = sequence;
  2704. lastDebugResponse.set(response);
  2705. }
  2706. };
  2707. class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
  2708. {
  2709. public:
  2710. CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
  2711. {
  2712. }
  2713. virtual bool isEnd() const
  2714. {
  2715. return true;
  2716. }
  2717. };
  2718. class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
  2719. {
  2720. unsigned __int64 rowLimit;
  2721. unsigned __int64 keyedLimit;
  2722. unsigned __int64 stopAfter;
  2723. public:
  2724. CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
  2725. {
  2726. rowLimit = _rowLimit;
  2727. keyedLimit = _keyedLimit;
  2728. stopAfter = _stopAfter;
  2729. }
  2730. virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
  2731. {
  2732. _rowLimit = rowLimit;
  2733. _keyedLimit = keyedLimit;
  2734. _stopAfter = stopAfter;
  2735. return true;
  2736. }
  2737. };
  2738. class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
  2739. {
  2740. protected:
  2741. unsigned cacheTableSize;
  2742. unsigned cacheTableSpace;
  2743. IRoxieServerQueryPacket **cacheTable;
  2744. mutable ILRUChain *prev;
  2745. mutable ILRUChain *next;
  2746. mutable CriticalSection crit;
  2747. virtual ILRUChain *queryPrev() const { return prev; }
  2748. virtual ILRUChain *queryNext() const { return next; }
  2749. virtual void setPrev(ILRUChain *p) { prev = p; }
  2750. virtual void setNext(ILRUChain *n) { next = n; }
  2751. virtual void unchain()
  2752. {
  2753. prev->setNext(next);
  2754. next->setPrev(prev);
  2755. next = NULL;
  2756. prev = NULL;
  2757. }
  2758. void moveToHead(IRoxieServerQueryPacket *mru)
  2759. {
  2760. mru->unchain();
  2761. mru->setNext(next);
  2762. next->setPrev(mru);
  2763. mru->setPrev(this);
  2764. next = mru;
  2765. }
  2766. IRoxieServerQueryPacket *removeLRU()
  2767. {
  2768. if (next==this)
  2769. assertex(next != this);
  2770. IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
  2771. goer->unchain(); // NOTE - this will modify the value of next
  2772. return goer;
  2773. }
  2774. void removeEntry(IRoxieServerQueryPacket *goer)
  2775. {
  2776. unsigned v = goer->queryHash() % cacheTableSize;
  2777. for (;;)
  2778. {
  2779. IRoxieServerQueryPacket *found = cacheTable[v];
  2780. assertex(found);
  2781. if (found == goer)
  2782. {
  2783. cacheTable[v] = NULL;
  2784. unsigned vn = v;
  2785. for (;;)
  2786. {
  2787. vn++;
  2788. if (vn==cacheTableSize) vn = 0;
  2789. IRoxieServerQueryPacket *found2 = cacheTable[vn];
  2790. if (!found2)
  2791. break;
  2792. unsigned vm = found2->queryHash() % cacheTableSize;
  2793. if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
  2794. {
  2795. cacheTable[v] = found2;
  2796. v = vn;
  2797. cacheTable[v] = NULL;
  2798. }
  2799. }
  2800. cacheTableSpace++;
  2801. break;
  2802. }
  2803. v++;
  2804. if (v==cacheTableSize)
  2805. v = 0;
  2806. }
  2807. goer->Release();
  2808. }
  2809. public:
  2810. CRoxieServerSideCache(unsigned _cacheSize)
  2811. {
  2812. cacheTableSize = (_cacheSize*4)/3;
  2813. cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
  2814. memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
  2815. cacheTableSpace = _cacheSize;
  2816. prev = this;
  2817. next = this;
  2818. }
  2819. ~CRoxieServerSideCache()
  2820. {
  2821. for (unsigned i = 0; i < cacheTableSize; i++)
  2822. {
  2823. ::Release(cacheTable[i]);
  2824. }
  2825. delete [] cacheTable;
  2826. }
  2827. virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
  2828. {
  2829. unsigned hash = p->hash();
  2830. unsigned et = hash % cacheTableSize;
  2831. if (traceServerSideCache)
  2832. {
  2833. StringBuffer s;
  2834. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
  2835. }
  2836. CriticalBlock b(crit);
  2837. for (;;)
  2838. {
  2839. IRoxieServerQueryPacket *found = cacheTable[et];
  2840. if (!found)
  2841. return NULL;
  2842. if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
  2843. {
  2844. const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
  2845. if (traceServerSideCache)
  2846. logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
  2847. logctx.noteStatistic(StNumServerCacheHits, 1);
  2848. return NULL;
  2849. // 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....
  2850. //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
  2851. //ret->setResult(found->getResult());
  2852. //return ret;
  2853. }
  2854. et++;
  2855. if (et == cacheTableSize)
  2856. et = 0;
  2857. }
  2858. }
  2859. virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
  2860. {
  2861. if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
  2862. {
  2863. unsigned hash = out->queryPacket()->hash();
  2864. out->setHash(hash);
  2865. unsigned et = hash % cacheTableSize;
  2866. if (traceServerSideCache)
  2867. {
  2868. StringBuffer s;
  2869. DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
  2870. }
  2871. CriticalBlock b(crit);
  2872. for (;;)
  2873. {
  2874. IRoxieServerQueryPacket *found = cacheTable[et];
  2875. if (!found)
  2876. {
  2877. if (cacheTableSpace)
  2878. {
  2879. out->setResult(LINK(in));
  2880. cacheTable[et] = LINK(out);
  2881. cacheTableSpace--;
  2882. moveToHead(out);
  2883. break;
  2884. }
  2885. else
  2886. {
  2887. IRoxieServerQueryPacket *goer = removeLRU();
  2888. removeEntry(goer);
  2889. et = hash % cacheTableSize;
  2890. continue;
  2891. }
  2892. }
  2893. else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
  2894. {
  2895. moveToHead(found);
  2896. return; // already in the cache. Because we don't cache until we have result, this can happen where
  2897. // multiple copies of a slave query are in-flight at once.
  2898. }
  2899. et++;
  2900. if (et == cacheTableSize)
  2901. et = 0;
  2902. }
  2903. }
  2904. // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
  2905. // Can I easily spot a null result? Do I want to cache null results separately? only?
  2906. }
  2907. // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
  2908. // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
  2909. // more than make up for it
  2910. };
  2911. class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
  2912. {
  2913. ConstPointerArray &data;
  2914. Linked<IMessageResult> result;
  2915. public:
  2916. IMPLEMENT_IINTERFACE;
  2917. CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
  2918. : data(_data), result(_result)
  2919. {
  2920. }
  2921. virtual bool atEOF() const
  2922. {
  2923. return data.length()==0;
  2924. }
  2925. virtual bool isSerialized() const
  2926. {
  2927. return false;
  2928. }
  2929. virtual const void * getNext(int length)
  2930. {
  2931. if (!data.length())
  2932. return NULL;
  2933. const void *ret = data.item(0);
  2934. data.remove(0);
  2935. return ret;
  2936. }
  2937. };
  2938. // MORE - should possibly move more over to the lazy version used in indexread?
  2939. class CRowArrayMessageResult : implements IMessageResult, public CInterface
  2940. {
  2941. ConstPointerArray data;
  2942. public:
  2943. IMPLEMENT_IINTERFACE;
  2944. CRowArrayMessageResult()
  2945. {
  2946. }
  2947. ~CRowArrayMessageResult()
  2948. {
  2949. ReleaseRoxieRows(data);
  2950. }
  2951. virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
  2952. {
  2953. CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
  2954. return new CRowArrayMessageUnpackCursor(_this->data, _this);
  2955. }
  2956. virtual const void *getMessageHeader(unsigned &length) const
  2957. {
  2958. throwUnexpected(); // should never get called - I don't have a header available
  2959. }
  2960. virtual const void *getMessageMetadata(unsigned &length) const
  2961. {
  2962. length = 0;
  2963. return NULL;
  2964. }
  2965. virtual void discard() const
  2966. {
  2967. throwUnexpected();
  2968. }
  2969. void append(const void *row)
  2970. {
  2971. data.append(row);
  2972. }
  2973. };
  2974. void throwRemoteException(IMessageUnpackCursor *extra)
  2975. {
  2976. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  2977. if (rowlen)
  2978. {
  2979. char *xml = (char *) extra->getNext(*rowlen);
  2980. ReleaseRoxieRow(rowlen);
  2981. Owned<IPropertyTree> p = createPTreeFromXMLString(xml, ipt_fast);
  2982. ReleaseRoxieRow(xml);
  2983. unsigned code = p->getPropInt("Code", 0);
  2984. const char *msg = p->queryProp("Message");
  2985. if (!msg)
  2986. msg = xml;
  2987. throw MakeStringException(code, "%s", msg);
  2988. }
  2989. throwUnexpected();
  2990. }
  2991. class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
  2992. {
  2993. friend class CRemoteResultMerger;
  2994. class CRemoteResultMerger
  2995. {
  2996. class HeapEntry : public CInterface
  2997. {
  2998. private:
  2999. CRemoteResultAdaptor &adaptor;
  3000. IMessageUnpackCursor *cursor;
  3001. public:
  3002. const void *current;
  3003. bool isLast;
  3004. bool lastIsComplete;
  3005. IRoxieServerQueryPacket *packet;
  3006. unsigned seq;
  3007. public:
  3008. inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
  3009. {
  3010. cursor = _cursor;
  3011. lastIsComplete = _lastIsComplete;
  3012. return next();
  3013. }
  3014. public:
  3015. HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
  3016. {
  3017. cursor = NULL;
  3018. current = NULL;
  3019. isLast = false;
  3020. lastIsComplete = true;
  3021. }
  3022. ~HeapEntry()
  3023. {
  3024. ::Release(packet);
  3025. ::Release(cursor);
  3026. ReleaseRoxieRow(current);
  3027. }
  3028. bool isCompleteMatch() const
  3029. {
  3030. if (!isLast || lastIsComplete)
  3031. return true;
  3032. else
  3033. return false;
  3034. }
  3035. const void *next()
  3036. {
  3037. if (cursor)
  3038. {
  3039. ReleaseClearRoxieRow(current);
  3040. current = adaptor.getRow(cursor);
  3041. isLast = cursor->atEOF();
  3042. if (!current)
  3043. {
  3044. cursor->Release();
  3045. cursor = NULL;
  3046. }
  3047. }
  3048. return current;
  3049. }
  3050. unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
  3051. {
  3052. // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
  3053. unsigned skipped = 0;
  3054. for (;;)
  3055. {
  3056. int c = compare->docompare(current, seek, numFields);
  3057. //If larger than the seek values, then we may be allowed to return an inexact match,
  3058. //if equal then it is required to be an exact match,
  3059. if (c > 0)
  3060. {
  3061. if (!requireExactMatch || isCompleteMatch())
  3062. break;
  3063. }
  3064. else if ((c == 0) && isCompleteMatch())
  3065. break;
  3066. skipped++;
  3067. if (!next())
  3068. break;
  3069. }
  3070. return skipped;
  3071. }
  3072. };
  3073. CRemoteResultAdaptor &adaptor;
  3074. CIArrayOf<HeapEntry> heapEntries;
  3075. UnsignedArray heap;
  3076. IRowManager *rowManager;
  3077. unsigned numPending;
  3078. unsigned numFields;
  3079. bool endSeen;
  3080. bool remakePending;
  3081. IRangeCompare *compare;
  3082. bool deferredContinuation;
  3083. inline int doCompare(unsigned l, unsigned r)
  3084. {
  3085. int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
  3086. if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
  3087. return ret;
  3088. }
  3089. void makeHeap()
  3090. {
  3091. /* Permute blocks to establish the heap property
  3092. For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
  3093. The children of p must both be greater than or equal to p
  3094. The parent of a child c is given by p = (c-1)/2
  3095. */
  3096. unsigned i;
  3097. unsigned n = heap.length();
  3098. unsigned *s = heap.getArray();
  3099. for (i=1; i<n; i++)
  3100. {
  3101. unsigned r = s[i];
  3102. int c = i; /* child */
  3103. while (c > 0)
  3104. {
  3105. int p = (c-1)/2; /* parent */
  3106. if ( doCompare( s[c], s[p] ) >= 0 )
  3107. break;
  3108. s[c] = s[p];
  3109. s[p] = r;
  3110. c = p;
  3111. }
  3112. }
  3113. remakePending = false;
  3114. }
  3115. void remakeHeap()
  3116. {
  3117. /* The row associated with block[0] will have changed
  3118. This code restores the heap property
  3119. */
  3120. unsigned p = 0; /* parent */
  3121. unsigned n = heap.length();
  3122. unsigned *s = heap.getArray();
  3123. while (1)
  3124. {
  3125. unsigned c = p*2 + 1; /* child */
  3126. if ( c >= n )
  3127. break;
  3128. /* Select smaller child */
  3129. if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
  3130. /* If child is greater or equal than parent then we are done */
  3131. if ( doCompare( s[c], s[p] ) >= 0 )
  3132. break;
  3133. /* Swap parent and child */
  3134. unsigned r = s[c];
  3135. s[c] = s[p];
  3136. s[p] = r;
  3137. /* child becomes parent */
  3138. p = c;
  3139. }
  3140. remakePending = false;
  3141. }
  3142. void append(IRoxieServerQueryPacket *p, unsigned seq)
  3143. {
  3144. HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
  3145. IMessageResult *result = p->queryResult();
  3146. assertex(result);
  3147. if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3148. {
  3149. heapEntries.append(h);
  3150. heap.append(heap.ordinality());
  3151. }
  3152. else
  3153. h.Release();
  3154. }
  3155. void removeHeap(unsigned idx)
  3156. {
  3157. heapEntries.remove(idx);
  3158. ForEachItemIn(i, heap)
  3159. {
  3160. unsigned v = heap.item(i);
  3161. assertex(v != idx);
  3162. if (v > idx)
  3163. heap.replace(v-1, i);
  3164. }
  3165. }
  3166. bool isCompleteMatchFlag(IMessageResult *result)
  3167. {
  3168. unsigned metaLen;
  3169. const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
  3170. if (metaLen)
  3171. {
  3172. unsigned short continuationLen = *(unsigned short *) metaInfo;
  3173. if (continuationLen >= sizeof(bool))
  3174. {
  3175. metaInfo += sizeof(unsigned short);
  3176. return *(bool *) metaInfo;
  3177. }
  3178. }
  3179. return true; // if no continuation info, last row was complete.
  3180. }
  3181. public:
  3182. CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
  3183. {
  3184. init(NULL, NULL);
  3185. }
  3186. void init(ISteppingMeta *meta, IRowManager *_rowManager)
  3187. {
  3188. if (meta)
  3189. {
  3190. numFields = meta->getNumFields();
  3191. compare = meta->queryCompare();
  3192. }
  3193. else
  3194. {
  3195. numFields = 0;
  3196. compare = NULL;
  3197. }
  3198. rowManager = _rowManager;
  3199. numPending = 0;
  3200. endSeen = false;
  3201. remakePending = false;
  3202. deferredContinuation = false;
  3203. }
  3204. void reset()
  3205. {
  3206. heapEntries.kill();
  3207. heap.kill();
  3208. numPending = 0;
  3209. endSeen = false;
  3210. remakePending = false;
  3211. deferredContinuation = false;
  3212. }
  3213. inline bool noteEndSeen()
  3214. {
  3215. bool hadSeen = endSeen;
  3216. if (!endSeen)
  3217. makeHeap();
  3218. endSeen = true;
  3219. return !hadSeen;
  3220. }
  3221. void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
  3222. {
  3223. if (!p->isContinuation())
  3224. append(p, seq);
  3225. else
  3226. {
  3227. ForEachItemIn(idx, heapEntries)
  3228. {
  3229. HeapEntry &h = heapEntries.item(idx);
  3230. if (h.packet == p)
  3231. {
  3232. IMessageResult *result = p->queryResult();
  3233. if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
  3234. {
  3235. heap.zap(idx);
  3236. removeHeap(idx);
  3237. }
  3238. numPending--;
  3239. if (!numPending)
  3240. makeHeap();
  3241. return;
  3242. }
  3243. }
  3244. }
  3245. // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
  3246. return;
  3247. }
  3248. unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
  3249. {
  3250. HeapEntry &entry = heapEntries.item(idx);
  3251. unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
  3252. if (!entry.current)
  3253. {
  3254. IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
  3255. if (continuation)
  3256. {
  3257. continuation->Link();
  3258. entry.packet->Release();
  3259. entry.packet = continuation;
  3260. if (continuation->hasResult())
  3261. {
  3262. IMessageResult *result = continuation->queryResult();
  3263. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3264. entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3265. }
  3266. else
  3267. {
  3268. if (continuation->isDelayed())
  3269. {
  3270. continuation->setDelayed(false);
  3271. MemoryBuffer serializedSkip;
  3272. adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  3273. continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  3274. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3275. adaptor.sentsome.signal();
  3276. }
  3277. numPending++;
  3278. }
  3279. }
  3280. else
  3281. {
  3282. heap.zap(idx);
  3283. removeHeap(idx);
  3284. idx--;
  3285. }
  3286. }
  3287. return skipped;
  3288. }
  3289. const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  3290. {
  3291. // We discard all rows < seekval from all entries in heap
  3292. // If this results in additional slave requests, we return NULL so that we can wait for them
  3293. // If not, we rebuild the heap (if any were skipped) and return the first row
  3294. deferredContinuation = false;
  3295. if (heap.length())
  3296. {
  3297. unsigned skipped = 0;
  3298. unsigned idx = 0;
  3299. while(heapEntries.isItem(idx))
  3300. {
  3301. skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
  3302. idx++;
  3303. }
  3304. if (numPending)
  3305. return NULL; // can't answer yet, need more results from slaves
  3306. else
  3307. {
  3308. if (skipped)
  3309. makeHeap();
  3310. return next(wasCompleteMatch, stepExtra);
  3311. }
  3312. }
  3313. else
  3314. return NULL;
  3315. }
  3316. bool doContinuation(HeapEntry &topEntry, bool canDefer)
  3317. {
  3318. IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
  3319. if (continuation)
  3320. {
  3321. if (continuation->isDelayed() && canDefer)
  3322. {
  3323. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3324. adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
  3325. deferredContinuation = true;
  3326. }
  3327. else
  3328. {
  3329. deferredContinuation = false;
  3330. continuation->Link();
  3331. topEntry.packet->Release();
  3332. topEntry.packet = continuation;
  3333. if (continuation->hasResult())
  3334. {
  3335. IMessageResult *result = continuation->queryResult();
  3336. bool lastIsCompleteMatch = isCompleteMatchFlag(result);
  3337. topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
  3338. }
  3339. else
  3340. {
  3341. if (continuation->isDelayed()) // has the continuation been requested yet?
  3342. {
  3343. continuation->Link();
  3344. topEntry.packet->Release();
  3345. topEntry.packet = continuation;
  3346. continuation->setDelayed(false);
  3347. if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
  3348. adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
  3349. ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
  3350. adaptor.sentsome.signal();
  3351. }
  3352. numPending++; // we are waiting for one that is already in flight
  3353. }
  3354. }
  3355. return true; // next not known yet
  3356. }
  3357. else
  3358. return false;
  3359. }
  3360. const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  3361. {
  3362. OwnedConstRoxieRow ret;
  3363. if (heap.length())
  3364. {
  3365. if (deferredContinuation)
  3366. {
  3367. unsigned top = heap.item(0);
  3368. HeapEntry &topEntry = heapEntries.item(top);
  3369. doContinuation(topEntry, false);
  3370. return NULL;
  3371. }
  3372. if (remakePending)
  3373. remakeHeap();
  3374. unsigned top = heap.item(0);
  3375. HeapEntry &topEntry = heapEntries.item(top);
  3376. ret.set(topEntry.current);
  3377. wasCompleteMatch = topEntry.isCompleteMatch();
  3378. const void *next = topEntry.next();
  3379. if (!next)
  3380. {
  3381. if (!doContinuation(topEntry, stepExtra.returnMismatches()))
  3382. {
  3383. unsigned last = heap.popGet();
  3384. if (heap.length())
  3385. heap.replace(last, 0);
  3386. removeHeap(top);
  3387. }
  3388. }
  3389. remakePending = true;
  3390. }
  3391. return ret.getClear();
  3392. }
  3393. bool ready()
  3394. {
  3395. return endSeen && numPending == 0;
  3396. }
  3397. };
  3398. IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
  3399. {
  3400. if (serverSideCache && !debugContext)
  3401. {
  3402. IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
  3403. if (ret)
  3404. {
  3405. p->Release();
  3406. cached = true;
  3407. return ret;
  3408. }
  3409. }
  3410. cached = false;
  3411. return new CRoxieServerQueryPacket(p);
  3412. }
  3413. #ifdef _DEBUG
  3414. void dumpPending()
  3415. {
  3416. CriticalBlock b(pendingCrit);
  3417. ForEachItemIn(idx, pending)
  3418. {
  3419. IRoxieServerQueryPacket &p = pending.item(idx);
  3420. StringBuffer s;
  3421. unsigned __int64 dummy;
  3422. if (p.isEnd())
  3423. s.append("END");
  3424. else if (p.isLimit(dummy, dummy, dummy))
  3425. s.append("LIMIT");
  3426. else
  3427. {
  3428. IRoxieQueryPacket *i = p.queryPacket();
  3429. s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
  3430. if (i)
  3431. {
  3432. RoxiePacketHeader &header = i->queryHeader();
  3433. header.toString(s);
  3434. }
  3435. }
  3436. DBGLOG("Pending %d %s", idx, s.str());
  3437. }
  3438. }
  3439. #endif
  3440. void abortPending()
  3441. {
  3442. CriticalBlock b(pendingCrit);
  3443. ForEachItemIn(idx, pending)
  3444. {
  3445. IRoxieServerQueryPacket &p = pending.item(idx);
  3446. if (!p.hasResult())
  3447. {
  3448. IRoxieQueryPacket *i = p.queryPacket();
  3449. if (i)
  3450. {
  3451. RoxiePacketHeader &header = i->queryHeader();
  3452. ROQ->sendAbort(header, activity.queryLogCtx());
  3453. }
  3454. }
  3455. }
  3456. pending.kill();
  3457. }
  3458. void checkDelayed()
  3459. {
  3460. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3461. {
  3462. bool allDelayed = true;
  3463. CriticalBlock b(pendingCrit);
  3464. unsigned sendIdx = (unsigned) -1;
  3465. ForEachItemIn(idx, pending)
  3466. {
  3467. IRoxieServerQueryPacket &p = pending.item(idx);
  3468. if (p.queryPacket())
  3469. {
  3470. if (p.isDelayed())
  3471. {
  3472. if (sendIdx == (unsigned) -1)
  3473. sendIdx = idx;
  3474. }
  3475. else if (!p.hasResult())
  3476. {
  3477. allDelayed = false;
  3478. break;
  3479. }
  3480. }
  3481. }
  3482. if (allDelayed && sendIdx != (unsigned) -1)
  3483. {
  3484. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3485. activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
  3486. pending.item(sendIdx).setDelayed(false);
  3487. ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
  3488. sentsome.signal();
  3489. }
  3490. }
  3491. else if (deferredStart)
  3492. {
  3493. CriticalBlock b(pendingCrit);
  3494. ForEachItemIn(idx, pending)
  3495. {
  3496. IRoxieServerQueryPacket &p = pending.item(idx);
  3497. if (p.isDelayed())
  3498. {
  3499. if (activity.queryLogCtx().queryTraceLevel() > 10)
  3500. activity.queryLogCtx().CTXLOG("About to send deferred start from next");
  3501. p.setDelayed(false);
  3502. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  3503. sentsome.signal();
  3504. }
  3505. }
  3506. deferredStart = false;
  3507. }
  3508. }
  3509. void retryPending()
  3510. {
  3511. CriticalBlock b(pendingCrit);
  3512. checkDelayed();
  3513. ForEachItemIn(idx, pending)
  3514. {
  3515. IRoxieServerQueryPacket &p = pending.item(idx);
  3516. if (!p.hasResult() && !p.isDelayed())
  3517. {
  3518. IRoxieQueryPacket *i = p.queryPacket();
  3519. if (i)
  3520. {
  3521. if (!i->queryHeader().retry())
  3522. {
  3523. StringBuffer s;
  3524. 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());
  3525. activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
  3526. throw E;
  3527. }
  3528. if (!localSlave)
  3529. {
  3530. ROQ->sendPacket(i, activity.queryLogCtx());
  3531. retriesSent++;
  3532. }
  3533. }
  3534. }
  3535. }
  3536. }
  3537. class ChannelBuffer
  3538. {
  3539. protected:
  3540. unsigned bufferLeft;
  3541. MemoryBuffer buffer;
  3542. char *nextBuf;
  3543. unsigned overflowSequence;
  3544. unsigned channel; // == bonded channel
  3545. bool needsFlush;
  3546. InterruptableSemaphore flowController;
  3547. const CRemoteResultAdaptor &owner;
  3548. CriticalSection crit;
  3549. public:
  3550. ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : channel(_channel), flowController(perChannelFlowLimit), owner(_owner)
  3551. {
  3552. overflowSequence = 0;
  3553. needsFlush = false;
  3554. bufferLeft = 0;
  3555. nextBuf = NULL;
  3556. }
  3557. void init(unsigned minSize)
  3558. {
  3559. assertex(!buffer.length());
  3560. if (minSize < MIN_PAYLOAD_SIZE)
  3561. minSize = MIN_PAYLOAD_SIZE;
  3562. unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
  3563. unsigned bufferSize = headerSize+minSize;
  3564. if (bufferSize < mtu_size)
  3565. bufferSize = mtu_size;
  3566. buffer.reserveTruncate(bufferSize);
  3567. bufferLeft = bufferSize - headerSize;
  3568. assertex(buffer.toByteArray());
  3569. nextBuf = (char *) buffer.toByteArray() + headerSize;
  3570. needsFlush = false;
  3571. }
  3572. inline IRoxieQueryPacket *flush()
  3573. {
  3574. CriticalBlock cb(crit);
  3575. Owned<IRoxieQueryPacket> ret;
  3576. if (needsFlush)
  3577. {
  3578. buffer.setLength(nextBuf - buffer.toByteArray());
  3579. RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
  3580. h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
  3581. //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
  3582. byte * tgt = (byte*)(h+1);
  3583. owner.copyHeader(tgt, channel);
  3584. ret.setown(createRoxiePacket(buffer));
  3585. if (overflowSequence == OVERFLOWSEQUENCE_MAX)
  3586. overflowSequence = 1; // don't wrap to 0 - that is a bit special
  3587. else
  3588. overflowSequence++;
  3589. needsFlush = false;
  3590. bufferLeft = 0;
  3591. if (owner.flowControlled)
  3592. {
  3593. CriticalUnblock cub(crit);
  3594. while (!flowController.wait(1000))
  3595. {
  3596. StringBuffer s;
  3597. owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
  3598. }
  3599. }
  3600. }
  3601. return ret.getClear();
  3602. }
  3603. inline void signal()
  3604. {
  3605. if (owner.flowControlled)
  3606. flowController.signal();
  3607. }
  3608. inline void interrupt(IException *e)
  3609. {
  3610. flowController.interrupt(e);
  3611. }
  3612. inline void *getBuffer(unsigned size)
  3613. {
  3614. CriticalBlock cb(crit);
  3615. if (bufferLeft >= size)
  3616. {
  3617. needsFlush = true;
  3618. void * ret = nextBuf;
  3619. nextBuf += size;
  3620. bufferLeft -= size;
  3621. return ret;
  3622. }
  3623. else if (!needsFlush)
  3624. {
  3625. init(size);
  3626. return getBuffer(size);
  3627. }
  3628. else if (owner.mergeOrder)
  3629. {
  3630. return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
  3631. }
  3632. else
  3633. return NULL; // will force it to flush and start a new packet
  3634. }
  3635. };
  3636. private:
  3637. friend class CRemoteResultMerger;
  3638. bool allread;
  3639. bool contextCached;
  3640. bool preserveOrder;
  3641. bool eogSent = false;
  3642. InterruptableSemaphore sentsome;
  3643. Owned <IMessageCollator> mc;
  3644. Owned<IMessageUnpackCursor> mu;
  3645. Owned<IMessageResult> mr;
  3646. ChannelBuffer **buffers;
  3647. IHThorArg &helper;
  3648. unsigned __int64 stopAfter;
  3649. unsigned resendSequence;
  3650. IHThorArg *colocalArg;
  3651. IArrayOf<IRoxieServerQueryPacket> pending;
  3652. CriticalSection pendingCrit;
  3653. IRoxieServerSideCache *serverSideCache;
  3654. unsigned sentSequence;
  3655. Owned<IOutputRowDeserializer> deserializer;
  3656. Owned<IEngineRowAllocator> rowAllocator;
  3657. CRemoteResultMerger merger;
  3658. // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
  3659. MemoryBuffer tempRowBuffer;
  3660. Owned<ISerialStream> bufferStream;
  3661. CThorStreamDeserializerSource rowSource;
  3662. protected:
  3663. IRowManager *rowManager;
  3664. unsigned __int64 rowLimit;
  3665. unsigned __int64 keyedLimit;
  3666. IRoxieServerErrorHandler *errorHandler;
  3667. CachedOutputMetaData meta;
  3668. public:
  3669. ISteppingMeta *mergeOrder;
  3670. IRoxieSlaveContext *ctx;
  3671. IDebuggableContext *debugContext;
  3672. IRoxieServerActivity &activity;
  3673. unsigned parentExtractSize;
  3674. const byte * parentExtract;
  3675. bool flowControlled;
  3676. bool deferredStart;
  3677. MemoryBuffer logInfo;
  3678. MemoryBuffer cachedContext;
  3679. const RemoteActivityId &remoteId;
  3680. ruid_t ruid;
  3681. mutable CriticalSection buffersCrit;
  3682. unsigned processed;
  3683. cycle_t totalCycles;
  3684. bool timeActivities;
  3685. //private: //vc6 doesn't like this being private yet accessed by nested class...
  3686. const void *getRow(IMessageUnpackCursor *mu)
  3687. {
  3688. if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
  3689. return mu->getNext(meta.getFixedSize());
  3690. else
  3691. {
  3692. RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
  3693. if (rowlen)
  3694. {
  3695. RecordLengthType len = *rowlen;
  3696. ReleaseRoxieRow(rowlen);
  3697. const void *slaveRec = mu->getNext(len);
  3698. if (deserializer && mu->isSerialized())
  3699. {
  3700. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  3701. tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
  3702. size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
  3703. ReleaseRoxieRow(slaveRec);
  3704. return rowBuilder.finalizeRowClear(outsize);
  3705. }
  3706. else
  3707. return slaveRec;
  3708. }
  3709. else
  3710. return NULL;
  3711. }
  3712. }
  3713. private:
  3714. ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
  3715. {
  3716. CriticalBlock cb(buffersCrit);
  3717. ChannelBuffer *b = buffers[channel];
  3718. if (!b && force)
  3719. {
  3720. if (!contextCached)
  3721. {
  3722. logInfo.clear();
  3723. unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
  3724. unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
  3725. const QueryOptions &options = ctx->queryOptions();
  3726. if (activity.queryLogCtx().isIntercepted())
  3727. loggingFlags |= LOGGING_INTERCEPTED;
  3728. if (options.timeActivities)
  3729. loggingFlags |= LOGGING_TIMEACTIVITIES;
  3730. if (activity.queryLogCtx().isBlind())
  3731. loggingFlags |= LOGGING_BLIND;
  3732. if (options.checkingHeap)
  3733. loggingFlags |= LOGGING_CHECKINGHEAP;
  3734. if (ctx->queryWorkUnit())
  3735. loggingFlags |= LOGGING_WUID;
  3736. if (debugContext)
  3737. {
  3738. loggingFlags |= LOGGING_DEBUGGERACTIVE;
  3739. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3740. MemoryBuffer bpInfo;
  3741. debugContext->serialize(bpInfo);
  3742. bpInfo.append((__uint64)(memsize_t) &activity);
  3743. logInfo.append((unsigned short) bpInfo.length());
  3744. logInfo.append(bpInfo.length(), bpInfo.toByteArray());
  3745. }
  3746. else
  3747. logInfo.append(loggingFlags).append(ctxTraceLevel);
  3748. StringBuffer logPrefix;
  3749. activity.queryLogCtx().getLogPrefix(logPrefix);
  3750. logInfo.append(logPrefix);
  3751. activity.serializeCreateStartContext(cachedContext.clear());
  3752. activity.serializeExtra(cachedContext);
  3753. if (activity.queryVarFileInfo())
  3754. {
  3755. activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
  3756. cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
  3757. }
  3758. contextCached = true;
  3759. }
  3760. b = buffers[channel] = new ChannelBuffer(*this, channel);
  3761. }
  3762. return b;
  3763. }
  3764. void processRow(const void *got)
  3765. {
  3766. processed++;
  3767. if (processed > rowLimit)
  3768. {
  3769. ReleaseRoxieRow(got);
  3770. errorHandler->onLimitExceeded(false); // NOTE - should throw exception
  3771. throwUnexpected();
  3772. }
  3773. else if (processed > keyedLimit)
  3774. {
  3775. ReleaseRoxieRow(got);
  3776. errorHandler->onLimitExceeded(true); // NOTE - should throw exception
  3777. throwUnexpected();
  3778. }
  3779. }
  3780. public:
  3781. IMPLEMENT_IINTERFACE;
  3782. CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
  3783. : preserveOrder(_preserveOrder), helper(_helper), merger(*this), meta(_meta), activity(_activity), flowControlled(_flowControlled), remoteId(_remoteId)
  3784. {
  3785. ctx = _ctx;
  3786. errorHandler = _errorHandler;
  3787. colocalArg = NULL;
  3788. allread = false;
  3789. ruid = 0;
  3790. rowLimit = (unsigned __int64) -1;
  3791. keyedLimit = (unsigned __int64) -1;
  3792. contextCached = false;
  3793. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  3794. buffers = new ChannelBuffer*[numChannels+1];
  3795. memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
  3796. parentExtractSize = 0;
  3797. rowManager = NULL;
  3798. parentExtract = NULL;
  3799. debugContext = NULL;
  3800. mergeOrder = NULL;
  3801. deferredStart = false;
  3802. processed = 0;
  3803. sentSequence = 0;
  3804. resendSequence = 0;
  3805. totalCycles = 0;
  3806. serverSideCache = activity.queryServerSideCache();
  3807. bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
  3808. rowSource.setStream(bufferStream);
  3809. timeActivities = defaultTimeActivities;
  3810. }
  3811. ~CRemoteResultAdaptor()
  3812. {
  3813. if (mc)
  3814. {
  3815. ROQ->queryReceiveManager()->detachCollator(mc);
  3816. mc.clear();
  3817. }
  3818. for (unsigned channel = 0; channel <= numChannels; channel++)
  3819. {
  3820. delete(buffers[channel]);
  3821. }
  3822. delete [] buffers;
  3823. }
  3824. void setMeta(IOutputMetaData *newmeta)
  3825. {
  3826. meta.set(newmeta);
  3827. }
  3828. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  3829. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  3830. virtual IRoxieServerActivity *queryActivity()
  3831. {
  3832. return &activity;
  3833. }
  3834. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  3835. {
  3836. return NULL;
  3837. }
  3838. void setMergeInfo(ISteppingMeta *_mergeOrder)
  3839. {
  3840. mergeOrder = _mergeOrder;
  3841. deferredStart = true;
  3842. }
  3843. void send(IRoxieQueryPacket *p)
  3844. {
  3845. if (p)
  3846. {
  3847. Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
  3848. assertex(p->queryHeader().uid==ruid);
  3849. // MORE: Maybe we should base the fastlane flag on some other
  3850. // criteria !! (i.e A Roxie server prediction based on the
  3851. // activity type/activity behaviour/expected reply size .. etc).
  3852. //
  3853. // Currently (code below) based on high priority, seq=0, and none-child activity.
  3854. // But this could still cause too many reply packets on the fatlane
  3855. // (higher priority output Q), which may cause the activities on the
  3856. // low priority output Q to not get service on time.
  3857. if ((colocalArg == 0) && // not a child query activity??
  3858. (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
  3859. (p->queryHeader().overflowSequence == 0) &&
  3860. (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
  3861. p->queryHeader().retries |= ROXIE_FASTLANE;
  3862. if (p->queryHeader().channel)
  3863. {
  3864. bool cached = false;
  3865. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
  3866. if (deferredStart)
  3867. rsqp->setDelayed(true);
  3868. rsqp->setSequence(sentSequence++);
  3869. {
  3870. CriticalBlock b(pendingCrit);
  3871. pending.append(*rsqp);
  3872. }
  3873. if (!deferredStart)
  3874. {
  3875. if (!cached)
  3876. ROQ->sendPacket(p, activity.queryLogCtx());
  3877. sentsome.signal();
  3878. }
  3879. }
  3880. else
  3881. {
  3882. // 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
  3883. // Need to add first, then send
  3884. unsigned i;
  3885. bool allCached = true;
  3886. for (i = 1; i <= numChannels; i++)
  3887. {
  3888. IRoxieQueryPacket *q = p->clonePacket(i);
  3889. bool thisChannelCached;
  3890. IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
  3891. if (!thisChannelCached)
  3892. allCached = false;
  3893. rsqp->setSequence(sentSequence++);
  3894. if (deferredStart)
  3895. {
  3896. rsqp->setDelayed(true);
  3897. }
  3898. {
  3899. CriticalBlock b(pendingCrit);
  3900. pending.append(*rsqp);
  3901. }
  3902. if (!deferredStart)
  3903. sentsome.signal();
  3904. }
  3905. if (!allCached && !deferredStart)
  3906. ROQ->sendPacket(p, activity.queryLogCtx());
  3907. buffers[0]->signal(); // since replies won't come back on that channel...
  3908. p->Release();
  3909. }
  3910. }
  3911. }
  3912. void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
  3913. {
  3914. unsigned channel = partNo ? getBondedChannel(partNo) : 0;
  3915. size += sizeof(PartNoType);
  3916. ChannelBuffer *b = queryChannelBuffer(channel, true);
  3917. char *buffer = (char *) b->getBuffer(size);
  3918. if (!buffer)
  3919. {
  3920. send(b->flush());
  3921. buffer = (char *) b->getBuffer(size);
  3922. }
  3923. PartNoType sp;
  3924. sp.partNo = partNo;
  3925. sp.fileNo = fileNo;
  3926. memcpy(buffer, &sp, sizeof(sp));
  3927. buffer += sizeof(sp);
  3928. return buffer;
  3929. }
  3930. void injectResult(IMessageResult *result)
  3931. {
  3932. IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
  3933. f->setSequence(sentSequence++);
  3934. f->setResult(result);
  3935. CriticalBlock b(pendingCrit);
  3936. pending.append(*f);
  3937. sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
  3938. }
  3939. void flush()
  3940. {
  3941. for (unsigned channel = 0; channel <= numChannels; channel++)
  3942. {
  3943. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3944. if (b)
  3945. send(b->flush());
  3946. }
  3947. }
  3948. void interruptBuffers(IException *e)
  3949. {
  3950. for (unsigned channel = 0; channel <= numChannels; channel++)
  3951. {
  3952. ChannelBuffer *b = queryChannelBuffer(channel, false);
  3953. if (b)
  3954. b->interrupt(LINK(e));
  3955. }
  3956. }
  3957. void senddone()
  3958. {
  3959. CriticalBlock b(pendingCrit);
  3960. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3961. sentsome.signal();
  3962. }
  3963. bool fireException(IException *e)
  3964. {
  3965. {
  3966. CriticalBlock b(pendingCrit);
  3967. pending.append(*new CRoxieServerQueryPacketEndMarker);
  3968. }
  3969. interruptBuffers(e);
  3970. if (mc)
  3971. mc->interrupt(LINK(e));
  3972. sentsome.interrupt(e);
  3973. return true;
  3974. }
  3975. virtual void onCreate(IHThorArg *_colocalArg)
  3976. {
  3977. debugContext = ctx->queryDebugContext();
  3978. colocalArg = _colocalArg;
  3979. if (meta.needsSerializeDisk())
  3980. {
  3981. deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
  3982. rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
  3983. }
  3984. if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
  3985. deferredStart = true;
  3986. timeActivities = ctx->queryOptions().timeActivities;
  3987. }
  3988. virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  3989. {
  3990. #ifdef TRACE_STARTSTOP
  3991. if (traceStartStop)
  3992. activity.queryLogCtx().CTXLOG("RRAonstart");
  3993. #endif
  3994. sentsome.reinit();
  3995. ruid = getNextRuid();
  3996. rowManager = &ctx->queryRowManager();
  3997. if (mergeOrder)
  3998. merger.init(mergeOrder, rowManager);
  3999. if (mc)
  4000. {
  4001. ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
  4002. }
  4003. mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
  4004. allread = false;
  4005. mu.clear();
  4006. contextCached = false;
  4007. processed = 0;
  4008. resendSequence = 0;
  4009. sentSequence = 0;
  4010. for (unsigned channel = 0; channel <= numChannels; channel++)
  4011. {
  4012. delete(buffers[channel]);
  4013. buffers[channel] = NULL;
  4014. }
  4015. flush();
  4016. parentExtractSize = _parentExtractSize;
  4017. parentExtract = _parentExtract;
  4018. }
  4019. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4020. {
  4021. #ifdef TRACE_STARTSTOP
  4022. if (traceStartStop)
  4023. activity.queryLogCtx().CTXLOG("RRAstart");
  4024. #endif
  4025. activity.start(parentExtractSize, parentExtract, paused);
  4026. }
  4027. void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
  4028. {
  4029. if (ctx->queryProbeManager())
  4030. {
  4031. if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
  4032. if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
  4033. if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
  4034. }
  4035. {
  4036. CriticalBlock b(pendingCrit);
  4037. if (pending.length())
  4038. {
  4039. #ifdef _DEBUG
  4040. dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
  4041. #endif
  4042. assertex(pending.length()==0);
  4043. }
  4044. pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
  4045. }
  4046. sentsome.signal();
  4047. rowLimit = _rowLimit;
  4048. keyedLimit = _keyedLimit;
  4049. stopAfter = _stopAfter;
  4050. }
  4051. virtual void stop()
  4052. {
  4053. #ifdef TRACE_STARTSTOP
  4054. if (traceStartStop)
  4055. activity.queryLogCtx().CTXLOG("RRAstop");
  4056. #endif
  4057. onStop();
  4058. activity.stop();
  4059. }
  4060. void onStop()
  4061. {
  4062. #ifdef TRACE_STARTSTOP
  4063. if (traceStartStop)
  4064. activity.queryLogCtx().CTXLOG("RRAonstop");
  4065. #endif
  4066. abortPending();
  4067. interruptBuffers(NULL);
  4068. sentsome.interrupt();
  4069. if (mc) // May not be set if start() chain threw exception
  4070. mc->interrupt();
  4071. }
  4072. virtual void reset()
  4073. {
  4074. #ifdef TRACE_STARTSTOP
  4075. if (traceStartStop)
  4076. activity.queryLogCtx().CTXLOG("RRAreset");
  4077. #endif
  4078. activity.reset();
  4079. onReset();
  4080. }
  4081. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  4082. {
  4083. // Make sure parent activity calls up the tree
  4084. PointerArrayOf<IEngineRowStream> instreams;
  4085. IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
  4086. assertex (junction == NULL);
  4087. // I return a single strand (we could change that sometime I guess...)
  4088. streams.append(this);
  4089. return NULL;
  4090. }
  4091. virtual void resetEOF()
  4092. {
  4093. throwUnexpected();
  4094. }
  4095. virtual void onReset()
  4096. {
  4097. #ifdef TRACE_STARTSTOP
  4098. if (traceStartStop)
  4099. activity.queryLogCtx().CTXLOG("RRAonreset");
  4100. #endif
  4101. if (mc)
  4102. ROQ->queryReceiveManager()->detachCollator(mc);
  4103. merger.reset();
  4104. pending.kill();
  4105. if (mc && ctx)
  4106. ctx->addSlavesReplyLen(mc->queryBytesReceived());
  4107. mc.clear(); // Or we won't free memory for graphs that get recreated
  4108. mu.clear(); //ditto
  4109. deferredStart = false;
  4110. // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
  4111. }
  4112. virtual IOutputMetaData * queryOutputMeta() const
  4113. {
  4114. return helper.queryOutputMeta();
  4115. }
  4116. virtual unsigned __int64 queryTotalCycles() const
  4117. {
  4118. return totalCycles;
  4119. }
  4120. void gatherStats(CRuntimeStatisticCollection & merged) const
  4121. {
  4122. if (rowAllocator)
  4123. rowAllocator->gatherStats(merged);
  4124. }
  4125. const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4126. {
  4127. if (activity.queryLogCtx().queryTraceLevel() > 20)
  4128. {
  4129. StringBuffer recstr;
  4130. unsigned i;
  4131. for (i = 0; i < seekLen; i++)
  4132. {
  4133. recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  4134. }
  4135. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
  4136. }
  4137. assertex(mergeOrder);
  4138. if (deferredStart)
  4139. {
  4140. CriticalBlock b(pendingCrit);
  4141. ForEachItemIn(idx, pending)
  4142. {
  4143. IRoxieServerQueryPacket &p = pending.item(idx);
  4144. if (p.isDelayed())
  4145. {
  4146. p.setDelayed(false);
  4147. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4148. activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
  4149. MemoryBuffer serializedSkip;
  4150. activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
  4151. p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
  4152. ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
  4153. sentsome.signal();
  4154. }
  4155. }
  4156. deferredStart = false;
  4157. }
  4158. SimpleActivityTimer t(totalCycles, timeActivities);
  4159. if (processed==stopAfter)
  4160. return NULL;
  4161. if (allread)
  4162. return NULL;
  4163. for (;;)
  4164. {
  4165. if (merger.ready())
  4166. {
  4167. const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
  4168. if (got)
  4169. {
  4170. processRow(got);
  4171. return got;
  4172. }
  4173. }
  4174. if (!reload()) // MORE - should pass the seek info here...
  4175. return NULL;
  4176. }
  4177. }
  4178. virtual const void *nextRow()
  4179. {
  4180. // If we are merging then we need to do a heapsort on all
  4181. SimpleActivityTimer t(totalCycles, timeActivities);
  4182. if (activity.queryLogCtx().queryTraceLevel() > 10)
  4183. {
  4184. activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
  4185. }
  4186. for (;;)
  4187. {
  4188. checkDelayed();
  4189. if (processed==stopAfter)
  4190. return NULL;
  4191. if (allread)
  4192. return NULL;
  4193. // If we can still consume from the merger or the most recently retrieved mu, do so.
  4194. const void *got = NULL;
  4195. if (mergeOrder && merger.ready())
  4196. {
  4197. bool matched = true;
  4198. got = merger.next(matched, dummySmartStepExtra);
  4199. }
  4200. else if (mu)
  4201. {
  4202. got = getRow(mu);
  4203. if (!got && meta.isGrouped() && !eogSent)
  4204. {
  4205. eogSent = true;
  4206. return NULL;
  4207. }
  4208. }
  4209. if (got)
  4210. {
  4211. processRow(got);
  4212. return got;
  4213. }
  4214. eogSent = false;
  4215. if (!reload())
  4216. return NULL;
  4217. }
  4218. }
  4219. bool reload()
  4220. {
  4221. // Wait for something to be returned from a slave....
  4222. mu.clear();
  4223. sentsome.wait();
  4224. // must be at least an endMarker on the queue since sentsome was signalled
  4225. {
  4226. CriticalBlock b(pendingCrit);
  4227. IRoxieServerQueryPacket &top = pending.item(0);
  4228. if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
  4229. {
  4230. pending.remove(0);
  4231. return true;
  4232. }
  4233. else if (top.isEnd())
  4234. {
  4235. pending.remove(0);
  4236. allread = true;
  4237. if (activity.queryLogCtx().queryTraceLevel() > 5)
  4238. activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
  4239. return false;
  4240. }
  4241. else if (mergeOrder)
  4242. {
  4243. unsigned idx = 0;
  4244. bool added = false;
  4245. while (pending.isItem(idx))
  4246. {
  4247. IRoxieServerQueryPacket &item = pending.item(idx);
  4248. if (item.isEnd())
  4249. {
  4250. if (merger.noteEndSeen())
  4251. {
  4252. sentsome.signal(); // Because we waited, yet didn't actually consume anything
  4253. added = true;
  4254. }
  4255. break;
  4256. }
  4257. else if (item.hasResult())
  4258. {
  4259. merger.noteResult(&item, item.getSequence());
  4260. pending.remove(idx);
  4261. added = true;
  4262. }
  4263. else if (item.isContinuation())
  4264. idx++;
  4265. else
  4266. break;
  4267. }
  4268. if (added)
  4269. return true;
  4270. }
  4271. else if (top.hasResult())
  4272. {
  4273. mr.setown(pending.item(0).getResult());
  4274. mu.setown(mr->getCursor(rowManager));
  4275. pending.remove(0);
  4276. return true;
  4277. }
  4278. }
  4279. getNextUnpacker();
  4280. return true;
  4281. }
  4282. void getNextUnpacker()
  4283. {
  4284. mu.clear();
  4285. unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
  4286. for (;;)
  4287. {
  4288. checkDelayed();
  4289. unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
  4290. activity.queryContext()->checkAbort();
  4291. bool anyActivity;
  4292. if (ctxTraceLevel > 5)
  4293. activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
  4294. mr.setown(mc->getNextResult(timeout, anyActivity));
  4295. if (ctxTraceLevel > 6)
  4296. activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
  4297. activity.queryContext()->checkAbort();
  4298. if (mr)
  4299. {
  4300. unsigned roxieHeaderLen;
  4301. const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
  4302. #ifdef _DEBUG
  4303. assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
  4304. #endif
  4305. if (ctxTraceLevel > 5)
  4306. {
  4307. StringBuffer s;
  4308. activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
  4309. }
  4310. CriticalBlock b(pendingCrit);
  4311. unsigned idx = 0;
  4312. IRoxieServerQueryPacket *original = NULL;
  4313. IRoxieQueryPacket *op;
  4314. while (pending.isItem(idx))
  4315. {
  4316. original = &pending.item(idx);
  4317. op = original->queryPacket();
  4318. if (op && header.matchPacket(op->queryHeader()))
  4319. break;
  4320. original = NULL;
  4321. idx++;
  4322. }
  4323. if (!original || original->hasResult())
  4324. {
  4325. switch (header.activityId)
  4326. {
  4327. case ROXIE_FILECALLBACK:
  4328. {
  4329. // tell slave to abort
  4330. //if (ctxTraceLevel > 5)
  4331. {
  4332. StringBuffer s;
  4333. activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
  4334. }
  4335. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4336. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4337. if (len)
  4338. {
  4339. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4340. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4341. const char *rowdata = (const char *) row.get();
  4342. // bool isOpt = * (bool *) rowdata;
  4343. // bool isLocal = * (bool *) (rowdata+1);
  4344. ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
  4345. }
  4346. else
  4347. throwUnexpected();
  4348. break;
  4349. }
  4350. // MORE - ROXIE_ALIVE perhaps should go here too
  4351. default:
  4352. if (ctxTraceLevel > 3)
  4353. activity.queryLogCtx().CTXLOG("Discarding packet %p %x - original %p is NULL or has result already", mr.get(), header.activityId, original);
  4354. mr->discard();
  4355. break;
  4356. }
  4357. mr.clear();
  4358. }
  4359. else
  4360. {
  4361. resultsReceived++;
  4362. switch (header.activityId)
  4363. {
  4364. case ROXIE_DEBUGCALLBACK:
  4365. {
  4366. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4367. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4368. if (len)
  4369. {
  4370. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4371. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4372. char *rowdata = (char *) row.get();
  4373. if (ctxTraceLevel > 5)
  4374. {
  4375. StringBuffer s;
  4376. activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
  4377. }
  4378. MemoryBuffer slaveInfo;
  4379. slaveInfo.setBuffer(*rowlen, rowdata, false);
  4380. unsigned debugSequence;
  4381. slaveInfo.read(debugSequence);
  4382. Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
  4383. if (!reply)
  4384. reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
  4385. if (reply)
  4386. {
  4387. original->setDebugResponse(debugSequence, reply);
  4388. ROQ->sendPacket(reply, activity.queryLogCtx());
  4389. }
  4390. }
  4391. else
  4392. throwUnexpected();
  4393. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4394. // Leave original message on pending queue in original location - this is not a reply to it.
  4395. break;
  4396. }
  4397. case ROXIE_FILECALLBACK:
  4398. {
  4399. // we need to send back to the slave a message containing the file info requested.
  4400. Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
  4401. OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
  4402. if (len)
  4403. {
  4404. RecordLengthType *rowlen = (RecordLengthType *) len.get();
  4405. OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
  4406. const char *rowdata = (const char *) row.get();
  4407. bool isOpt = * (bool *) rowdata;
  4408. bool isLocal = * (bool *) (rowdata+1);
  4409. const char *lfn = rowdata+2;
  4410. if (ctxTraceLevel > 5)
  4411. {
  4412. StringBuffer s;
  4413. activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
  4414. }
  4415. activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
  4416. }
  4417. else
  4418. throwUnexpected();
  4419. // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
  4420. // Leave original message on pending queue in original location - this is not a reply to it.
  4421. break;
  4422. }
  4423. case ROXIE_KEYEDLIMIT_EXCEEDED:
  4424. activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
  4425. errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
  4426. throwUnexpected();
  4427. case ROXIE_LIMIT_EXCEEDED:
  4428. activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
  4429. errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
  4430. throwUnexpected();
  4431. case ROXIE_TRACEINFO:
  4432. {
  4433. Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
  4434. for (;;)
  4435. {
  4436. RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
  4437. if (rowlen)
  4438. {
  4439. char *logInfo = (char *) extra->getNext(*rowlen);
  4440. MemoryBuffer buf;
  4441. buf.setBuffer(*rowlen, logInfo, false);
  4442. switch ((TracingCategory) *logInfo)
  4443. {
  4444. case LOG_TRACING:
  4445. case LOG_ERROR:
  4446. activity.queryLogCtx().CTXLOGl(new LogItem(buf));
  4447. break;
  4448. case LOG_STATVALUES:
  4449. buf.skip(1);
  4450. activity.mergeStats(buf);
  4451. break;
  4452. case LOG_CHILDCOUNT:
  4453. case LOG_CHILDSTATS:
  4454. //These need rethinking - all child stats should be serialized in a single block, and should be merged into
  4455. //the information for an activity, ready for reporting later
  4456. unsigned graphId, childId;
  4457. buf.skip(1);
  4458. buf.read(graphId);
  4459. buf.read(childId);
  4460. if (*logInfo == LOG_CHILDCOUNT)
  4461. {
  4462. unsigned idx;
  4463. unsigned childProcessed;
  4464. unsigned childStrands;
  4465. buf.read(idx);
  4466. buf.read(childProcessed);
  4467. buf.read(childStrands);
  4468. if (traceLevel > 5)
  4469. activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
  4470. //activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
  4471. }
  4472. else
  4473. {
  4474. CRuntimeStatisticCollection childStats(allStatistics);
  4475. childStats.deserialize(buf);
  4476. if (traceLevel > 5)
  4477. {
  4478. StringBuffer s;
  4479. activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
  4480. }
  4481. //activity.queryContext()->mergeActivityStats(childStats, graphId, childId);
  4482. activity.mergeStats(childStats);
  4483. }
  4484. }
  4485. ReleaseRoxieRow(rowlen);
  4486. ReleaseRoxieRow(logInfo);
  4487. }
  4488. else
  4489. break;
  4490. }
  4491. break;
  4492. }
  4493. case ROXIE_EXCEPTION:
  4494. if (ctxTraceLevel > 1)
  4495. {
  4496. StringBuffer s;
  4497. activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
  4498. }
  4499. op->queryHeader().noteException(header.retries);
  4500. if (op->queryHeader().allChannelsFailed())
  4501. {
  4502. activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
  4503. Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
  4504. throwRemoteException(exceptionData);
  4505. }
  4506. // Leave it on pending queue in original location
  4507. break;
  4508. case ROXIE_ALIVE:
  4509. if (ctxTraceLevel > 4)
  4510. {
  4511. StringBuffer s;
  4512. activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
  4513. }
  4514. op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
  4515. // Leave it on pending queue in original location
  4516. break;
  4517. default:
  4518. if (header.retries & ROXIE_RETRIES_MASK)
  4519. retriesNeeded++;
  4520. unsigned metaLen;
  4521. const void *metaData = mr->getMessageMetadata(metaLen);
  4522. if (metaLen)
  4523. {
  4524. // We got back first chunk but there is more.
  4525. // resend the packet, with the cursor info provided.
  4526. // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
  4527. if (ctxTraceLevel > 1)
  4528. {
  4529. StringBuffer s;
  4530. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4531. }
  4532. if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
  4533. {
  4534. StringBuffer s;
  4535. activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
  4536. activity.queryLogCtx().CTXLOG("Additional data is corrupt");
  4537. throwUnexpected();
  4538. }
  4539. MemoryBuffer nextQuery;
  4540. nextQuery.append(sizeof(RoxiePacketHeader), &header);
  4541. nextQuery.append(metaLen, metaData);
  4542. nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
  4543. nextQuery.append(op->getContextLength(), op->queryContextData());
  4544. if (resendSequence == CONTINUESEQUENCE_MAX)
  4545. {
  4546. activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
  4547. resendSequence = 1;
  4548. }
  4549. else
  4550. resendSequence++;
  4551. RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
  4552. newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
  4553. newHeader->retries &= ~ROXIE_RETRIES_MASK;
  4554. IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
  4555. CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
  4556. fqp->setSequence(original->getSequence());
  4557. pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
  4558. original->setContinuation(LINK(fqp));
  4559. if (mergeOrder)
  4560. fqp->setDelayed(true);
  4561. else
  4562. {
  4563. ROQ->sendPacket(resend, activity.queryLogCtx());
  4564. sentsome.signal();
  4565. }
  4566. // Note that we don't attempt to cache results that have continuation records - too tricky !
  4567. }
  4568. else
  4569. {
  4570. if (serverSideCache)
  4571. serverSideCache->noteCachedResult(original, mr);
  4572. }
  4573. unsigned channel = header.channel;
  4574. {
  4575. ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
  4576. if (b)
  4577. b->signal();
  4578. }
  4579. original->setResult(mr.getClear());
  4580. sentsome.signal();
  4581. return;
  4582. }
  4583. }
  4584. }
  4585. else
  4586. {
  4587. if (!anyActivity && !localSlave)
  4588. {
  4589. activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
  4590. retryPending();
  4591. }
  4592. }
  4593. }
  4594. }
  4595. inline unsigned headerLength() const
  4596. {
  4597. return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
  4598. }
  4599. void copyHeader(byte *tgt, unsigned channel) const
  4600. {
  4601. unsigned len = logInfo.length();
  4602. memcpy(tgt, logInfo.toByteArray(), len);
  4603. tgt += len;
  4604. *(unsigned *) tgt = parentExtractSize;
  4605. tgt += sizeof(unsigned);
  4606. memcpy(tgt, parentExtract, parentExtractSize);
  4607. tgt += parentExtractSize;
  4608. memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
  4609. tgt += cachedContext.length();
  4610. }
  4611. };
  4612. class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
  4613. {
  4614. Owned <IException> exception;
  4615. bool skipping;
  4616. ConstPointerArray buff;
  4617. unsigned index;
  4618. bool pulled;
  4619. void pullInput()
  4620. {
  4621. try
  4622. {
  4623. if (exception)
  4624. throw exception.getClear();
  4625. unsigned __int64 count = 0;
  4626. for (;;)
  4627. {
  4628. const void * next = CRemoteResultAdaptor::nextRow();
  4629. if (next == NULL)
  4630. {
  4631. next = CRemoteResultAdaptor::nextRow();
  4632. if(next == NULL)
  4633. break;
  4634. buff.append(NULL);
  4635. }
  4636. count++;
  4637. if (count > rowLimit)
  4638. {
  4639. ReleaseRoxieRow(next);
  4640. ReleaseRoxieRows(buff);
  4641. errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
  4642. throwUnexpected();
  4643. }
  4644. else if (count > keyedLimit)
  4645. {
  4646. ReleaseRoxieRow(next);
  4647. ReleaseRoxieRows(buff);
  4648. errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
  4649. throwUnexpected();
  4650. }
  4651. buff.append(next);
  4652. }
  4653. }
  4654. catch (IException *E)
  4655. {
  4656. if (QUERYINTERFACE(E, LimitSkipException))
  4657. {
  4658. Owned<IException> cleanup = E;
  4659. ReleaseRoxieRows(buff);
  4660. const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
  4661. if (onfail)
  4662. buff.append(onfail);
  4663. }
  4664. else
  4665. throw;
  4666. }
  4667. pulled = true;
  4668. }
  4669. public:
  4670. CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
  4671. CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
  4672. {
  4673. skipping = _skipping;
  4674. index = 0;
  4675. pulled = false;
  4676. }
  4677. void setException(IException *E)
  4678. {
  4679. exception.setown(E);
  4680. }
  4681. virtual void onReset()
  4682. {
  4683. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  4684. buff.kill();
  4685. index = 0;
  4686. pulled = false;
  4687. exception.clear();
  4688. CRemoteResultAdaptor::onReset();
  4689. }
  4690. void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
  4691. {
  4692. index = 0;
  4693. pulled = false;
  4694. CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
  4695. }
  4696. virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4697. {
  4698. // 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
  4699. if (exception)
  4700. throw exception.getClear();
  4701. return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  4702. }
  4703. virtual const void *nextRow()
  4704. {
  4705. if (skipping)
  4706. {
  4707. if(!pulled)
  4708. pullInput();
  4709. if(buff.isItem(index))
  4710. {
  4711. const void * next = buff.item(index++);
  4712. if(next)
  4713. processed++;
  4714. return next;
  4715. }
  4716. return NULL;
  4717. }
  4718. else
  4719. {
  4720. if (exception)
  4721. throw exception.getClear();
  4722. return CRemoteResultAdaptor::nextRow();
  4723. }
  4724. }
  4725. };
  4726. //=================================================================================
  4727. class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
  4728. {
  4729. IHThorApplyArg &helper;
  4730. public:
  4731. CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4732. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
  4733. {
  4734. }
  4735. virtual void onExecute()
  4736. {
  4737. helper.start();
  4738. for (;;)
  4739. {
  4740. const void * next = inputStream->ungroupedNextRow();
  4741. if (!next)
  4742. break;
  4743. helper.apply(next);
  4744. ReleaseRoxieRow(next);
  4745. }
  4746. helper.end();
  4747. }
  4748. };
  4749. class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
  4750. {
  4751. bool isRoot;
  4752. public:
  4753. CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4754. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  4755. {
  4756. }
  4757. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4758. {
  4759. return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
  4760. }
  4761. virtual bool isSink() const
  4762. {
  4763. return isRoot;
  4764. }
  4765. };
  4766. IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  4767. {
  4768. return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  4769. }
  4770. //=================================================================================
  4771. class CRoxieServerNullActivity : public CRoxieServerActivity
  4772. {
  4773. public:
  4774. CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4775. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4776. {
  4777. }
  4778. virtual const void *nextRow()
  4779. {
  4780. return NULL;
  4781. }
  4782. };
  4783. IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4784. {
  4785. return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
  4786. }
  4787. class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
  4788. {
  4789. public:
  4790. CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4791. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4792. {
  4793. }
  4794. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4795. {
  4796. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  4797. }
  4798. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4799. {
  4800. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
  4801. }
  4802. };
  4803. IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4804. {
  4805. return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4806. }
  4807. //=================================================================================
  4808. class CRoxieServerNullSinkActivity : public CRoxieServerInternalSinkActivity
  4809. {
  4810. public:
  4811. CRoxieServerNullSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4812. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0)
  4813. {
  4814. }
  4815. virtual void onExecute() override
  4816. {
  4817. }
  4818. };
  4819. IRoxieServerActivity * createRoxieServerNullSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4820. {
  4821. return new CRoxieServerNullSinkActivity(_ctx, _factory, _probeManager);
  4822. }
  4823. //=================================================================================
  4824. class CRoxieServerPassThroughActivity : public CRoxieServerActivity
  4825. {
  4826. public:
  4827. CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4828. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4829. {
  4830. }
  4831. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  4832. {
  4833. return input->gatherConjunctions(collector);
  4834. }
  4835. virtual void resetEOF()
  4836. {
  4837. inputStream->resetEOF();
  4838. }
  4839. virtual const void *nextRow()
  4840. {
  4841. const void * next = inputStream->nextRow();
  4842. if (next)
  4843. processed++;
  4844. return next;
  4845. }
  4846. virtual bool isPassThrough()
  4847. {
  4848. return true;
  4849. }
  4850. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  4851. {
  4852. ActivityTimer t(totalCycles, timeActivities);
  4853. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  4854. if (next)
  4855. processed++;
  4856. return next;
  4857. }
  4858. IInputSteppingMeta * querySteppingMeta()
  4859. {
  4860. return input->querySteppingMeta();
  4861. }
  4862. };
  4863. IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4864. {
  4865. return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
  4866. }
  4867. //=================================================================================
  4868. class CRoxieServerChildBaseActivity : public CRoxieServerActivity
  4869. {
  4870. protected:
  4871. bool eof;
  4872. bool first;
  4873. public:
  4874. CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4875. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  4876. {
  4877. eof = false;
  4878. first = true;
  4879. }
  4880. ~CRoxieServerChildBaseActivity()
  4881. {
  4882. }
  4883. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  4884. {
  4885. eof = false;
  4886. first = true;
  4887. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  4888. }
  4889. };
  4890. class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
  4891. {
  4892. public:
  4893. CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4894. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4895. {
  4896. }
  4897. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  4898. {
  4899. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  4900. }
  4901. };
  4902. //=================================================================================
  4903. class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
  4904. {
  4905. IHThorChildIteratorArg &helper;
  4906. public:
  4907. CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4908. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
  4909. {
  4910. }
  4911. virtual bool needsAllocator() const { return true; }
  4912. virtual const void *nextRow()
  4913. {
  4914. ActivityTimer t(totalCycles, timeActivities);
  4915. if (eof)
  4916. return NULL;
  4917. bool ok;
  4918. if (first)
  4919. {
  4920. ok = helper.first();
  4921. first = false;
  4922. }
  4923. else
  4924. ok = helper.next();
  4925. try
  4926. {
  4927. while (ok)
  4928. {
  4929. processed++;
  4930. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4931. unsigned outSize = helper.transform(rowBuilder);
  4932. if (outSize)
  4933. return rowBuilder.finalizeRowClear(outSize);
  4934. ok = helper.next();
  4935. }
  4936. }
  4937. catch (IException *E)
  4938. {
  4939. throw makeWrappedException(E);
  4940. }
  4941. eof = true;
  4942. return NULL;
  4943. }
  4944. };
  4945. class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
  4946. {
  4947. public:
  4948. CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4949. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  4950. {
  4951. }
  4952. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  4953. {
  4954. return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
  4955. }
  4956. };
  4957. IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  4958. {
  4959. return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  4960. }
  4961. //=================================================================================
  4962. class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
  4963. {
  4964. IHThorChildNormalizeArg &helper;
  4965. public:
  4966. CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  4967. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
  4968. {
  4969. }
  4970. virtual bool needsAllocator() const { return true; }
  4971. virtual const void *nextRow()
  4972. {
  4973. ActivityTimer t(totalCycles, timeActivities);
  4974. if (eof)
  4975. return NULL;
  4976. bool ok;
  4977. if (first)
  4978. {
  4979. ok = helper.first();
  4980. first = false;
  4981. }
  4982. else
  4983. ok = helper.next();
  4984. if (ok)
  4985. {
  4986. try
  4987. {
  4988. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  4989. do {
  4990. unsigned outSize = helper.transform(rowBuilder);
  4991. if (outSize)
  4992. {
  4993. processed++;
  4994. return rowBuilder.finalizeRowClear(outSize);
  4995. }
  4996. ok = helper.next();
  4997. }
  4998. while (ok);
  4999. }
  5000. catch (IException *E)
  5001. {
  5002. throw makeWrappedException(E);
  5003. }
  5004. }
  5005. eof = true;
  5006. return NULL;
  5007. }
  5008. };
  5009. class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
  5010. {
  5011. public:
  5012. CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5013. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5014. {
  5015. }
  5016. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5017. {
  5018. return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
  5019. }
  5020. };
  5021. IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5022. {
  5023. return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5024. }
  5025. //=================================================================================
  5026. class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
  5027. {
  5028. IHThorChildAggregateArg &helper;
  5029. public:
  5030. CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5031. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
  5032. {
  5033. }
  5034. virtual bool needsAllocator() const { return true; }
  5035. virtual const void *nextRow()
  5036. {
  5037. ActivityTimer t(totalCycles, timeActivities);
  5038. if (eof)
  5039. return NULL;
  5040. eof = true;
  5041. processed++;
  5042. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5043. helper.clearAggregate(rowBuilder);
  5044. helper.processRows(rowBuilder);
  5045. size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
  5046. return rowBuilder.finalizeRowClear(finalSize);
  5047. }
  5048. };
  5049. class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5050. {
  5051. public:
  5052. CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5053. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5054. {
  5055. }
  5056. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5057. {
  5058. return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
  5059. }
  5060. };
  5061. IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5062. {
  5063. return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5064. }
  5065. //=================================================================================
  5066. class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
  5067. {
  5068. IHThorChildGroupAggregateArg &helper;
  5069. RowAggregator aggregated;
  5070. public:
  5071. IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
  5072. CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5073. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
  5074. aggregated(helper, helper)
  5075. {
  5076. }
  5077. void processRow(const void * next)
  5078. {
  5079. aggregated.addRow(next);
  5080. }
  5081. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5082. {
  5083. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5084. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  5085. }
  5086. virtual void reset()
  5087. {
  5088. aggregated.reset();
  5089. CRoxieServerChildBaseActivity::reset();
  5090. }
  5091. virtual bool needsAllocator() const { return true; }
  5092. virtual const void *nextRow()
  5093. {
  5094. ActivityTimer t(totalCycles, timeActivities);
  5095. if (eof)
  5096. return NULL;
  5097. if (first)
  5098. {
  5099. helper.processRows(this);
  5100. first = false;
  5101. }
  5102. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  5103. if (next)
  5104. {
  5105. processed++;
  5106. return next->finalizeRowClear();
  5107. }
  5108. eof = true;
  5109. return NULL;
  5110. }
  5111. };
  5112. class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
  5113. {
  5114. public:
  5115. CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5116. : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5117. {
  5118. }
  5119. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5120. {
  5121. return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
  5122. }
  5123. };
  5124. IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5125. {
  5126. return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5127. }
  5128. //=================================================================================
  5129. class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
  5130. {
  5131. IHThorChildThroughNormalizeArg &helper;
  5132. const void * lastInput;
  5133. unsigned numProcessedLastGroup;
  5134. bool ok;
  5135. public:
  5136. CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5137. : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
  5138. {
  5139. lastInput = NULL;
  5140. numProcessedLastGroup = 0;
  5141. ok = false;
  5142. }
  5143. virtual void stop()
  5144. {
  5145. CRoxieServerChildBaseActivity::stop();
  5146. ReleaseRoxieRow(lastInput);
  5147. lastInput = NULL;
  5148. }
  5149. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5150. {
  5151. CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
  5152. numProcessedLastGroup = processed;
  5153. ok = false;
  5154. }
  5155. virtual bool needsAllocator() const { return true; }
  5156. virtual const void *nextRow()
  5157. {
  5158. ActivityTimer t(totalCycles, timeActivities);
  5159. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5160. for (;;)
  5161. {
  5162. if (ok)
  5163. ok = helper.next();
  5164. while (!ok)
  5165. {
  5166. ReleaseRoxieRow(lastInput);
  5167. lastInput = inputStream->nextRow();
  5168. if (!lastInput)
  5169. {
  5170. if (numProcessedLastGroup != processed)
  5171. {
  5172. numProcessedLastGroup = processed;
  5173. return NULL;
  5174. }
  5175. lastInput = inputStream->nextRow();
  5176. if (!lastInput)
  5177. return NULL;
  5178. }
  5179. ok = helper.first(lastInput);
  5180. }
  5181. try
  5182. {
  5183. do
  5184. {
  5185. unsigned outSize = helper.transform(rowBuilder);
  5186. if (outSize)
  5187. {
  5188. processed++;
  5189. return rowBuilder.finalizeRowClear(outSize);
  5190. }
  5191. ok = helper.next();
  5192. } while (ok);
  5193. }
  5194. catch (IException *E)
  5195. {
  5196. throw makeWrappedException(E);
  5197. }
  5198. }
  5199. }
  5200. };
  5201. class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
  5202. {
  5203. public:
  5204. CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5205. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5206. {
  5207. }
  5208. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5209. {
  5210. return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
  5211. }
  5212. };
  5213. IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5214. {
  5215. return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5216. }
  5217. //=================================================================================
  5218. class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
  5219. {
  5220. IHThorDistributionArg &helper;
  5221. public:
  5222. CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5223. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
  5224. {
  5225. }
  5226. virtual void onExecute()
  5227. {
  5228. MemoryAttr ma;
  5229. IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
  5230. helper.clearAggregate(accumulator);
  5231. OwnedConstRoxieRow nextrec(inputStream->nextRow());
  5232. for (;;)
  5233. {
  5234. if (!nextrec)
  5235. {
  5236. nextrec.setown(inputStream->nextRow());
  5237. if (!nextrec)
  5238. break;
  5239. }
  5240. helper.process(accumulator, nextrec);
  5241. nextrec.setown(inputStream->nextRow());
  5242. }
  5243. StringBuffer result;
  5244. result.append("<XML>");
  5245. helper.gatherResult(accumulator, result);
  5246. result.append("</XML>");
  5247. helper.sendResult(result.length(), result.str());
  5248. helper.destruct(accumulator);
  5249. }
  5250. };
  5251. class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
  5252. {
  5253. bool isRoot;
  5254. public:
  5255. CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5256. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5257. {
  5258. }
  5259. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5260. {
  5261. return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
  5262. }
  5263. virtual bool isSink() const
  5264. {
  5265. return isRoot;
  5266. }
  5267. };
  5268. IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5269. {
  5270. return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5271. }
  5272. //=================================================================================
  5273. class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
  5274. {
  5275. IHThorLinkedRawIteratorArg &helper;
  5276. public:
  5277. CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5278. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
  5279. {
  5280. }
  5281. virtual const void *nextRow()
  5282. {
  5283. ActivityTimer t(totalCycles, timeActivities);
  5284. const void *ret =helper.next();
  5285. if (ret)
  5286. {
  5287. LinkRoxieRow(ret);
  5288. processed++;
  5289. }
  5290. return ret;
  5291. }
  5292. };
  5293. class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
  5294. {
  5295. public:
  5296. CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5297. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5298. {
  5299. }
  5300. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5301. {
  5302. return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
  5303. }
  5304. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5305. {
  5306. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  5307. }
  5308. };
  5309. IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5310. {
  5311. return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5312. }
  5313. //=================================================================================
  5314. class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
  5315. {
  5316. public:
  5317. CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5318. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  5319. {
  5320. }
  5321. virtual const void *nextRow()
  5322. {
  5323. throwUnexpected();
  5324. }
  5325. virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
  5326. {
  5327. try
  5328. {
  5329. start(parentExtractSize, parentExtract, false);
  5330. {
  5331. ActivityTimer t(totalCycles, timeActivities);
  5332. MemoryBuffer result;
  5333. IRecordSize * inputMeta = input->queryOutputMeta();
  5334. for (;;)
  5335. {
  5336. const void *nextrec = inputStream->ungroupedNextRow();
  5337. if (!nextrec)
  5338. break;
  5339. result.append(inputMeta->getRecordSize(nextrec), nextrec);
  5340. ReleaseRoxieRow(nextrec);
  5341. }
  5342. retSize = result.length();
  5343. ret = result.detach();
  5344. }
  5345. stop();
  5346. reset();
  5347. }
  5348. catch(IException *E)
  5349. {
  5350. ctx->notifyAbort(E);
  5351. abort();
  5352. reset();
  5353. throw;
  5354. }
  5355. catch(...)
  5356. {
  5357. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  5358. ctx->notifyAbort(E);
  5359. abort();
  5360. reset();
  5361. throw;
  5362. }
  5363. }
  5364. };
  5365. class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
  5366. {
  5367. bool isRoot;
  5368. public:
  5369. CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5370. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  5371. {
  5372. }
  5373. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5374. {
  5375. return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
  5376. }
  5377. virtual bool isSink() const
  5378. {
  5379. return isRoot;
  5380. }
  5381. };
  5382. IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  5383. {
  5384. return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  5385. }
  5386. //=================================================================================
  5387. class CRoxieServerInlineTableActivity : public CRoxieServerActivity
  5388. {
  5389. IHThorInlineTableArg &helper;
  5390. __uint64 curRow;
  5391. __uint64 numRows;
  5392. public:
  5393. CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5394. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
  5395. {
  5396. curRow = 0;
  5397. numRows = 0;
  5398. }
  5399. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5400. {
  5401. curRow = 0;
  5402. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5403. numRows = helper.numRows();
  5404. }
  5405. virtual bool needsAllocator() const { return true; }
  5406. virtual const void *nextRow()
  5407. {
  5408. ActivityTimer t(totalCycles, timeActivities);
  5409. // Filtering empty rows, returns the next valid row
  5410. while (curRow < numRows)
  5411. {
  5412. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5413. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5414. if (outSize)
  5415. {
  5416. processed++;
  5417. return rowBuilder.finalizeRowClear(outSize);
  5418. }
  5419. }
  5420. return NULL;
  5421. }
  5422. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5423. {
  5424. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5425. }
  5426. };
  5427. class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
  5428. {
  5429. IHThorInlineTableArg &helper;
  5430. __uint64 numRows;
  5431. //An inline table that isn't stranded
  5432. class InlineTableSimpleProcessor : public StrandProcessor
  5433. {
  5434. protected:
  5435. IHThorInlineTableArg &helper;
  5436. __uint64 curRow;
  5437. __uint64 maxRows;
  5438. public:
  5439. InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
  5440. : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
  5441. {
  5442. }
  5443. virtual void start() override
  5444. {
  5445. StrandProcessor::start();
  5446. curRow = 0;
  5447. maxRows = queryParent().numRows;
  5448. }
  5449. virtual const void * nextRow()
  5450. {
  5451. ActivityTimer t(totalCycles, timeActivities);
  5452. //Return rows while the current section is active
  5453. while (curRow < maxRows)
  5454. {
  5455. RtlDynamicRowBuilder rowBuilder(*rowAllocator);
  5456. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5457. if (outSize)
  5458. {
  5459. processed++;
  5460. return rowBuilder.finalizeRowClear(outSize);
  5461. }
  5462. }
  5463. return NULL;
  5464. }
  5465. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5466. };
  5467. class InlineTableStrandProcessor : public StrandProcessor
  5468. {
  5469. protected:
  5470. IHThorInlineTableArg &helper;
  5471. unsigned whichStrand;
  5472. unsigned numStrands = 0;
  5473. __uint64 sectionSize;
  5474. __uint64 curRow = 0;
  5475. __uint64 sectionMaxRows = 0;
  5476. __uint64 maxRows = 0;
  5477. bool isOrdered;
  5478. bool eosPending;
  5479. public:
  5480. InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
  5481. : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
  5482. {
  5483. sectionSize = queryParent().strandOptions.blockSize;
  5484. eosPending = false;
  5485. }
  5486. virtual void start() override
  5487. {
  5488. StrandProcessor::start();
  5489. numStrands = queryParent().numStrands();
  5490. maxRows = queryParent().numRows;
  5491. curRow = std::min(whichStrand * sectionSize, maxRows);
  5492. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5493. eosPending = isOrdered && (curRow != maxRows);
  5494. }
  5495. virtual const void * nextRow()
  5496. {
  5497. ActivityTimer t(totalCycles, timeActivities);
  5498. for (;;)
  5499. {
  5500. //Return rows while the current section is active
  5501. while (curRow < sectionMaxRows)
  5502. {
  5503. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  5504. unsigned outSize = helper.getRow(rowBuilder, curRow++);
  5505. if (outSize)
  5506. {
  5507. processed++;
  5508. return rowBuilder.finalizeRowClear(outSize);
  5509. }
  5510. }
  5511. if (curRow == maxRows)
  5512. return NULL;
  5513. //Update current position to the next section
  5514. curRow += (numStrands - 1) * sectionSize;
  5515. if (curRow > maxRows)
  5516. curRow = maxRows;
  5517. sectionMaxRows = std::min(curRow + sectionSize, maxRows);
  5518. //If we have output a block of rows, then send the block as a unit - results now come from the next strand
  5519. if (eosPending)
  5520. {
  5521. //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
  5522. eosPending = isOrdered && (curRow != maxRows);
  5523. return queryEndOfSectionMarker();
  5524. }
  5525. }
  5526. }
  5527. CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
  5528. };
  5529. public:
  5530. CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  5531. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
  5532. {
  5533. numRows = 0;
  5534. }
  5535. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
  5536. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
  5537. {
  5538. if (strandOptions.numStrands <= 1)
  5539. return new InlineTableSimpleProcessor(*this, helper);
  5540. return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
  5541. }
  5542. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5543. {
  5544. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  5545. numRows = helper.numRows();
  5546. onStartStrands();
  5547. startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
  5548. }
  5549. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5550. {
  5551. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5552. }
  5553. };
  5554. class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
  5555. {
  5556. StrandOptions strandOptions;
  5557. public:
  5558. CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5559. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  5560. {
  5561. optStableInput = false; // do not force the output to be ordered
  5562. }
  5563. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5564. {
  5565. return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
  5566. }
  5567. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5568. {
  5569. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
  5570. }
  5571. };
  5572. IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5573. {
  5574. return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5575. }
  5576. //=================================================================================
  5577. class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
  5578. {
  5579. IHThorWorkunitReadArg &helper;
  5580. CriticalSection readerCrit;
  5581. Owned<IWorkUnitRowReader> wuReader;
  5582. public:
  5583. CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  5584. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
  5585. {
  5586. }
  5587. virtual void onCreate(IHThorArg *_colocalParent)
  5588. {
  5589. CRoxieServerActivity::onCreate(_colocalParent);
  5590. if (!ctx->queryServerContext())
  5591. {
  5592. throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
  5593. }
  5594. }
  5595. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5596. {
  5597. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5598. IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
  5599. OwnedRoxieString fromWuid(helper.getWUID());
  5600. wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
  5601. // MORE _ should that be in onCreate?
  5602. }
  5603. virtual void reset()
  5604. {
  5605. {
  5606. CriticalBlock b(readerCrit);
  5607. wuReader.clear();
  5608. }
  5609. CRoxieServerActivity::reset();
  5610. };
  5611. virtual bool needsAllocator() const { return true; }
  5612. virtual const void *nextRow()
  5613. {
  5614. ActivityTimer t(totalCycles, timeActivities);
  5615. Linked<IWorkUnitRowReader> useReader;
  5616. {
  5617. CriticalBlock b(readerCrit);
  5618. if (!wuReader)
  5619. return NULL;
  5620. useReader.set(wuReader);
  5621. }
  5622. const void *ret = useReader->nextRow();
  5623. if (ret)
  5624. processed++;
  5625. return ret;
  5626. }
  5627. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  5628. {
  5629. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  5630. }
  5631. };
  5632. class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
  5633. {
  5634. public:
  5635. CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5636. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  5637. {
  5638. }
  5639. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  5640. {
  5641. return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
  5642. }
  5643. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  5644. {
  5645. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
  5646. }
  5647. };
  5648. IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  5649. {
  5650. return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  5651. }
  5652. //=================================================================================
  5653. interface ILocalGraphEx : public IEclGraphResults
  5654. {
  5655. public:
  5656. virtual void setResult(unsigned id, IGraphResult * result) = 0;
  5657. virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
  5658. virtual void setGraphLoopResult(IGraphResult * result) = 0;
  5659. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
  5660. };
  5661. class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5662. {
  5663. public:
  5664. CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
  5665. IMPLEMENT_IINTERFACE
  5666. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5667. {
  5668. connectInputStreams(ctx, consumerOrdered);
  5669. streams.append(this);
  5670. return NULL;
  5671. }
  5672. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5673. {
  5674. inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
  5675. }
  5676. virtual IOutputMetaData * queryOutputMeta() const
  5677. {
  5678. return input->queryOutputMeta();
  5679. }
  5680. virtual unsigned __int64 queryTotalCycles() const
  5681. {
  5682. return input->queryTotalCycles();
  5683. }
  5684. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5685. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5686. virtual IRoxieServerActivity *queryActivity()
  5687. {
  5688. return input->queryActivity();
  5689. }
  5690. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5691. {
  5692. return input->queryIndexReadActivity();
  5693. }
  5694. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5695. {
  5696. CriticalBlock procedure(cs);
  5697. input->start(parentExtractSize, parentExtract, paused);
  5698. startJunction(junction);
  5699. }
  5700. virtual void stop()
  5701. {
  5702. CriticalBlock procedure(cs);
  5703. inputStream->stop();
  5704. }
  5705. virtual void reset()
  5706. {
  5707. CriticalBlock procedure(cs);
  5708. input->reset();
  5709. resetJunction(junction);
  5710. }
  5711. virtual void resetEOF()
  5712. {
  5713. CriticalBlock procedure(cs);
  5714. inputStream->resetEOF();
  5715. }
  5716. virtual const void *nextRow()
  5717. {
  5718. CriticalBlock procedure(cs);
  5719. return inputStream->nextRow();
  5720. }
  5721. virtual bool nextGroup(ConstPointerArray & group)
  5722. {
  5723. CriticalBlock procedure(cs);
  5724. return inputStream->nextGroup(group);
  5725. }
  5726. private:
  5727. CriticalSection cs;
  5728. Linked<IFinalRoxieInput> input;
  5729. Linked<IEngineRowStream> inputStream;
  5730. Owned<IStrandJunction> junction;
  5731. unsigned sourceIdx;
  5732. };
  5733. //=================================================================================
  5734. class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  5735. {
  5736. public:
  5737. IMPLEMENT_IINTERFACE;
  5738. CPseudoRoxieInput()
  5739. {
  5740. }
  5741. virtual unsigned __int64 queryTotalCycles() const
  5742. {
  5743. return 0;
  5744. }
  5745. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  5746. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  5747. virtual IRoxieServerActivity *queryActivity()
  5748. {
  5749. throwUnexpected();
  5750. }
  5751. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  5752. {
  5753. throwUnexpected();
  5754. }
  5755. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5756. {
  5757. assertex(!idx);
  5758. streams.append(this);
  5759. return NULL;
  5760. }
  5761. virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
  5762. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
  5763. virtual void stop() { }
  5764. virtual void reset() { }
  5765. virtual void checkAbort() { }
  5766. virtual void resetEOF() { }
  5767. };
  5768. class CIndirectRoxieInput : public CPseudoRoxieInput
  5769. {
  5770. public:
  5771. CIndirectRoxieInput() : input(NULL)
  5772. {
  5773. stream = NULL;
  5774. sourceIdx = 0;
  5775. }
  5776. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5777. {
  5778. input->start(parentExtractSize, parentExtract, paused);
  5779. startJunction(junction);
  5780. }
  5781. virtual void stop()
  5782. {
  5783. stream->stop();
  5784. }
  5785. virtual void reset()
  5786. {
  5787. input->reset();
  5788. resetJunction(junction);
  5789. }
  5790. virtual const void * nextRow()
  5791. {
  5792. return stream->nextRow();
  5793. }
  5794. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  5795. {
  5796. return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  5797. }
  5798. virtual unsigned __int64 queryTotalCycles() const
  5799. {
  5800. return input ? input->queryTotalCycles() : 0;
  5801. }
  5802. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  5803. {
  5804. return input->gatherConjunctions(collector);
  5805. }
  5806. virtual void resetEOF()
  5807. {
  5808. stream->resetEOF();
  5809. }
  5810. virtual unsigned numConcreteOutputs() const
  5811. {
  5812. return input->numConcreteOutputs();
  5813. }
  5814. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  5815. {
  5816. return input->queryConcreteInput(idx);
  5817. }
  5818. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  5819. {
  5820. return input->queryConcreteOutputStream(whichInput);
  5821. }
  5822. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  5823. {
  5824. return input->queryConcreteOutputJunction(idx);
  5825. }
  5826. virtual IOutputMetaData * queryOutputMeta() const
  5827. {
  5828. return input->queryOutputMeta();
  5829. }
  5830. virtual IRoxieServerActivity *queryActivity()
  5831. {
  5832. return input->queryActivity();
  5833. }
  5834. inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
  5835. {
  5836. input = _input;
  5837. sourceIdx = _sourceIdx;
  5838. }
  5839. inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  5840. {
  5841. stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
  5842. }
  5843. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  5844. {
  5845. assertex(idx == 0);
  5846. connectInputStreams(ctx, consumerOrdered);
  5847. streams.append(this);
  5848. return NULL;
  5849. }
  5850. inline IFinalRoxieInput *queryInput() const
  5851. {
  5852. return input;
  5853. }
  5854. protected:
  5855. unsigned sourceIdx;
  5856. IFinalRoxieInput *input;
  5857. IEngineRowStream *stream;
  5858. Owned<IStrandJunction> junction;
  5859. };
  5860. class CExtractMapperInput : public CIndirectRoxieInput
  5861. {
  5862. unsigned savedParentExtractSize;
  5863. const byte * savedParentExtract;
  5864. public:
  5865. CExtractMapperInput()
  5866. {
  5867. savedParentExtractSize = 0;
  5868. savedParentExtract = NULL;
  5869. }
  5870. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5871. {
  5872. CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
  5873. }
  5874. void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
  5875. {
  5876. savedParentExtractSize = _savedParentExtractSize;
  5877. savedParentExtract = _savedParentExtract;
  5878. }
  5879. };
  5880. class CGraphResult : implements IGraphResult, public CInterface
  5881. {
  5882. CriticalSection cs;
  5883. const byte **rowset;
  5884. size32_t count;
  5885. bool complete;
  5886. void clear()
  5887. {
  5888. CriticalBlock func(cs);
  5889. rtlReleaseRowset(count, rowset);
  5890. rowset = NULL;
  5891. count = 0;
  5892. complete = false;
  5893. }
  5894. public:
  5895. IMPLEMENT_IINTERFACE
  5896. CGraphResult()
  5897. {
  5898. complete = false; // dummy result is not supposed to be used...
  5899. rowset = NULL;
  5900. count = 0;
  5901. }
  5902. CGraphResult(size32_t _count, const byte **_rowset)
  5903. : rowset(_rowset), count(_count)
  5904. {
  5905. complete = true;
  5906. }
  5907. ~CGraphResult()
  5908. {
  5909. clear();
  5910. }
  5911. // interface IGraphResult
  5912. virtual IEngineRowStream * createIterator()
  5913. {
  5914. if (!complete)
  5915. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5916. return new CGraphResultIterator(this);
  5917. }
  5918. virtual void getLinkedResult(unsigned & countResult, const byte * * & result) override
  5919. {
  5920. if (!complete)
  5921. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5922. result = rtlLinkRowset(rowset);
  5923. countResult = count;
  5924. }
  5925. virtual const void * getLinkedRowResult()
  5926. {
  5927. if (!complete)
  5928. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
  5929. if (count != 1)
  5930. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
  5931. const void * ret = rowset[0];
  5932. LinkRoxieRow(ret);
  5933. return ret;
  5934. }
  5935. //other
  5936. const void * getRow(unsigned i)
  5937. {
  5938. CriticalBlock func(cs);
  5939. if (i >= count)
  5940. return NULL;
  5941. const void * ret = rowset[i];
  5942. if (ret) LinkRoxieRow(ret);
  5943. return ret;
  5944. }
  5945. protected:
  5946. class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
  5947. {
  5948. unsigned i;
  5949. Linked<CGraphResult> result;
  5950. public:
  5951. CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
  5952. public:
  5953. virtual const void * nextRow()
  5954. {
  5955. return result->getRow(i++);
  5956. }
  5957. virtual void stop()
  5958. {
  5959. }
  5960. virtual void resetEOF()
  5961. {
  5962. throwUnexpected();
  5963. }
  5964. };
  5965. };
  5966. //=================================================================================
  5967. class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
  5968. {
  5969. IHThorLocalResultReadArg &helper;
  5970. CriticalSection iterCrit;
  5971. Owned<IEngineRowStream> iter;
  5972. ILocalGraphEx * graph;
  5973. unsigned graphId;
  5974. unsigned sequence;
  5975. public:
  5976. CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  5977. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
  5978. {
  5979. graph = NULL;
  5980. sequence = 0;
  5981. }
  5982. virtual void onCreate(IHThorArg *_colocalParent)
  5983. {
  5984. CRoxieServerActivity::onCreate(_colocalParent);
  5985. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  5986. sequence = helper.querySequence();
  5987. }
  5988. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  5989. {
  5990. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  5991. iter.setown(graph->createResultIterator(sequence));
  5992. }
  5993. virtual void reset()
  5994. {
  5995. {
  5996. CriticalBlock b(iterCrit);
  5997. iter.clear();
  5998. }
  5999. CRoxieServerActivity::reset();
  6000. };
  6001. virtual const void *nextRow()
  6002. {
  6003. ActivityTimer t(totalCycles, timeActivities);
  6004. Linked<IEngineRowStream> useIter;
  6005. {
  6006. CriticalBlock b(iterCrit);
  6007. if (!iter)
  6008. return NULL;
  6009. useIter.set(iter);
  6010. }
  6011. const void * next = useIter->nextRow();
  6012. if (next)
  6013. {
  6014. processed++;
  6015. rowsIn++;
  6016. }
  6017. return next;
  6018. }
  6019. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6020. {
  6021. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6022. }
  6023. };
  6024. class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
  6025. {
  6026. unsigned graphId;
  6027. public:
  6028. CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6029. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6030. {
  6031. }
  6032. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6033. {
  6034. return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
  6035. }
  6036. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6037. {
  6038. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6039. }
  6040. };
  6041. IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6042. {
  6043. return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6044. }
  6045. //=================================================================================
  6046. class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
  6047. {
  6048. IHThorLocalResultReadArg &helper;
  6049. unsigned sequence;
  6050. public:
  6051. CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6052. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
  6053. {
  6054. sequence = 0;
  6055. }
  6056. virtual void onCreate(IHThorArg *_colocalParent)
  6057. {
  6058. CRoxieServerActivity::onCreate(_colocalParent);
  6059. sequence = helper.querySequence();
  6060. }
  6061. virtual const void *nextRow()
  6062. {
  6063. ActivityTimer t(totalCycles, timeActivities);
  6064. const void * next = inputStream->nextRow();
  6065. if (next)
  6066. {
  6067. processed++;
  6068. rowsIn++;
  6069. }
  6070. return next;
  6071. }
  6072. virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
  6073. {
  6074. if (id == sequence)
  6075. {
  6076. CRoxieServerActivity::setInput(0, _sourceIdx, _input);
  6077. connectInputStreams(true);
  6078. return true;
  6079. }
  6080. return false;
  6081. }
  6082. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6083. {
  6084. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6085. }
  6086. };
  6087. class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
  6088. {
  6089. public:
  6090. CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6091. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6092. {
  6093. }
  6094. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6095. {
  6096. return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
  6097. }
  6098. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6099. {
  6100. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
  6101. }
  6102. };
  6103. IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6104. {
  6105. return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6106. }
  6107. //=====================================================================================================
  6108. class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
  6109. {
  6110. IHThorLocalResultWriteArg &helper;
  6111. ILocalGraphEx * graph;
  6112. unsigned graphId;
  6113. public:
  6114. CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6115. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
  6116. {
  6117. graph = NULL;
  6118. }
  6119. virtual bool needsAllocator() const { return true; }
  6120. virtual void onCreate(IHThorArg *_colocalParent)
  6121. {
  6122. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6123. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6124. }
  6125. virtual void onExecute()
  6126. {
  6127. RtlLinkedDatasetBuilder builder(rowAllocator);
  6128. inputStream->readAll(builder);
  6129. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6130. graph->setResult(helper.querySequence(), result);
  6131. }
  6132. virtual const void *nextRow()
  6133. {
  6134. return inputStream->nextRow(); // I can act as a passthrough input
  6135. }
  6136. IFinalRoxieInput * querySelectOutput(unsigned id)
  6137. {
  6138. if (id == helper.querySequence())
  6139. {
  6140. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6141. return LINK(this);
  6142. }
  6143. return NULL;
  6144. }
  6145. };
  6146. class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6147. {
  6148. unsigned graphId;
  6149. public:
  6150. CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6151. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6152. {
  6153. isInternal = true;
  6154. Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
  6155. }
  6156. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6157. {
  6158. return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6159. }
  6160. };
  6161. IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6162. {
  6163. return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6164. }
  6165. //=====================================================================================================
  6166. class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
  6167. {
  6168. IHThorDictionaryResultWriteArg &helper;
  6169. ILocalGraphEx * graph;
  6170. unsigned graphId;
  6171. public:
  6172. CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
  6173. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
  6174. {
  6175. graph = NULL;
  6176. }
  6177. virtual bool needsAllocator() const { return true; }
  6178. virtual void onCreate(IHThorArg *_colocalParent)
  6179. {
  6180. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6181. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6182. }
  6183. virtual void onExecute()
  6184. {
  6185. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  6186. for (;;)
  6187. {
  6188. const void *row = inputStream->ungroupedNextRow();
  6189. if (!row)
  6190. break;
  6191. builder.appendOwn(row);
  6192. processed++;
  6193. }
  6194. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6195. graph->setResult(helper.querySequence(), result);
  6196. }
  6197. virtual const void *nextRow()
  6198. {
  6199. return inputStream->nextRow(); // I can act as a passthrough input
  6200. }
  6201. IFinalRoxieInput * querySelectOutput(unsigned id)
  6202. {
  6203. if (id == helper.querySequence())
  6204. {
  6205. executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
  6206. return LINK(this);
  6207. }
  6208. return NULL;
  6209. }
  6210. };
  6211. class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6212. {
  6213. unsigned graphId;
  6214. public:
  6215. CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6216. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
  6217. {
  6218. isInternal = true;
  6219. }
  6220. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6221. {
  6222. return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
  6223. }
  6224. };
  6225. IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
  6226. {
  6227. return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
  6228. }
  6229. //=================================================================================
  6230. class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
  6231. {
  6232. protected:
  6233. IHThorGraphLoopResultReadArg &helper;
  6234. CriticalSection iterCrit;
  6235. Owned<IFinalRoxieInput> iterInput;
  6236. Owned<IEngineRowStream> iterStream;
  6237. Owned<IStrandJunction> iterJunction;
  6238. ILocalGraphEx * graph;
  6239. unsigned graphId;
  6240. unsigned sequence;
  6241. public:
  6242. CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  6243. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
  6244. {
  6245. graph = NULL;
  6246. sequence = 0;
  6247. }
  6248. virtual void onCreate(IHThorArg *_colocalParent)
  6249. {
  6250. CRoxieServerActivity::onCreate(_colocalParent);
  6251. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6252. }
  6253. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6254. {
  6255. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6256. if (iterInput)
  6257. iterInput->start(parentExtractSize, parentExtract, paused);
  6258. else
  6259. {
  6260. sequence = helper.querySequence();
  6261. if ((int)sequence >= 0)
  6262. {
  6263. try
  6264. {
  6265. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6266. iterInput.clear();
  6267. }
  6268. catch (IException * E)
  6269. {
  6270. throw makeWrappedException(E);
  6271. }
  6272. }
  6273. }
  6274. startJunction(iterJunction);
  6275. }
  6276. virtual void stop()
  6277. {
  6278. if (iterStream)
  6279. iterStream->stop();
  6280. CRoxieServerActivity::stop();
  6281. }
  6282. virtual void reset()
  6283. {
  6284. {
  6285. CriticalBlock b(iterCrit);
  6286. if (iterInput)
  6287. iterInput->reset();
  6288. resetJunction(iterJunction);
  6289. iterInput.clear();
  6290. iterStream.clear();
  6291. iterJunction.clear();
  6292. }
  6293. CRoxieServerActivity::reset();
  6294. };
  6295. virtual const void *nextRow()
  6296. {
  6297. ActivityTimer t(totalCycles, timeActivities);
  6298. Linked<IEngineRowStream> useStream;
  6299. {
  6300. CriticalBlock b(iterCrit);
  6301. if (!iterStream)
  6302. return NULL;
  6303. useStream.set(iterStream);
  6304. }
  6305. const void * next = useStream->nextRow();
  6306. if (next)
  6307. {
  6308. processed++;
  6309. rowsIn++;
  6310. }
  6311. return next;
  6312. }
  6313. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  6314. {
  6315. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  6316. }
  6317. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  6318. {
  6319. ensureCreated();
  6320. basehelper.onStart(parentExtract, NULL);
  6321. processor.noteUseIteration(helper.querySequence());
  6322. }
  6323. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  6324. {
  6325. //helper already initialised from the gatherIterationUsage() call.
  6326. CRoxieServerActivity::connectInputStreams(true);
  6327. iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
  6328. iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
  6329. }
  6330. virtual IInputSteppingMeta * querySteppingMeta()
  6331. {
  6332. assertex(iterInput);
  6333. return iterInput->querySteppingMeta();
  6334. }
  6335. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6336. {
  6337. assertex(iterStream);
  6338. return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6339. }
  6340. };
  6341. //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
  6342. class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
  6343. {
  6344. public:
  6345. CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
  6346. : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
  6347. {
  6348. sequence = _sequence;
  6349. }
  6350. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6351. {
  6352. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6353. if ((int)sequence >= 0)
  6354. {
  6355. try
  6356. {
  6357. iterStream.setown(graph->createGraphLoopResultIterator(sequence));
  6358. iterInput.clear();
  6359. }
  6360. catch (IException * E)
  6361. {
  6362. throw makeWrappedException(E);
  6363. }
  6364. }
  6365. }
  6366. };
  6367. class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  6368. {
  6369. unsigned graphId;
  6370. public:
  6371. CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  6372. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  6373. {
  6374. }
  6375. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6376. {
  6377. return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  6378. }
  6379. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  6380. {
  6381. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
  6382. }
  6383. };
  6384. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  6385. {
  6386. return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  6387. }
  6388. //=====================================================================================================
  6389. class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
  6390. {
  6391. ILocalGraphEx * graph;
  6392. unsigned graphId;
  6393. public:
  6394. CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
  6395. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), graphId(_graphId)
  6396. {
  6397. graph = NULL;
  6398. }
  6399. virtual bool needsAllocator() const { return true; }
  6400. virtual void onCreate(IHThorArg *_colocalParent)
  6401. {
  6402. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  6403. graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
  6404. }
  6405. virtual void onExecute()
  6406. {
  6407. RtlLinkedDatasetBuilder builder(rowAllocator);
  6408. inputStream->readAll(builder);
  6409. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  6410. graph->setGraphLoopResult(result);
  6411. }
  6412. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  6413. {
  6414. if (idx==0)
  6415. return this;
  6416. else
  6417. return NULL;
  6418. }
  6419. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6420. {
  6421. return input->gatherConjunctions(collector);
  6422. }
  6423. virtual void resetEOF()
  6424. {
  6425. inputStream->resetEOF();
  6426. }
  6427. virtual const void *nextRow()
  6428. {
  6429. const void * next = inputStream->nextRow();
  6430. if (next)
  6431. processed++;
  6432. return next;
  6433. }
  6434. virtual bool isPassThrough()
  6435. {
  6436. return true;
  6437. }
  6438. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6439. {
  6440. ActivityTimer t(totalCycles, timeActivities);
  6441. const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6442. if (next)
  6443. processed++;
  6444. return next;
  6445. }
  6446. IInputSteppingMeta * querySteppingMeta()
  6447. {
  6448. return input->querySteppingMeta();
  6449. }
  6450. virtual IOutputMetaData * queryOutputMeta() const
  6451. {
  6452. return input->queryOutputMeta();
  6453. }
  6454. };
  6455. class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
  6456. {
  6457. unsigned graphId;
  6458. public:
  6459. CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6460. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
  6461. {
  6462. isInternal = true;
  6463. Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
  6464. }
  6465. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6466. {
  6467. return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
  6468. }
  6469. };
  6470. IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
  6471. {
  6472. return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
  6473. }
  6474. //=================================================================================
  6475. class CRoxieServerDedupActivity : public CRoxieServerActivity
  6476. {
  6477. protected:
  6478. IHThorDedupArg &helper;
  6479. unsigned numKept;
  6480. unsigned numToKeep;
  6481. public:
  6482. CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6483. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6484. {
  6485. numKept = 0;
  6486. numToKeep = 0;
  6487. }
  6488. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6489. {
  6490. numKept = 0;
  6491. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6492. numToKeep = helper.numToKeep();
  6493. }
  6494. };
  6495. class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
  6496. {
  6497. IRangeCompare * stepCompare;
  6498. const void *prev;
  6499. public:
  6500. CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6501. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
  6502. {
  6503. prev = NULL;
  6504. stepCompare = NULL;
  6505. }
  6506. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6507. {
  6508. prev = NULL;
  6509. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6510. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  6511. stepCompare = NULL;
  6512. if (stepMeta)
  6513. stepCompare = stepMeta->queryCompare();
  6514. }
  6515. virtual void reset()
  6516. {
  6517. ReleaseClearRoxieRow(prev);
  6518. CRoxieServerDedupActivity::reset();
  6519. }
  6520. virtual const void * nextRow()
  6521. {
  6522. ActivityTimer t(totalCycles, timeActivities);
  6523. const void * next;
  6524. for (;;)
  6525. {
  6526. next = inputStream->nextRow();
  6527. if (!prev || !next || !helper.matches(prev,next))
  6528. {
  6529. numKept = 0;
  6530. break;
  6531. }
  6532. if (numKept < numToKeep-1)
  6533. {
  6534. numKept++;
  6535. break;
  6536. }
  6537. ReleaseRoxieRow(next);
  6538. }
  6539. ReleaseRoxieRow(prev);
  6540. prev = next;
  6541. if (next)
  6542. {
  6543. LinkRoxieRow(next);
  6544. processed++;
  6545. }
  6546. return next;
  6547. }
  6548. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  6549. {
  6550. ActivityTimer t(totalCycles, timeActivities);
  6551. const void * next;
  6552. for (;;)
  6553. {
  6554. next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  6555. //If the record was an in-exact match from the index then return it immediately
  6556. //and don't cause it to dedup following legal records.
  6557. if (!wasCompleteMatch)
  6558. {
  6559. assertex(stepExtra.returnMismatches());
  6560. return next;
  6561. }
  6562. if (!prev || !next || !helper.matches(prev,next))
  6563. {
  6564. numKept = 0;
  6565. break;
  6566. }
  6567. if (numKept < numToKeep-1)
  6568. {
  6569. numKept++;
  6570. break;
  6571. }
  6572. //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
  6573. if (stepExtra.returnMismatches())
  6574. {
  6575. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  6576. //condition to advance
  6577. if (stepCompare->docompare(next, seek, numFields) != 0)
  6578. {
  6579. wasCompleteMatch = false;
  6580. break;
  6581. }
  6582. }
  6583. ReleaseRoxieRow(next);
  6584. }
  6585. ReleaseRoxieRow(prev);
  6586. prev = next;
  6587. if (next)
  6588. {
  6589. LinkRoxieRow(next);
  6590. processed++;
  6591. }
  6592. return next;
  6593. }
  6594. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  6595. {
  6596. return input->gatherConjunctions(collector);
  6597. }
  6598. virtual void resetEOF()
  6599. {
  6600. inputStream->resetEOF();
  6601. }
  6602. IInputSteppingMeta * querySteppingMeta()
  6603. {
  6604. return input->querySteppingMeta();
  6605. }
  6606. };
  6607. //=================================================================================
  6608. class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
  6609. {
  6610. const void *kept;
  6611. bool first;
  6612. ICompare * compareBest;
  6613. public:
  6614. CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6615. : CRoxieServerDedupActivity(_ctx, _factory, _probeManager), compareBest(nullptr)
  6616. {
  6617. kept = nullptr;
  6618. first = true;
  6619. if (helper.keepBest())
  6620. compareBest = helper.queryCompareBest();
  6621. }
  6622. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6623. {
  6624. first = true;
  6625. kept = nullptr;
  6626. CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
  6627. if (numToKeep>1)
  6628. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "DEDUP with RIGHT and NumToKeep>1 not supported");
  6629. }
  6630. virtual void reset()
  6631. {
  6632. ReleaseClearRoxieRow(kept);
  6633. CRoxieServerActivity::reset();
  6634. }
  6635. virtual const void * nextRow()
  6636. {
  6637. ActivityTimer t(totalCycles, timeActivities);
  6638. if (first)
  6639. {
  6640. kept = inputStream->nextRow();
  6641. first = false;
  6642. }
  6643. const void * next;
  6644. for (;;)
  6645. {
  6646. next = inputStream->nextRow();
  6647. if (!kept || !next || !helper.matches(kept,next))
  6648. break;
  6649. if (compareBest && compareBest->docompare(kept,next) <= 0)
  6650. continue;
  6651. ReleaseRoxieRow(kept);
  6652. kept = next;
  6653. }
  6654. const void * ret = kept;
  6655. kept = next;
  6656. // CTXLOG("dedup returns %p", ret);
  6657. if (ret) processed++;
  6658. return ret;
  6659. }
  6660. };
  6661. class CRoxieServerDedupAllActivity : public CRoxieServerActivity
  6662. {
  6663. IHThorDedupArg &helper;
  6664. unsigned survivorIndex;
  6665. ConstPointerArray survivors;
  6666. bool keepLeft;
  6667. bool eof;
  6668. bool first;
  6669. ICompare *primaryCompare;
  6670. public:
  6671. CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
  6672. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
  6673. {
  6674. keepLeft = _keepLeft;
  6675. primaryCompare = helper.queryComparePrimary();
  6676. eof = false;
  6677. first = true;
  6678. survivorIndex = 0;
  6679. }
  6680. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6681. {
  6682. eof = false;
  6683. first = true;
  6684. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6685. }
  6686. virtual void reset()
  6687. {
  6688. while (survivors.isItem(survivorIndex))
  6689. {
  6690. ReleaseRoxieRow(survivors.item(survivorIndex++));
  6691. }
  6692. survivors.kill();
  6693. eof = false;
  6694. first = true;
  6695. CRoxieServerActivity::reset();
  6696. }
  6697. void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
  6698. {
  6699. for (unsigned idxL = first; idxL < last; idxL++)
  6700. {
  6701. const void * left = group.item(idxL);
  6702. if (left)
  6703. {
  6704. for (unsigned idxR = first; idxR < last; idxR++)
  6705. {
  6706. const void * right = group.item(idxR);
  6707. if ((idxL != idxR) && right)
  6708. {
  6709. if (helper.matches(left, right))
  6710. {
  6711. if (keepLeft)
  6712. {
  6713. group.replace(NULL, idxR);
  6714. ReleaseRoxieRow(right);
  6715. }
  6716. else
  6717. {
  6718. group.replace(NULL, idxL);
  6719. ReleaseRoxieRow(left);
  6720. break;
  6721. }
  6722. }
  6723. }
  6724. }
  6725. }
  6726. }
  6727. }
  6728. void dedupRange(unsigned first, unsigned last, void ** rows)
  6729. {
  6730. for (unsigned idxL = first; idxL < last; idxL++)
  6731. {
  6732. void * left = rows[idxL];
  6733. if (left)
  6734. {
  6735. for (unsigned idxR = first; idxR < last; idxR++)
  6736. {
  6737. void * right = rows[idxR];
  6738. if ((idxL != idxR) && right)
  6739. {
  6740. if (helper.matches(left, right))
  6741. {
  6742. if (keepLeft)
  6743. {
  6744. rows[idxR] = NULL;
  6745. ReleaseRoxieRow(right);
  6746. }
  6747. else
  6748. {
  6749. rows[idxL] = NULL;
  6750. ReleaseRoxieRow(left);
  6751. break;
  6752. }
  6753. }
  6754. }
  6755. }
  6756. }
  6757. }
  6758. }
  6759. bool calcNextDedupAll()
  6760. {
  6761. survivors.kill();
  6762. survivorIndex = 0;
  6763. ConstPointerArray group;
  6764. if (eof || !inputStream->nextGroup(group))
  6765. {
  6766. eof = true;
  6767. return false;
  6768. }
  6769. unsigned max = group.ordinality();
  6770. if (primaryCompare)
  6771. {
  6772. //hard, if not impossible, to hit this code once optimisations in place
  6773. MemoryAttr indexbuff(max*sizeof(void *));
  6774. void ** temp = (void **)indexbuff.bufferBase();
  6775. void * *rows = const_cast<void * *>(group.getArray());
  6776. msortvecstableinplace(rows, max, *primaryCompare, temp);
  6777. unsigned first = 0;
  6778. for (unsigned idx = 1; idx < max; idx++)
  6779. {
  6780. if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
  6781. {
  6782. dedupRange(first, idx, rows);
  6783. first = idx;
  6784. }
  6785. }
  6786. dedupRange(first, max, rows);
  6787. for(unsigned idx2=0; idx2<max; ++idx2)
  6788. {
  6789. void * cur = rows[idx2];
  6790. if(cur)
  6791. survivors.append(cur);
  6792. }
  6793. }
  6794. else
  6795. {
  6796. dedupRange(0, max, group);
  6797. for(unsigned idx=0; idx<max; ++idx)
  6798. {
  6799. const void * cur = group.item(idx);
  6800. if(cur)
  6801. survivors.append(cur);
  6802. }
  6803. }
  6804. return true;
  6805. }
  6806. virtual const void *nextRow()
  6807. {
  6808. ActivityTimer t(totalCycles, timeActivities);
  6809. if (first)
  6810. {
  6811. calcNextDedupAll();
  6812. first = false;
  6813. }
  6814. while (survivors.isItem(survivorIndex))
  6815. {
  6816. const void *ret = survivors.item(survivorIndex++);
  6817. if (ret)
  6818. {
  6819. processed++;
  6820. return ret;
  6821. }
  6822. }
  6823. calcNextDedupAll();
  6824. return NULL;
  6825. }
  6826. };
  6827. class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
  6828. {
  6829. bool compareAll;
  6830. bool keepLeft;
  6831. bool keepBest;
  6832. public:
  6833. CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6834. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  6835. {
  6836. Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
  6837. compareAll = helper->compareAll();
  6838. keepLeft = helper->keepLeft();
  6839. keepBest = helper->keepBest();
  6840. }
  6841. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  6842. {
  6843. if (compareAll)
  6844. return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
  6845. else if (keepLeft && !keepBest)
  6846. return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
  6847. else
  6848. return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
  6849. }
  6850. };
  6851. IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  6852. {
  6853. return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  6854. }
  6855. //=================================================================================
  6856. class CRoxieServerHashDedupActivity : public CRoxieServerActivity
  6857. {
  6858. bool eof;
  6859. IHThorHashDedupArg &helper;
  6860. class HashDedupElement
  6861. {
  6862. public:
  6863. HashDedupElement(unsigned _hash, const void *_keyRow)
  6864. : hash(_hash), keyRow(_keyRow)
  6865. {
  6866. }
  6867. ~HashDedupElement()
  6868. {
  6869. ReleaseRoxieRow(keyRow);
  6870. }
  6871. inline unsigned queryHash() const
  6872. {
  6873. return hash;
  6874. }
  6875. inline const void *queryRow() const
  6876. {
  6877. return keyRow;
  6878. }
  6879. inline const void *getRowClear()
  6880. {
  6881. const void * row = keyRow;
  6882. keyRow = nullptr;
  6883. return row;
  6884. }
  6885. private:
  6886. unsigned hash;
  6887. const void *keyRow;
  6888. };
  6889. static CClassMeta<HashDedupElement> hashDedupElementMeta;
  6890. class HashDedupTable : public SuperHashTable
  6891. {
  6892. public:
  6893. HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
  6894. : helper(_helper),
  6895. keySize(helper.queryKeySize()),
  6896. activity(_activity)
  6897. {
  6898. bestCompare=helper.queryCompareBest();
  6899. }
  6900. virtual ~HashDedupTable()
  6901. {
  6902. //elementRowAllocator is a unique allocator, so all rows can be freed in a single call
  6903. elementRowAllocator->releaseAllRows();
  6904. tablecount = 0;
  6905. }
  6906. virtual unsigned getHashFromElement(const void *et) const
  6907. {
  6908. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6909. return element->queryHash();
  6910. }
  6911. virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
  6912. virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
  6913. virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
  6914. virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
  6915. {
  6916. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6917. if (fphash != element->queryHash())
  6918. return false;
  6919. return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
  6920. }
  6921. virtual void onAdd(void *et) {}
  6922. virtual void onRemove(void *et)
  6923. {
  6924. ReleaseRoxieRow(et);
  6925. }
  6926. void onCreate(IRoxieSlaveContext *ctx)
  6927. {
  6928. keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
  6929. elementRowAllocator.setown(activity.createRowAllocatorEx(&hashDedupElementMeta, roxiemem::RHFunique|roxiemem::RHFscanning|roxiemem::RHFdelayrelease));
  6930. }
  6931. void reset()
  6932. {
  6933. kill();
  6934. }
  6935. bool insert(const void * row)
  6936. {
  6937. unsigned hash = helper.queryHash()->hash(row);
  6938. RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
  6939. size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
  6940. OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
  6941. if (find(hash, keyRow.get()))
  6942. return false;
  6943. addNew(createElement(hash, keyRow.getClear()), hash);
  6944. return true;
  6945. }
  6946. bool insertBest(const void * nextrow)
  6947. {
  6948. unsigned hash = helper.queryHash()->hash(nextrow);
  6949. const void *et = find(hash, nextrow);
  6950. if (et)
  6951. {
  6952. const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
  6953. const void * row = element->queryRow();
  6954. if (bestCompare->docompare(row,nextrow) <= 0)
  6955. return false;
  6956. removeExact( const_cast<void *>(et));
  6957. // drop-through to add new row
  6958. }
  6959. addNew(createElement(hash, nextrow), hash);
  6960. return true;
  6961. }
  6962. void gatherStats(CRuntimeStatisticCollection & merged) const
  6963. {
  6964. if (keyRowAllocator)
  6965. keyRowAllocator->gatherStats(merged);
  6966. }
  6967. private:
  6968. inline void *createElement(unsigned hash, const void *row)
  6969. {
  6970. return elementRowAllocator->finalizeRow(sizeof(HashDedupElement), new (elementRowAllocator->createRow()) HashDedupElement(hash, row), sizeof(HashDedupElement));
  6971. }
  6972. IHThorHashDedupArg & helper;
  6973. CachedOutputMetaData keySize;
  6974. Owned<IEngineRowAllocator> keyRowAllocator;
  6975. Owned<IEngineRowAllocator> elementRowAllocator;
  6976. CRoxieServerHashDedupActivity & activity;
  6977. ICompare * bestCompare;
  6978. } table;
  6979. public:
  6980. CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  6981. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this), hashTableFilled(false), hashDedupTableIter(table)
  6982. {
  6983. eof = false;
  6984. keepBest = helper.keepBest();
  6985. }
  6986. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  6987. {
  6988. eof = false;
  6989. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  6990. }
  6991. virtual void onCreate(IHThorArg *_colocalParent)
  6992. {
  6993. CRoxieServerActivity::onCreate(colocalParent);
  6994. table.onCreate(ctx);
  6995. }
  6996. virtual void reset()
  6997. {
  6998. table.reset();
  6999. eof = false;
  7000. CRoxieServerActivity::reset();
  7001. hashTableFilled = false;
  7002. }
  7003. virtual const void *nextRow()
  7004. {
  7005. ActivityTimer t(totalCycles, timeActivities);
  7006. if (keepBest)
  7007. {
  7008. if (eof)
  7009. return NULL;
  7010. // Populate hash table with best rows
  7011. if (!hashTableFilled)
  7012. {
  7013. const void * next = inputStream->nextRow();
  7014. while(next)
  7015. {
  7016. if (!table.insertBest(next))
  7017. ReleaseRoxieRow(next);
  7018. next = inputStream->nextRow();
  7019. }
  7020. if (table.count() == 0)
  7021. eof = true;
  7022. hashTableFilled = true;
  7023. hashDedupTableIter.first();
  7024. }
  7025. // Iterate throw hash table returning rows
  7026. if (hashDedupTableIter.isValid())
  7027. {
  7028. HashDedupElement &el = hashDedupTableIter.query();
  7029. const void * row = el.getRowClear();
  7030. hashDedupTableIter.next();
  7031. return row;
  7032. }
  7033. table.reset();
  7034. hashTableFilled = false;
  7035. return NULL;
  7036. }
  7037. else
  7038. {
  7039. while(!eof)
  7040. {
  7041. const void * next = inputStream->nextRow();
  7042. if(!next)
  7043. {
  7044. if (table.count() == 0)
  7045. eof = true;
  7046. table.reset();
  7047. return NULL;
  7048. }
  7049. if(table.insert(next))
  7050. return next;
  7051. else
  7052. ReleaseRoxieRow(next);
  7053. }
  7054. return NULL;
  7055. }
  7056. }
  7057. private:
  7058. bool keepBest;
  7059. bool hashTableFilled;
  7060. SuperHashIteratorOf<HashDedupElement> hashDedupTableIter;
  7061. };
  7062. CClassMeta<CRoxieServerHashDedupActivity::HashDedupElement> CRoxieServerHashDedupActivity::hashDedupElementMeta;
  7063. class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
  7064. {
  7065. public:
  7066. CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7067. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7068. {
  7069. }
  7070. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7071. {
  7072. return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
  7073. }
  7074. };
  7075. IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7076. {
  7077. return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7078. }
  7079. //=================================================================================
  7080. class CRoxieServerRollupActivity : public CRoxieServerActivity
  7081. {
  7082. IHThorRollupArg &helper;
  7083. OwnedConstRoxieRow left;
  7084. OwnedConstRoxieRow prev;
  7085. OwnedConstRoxieRow right;
  7086. bool readFirstRow;
  7087. public:
  7088. CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7089. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
  7090. {
  7091. readFirstRow = false;
  7092. }
  7093. ~CRoxieServerRollupActivity()
  7094. {
  7095. }
  7096. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7097. {
  7098. readFirstRow = false;
  7099. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7100. }
  7101. virtual void reset()
  7102. {
  7103. left.clear();
  7104. prev.clear();
  7105. right.clear();
  7106. CRoxieServerActivity::reset();
  7107. }
  7108. virtual bool needsAllocator() const { return true; }
  7109. virtual const void * nextRow()
  7110. {
  7111. ActivityTimer t(totalCycles, timeActivities);
  7112. if (!readFirstRow)
  7113. {
  7114. left.setown(inputStream->nextRow());
  7115. prev.set(left);
  7116. readFirstRow = true;
  7117. }
  7118. for (;;)
  7119. {
  7120. right.setown(inputStream->nextRow());
  7121. if(!prev || !right || !helper.matches(prev,right))
  7122. {
  7123. const void * ret = left.getClear();
  7124. if(ret)
  7125. processed++;
  7126. left.setown(right.getClear());
  7127. prev.set(left);
  7128. return ret;
  7129. }
  7130. try
  7131. {
  7132. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7133. unsigned outSize = helper.transform(rowBuilder, left, right);
  7134. if (outSize)
  7135. left.setown(rowBuilder.finalizeRowClear(outSize));
  7136. if (helper.getFlags() & RFrolledismatchleft)
  7137. prev.set(left);
  7138. else
  7139. prev.set(right);
  7140. }
  7141. catch(IException * E)
  7142. {
  7143. throw makeWrappedException(E);
  7144. }
  7145. }
  7146. }
  7147. };
  7148. class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
  7149. {
  7150. public:
  7151. CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7152. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7153. {
  7154. }
  7155. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7156. {
  7157. return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
  7158. }
  7159. };
  7160. IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7161. {
  7162. return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7163. }
  7164. //=================================================================================
  7165. class CRoxieServerNormalizeActivity : public CRoxieServerActivity
  7166. {
  7167. IHThorNormalizeArg &helper;
  7168. unsigned numThisRow;
  7169. unsigned curRow;
  7170. const void *buffer;
  7171. unsigned numProcessedLastGroup;
  7172. public:
  7173. CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7174. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
  7175. {
  7176. buffer = NULL;
  7177. numThisRow = 0;
  7178. curRow = 0;
  7179. numProcessedLastGroup = 0;
  7180. }
  7181. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7182. {
  7183. numThisRow = 0;
  7184. curRow = 0;
  7185. numProcessedLastGroup = 0;
  7186. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7187. }
  7188. virtual void reset()
  7189. {
  7190. ReleaseClearRoxieRow(buffer);
  7191. CRoxieServerActivity::reset();
  7192. }
  7193. virtual bool needsAllocator() const { return true; }
  7194. virtual const void * nextRow()
  7195. {
  7196. ActivityTimer t(totalCycles, timeActivities);
  7197. for (;;)
  7198. {
  7199. while (curRow == numThisRow)
  7200. {
  7201. if (buffer)
  7202. ReleaseClearRoxieRow(buffer);
  7203. buffer = inputStream->nextRow();
  7204. if (!buffer && (processed == numProcessedLastGroup))
  7205. buffer = inputStream->nextRow();
  7206. if (!buffer)
  7207. {
  7208. numProcessedLastGroup = processed;
  7209. return NULL;
  7210. }
  7211. curRow = 0;
  7212. numThisRow = helper.numExpandedRows(buffer);
  7213. }
  7214. try
  7215. {
  7216. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7217. unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
  7218. if (actualSize != 0)
  7219. {
  7220. processed++;
  7221. return rowBuilder.finalizeRowClear(actualSize);
  7222. }
  7223. }
  7224. catch (IException *E)
  7225. {
  7226. throw makeWrappedException(E);
  7227. }
  7228. }
  7229. }
  7230. };
  7231. class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
  7232. {
  7233. public:
  7234. CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7235. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7236. {
  7237. }
  7238. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7239. {
  7240. return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
  7241. }
  7242. };
  7243. IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7244. {
  7245. return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7246. }
  7247. //=================================================================================
  7248. class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
  7249. {
  7250. IHThorNormalizeChildArg &helper;
  7251. unsigned numThisRow;
  7252. unsigned curRow;
  7253. const void *buffer;
  7254. unsigned numProcessedLastGroup;
  7255. INormalizeChildIterator * cursor;
  7256. const void * curChildRow;
  7257. bool advanceInput()
  7258. {
  7259. for (;;)
  7260. {
  7261. ReleaseClearRoxieRow(buffer);
  7262. buffer = inputStream->nextRow();
  7263. if (!buffer && (processed == numProcessedLastGroup))
  7264. buffer = inputStream->nextRow();
  7265. if (!buffer)
  7266. {
  7267. numProcessedLastGroup = processed;
  7268. return false;
  7269. }
  7270. curChildRow = cursor->first(buffer);
  7271. if (curChildRow)
  7272. {
  7273. curRow = 0;
  7274. return true;
  7275. }
  7276. }
  7277. }
  7278. public:
  7279. CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7280. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
  7281. {
  7282. buffer = NULL;
  7283. cursor = NULL;
  7284. numThisRow = 0;
  7285. curRow = 0;
  7286. numProcessedLastGroup = 0;
  7287. curChildRow = NULL;
  7288. }
  7289. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7290. {
  7291. numThisRow = 0;
  7292. curRow = 0;
  7293. numProcessedLastGroup = 0;
  7294. curChildRow = NULL;
  7295. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7296. cursor = helper.queryIterator();
  7297. }
  7298. virtual void stop()
  7299. {
  7300. CRoxieServerActivity::stop();
  7301. }
  7302. virtual void reset()
  7303. {
  7304. cursor = NULL;
  7305. ReleaseClearRoxieRow(buffer);
  7306. CRoxieServerActivity::reset();
  7307. }
  7308. virtual bool needsAllocator() const { return true; }
  7309. const void *nextRow()
  7310. {
  7311. ActivityTimer t(totalCycles, timeActivities);
  7312. for (;;)
  7313. {
  7314. if (!buffer)
  7315. {
  7316. if (!advanceInput())
  7317. return NULL;
  7318. }
  7319. try
  7320. {
  7321. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7322. size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
  7323. curChildRow = cursor->next();
  7324. if (!curChildRow)
  7325. ReleaseClearRoxieRow(buffer);
  7326. if (outSize != 0)
  7327. {
  7328. processed++;
  7329. return rowBuilder.finalizeRowClear(outSize);
  7330. }
  7331. }
  7332. catch (IException *E)
  7333. {
  7334. throw makeWrappedException(E);
  7335. }
  7336. }
  7337. }
  7338. };
  7339. class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
  7340. {
  7341. public:
  7342. CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7343. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7344. {
  7345. }
  7346. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7347. {
  7348. return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
  7349. }
  7350. };
  7351. IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7352. {
  7353. return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7354. }
  7355. //=================================================================================
  7356. class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
  7357. {
  7358. IHThorNormalizeLinkedChildArg &helper;
  7359. OwnedConstRoxieRow curParent;
  7360. OwnedConstRoxieRow curChild;
  7361. unsigned numProcessedLastGroup;
  7362. bool advanceInput()
  7363. {
  7364. for (;;)
  7365. {
  7366. curParent.setown(inputStream->nextRow());
  7367. if (!curParent && (processed == numProcessedLastGroup))
  7368. curParent.setown(inputStream->nextRow());
  7369. if (!curParent)
  7370. {
  7371. numProcessedLastGroup = processed;
  7372. return false;
  7373. }
  7374. curChild.set(helper.first(curParent));
  7375. if (curChild)
  7376. return true;
  7377. }
  7378. }
  7379. public:
  7380. CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7381. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
  7382. {
  7383. numProcessedLastGroup = 0;
  7384. }
  7385. ~CRoxieServerNormalizeLinkedChildActivity()
  7386. {
  7387. }
  7388. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7389. {
  7390. numProcessedLastGroup = 0;
  7391. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7392. }
  7393. virtual void reset()
  7394. {
  7395. curParent.clear();
  7396. curChild.clear();
  7397. CRoxieServerActivity::reset();
  7398. }
  7399. const void *nextRow()
  7400. {
  7401. ActivityTimer t(totalCycles, timeActivities);
  7402. for (;;)
  7403. {
  7404. if (!curParent)
  7405. {
  7406. if (!advanceInput())
  7407. return NULL;
  7408. }
  7409. try
  7410. {
  7411. const void *ret = curChild.getClear();
  7412. curChild.set(helper.next());
  7413. if (!curChild)
  7414. curParent.clear();
  7415. if (ret)
  7416. {
  7417. processed++;
  7418. return ret;
  7419. }
  7420. }
  7421. catch (IException *E)
  7422. {
  7423. throw makeWrappedException(E);
  7424. }
  7425. }
  7426. }
  7427. };
  7428. class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
  7429. {
  7430. public:
  7431. CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7432. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7433. {
  7434. }
  7435. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7436. {
  7437. return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
  7438. }
  7439. };
  7440. IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7441. {
  7442. return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7443. }
  7444. //=================================================================================
  7445. class CRoxieServerSortActivity : public CRoxieServerActivity
  7446. {
  7447. protected:
  7448. IHThorSortArg &helper;
  7449. ICompare *compare;
  7450. Owned<ISortAlgorithm> sorter;
  7451. bool readInput;
  7452. RoxieSortAlgorithm sortAlgorithm;
  7453. unsigned sortFlags;
  7454. public:
  7455. CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
  7456. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
  7457. {
  7458. compare = helper.queryCompare();
  7459. readInput = false;
  7460. }
  7461. virtual void onCreate(IHThorArg *_colocalParent)
  7462. {
  7463. CRoxieServerActivity::onCreate(_colocalParent);
  7464. if (sortAlgorithm==unknownSortAlgorithm)
  7465. sorter.clear();
  7466. else
  7467. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7468. }
  7469. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7470. {
  7471. assertex(!readInput);
  7472. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7473. }
  7474. virtual void reset()
  7475. {
  7476. if (sorter)
  7477. sorter->reset();
  7478. readInput = false;
  7479. CRoxieServerActivity::reset();
  7480. }
  7481. static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
  7482. {
  7483. RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
  7484. if (!algorithmName)
  7485. algorithmName = "";
  7486. if (stricmp(algorithmName, "quicksort")==0)
  7487. {
  7488. switch (sortFlags & (TAFstable|TAFspill))
  7489. {
  7490. case 0: sortAlgorithm = quickSortAlgorithm; break;
  7491. case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
  7492. case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
  7493. case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
  7494. }
  7495. }
  7496. else if (stricmp(algorithmName, "parquicksort")==0)
  7497. {
  7498. switch (sortFlags & TAFstable)
  7499. {
  7500. case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
  7501. case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
  7502. default: throwUnexpected();
  7503. }
  7504. }
  7505. else if (stricmp(algorithmName, "heapsort")==0)
  7506. sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
  7507. else if (stricmp(algorithmName, "mergesort")==0)
  7508. sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
  7509. else if (stricmp(algorithmName, "parmergesort")==0)
  7510. sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
  7511. else if (stricmp(algorithmName, "tbbqsort")==0)
  7512. sortAlgorithm = tbbQuickSortAlgorithm;
  7513. else if (stricmp(algorithmName, "tbbstableqsort")==0)
  7514. sortAlgorithm = tbbStableQuickSortAlgorithm;
  7515. else
  7516. {
  7517. if (*algorithmName)
  7518. OWARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
  7519. if (sortFlags & TAFspill)
  7520. sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
  7521. else if (sortFlags & TAFunstable)
  7522. sortAlgorithm = quickSortAlgorithm;
  7523. else
  7524. sortAlgorithm = heapSortAlgorithm;
  7525. }
  7526. return sortAlgorithm;
  7527. }
  7528. virtual const void * nextRow()
  7529. {
  7530. ActivityTimer t(totalCycles, timeActivities);
  7531. if (!readInput)
  7532. {
  7533. if (sortAlgorithm == unknownSortAlgorithm)
  7534. {
  7535. sorter.clear();
  7536. OwnedRoxieString algorithmName(helper.getAlgorithm());
  7537. sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
  7538. sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
  7539. }
  7540. sorter->prepare(inputStream);
  7541. noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
  7542. readInput = true;
  7543. }
  7544. const void *ret = sorter->next();
  7545. if (ret)
  7546. processed++;
  7547. else
  7548. {
  7549. sorter->reset();
  7550. readInput = false; // ready for next group
  7551. }
  7552. return ret;
  7553. }
  7554. };
  7555. class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
  7556. {
  7557. RoxieSortAlgorithm sortAlgorithm;
  7558. unsigned sortFlags;
  7559. public:
  7560. CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7561. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7562. {
  7563. Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
  7564. const char *algorithmName = NULL;
  7565. sortFlags = sortHelper->getAlgorithmFlags();
  7566. if (sortFlags & TAFconstant)
  7567. algorithmName = sortHelper->getAlgorithm();
  7568. bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
  7569. if (forceSpill)
  7570. sortFlags |= TAFspill;
  7571. if (!(sortFlags & TAFunstable))
  7572. sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
  7573. if (sortFlags & TAFconstant)
  7574. sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
  7575. else
  7576. sortAlgorithm = unknownSortAlgorithm;
  7577. }
  7578. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7579. {
  7580. return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
  7581. }
  7582. virtual const StatisticsMapping &queryStatsMapping() const
  7583. {
  7584. return sortStatistics;
  7585. }
  7586. };
  7587. IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7588. {
  7589. return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7590. }
  7591. //=====================================================================================================
  7592. static int compareUint64(const void * _left, const void * _right)
  7593. {
  7594. const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
  7595. const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
  7596. if (left < right)
  7597. return -1;
  7598. if (left > right)
  7599. return -1;
  7600. return 0;
  7601. }
  7602. class CRoxieServerQuantileActivity : public CRoxieServerActivity
  7603. {
  7604. protected:
  7605. Owned<ISortAlgorithm> sorter;
  7606. IHThorQuantileArg &helper;
  7607. ConstPointerArray sorted;
  7608. ICompare *compare;
  7609. unsigned flags;
  7610. double skew;
  7611. unsigned __int64 numDivisions;
  7612. bool rangeIsAll;
  7613. size32_t rangeSize;
  7614. rtlDataAttr rangeValues;
  7615. bool calculated;
  7616. bool processedAny;
  7617. bool anyThisGroup;
  7618. bool eof;
  7619. unsigned curQuantile;
  7620. unsigned curIndex;
  7621. unsigned curIndexExtra;
  7622. unsigned skipSize;
  7623. unsigned skipExtra;
  7624. unsigned prevIndex;
  7625. public:
  7626. CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
  7627. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
  7628. {
  7629. compare = helper.queryCompare();
  7630. skew = 0.0;
  7631. numDivisions = 0;
  7632. calculated = false;
  7633. processedAny = false;
  7634. anyThisGroup = false;
  7635. eof = false;
  7636. rangeIsAll = true;
  7637. rangeSize = 0;
  7638. curQuantile = 0;
  7639. prevIndex = 0;
  7640. curIndex = 0;
  7641. curIndexExtra = 0;
  7642. skipSize = 0;
  7643. skipExtra = 0;
  7644. if (flags & TQFunstable)
  7645. sorter.setown(createQuickSortAlgorithm(compare));
  7646. else
  7647. sorter.setown(createMergeSortAlgorithm(compare));
  7648. }
  7649. virtual void reset()
  7650. {
  7651. sorter->reset();
  7652. calculated = false;
  7653. processedAny = false;
  7654. anyThisGroup = false;
  7655. ReleaseRoxieRows(sorted);
  7656. CRoxieServerActivity::reset();
  7657. }
  7658. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7659. {
  7660. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7661. skew = helper.getSkew();
  7662. numDivisions = helper.getNumDivisions();
  7663. //Check for -ve integer values and treat as out of range
  7664. if ((__int64)numDivisions < 1)
  7665. numDivisions = 1;
  7666. if (flags & TQFhasrange)
  7667. helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
  7668. else
  7669. {
  7670. rangeIsAll = true;
  7671. rangeSize = 0;
  7672. }
  7673. if (rangeSize)
  7674. {
  7675. //Sort the range items into order to allow quick comparison
  7676. qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
  7677. }
  7678. calculated = false;
  7679. processedAny = false;
  7680. anyThisGroup = false;
  7681. eof = false;
  7682. curQuantile = 0;
  7683. prevIndex = 0;
  7684. curIndex = 0;
  7685. curIndexExtra = 0;
  7686. }
  7687. virtual bool needsAllocator() const { return true; }
  7688. virtual const void * nextRow()
  7689. {
  7690. ActivityTimer t(totalCycles, timeActivities);
  7691. if (eof)
  7692. return NULL;
  7693. const void * ret = NULL;
  7694. for(;;)
  7695. {
  7696. if (!calculated)
  7697. {
  7698. if (flags & TQFlocalsorted)
  7699. {
  7700. for (;;)
  7701. {
  7702. const void * next = inputStream->nextRow();
  7703. if (!next)
  7704. break;
  7705. sorted.append(next);
  7706. }
  7707. }
  7708. else
  7709. {
  7710. sorter->prepare(inputStream);
  7711. sorter->getSortedGroup(sorted);
  7712. }
  7713. if (sorted.ordinality() == 0)
  7714. {
  7715. if (processedAny)
  7716. {
  7717. eof = true;
  7718. return NULL;
  7719. }
  7720. //Unusual case 0 rows - add a default row instead
  7721. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7722. size32_t thisSize = helper.createDefault(rowBuilder);
  7723. sorted.append(rowBuilder.finalizeRowClear(thisSize));
  7724. }
  7725. calculated = true;
  7726. processedAny = true;
  7727. anyThisGroup = false;
  7728. curQuantile = 0;
  7729. curIndex = 0;
  7730. curIndexExtra = (unsigned)((numDivisions-1) / 2); // to ensure correctly rounded up
  7731. prevIndex = curIndex-1; // Ensure it doesn't match
  7732. skipSize = (unsigned)(sorted.ordinality() / numDivisions);
  7733. skipExtra = (unsigned)(sorted.ordinality() % numDivisions);
  7734. }
  7735. if (isQuantileIncluded(curQuantile))
  7736. {
  7737. if (!(flags & TQFdedup) || (prevIndex != curIndex))
  7738. {
  7739. const void * lhs = sorted.item(curIndex);
  7740. if (flags & TQFneedtransform)
  7741. {
  7742. unsigned outSize;
  7743. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  7744. try
  7745. {
  7746. outSize = helper.transform(rowBuilder, lhs, curQuantile);
  7747. }
  7748. catch (IException *E)
  7749. {
  7750. throw makeWrappedException(E);
  7751. }
  7752. if (outSize)
  7753. ret = rowBuilder.finalizeRowClear(outSize);
  7754. }
  7755. else
  7756. {
  7757. LinkRoxieRow(lhs);
  7758. ret = lhs;
  7759. }
  7760. prevIndex = curIndex; // even if output was skipped?
  7761. }
  7762. }
  7763. curIndex += skipSize;
  7764. curIndexExtra += skipExtra;
  7765. if (curIndexExtra >= numDivisions)
  7766. {
  7767. curIndex++;
  7768. curIndexExtra -= numDivisions;
  7769. }
  7770. //Ensure the current index always stays valid.
  7771. if (curIndex >= sorted.ordinality())
  7772. curIndex = sorted.ordinality()-1;
  7773. curQuantile++;
  7774. if (curQuantile > numDivisions)
  7775. {
  7776. ReleaseRoxieRows(sorted);
  7777. sorter->reset();
  7778. calculated = false; // ready for next group
  7779. }
  7780. if (ret)
  7781. {
  7782. anyThisGroup = true;
  7783. processed++;
  7784. return ret;
  7785. }
  7786. if (curQuantile > numDivisions)
  7787. {
  7788. if (anyThisGroup)
  7789. return NULL;
  7790. }
  7791. }
  7792. }
  7793. bool isQuantileIncluded(unsigned quantile) const
  7794. {
  7795. if (quantile == 0)
  7796. return (flags & TQFfirst) != 0;
  7797. if (quantile == numDivisions)
  7798. return (flags & TQFlast) != 0;
  7799. if (rangeIsAll)
  7800. return true;
  7801. //Compare against the list of ranges provided
  7802. //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
  7803. unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
  7804. const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
  7805. for (unsigned i = 0; i < rangeNum; i++)
  7806. {
  7807. if (ranges[i] == quantile)
  7808. return true;
  7809. }
  7810. return false;
  7811. }
  7812. };
  7813. class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
  7814. {
  7815. unsigned flags;
  7816. public:
  7817. CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7818. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7819. {
  7820. Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
  7821. flags = quantileHelper->getFlags();
  7822. }
  7823. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7824. {
  7825. return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
  7826. }
  7827. };
  7828. IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7829. {
  7830. return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7831. }
  7832. //=====================================================================================================
  7833. class CRoxieServerSortedActivity : public CRoxieServerActivity
  7834. {
  7835. IHThorSortedArg &helper;
  7836. ICompare * compare;
  7837. const void *prev;
  7838. IRangeCompare * stepCompare;
  7839. public:
  7840. CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  7841. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
  7842. {
  7843. prev = NULL;
  7844. compare = helper.queryCompare();
  7845. stepCompare = NULL;
  7846. }
  7847. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  7848. {
  7849. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  7850. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  7851. if (stepMeta)
  7852. stepCompare = stepMeta->queryCompare();
  7853. prev = NULL;
  7854. }
  7855. virtual void reset()
  7856. {
  7857. ReleaseClearRoxieRow(prev);
  7858. CRoxieServerActivity::reset();
  7859. }
  7860. virtual const void * nextRow()
  7861. {
  7862. ActivityTimer t(totalCycles, timeActivities);
  7863. const void *ret = inputStream->nextRow();
  7864. if (ret && prev && compare->docompare(prev, ret) > 0)
  7865. {
  7866. // MORE - better to give mismatching rows that indexes?
  7867. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7868. }
  7869. ReleaseRoxieRow(prev);
  7870. prev = ret;
  7871. if (ret)
  7872. {
  7873. LinkRoxieRow(prev);
  7874. processed++;
  7875. }
  7876. return ret;
  7877. }
  7878. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  7879. {
  7880. ActivityTimer t(totalCycles, timeActivities);
  7881. const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  7882. if (ret && prev && compare->docompare(prev, ret) > 0)
  7883. {
  7884. // MORE - better to give mismatching rows that indexes?
  7885. throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
  7886. }
  7887. ReleaseRoxieRow(prev);
  7888. prev = ret;
  7889. if (ret)
  7890. {
  7891. LinkRoxieRow(prev);
  7892. processed++;
  7893. }
  7894. return ret;
  7895. }
  7896. IInputSteppingMeta * querySteppingMeta()
  7897. {
  7898. return input->querySteppingMeta();
  7899. }
  7900. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  7901. {
  7902. return input->gatherConjunctions(collector);
  7903. }
  7904. virtual void resetEOF()
  7905. {
  7906. inputStream->resetEOF();
  7907. }
  7908. };
  7909. class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
  7910. {
  7911. public:
  7912. CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7913. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  7914. {
  7915. }
  7916. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  7917. {
  7918. return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
  7919. }
  7920. };
  7921. IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  7922. {
  7923. return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  7924. }
  7925. //=====================================================================================================
  7926. class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
  7927. {
  7928. /*
  7929. BE VERY CAREFUL - this code is tricky.
  7930. Note that starts and stops (and resets) can occur in strange orders
  7931. The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
  7932. The last stop should call the upstream stop.
  7933. The first reset should call the upstream reset.
  7934. 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
  7935. not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
  7936. Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
  7937. ignored in the minIndex calculation
  7938. */
  7939. public:
  7940. IHThorArg &helper;
  7941. unsigned activeOutputs;
  7942. unsigned numOutputs;
  7943. unsigned numOriginalOutputs;
  7944. QueueOf<const void, true> buffer;
  7945. CriticalSection crit;
  7946. CriticalSection crit2;
  7947. unsigned tailIdx;
  7948. unsigned headIdx;
  7949. Owned<IException> readError;
  7950. Owned<IException> startError;
  7951. class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
  7952. {
  7953. bool eof, eofpending, stopped;
  7954. public:
  7955. CRoxieServerThroughSpillActivity *parent;
  7956. unsigned idx;
  7957. unsigned oid;
  7958. unsigned processed = 0;
  7959. unsigned numStarts = 0;
  7960. cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
  7961. public:
  7962. IMPLEMENT_IINTERFACE;
  7963. OutputAdaptor()
  7964. {
  7965. parent = NULL;
  7966. oid = 0;
  7967. idx = 0;
  7968. processed = 0;
  7969. totalCycles = 0;
  7970. eofpending = false;
  7971. eof = false;
  7972. stopped = false;
  7973. }
  7974. ~OutputAdaptor()
  7975. {
  7976. if (traceStartStop)
  7977. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  7978. }
  7979. void init()
  7980. {
  7981. if (traceStartStop)
  7982. DBGLOG("%p init Input adaptor %d", this, oid);
  7983. idx = 0;
  7984. eofpending = false;
  7985. eof = false;
  7986. stopped = false;
  7987. }
  7988. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
  7989. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  7990. virtual IRoxieServerActivity *queryActivity()
  7991. {
  7992. return parent;
  7993. }
  7994. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  7995. {
  7996. return parent->queryIndexReadActivity();
  7997. }
  7998. virtual unsigned __int64 queryTotalCycles() const
  7999. {
  8000. return totalCycles;
  8001. }
  8002. virtual const void * nextRow()
  8003. {
  8004. SimpleActivityTimer t(totalCycles, parent->timeActivities);
  8005. if (eof)
  8006. return NULL;
  8007. const void *ret = parent->readBuffered(idx, oid);
  8008. #ifdef TRACE_SPLIT
  8009. parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
  8010. #endif
  8011. if (ret)
  8012. {
  8013. processed++;
  8014. eofpending = false;
  8015. }
  8016. else if (eofpending)
  8017. eof = true;
  8018. else
  8019. eofpending = true;
  8020. return ret;
  8021. }
  8022. virtual IOutputMetaData * queryOutputMeta() const
  8023. {
  8024. return parent->queryOutputMeta();
  8025. }
  8026. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8027. {
  8028. // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
  8029. // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
  8030. // for minIndex to give the correct answers
  8031. // therefore, we call init() on all adaptors on receipt of the first start() or stop()
  8032. if (traceStartStop)
  8033. parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
  8034. parent->start(oid, parentExtractSize, parentExtract, paused);
  8035. numStarts++;
  8036. }
  8037. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  8038. {
  8039. parent->connectInputStreams(consumerOrdered);
  8040. streams.append(this);
  8041. return NULL;
  8042. }
  8043. virtual void stop()
  8044. {
  8045. if (traceStartStop)
  8046. parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
  8047. if (!stopped)
  8048. {
  8049. parent->stop(oid, idx); // NOTE - may call init()
  8050. stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  8051. }
  8052. };
  8053. virtual void reset()
  8054. {
  8055. if (traceStartStop)
  8056. parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
  8057. parent->reset(oid);
  8058. idx = 0; // value should not be relevant really but this is the safest...
  8059. stopped = false;
  8060. };
  8061. virtual void resetEOF()
  8062. {
  8063. parent->resetEOF();
  8064. }
  8065. virtual void checkAbort()
  8066. {
  8067. parent->checkAbort();
  8068. }
  8069. } *adaptors;
  8070. bool *used;
  8071. unsigned nextFreeOutput()
  8072. {
  8073. unsigned i = numOutputs;
  8074. while (i)
  8075. {
  8076. i--;
  8077. if (!used[i])
  8078. return i;
  8079. }
  8080. throwUnexpected();
  8081. }
  8082. unsigned minIndex(unsigned exceptOid)
  8083. {
  8084. // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
  8085. // this is trying to determine whether any of the adaptors will in the future read a given record
  8086. unsigned minIdx = (unsigned) -1;
  8087. for (unsigned i = 0; i < numOutputs; i++)
  8088. {
  8089. if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
  8090. minIdx = adaptors[i].idx;
  8091. }
  8092. return minIdx;
  8093. }
  8094. inline bool isLastTailReader(unsigned exceptOid)
  8095. {
  8096. for (unsigned i = 0; i < numOutputs; i++)
  8097. {
  8098. if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
  8099. return false;
  8100. }
  8101. return true;
  8102. }
  8103. void initOutputs()
  8104. {
  8105. activeOutputs = numOutputs;
  8106. for (unsigned i = 0; i < numOriginalOutputs; i++)
  8107. if (used[i])
  8108. adaptors[i].init();
  8109. state = STATEstarting;
  8110. }
  8111. public:
  8112. CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8113. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
  8114. {
  8115. numOriginalOutputs = numOutputs;
  8116. adaptors = new OutputAdaptor[numOutputs];
  8117. used = new bool[numOutputs];
  8118. for (unsigned i = 0; i < numOutputs; i++)
  8119. {
  8120. adaptors[i].parent = this;
  8121. adaptors[i].oid = i;
  8122. used[i] = false;
  8123. }
  8124. tailIdx = 0;
  8125. headIdx = 0;
  8126. activeOutputs = numOutputs;
  8127. }
  8128. ~CRoxieServerThroughSpillActivity()
  8129. {
  8130. delete [] adaptors;
  8131. delete [] used;
  8132. }
  8133. const void *readBuffered(unsigned &idx, unsigned oid)
  8134. {
  8135. //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
  8136. const unsigned curIdx = idx;
  8137. if (curIdx == headIdx) // test once without getting the crit2 sec
  8138. {
  8139. CriticalBlock b2(crit2); // but only one puller gets to read the head
  8140. if (curIdx == headIdx) // test again now that we have it
  8141. {
  8142. 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
  8143. if (readError)
  8144. throw readError.getLink(); // Read exceptions are only throw if you try to read past the row where they happened
  8145. try
  8146. {
  8147. const void *row = inputStream->nextRow();
  8148. if (activeOutputs==1)
  8149. {
  8150. #ifdef TRACE_SPLIT
  8151. CTXLOG("spill %d optimised return of %p", activityId, row);
  8152. #endif
  8153. headIdx++;
  8154. idx++;
  8155. return row; // optimization for the case where only one output still active.
  8156. }
  8157. CriticalBlock b(crit);
  8158. headIdx++;
  8159. idx++;
  8160. if (activeOutputs==1)
  8161. return row; // optimization for the case where only one output still active.
  8162. buffer.enqueue(row);
  8163. if (row) LinkRoxieRow(row);
  8164. return row;
  8165. }
  8166. catch (IException *E)
  8167. {
  8168. #ifdef TRACE_SPLIT
  8169. CTXLOG("spill %d caught exception", activityId);
  8170. #endif
  8171. readError.set(E);
  8172. throw;
  8173. }
  8174. catch (...)
  8175. {
  8176. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
  8177. readError.set(E);
  8178. throw E;
  8179. }
  8180. }
  8181. }
  8182. CriticalBlock b(crit);
  8183. 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
  8184. unsigned lidx = curIdx - tailIdx;
  8185. idx++;
  8186. if (!lidx)
  8187. {
  8188. // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
  8189. // 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
  8190. if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
  8191. {
  8192. tailIdx++;
  8193. const void *ret = buffer.dequeue(); // no need to link - last puller
  8194. #ifdef TRACE_SPLIT
  8195. CTXLOG("last puller return of %p", ret);
  8196. #endif
  8197. return ret;
  8198. }
  8199. }
  8200. const void *ret = buffer.item(lidx);
  8201. if (ret) LinkRoxieRow(ret);
  8202. #ifdef TRACE_SPLIT
  8203. CTXLOG("standard return of %p", ret);
  8204. #endif
  8205. return ret;
  8206. }
  8207. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8208. {
  8209. CriticalBlock b(crit);
  8210. if (startError)
  8211. throw startError.getLink();
  8212. if (collectFactoryStatistics)
  8213. factory->noteStarted(oid);
  8214. if (traceStartStop)
  8215. CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8216. if (state != STATEstarted)
  8217. {
  8218. if (state != STATEstarting)
  8219. initOutputs();
  8220. tailIdx = 0;
  8221. headIdx = 0;
  8222. startError.clear();
  8223. readError.clear();
  8224. try
  8225. {
  8226. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8227. }
  8228. catch (IException *E)
  8229. {
  8230. #ifdef TRACE_SPLIT
  8231. CTXLOG("spill %d caught exception in start", activityId);
  8232. #endif
  8233. startError.set(E);
  8234. throw;
  8235. }
  8236. catch (...)
  8237. {
  8238. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
  8239. startError.set(E);
  8240. throw E;
  8241. }
  8242. }
  8243. }
  8244. void stop(unsigned oid, unsigned & idx)
  8245. {
  8246. // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
  8247. CriticalBlock b(crit);
  8248. #ifdef TRACE_STARTSTOP
  8249. if (traceStartStop)
  8250. {
  8251. CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8252. if (watchActivityId && watchActivityId==activityId)
  8253. {
  8254. CTXLOG("WATCH: stop %d", activityId);
  8255. }
  8256. }
  8257. #endif
  8258. if (state != STATEstarting && state != STATEstarted)
  8259. initOutputs();
  8260. if (activeOutputs > 1)
  8261. {
  8262. if (tailIdx==idx)
  8263. {
  8264. // Discard all buffered rows that are there purely for this adaptor to read them
  8265. unsigned min = minIndex(oid);
  8266. if (min != (unsigned) -1)
  8267. // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
  8268. // Should never happen though if there are still some active.
  8269. // there may be a small window where adaptors are blocked on the semaphore...
  8270. {
  8271. #ifdef TRACE_SPLIT
  8272. CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
  8273. #endif
  8274. while (tailIdx < min)
  8275. {
  8276. ReleaseRoxieRow(buffer.dequeue());
  8277. tailIdx++;
  8278. }
  8279. }
  8280. }
  8281. activeOutputs--;
  8282. idx = (unsigned) -1; // causes minIndex not to save rows for me...
  8283. return;
  8284. }
  8285. #ifdef TRACE_SPLIT
  8286. CTXLOG("%p: All outputs done", this);
  8287. #endif
  8288. activeOutputs = numOutputs;
  8289. CRoxieServerActivity::stop();
  8290. };
  8291. void reset(unsigned oid)
  8292. {
  8293. if (traceStartStop)
  8294. CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
  8295. activeOutputs = numOutputs;
  8296. while (buffer.ordinality())
  8297. ReleaseRoxieRow(buffer.dequeue());
  8298. startError.clear();
  8299. readError.clear();
  8300. if (state != STATEreset) // make sure input is only reset once
  8301. CRoxieServerActivity::reset();
  8302. };
  8303. void connectInputStreams(bool consumerOrdered)
  8304. {
  8305. if (!inputStream)
  8306. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  8307. }
  8308. virtual const void *nextRow()
  8309. {
  8310. throwUnexpected(); // Internal logic error - we are not anybody's input
  8311. }
  8312. virtual IOutputMetaData * queryOutputMeta() const
  8313. {
  8314. // if (outputMeta)
  8315. // return outputMeta;
  8316. // else
  8317. return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
  8318. }
  8319. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  8320. {
  8321. if (idx==(unsigned)-1)
  8322. idx = nextFreeOutput(); // MORE - what is this used for?
  8323. assertex(idx < numOriginalOutputs);
  8324. assertex(!used[idx]);
  8325. used[idx] = true;
  8326. return &adaptors[idx];
  8327. }
  8328. virtual void resetOutputsUsed()
  8329. {
  8330. numOutputs = 1;
  8331. activeOutputs = 1;
  8332. // MORE RKC->GH should we be clearing the used array here? anywhere?
  8333. }
  8334. virtual void noteOutputUsed()
  8335. {
  8336. assertex(numOutputs < numOriginalOutputs);
  8337. numOutputs++;
  8338. activeOutputs = numOutputs;
  8339. }
  8340. virtual bool isPassThrough()
  8341. {
  8342. return numOutputs==1;
  8343. }
  8344. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  8345. {
  8346. for (unsigned i = 0; i < numOutputs; i++)
  8347. addEdgeStats(statsBuilder, i, adaptors[i].numStarts, adaptors[i].processed, 0);
  8348. }
  8349. };
  8350. class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
  8351. {
  8352. public:
  8353. CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8354. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8355. {
  8356. Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
  8357. setNumOutputs(helper->getTempUsageCount() + 1);
  8358. }
  8359. CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8360. : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
  8361. {
  8362. setNumOutputs(_numOutputs);
  8363. }
  8364. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8365. {
  8366. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8367. }
  8368. };
  8369. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8370. {
  8371. return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8372. }
  8373. IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
  8374. {
  8375. return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
  8376. }
  8377. //----------------------------------------------------------------------------------------------
  8378. class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
  8379. {
  8380. public:
  8381. CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8382. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8383. {
  8384. Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
  8385. setNumOutputs(helper->numBranches());
  8386. }
  8387. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8388. {
  8389. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  8390. }
  8391. };
  8392. IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8393. {
  8394. return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8395. }
  8396. //=====================================================================================================
  8397. #define PIPE_BUFSIZE 0x8000
  8398. static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
  8399. {
  8400. StringBuffer msg;
  8401. if(pipe->hasError())
  8402. {
  8403. try
  8404. {
  8405. char error[512];
  8406. size32_t sz = pipe->readError(sizeof(error), error);
  8407. if(sz && sz!=(size32_t)-1)
  8408. msg.append(", stderr: '").append(sz, error).append("'");
  8409. }
  8410. catch (IException *e)
  8411. {
  8412. EXCLOG(e, "Error reading pipe stderr");
  8413. e->Release();
  8414. }
  8415. }
  8416. return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
  8417. }
  8418. class CRoxieServerPipeReadActivity : public CRoxieServerActivity
  8419. {
  8420. IHThorPipeReadArg &helper;
  8421. Owned<IPipeProcess> pipe;
  8422. StringAttr pipeCommand;
  8423. Owned<IOutputRowDeserializer> rowDeserializer;
  8424. Owned<IReadRowStream> readTransformer;
  8425. bool groupSignalled;
  8426. public:
  8427. CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8428. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
  8429. {
  8430. groupSignalled = true;
  8431. }
  8432. virtual bool needsAllocator() const { return true; }
  8433. virtual void onCreate(IHThorArg *_colocalParent)
  8434. {
  8435. CRoxieServerActivity::onCreate(_colocalParent);
  8436. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8437. }
  8438. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8439. {
  8440. groupSignalled = true; // i.e. don't start with a NULL row
  8441. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8442. if (!readTransformer)
  8443. {
  8444. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  8445. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
  8446. }
  8447. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8448. openPipe(pipeProgram);
  8449. }
  8450. virtual void stop()
  8451. {
  8452. CRoxieServerActivity::stop();
  8453. pipe.clear();
  8454. readTransformer->setStream(NULL);
  8455. }
  8456. virtual const void *nextRow()
  8457. {
  8458. ActivityTimer t(totalCycles, timeActivities);
  8459. while (!waitForPipe())
  8460. {
  8461. if (!pipe)
  8462. return NULL;
  8463. if (helper.getPipeFlags() & TPFgroupeachrow)
  8464. {
  8465. if (!groupSignalled)
  8466. {
  8467. groupSignalled = true;
  8468. return NULL;
  8469. }
  8470. }
  8471. }
  8472. const void *ret = readTransformer->next();
  8473. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8474. processed++;
  8475. groupSignalled = false;
  8476. return ret;
  8477. }
  8478. protected:
  8479. bool waitForPipe()
  8480. {
  8481. if (!pipe)
  8482. return false; // done
  8483. if (!readTransformer->eos())
  8484. return true;
  8485. verifyPipe();
  8486. return false;
  8487. }
  8488. void openPipe(char const * cmd)
  8489. {
  8490. pipeCommand.setown(cmd);
  8491. pipe.setown(createPipeProcess());
  8492. if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
  8493. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8494. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8495. readTransformer->setStream(pipeReader.get());
  8496. }
  8497. void verifyPipe()
  8498. {
  8499. if (pipe)
  8500. {
  8501. unsigned err = pipe->wait();
  8502. if(err && !(helper.getPipeFlags() & TPFnofail))
  8503. {
  8504. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8505. }
  8506. pipe.clear();
  8507. }
  8508. }
  8509. };
  8510. class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  8511. {
  8512. IHThorPipeThroughArg &helper;
  8513. RecordPullerThread puller;
  8514. Owned<IPipeProcess> pipe;
  8515. StringAttr pipeCommand;
  8516. InterruptableSemaphore pipeVerified;
  8517. InterruptableSemaphore pipeOpened;
  8518. CachedOutputMetaData inputMeta;
  8519. Owned<IOutputRowSerializer> rowSerializer;
  8520. Owned<IOutputRowDeserializer> rowDeserializer;
  8521. Owned<IPipeWriteXformHelper> writeTransformer;
  8522. Owned<IReadRowStream> readTransformer;
  8523. bool firstRead;
  8524. bool recreate;
  8525. bool inputExhausted;
  8526. bool groupSignalled;
  8527. public:
  8528. CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8529. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
  8530. {
  8531. recreate = helper.recreateEachRow();
  8532. groupSignalled = true;
  8533. firstRead = false;
  8534. inputExhausted = false;
  8535. }
  8536. virtual bool needsAllocator() const { return true; }
  8537. virtual void onCreate(IHThorArg *_colocalParent)
  8538. {
  8539. CRoxieServerActivity::onCreate(_colocalParent);
  8540. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8541. rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
  8542. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8543. }
  8544. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8545. {
  8546. firstRead = true;
  8547. inputExhausted = false;
  8548. groupSignalled = true; // i.e. don't start with a NULL row
  8549. pipeVerified.reinit();
  8550. pipeOpened.reinit();
  8551. writeTransformer->ready();
  8552. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8553. if (!readTransformer)
  8554. {
  8555. OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
  8556. readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
  8557. }
  8558. if(!recreate)
  8559. {
  8560. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8561. openPipe(pipeProgram);
  8562. }
  8563. puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
  8564. }
  8565. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  8566. {
  8567. if (idx)
  8568. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  8569. puller.setInput(this, _sourceIdx, _in);
  8570. inputMeta.set(_in->queryOutputMeta());
  8571. }
  8572. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  8573. {
  8574. puller.connectInputStreams(ctx, consumerOrdered);
  8575. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  8576. }
  8577. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  8578. {
  8579. if (idx==0)
  8580. return puller.queryInput();
  8581. else
  8582. return NULL;
  8583. }
  8584. virtual void stop()
  8585. {
  8586. pipeVerified.interrupt(NULL);
  8587. pipeOpened.interrupt(NULL);
  8588. puller.stop();
  8589. CRoxieServerActivity::stop();
  8590. pipe.clear();
  8591. if (readTransformer)
  8592. readTransformer->setStream(NULL);
  8593. }
  8594. virtual void reset()
  8595. {
  8596. puller.reset();
  8597. CRoxieServerActivity::reset();
  8598. }
  8599. virtual const void *nextRow()
  8600. {
  8601. ActivityTimer t(totalCycles, timeActivities);
  8602. while (!waitForPipe())
  8603. {
  8604. if (!pipe)
  8605. return NULL;
  8606. if (helper.getPipeFlags() & TPFgroupeachrow)
  8607. {
  8608. if (!groupSignalled)
  8609. {
  8610. groupSignalled = true;
  8611. return NULL;
  8612. }
  8613. }
  8614. }
  8615. const void *ret = readTransformer->next();
  8616. assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
  8617. processed++;
  8618. groupSignalled = false;
  8619. return ret;
  8620. }
  8621. virtual void processRow(const void *row)
  8622. {
  8623. // called from puller thread
  8624. if(recreate)
  8625. openPipe(helper.getNameFromRow(row));
  8626. writeTransformer->writeTranslatedText(row, pipe);
  8627. ReleaseRoxieRow(row);
  8628. if(recreate)
  8629. {
  8630. closePipe();
  8631. pipeVerified.wait();
  8632. }
  8633. }
  8634. virtual void processDone()
  8635. {
  8636. // called from puller thread
  8637. if(recreate)
  8638. {
  8639. inputExhausted = true;
  8640. pipeOpened.signal();
  8641. }
  8642. else
  8643. {
  8644. closePipe();
  8645. pipeVerified.wait();
  8646. }
  8647. }
  8648. virtual void processEOG()
  8649. {
  8650. }
  8651. void processGroup(const ConstPointerArray &)
  8652. {
  8653. throwUnexpected();
  8654. }
  8655. virtual bool fireException(IException *e)
  8656. {
  8657. pipeOpened.interrupt(LINK(e));
  8658. pipeVerified.interrupt(e);
  8659. return true;
  8660. }
  8661. private:
  8662. bool waitForPipe()
  8663. {
  8664. if (firstRead)
  8665. {
  8666. pipeOpened.wait();
  8667. firstRead = false;
  8668. }
  8669. if (!pipe)
  8670. return false; // done
  8671. if (!readTransformer->eos())
  8672. return true;
  8673. verifyPipe();
  8674. if (recreate && !inputExhausted)
  8675. pipeOpened.wait();
  8676. return false;
  8677. }
  8678. void openPipe(char const * cmd)
  8679. {
  8680. pipeCommand.setown(cmd);
  8681. pipe.setown(createPipeProcess());
  8682. if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
  8683. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8684. writeTransformer->writeHeader(pipe);
  8685. Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
  8686. readTransformer->setStream(pipeReader.get());
  8687. pipeOpened.signal();
  8688. }
  8689. void closePipe()
  8690. {
  8691. writeTransformer->writeFooter(pipe);
  8692. pipe->closeInput();
  8693. }
  8694. void verifyPipe()
  8695. {
  8696. if (pipe)
  8697. {
  8698. unsigned err = pipe->wait();
  8699. if(err && !(helper.getPipeFlags() & TPFnofail))
  8700. {
  8701. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8702. }
  8703. pipe.clear();
  8704. pipeVerified.signal();
  8705. }
  8706. }
  8707. };
  8708. class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
  8709. {
  8710. IHThorPipeWriteArg &helper;
  8711. Owned<IPipeProcess> pipe;
  8712. StringAttr pipeCommand;
  8713. CachedOutputMetaData inputMeta;
  8714. Owned<IOutputRowSerializer> rowSerializer;
  8715. Owned<IPipeWriteXformHelper> writeTransformer;
  8716. bool firstRead;
  8717. bool recreate;
  8718. bool inputExhausted;
  8719. public:
  8720. CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  8721. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
  8722. {
  8723. recreate = helper.recreateEachRow();
  8724. firstRead = false;
  8725. inputExhausted = false;
  8726. }
  8727. virtual bool needsAllocator() const { return true; }
  8728. virtual void onCreate(IHThorArg *_colocalParent)
  8729. {
  8730. CRoxieServerActivity::onCreate(_colocalParent);
  8731. inputMeta.set(input->queryOutputMeta());
  8732. rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
  8733. writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
  8734. }
  8735. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8736. {
  8737. firstRead = true;
  8738. inputExhausted = false;
  8739. writeTransformer->ready();
  8740. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8741. if(!recreate)
  8742. {
  8743. OwnedRoxieString pipeProgram(helper.getPipeProgram());
  8744. openPipe(pipeProgram);
  8745. }
  8746. }
  8747. virtual void stop()
  8748. {
  8749. if (!aborted && helper.getSequence() >= 0)
  8750. {
  8751. WorkunitUpdate wu = ctx->updateWorkUnit();
  8752. if (wu)
  8753. {
  8754. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  8755. if (result)
  8756. {
  8757. result->setResultTotalRowCount(processed);
  8758. result->setResultStatus(ResultStatusCalculated);
  8759. }
  8760. }
  8761. }
  8762. CRoxieServerActivity::stop();
  8763. pipe.clear();
  8764. }
  8765. virtual void onExecute()
  8766. {
  8767. for (;;)
  8768. {
  8769. const void *row = inputStream->ungroupedNextRow();
  8770. if (!row)
  8771. break;
  8772. processed++;
  8773. if(recreate)
  8774. openPipe(helper.getNameFromRow(row));
  8775. writeTransformer->writeTranslatedText(row, pipe);
  8776. ReleaseRoxieRow(row);
  8777. if(recreate)
  8778. closePipe();
  8779. }
  8780. closePipe();
  8781. }
  8782. private:
  8783. void openPipe(char const * cmd)
  8784. {
  8785. pipeCommand.setown(cmd);
  8786. pipe.setown(createPipeProcess());
  8787. if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
  8788. throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
  8789. writeTransformer->writeHeader(pipe);
  8790. }
  8791. void closePipe()
  8792. {
  8793. writeTransformer->writeFooter(pipe);
  8794. pipe->closeInput();
  8795. unsigned err = pipe->wait();
  8796. if(err && !(helper.getPipeFlags() & TPFnofail))
  8797. {
  8798. throw createPipeFailureException(pipeCommand.get(), err, pipe);
  8799. }
  8800. pipe.clear();
  8801. }
  8802. };
  8803. class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
  8804. {
  8805. public:
  8806. CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8807. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8808. {
  8809. }
  8810. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8811. {
  8812. return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
  8813. }
  8814. };
  8815. class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
  8816. {
  8817. public:
  8818. CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8819. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8820. {
  8821. }
  8822. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8823. {
  8824. return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
  8825. }
  8826. };
  8827. class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
  8828. {
  8829. public:
  8830. CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8831. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  8832. {
  8833. }
  8834. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8835. {
  8836. return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
  8837. }
  8838. };
  8839. IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8840. {
  8841. return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8842. }
  8843. IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8844. {
  8845. return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8846. }
  8847. IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  8848. {
  8849. return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  8850. }
  8851. //=====================================================================================================
  8852. class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
  8853. {
  8854. IHThorStreamedIteratorArg &helper;
  8855. Owned<IRowStream> rows;
  8856. public:
  8857. CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8858. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
  8859. {
  8860. }
  8861. ~CRoxieServerStreamedIteratorActivity()
  8862. {
  8863. }
  8864. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8865. {
  8866. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  8867. rows.setown(helper.createInput());
  8868. }
  8869. virtual void stop()
  8870. {
  8871. if (rows)
  8872. {
  8873. rows->stop();
  8874. rows.clear();
  8875. }
  8876. CRoxieServerActivity::stop();
  8877. }
  8878. virtual const void *nextRow()
  8879. {
  8880. ActivityTimer t(totalCycles, timeActivities);
  8881. assertex(rows != NULL);
  8882. const void * next = rows->nextRow();
  8883. if (next)
  8884. processed++;
  8885. return next;
  8886. }
  8887. };
  8888. class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
  8889. {
  8890. public:
  8891. CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8892. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  8893. {
  8894. }
  8895. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  8896. {
  8897. return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
  8898. }
  8899. };
  8900. IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  8901. {
  8902. return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  8903. }
  8904. //=====================================================================================================
  8905. class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
  8906. {
  8907. IHThorFilterArg &helper;
  8908. bool anyThisGroup;
  8909. IRangeCompare * stepCompare;
  8910. public:
  8911. CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  8912. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
  8913. {
  8914. anyThisGroup = false;
  8915. stepCompare = NULL;
  8916. }
  8917. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  8918. {
  8919. anyThisGroup = false;
  8920. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  8921. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
  8922. stepCompare = NULL;
  8923. if (!eof)
  8924. {
  8925. IInputSteppingMeta * stepMeta = input->querySteppingMeta();
  8926. if (stepMeta)
  8927. stepCompare = stepMeta->queryCompare();
  8928. }
  8929. }
  8930. virtual const void * nextRow()
  8931. {
  8932. ActivityTimer t(totalCycles, timeActivities);
  8933. if (eof)
  8934. return NULL;
  8935. for (;;)
  8936. {
  8937. OwnedConstRoxieRow ret(inputStream->nextRow());
  8938. if (!ret)
  8939. {
  8940. //stop returning two NULLs in a row.
  8941. if (anyThisGroup)
  8942. {
  8943. anyThisGroup = false;
  8944. return NULL;
  8945. }
  8946. ret.setown(inputStream->nextRow());
  8947. if (!ret)
  8948. {
  8949. eof = true;
  8950. return NULL; // eof...
  8951. }
  8952. }
  8953. if (helper.isValid(ret))
  8954. {
  8955. anyThisGroup = true;
  8956. processed++;
  8957. return ret.getClear();
  8958. }
  8959. }
  8960. }
  8961. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  8962. {
  8963. //Could assert that this isn't grouped
  8964. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  8965. ActivityTimer t(totalCycles, timeActivities);
  8966. if (eof)
  8967. return NULL;
  8968. for (;;)
  8969. {
  8970. OwnedConstRoxieRow ret(inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra));
  8971. if (!ret)
  8972. {
  8973. eof = true;
  8974. return NULL;
  8975. }
  8976. if (!wasCompleteMatch)
  8977. {
  8978. anyThisGroup = false; // RKC->GH - is this right??
  8979. return ret.getClear();
  8980. }
  8981. if (helper.isValid(ret))
  8982. {
  8983. anyThisGroup = true;
  8984. processed++;
  8985. return ret.getClear();
  8986. }
  8987. if (!stepExtra.returnMismatches())
  8988. {
  8989. ret.clear();
  8990. return nextRow();
  8991. }
  8992. //If asked to return mismatches we are only interested in mismatches that will force the stepped
  8993. //condition to advance
  8994. if (stepCompare->docompare(ret, seek, numFields) != 0)
  8995. {
  8996. wasCompleteMatch = false;
  8997. anyThisGroup = false; // WHY?
  8998. return ret.getClear();
  8999. }
  9000. }
  9001. }
  9002. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9003. {
  9004. return input->gatherConjunctions(collector);
  9005. }
  9006. virtual void resetEOF()
  9007. {
  9008. eof = prefiltered;
  9009. anyThisGroup = false;
  9010. inputStream->resetEOF();
  9011. }
  9012. IInputSteppingMeta * querySteppingMeta()
  9013. {
  9014. return input->querySteppingMeta();
  9015. }
  9016. };
  9017. class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
  9018. {
  9019. public:
  9020. CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9021. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9022. {
  9023. optStableInput = false;
  9024. }
  9025. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9026. {
  9027. return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
  9028. }
  9029. };
  9030. IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9031. {
  9032. return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9033. }
  9034. //=====================================================================================================
  9035. class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
  9036. {
  9037. IHThorFilterGroupArg &helper;
  9038. unsigned curIndex;
  9039. ConstPointerArray gathered;
  9040. IRangeCompare * stepCompare;
  9041. public:
  9042. CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9043. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
  9044. {
  9045. curIndex = 0;
  9046. stepCompare = NULL;
  9047. }
  9048. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9049. {
  9050. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  9051. lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
  9052. assertex(eof == !helper.canMatchAny());
  9053. curIndex = 0;
  9054. stepCompare = NULL;
  9055. if (!eof)
  9056. {
  9057. IInputSteppingMeta * inputStepping = input->querySteppingMeta();
  9058. if (inputStepping)
  9059. stepCompare = inputStepping->queryCompare();
  9060. }
  9061. }
  9062. virtual void reset()
  9063. {
  9064. releaseGathered();
  9065. CRoxieServerLateStartActivity::reset();
  9066. }
  9067. inline void releaseGathered()
  9068. {
  9069. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9070. gathered.kill();
  9071. curIndex = 0;
  9072. }
  9073. virtual const void * nextRow()
  9074. {
  9075. ActivityTimer t(totalCycles, timeActivities);
  9076. for (;;)
  9077. {
  9078. if (eof)
  9079. return NULL;
  9080. if (gathered.ordinality())
  9081. {
  9082. if (gathered.isItem(curIndex))
  9083. {
  9084. const void * ret = gathered.item(curIndex++);
  9085. processed++;
  9086. return ret;
  9087. }
  9088. curIndex = 0;
  9089. gathered.kill();
  9090. return NULL;
  9091. }
  9092. const void * ret = inputStream->nextRow();
  9093. while (ret)
  9094. {
  9095. gathered.append(ret);
  9096. ret = inputStream->nextRow();
  9097. }
  9098. unsigned num = gathered.ordinality();
  9099. if (num != 0)
  9100. {
  9101. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9102. ReleaseRoxieRows(gathered); // read next group
  9103. }
  9104. else
  9105. eof = true;
  9106. }
  9107. }
  9108. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  9109. {
  9110. ActivityTimer t(totalCycles, timeActivities);
  9111. if (eof)
  9112. return NULL;
  9113. if (gathered.ordinality())
  9114. {
  9115. while (gathered.isItem(curIndex))
  9116. {
  9117. const void * ret = gathered.item(curIndex++);
  9118. if (stepCompare->docompare(ret, seek, numFields) >= 0)
  9119. {
  9120. processed++;
  9121. return ret;
  9122. }
  9123. ReleaseRoxieRow(ret);
  9124. }
  9125. curIndex = 0;
  9126. gathered.kill();
  9127. //nextRowGE never returns an end of group marker.
  9128. }
  9129. //Not completely sure about this - it could lead the the start of a group being skipped,
  9130. //so the group filter could potentially work on a different group. If so, we'd need to check the
  9131. //next fields were a subset of the grouping fields - more an issue for the group activity.
  9132. //MORE: What do we do with wasCompleteMatch? something like the following????
  9133. #if 0
  9134. for (;;)
  9135. {
  9136. const void * ret;
  9137. if (stepExtra.returnMismatches())
  9138. {
  9139. bool matchedCompletely = true;
  9140. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9141. if (!wasCompleteMatch)
  9142. return ret;
  9143. }
  9144. else
  9145. ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9146. #endif
  9147. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  9148. while (ret)
  9149. {
  9150. gathered.append(ret);
  9151. ret = inputStream->nextRow();
  9152. }
  9153. unsigned num = gathered.ordinality();
  9154. if (num != 0)
  9155. {
  9156. if (!helper.isValid(num, (const void * *)gathered.getArray()))
  9157. ReleaseRoxieRows(gathered); // read next group
  9158. }
  9159. else
  9160. eof = true;
  9161. return IEngineRowStream::ungroupedNextRow();
  9162. }
  9163. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  9164. {
  9165. return input->gatherConjunctions(collector);
  9166. }
  9167. virtual void resetEOF()
  9168. {
  9169. eof = false;
  9170. releaseGathered();
  9171. inputStream->resetEOF();
  9172. }
  9173. IInputSteppingMeta * querySteppingMeta()
  9174. {
  9175. return input->querySteppingMeta();
  9176. }
  9177. };
  9178. class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
  9179. {
  9180. public:
  9181. CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9182. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9183. {
  9184. }
  9185. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9186. {
  9187. return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
  9188. }
  9189. };
  9190. IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9191. {
  9192. return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9193. }
  9194. //=================================================================================
  9195. class CRoxieServerSideEffectActivity : public CRoxieServerActivity
  9196. {
  9197. IHThorSideEffectArg &helper;
  9198. CriticalSection ecrit;
  9199. Owned<IException> exception;
  9200. bool executed;
  9201. public:
  9202. CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9203. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
  9204. {
  9205. executed = false;
  9206. }
  9207. virtual const void * nextRow()
  9208. {
  9209. ActivityTimer t(totalCycles, timeActivities);
  9210. CriticalBlock b(ecrit);
  9211. if (exception)
  9212. throw(exception.getLink());
  9213. if (!executed)
  9214. {
  9215. try
  9216. {
  9217. executed = true;
  9218. helper.action();
  9219. }
  9220. catch(IException *E)
  9221. {
  9222. exception.set(E);
  9223. throw;
  9224. }
  9225. }
  9226. return NULL;
  9227. }
  9228. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  9229. {
  9230. CriticalBlock b(ecrit);
  9231. if (exception)
  9232. throw(exception.getLink());
  9233. if (!executed)
  9234. {
  9235. try
  9236. {
  9237. ActivityTimer t(totalCycles, timeActivities);
  9238. executed = true;
  9239. start(parentExtractSize, parentExtract, false);
  9240. helper.action();
  9241. stop();
  9242. }
  9243. catch(IException *E)
  9244. {
  9245. ctx->notifyAbort(E);
  9246. abort();
  9247. exception.set(E);
  9248. throw;
  9249. }
  9250. }
  9251. }
  9252. virtual void reset()
  9253. {
  9254. executed = false;
  9255. exception.clear();
  9256. CRoxieServerActivity::reset();
  9257. }
  9258. };
  9259. class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
  9260. {
  9261. bool isRoot;
  9262. public:
  9263. CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9264. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  9265. {
  9266. }
  9267. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9268. {
  9269. return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
  9270. }
  9271. virtual bool isSink() const
  9272. {
  9273. return isRoot && !meta.queryOriginal();
  9274. }
  9275. };
  9276. IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  9277. {
  9278. return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  9279. }
  9280. //=================================================================================
  9281. class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
  9282. {
  9283. IHThorActionArg &helper;
  9284. public:
  9285. CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  9286. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
  9287. {
  9288. }
  9289. virtual void onExecute()
  9290. {
  9291. helper.action();
  9292. }
  9293. };
  9294. class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
  9295. {
  9296. public:
  9297. CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9298. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  9299. {
  9300. }
  9301. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9302. {
  9303. return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
  9304. }
  9305. };
  9306. IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  9307. {
  9308. return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  9309. }
  9310. //=================================================================================
  9311. class CRoxieServerSampleActivity : public CRoxieServerActivity
  9312. {
  9313. IHThorSampleArg &helper;
  9314. unsigned numSamples;
  9315. unsigned numToSkip;
  9316. unsigned whichSample;
  9317. bool anyThisGroup;
  9318. bool eof;
  9319. public:
  9320. CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9321. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
  9322. {
  9323. numSamples = 0;
  9324. numToSkip = 0;
  9325. whichSample = 0;
  9326. anyThisGroup = false;
  9327. eof = false;
  9328. }
  9329. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9330. {
  9331. anyThisGroup = false;
  9332. eof = false;
  9333. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9334. numSamples = helper.getProportion();
  9335. whichSample = helper.getSampleNumber();
  9336. numToSkip = (whichSample ? whichSample-1 : 0);
  9337. }
  9338. virtual const void * nextRow()
  9339. {
  9340. ActivityTimer t(totalCycles, timeActivities);
  9341. if (eof)
  9342. return NULL;
  9343. for (;;)
  9344. {
  9345. const void * ret = inputStream->nextRow();
  9346. if (!ret)
  9347. {
  9348. //this does work with groups - may or may not be useful...
  9349. //reset the sample for each group.... probably best.
  9350. numToSkip = (whichSample ? whichSample-1 : 0);
  9351. if (anyThisGroup)
  9352. {
  9353. anyThisGroup = false;
  9354. return NULL;
  9355. }
  9356. ret = inputStream->nextRow();
  9357. if (!ret)
  9358. {
  9359. eof = true;
  9360. return NULL; // eof...
  9361. }
  9362. }
  9363. if (numToSkip == 0)
  9364. {
  9365. anyThisGroup = true;
  9366. numToSkip = numSamples-1;
  9367. processed++;
  9368. return ret;
  9369. }
  9370. numToSkip--;
  9371. ReleaseRoxieRow(ret);
  9372. }
  9373. }
  9374. };
  9375. class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
  9376. {
  9377. public:
  9378. CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9379. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9380. {
  9381. }
  9382. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9383. {
  9384. return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
  9385. }
  9386. };
  9387. IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9388. {
  9389. return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9390. }
  9391. //=================================================================================
  9392. class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
  9393. {
  9394. IHThorChooseSetsArg &helper;
  9395. unsigned numSets;
  9396. unsigned * setCounts;
  9397. bool done;
  9398. public:
  9399. CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9400. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
  9401. {
  9402. setCounts = NULL;
  9403. numSets = 0;
  9404. done = false;
  9405. }
  9406. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9407. {
  9408. done = false;
  9409. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9410. numSets = helper.getNumSets();
  9411. setCounts = new unsigned[numSets];
  9412. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9413. helper.setCounts(setCounts);
  9414. }
  9415. virtual void reset()
  9416. {
  9417. delete [] setCounts;
  9418. setCounts = NULL;
  9419. CRoxieServerActivity::reset();
  9420. }
  9421. virtual const void * nextRow()
  9422. {
  9423. ActivityTimer t(totalCycles, timeActivities);
  9424. if (done)
  9425. return NULL;
  9426. for (;;)
  9427. {
  9428. const void * ret = inputStream->ungroupedNextRow();
  9429. if (!ret)
  9430. {
  9431. done = true;
  9432. return NULL;
  9433. }
  9434. processed++;
  9435. switch (helper.getRecordAction(ret))
  9436. {
  9437. case 2:
  9438. done = true;
  9439. return ret;
  9440. case 1:
  9441. return ret;
  9442. }
  9443. ReleaseRoxieRow(ret);
  9444. }
  9445. }
  9446. };
  9447. class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
  9448. {
  9449. public:
  9450. CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9451. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9452. {
  9453. }
  9454. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9455. {
  9456. return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
  9457. }
  9458. };
  9459. IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9460. {
  9461. return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9462. }
  9463. //=================================================================================
  9464. class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
  9465. {
  9466. protected:
  9467. IHThorChooseSetsExArg &helper;
  9468. unsigned numSets;
  9469. unsigned curIndex;
  9470. unsigned * setCounts;
  9471. count_t * limits;
  9472. bool done;
  9473. ConstPointerArray gathered;
  9474. virtual bool includeRow(const void * row) = 0;
  9475. virtual void calculateSelection() = 0;
  9476. public:
  9477. CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9478. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
  9479. {
  9480. setCounts = NULL;
  9481. limits = NULL;
  9482. done = false;
  9483. curIndex = 0;
  9484. numSets = 0;
  9485. }
  9486. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9487. {
  9488. done = false;
  9489. curIndex = 0;
  9490. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9491. numSets = helper.getNumSets();
  9492. setCounts = new unsigned[numSets];
  9493. memset(setCounts, 0, sizeof(unsigned)*numSets);
  9494. limits = (count_t *)calloc(sizeof(count_t), numSets);
  9495. helper.getLimits(limits);
  9496. }
  9497. virtual void reset()
  9498. {
  9499. delete [] setCounts;
  9500. setCounts = NULL;
  9501. free(limits);
  9502. limits = NULL;
  9503. roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
  9504. gathered.kill();
  9505. curIndex = 0;
  9506. CRoxieServerActivity::reset();
  9507. }
  9508. virtual const void * nextRow()
  9509. {
  9510. ActivityTimer t(totalCycles, timeActivities);
  9511. if (gathered.ordinality() == 0)
  9512. {
  9513. curIndex = 0;
  9514. if (!inputStream->nextGroup(gathered))
  9515. {
  9516. done = true;
  9517. return NULL;
  9518. }
  9519. ForEachItemIn(idx1, gathered)
  9520. {
  9521. unsigned category = helper.getCategory(gathered.item(idx1));
  9522. if (category)
  9523. setCounts[category-1]++;
  9524. }
  9525. calculateSelection();
  9526. }
  9527. while (gathered.isItem(curIndex))
  9528. {
  9529. const void * row = gathered.item(curIndex);
  9530. gathered.replace(NULL, curIndex);
  9531. curIndex++;
  9532. if (includeRow(row))
  9533. {
  9534. processed++;
  9535. return row;
  9536. }
  9537. ReleaseRoxieRow(row);
  9538. }
  9539. gathered.kill();
  9540. return NULL;
  9541. }
  9542. };
  9543. class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
  9544. {
  9545. unsigned * numToSkip;
  9546. public:
  9547. CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9548. {
  9549. numToSkip = NULL;
  9550. }
  9551. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9552. {
  9553. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9554. numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
  9555. }
  9556. virtual void reset()
  9557. {
  9558. free(numToSkip);
  9559. numToSkip = NULL;
  9560. CRoxieServerChooseSetsExActivity::reset();
  9561. }
  9562. protected:
  9563. virtual void calculateSelection()
  9564. {
  9565. for (unsigned idx=0; idx < numSets; idx++)
  9566. {
  9567. if (setCounts[idx] < limits[idx])
  9568. numToSkip[idx] = 0;
  9569. else
  9570. numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
  9571. }
  9572. }
  9573. virtual bool includeRow(const void * row)
  9574. {
  9575. unsigned category = helper.getCategory(row);
  9576. if (category)
  9577. {
  9578. if (numToSkip[category-1] == 0)
  9579. return true;
  9580. numToSkip[category-1]--;
  9581. }
  9582. return false;
  9583. }
  9584. };
  9585. class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
  9586. {
  9587. count_t * counter;
  9588. public:
  9589. CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
  9590. {
  9591. counter = NULL;
  9592. }
  9593. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9594. {
  9595. CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
  9596. counter = (count_t *)calloc(sizeof(count_t), numSets);
  9597. }
  9598. virtual void reset()
  9599. {
  9600. free(counter);
  9601. counter = NULL;
  9602. CRoxieServerChooseSetsExActivity::reset();
  9603. }
  9604. protected:
  9605. virtual void calculateSelection()
  9606. {
  9607. }
  9608. virtual bool includeRow(const void * row)
  9609. {
  9610. unsigned category = helper.getCategory(row);
  9611. if (category)
  9612. {
  9613. assertex(category <= numSets);
  9614. counter[category-1] += limits[category-1];
  9615. if(counter[category-1] >= setCounts[category-1])
  9616. {
  9617. counter[category-1] -= setCounts[category-1];
  9618. return true;
  9619. }
  9620. }
  9621. return false;
  9622. }
  9623. };
  9624. class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
  9625. {
  9626. public:
  9627. CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9628. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9629. {
  9630. }
  9631. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9632. {
  9633. return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
  9634. }
  9635. };
  9636. IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9637. {
  9638. return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9639. }
  9640. class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
  9641. {
  9642. public:
  9643. CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9644. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9645. {
  9646. }
  9647. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9648. {
  9649. return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
  9650. }
  9651. };
  9652. IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9653. {
  9654. return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9655. }
  9656. //=================================================================================
  9657. class CRoxieServerEnthActivity : public CRoxieServerActivity
  9658. {
  9659. IHThorEnthArg &helper;
  9660. unsigned __int64 numerator;
  9661. unsigned __int64 denominator;
  9662. unsigned __int64 counter;
  9663. bool eof;
  9664. public:
  9665. CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9666. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
  9667. {
  9668. eof = false;
  9669. numerator = denominator = counter = 0;
  9670. }
  9671. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9672. {
  9673. eof = false;
  9674. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9675. numerator = helper.getProportionNumerator();
  9676. denominator = helper.getProportionDenominator();
  9677. if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
  9678. counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
  9679. if (counter >= denominator)
  9680. counter %= denominator;
  9681. }
  9682. inline bool wanted()
  9683. {
  9684. counter += numerator;
  9685. if(counter >= denominator)
  9686. {
  9687. counter -= denominator;
  9688. return true;
  9689. }
  9690. return false;
  9691. }
  9692. virtual const void * nextRow()
  9693. {
  9694. ActivityTimer t(totalCycles, timeActivities);
  9695. if (eof)
  9696. return NULL;
  9697. const void * ret;
  9698. for (;;)
  9699. {
  9700. ret = inputStream->ungroupedNextRow();
  9701. if (!ret) //eof
  9702. {
  9703. eof = true;
  9704. return ret;
  9705. }
  9706. if (wanted())
  9707. return ret;
  9708. ReleaseRoxieRow(ret);
  9709. }
  9710. }
  9711. };
  9712. class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
  9713. {
  9714. public:
  9715. CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9716. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  9717. {
  9718. }
  9719. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  9720. {
  9721. return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
  9722. }
  9723. };
  9724. IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  9725. {
  9726. return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  9727. }
  9728. //=================================================================================
  9729. class CRoxieServerAggregateActivity : public CRoxieServerActivity
  9730. {
  9731. IHThorAggregateArg &helper;
  9732. bool eof;
  9733. bool isInputGrouped;
  9734. bool abortEarly;
  9735. public:
  9736. CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  9737. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
  9738. {
  9739. eof = false;
  9740. isInputGrouped = false;
  9741. abortEarly = false;
  9742. }
  9743. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  9744. {
  9745. eof = false;
  9746. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9747. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9748. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  9749. }
  9750. virtual bool needsAllocator() const { return true; }
  9751. virtual const void * nextRow()
  9752. {
  9753. ActivityTimer t(totalCycles, timeActivities);
  9754. if (eof)
  9755. return NULL;
  9756. const void * next = inputStream->nextRow();
  9757. if (!next && isInputGrouped)
  9758. {
  9759. eof = true;
  9760. return NULL;
  9761. }
  9762. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9763. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9764. if (next)
  9765. {
  9766. finalSize = helper.processFirst(rowBuilder, next);
  9767. ReleaseRoxieRow(next);
  9768. if (!abortEarly)
  9769. {
  9770. for (;;)
  9771. {
  9772. next = inputStream->nextRow();
  9773. if (!next)
  9774. break;
  9775. finalSize = helper.processNext(rowBuilder, next);
  9776. ReleaseRoxieRow(next);
  9777. }
  9778. }
  9779. }
  9780. if (!isInputGrouped) // either read all, or aborted early
  9781. eof = true;
  9782. processed++;
  9783. return rowBuilder.finalizeRowClear(finalSize);
  9784. }
  9785. };
  9786. class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
  9787. {
  9788. class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
  9789. {
  9790. protected:
  9791. IHThorAggregateArg &helper;
  9792. OwnedConstRoxieRow result;
  9793. bool eof = false;
  9794. bool isInputGrouped = false;
  9795. bool abortEarly = false;
  9796. public:
  9797. AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
  9798. : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
  9799. {
  9800. }
  9801. virtual const void * nextRow() override
  9802. {
  9803. ActivityTimer t(totalCycles, timeActivities);
  9804. if (eof || isAborting())
  9805. return NULL;
  9806. const void * next = inputStream->nextRow();
  9807. if (!next && isInputGrouped)
  9808. {
  9809. eof = true;
  9810. return NULL;
  9811. }
  9812. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9813. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9814. if (next)
  9815. {
  9816. finalSize = helper.processFirst(rowBuilder, next);
  9817. ReleaseRoxieRow(next);
  9818. if (!abortEarly)
  9819. {
  9820. for (;;)
  9821. {
  9822. next = inputStream->nextRow();
  9823. if (!next)
  9824. break;
  9825. finalSize = helper.processNext(rowBuilder, next);
  9826. ReleaseRoxieRow(next);
  9827. if (isAborting())
  9828. break;
  9829. }
  9830. }
  9831. }
  9832. if (!isInputGrouped) // either read all, or aborted early
  9833. eof = true;
  9834. processed++;
  9835. return rowBuilder.finalizeRowClear(finalSize);
  9836. }
  9837. virtual void threadmain() override
  9838. {
  9839. isInputGrouped = true; // gather no row if there are no input rows.
  9840. result.setown(nextRow());
  9841. queryActivity().noteStrandFinished(inputStream);
  9842. }
  9843. virtual void reset() override
  9844. {
  9845. StrandProcessor::reset();
  9846. result.clear();
  9847. eof = false;
  9848. }
  9849. //interface IOutputOutputCallback
  9850. virtual bool noteEndOfInputChunk() { return true; }
  9851. virtual void noteEndOfInput() {}
  9852. virtual void stopStream()
  9853. {
  9854. inputStream->stop();
  9855. }
  9856. const void * queryResult() const { return result; }
  9857. CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
  9858. };
  9859. //This class is only used when a single aggregate is being calculated.
  9860. class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
  9861. {
  9862. public:
  9863. explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
  9864. {
  9865. }
  9866. virtual const void *nextRow()
  9867. {
  9868. return parent.getCombinedAggregate();
  9869. }
  9870. virtual void stop()
  9871. {
  9872. parent.outputStopped();
  9873. }
  9874. virtual void resetEOF()
  9875. {
  9876. throwUnexpected();
  9877. }
  9878. protected:
  9879. CRoxieServerStrandedAggregateActivity & parent;
  9880. } combiner;
  9881. class NullCallback : implements IOrderedOutputCallback
  9882. {
  9883. public:
  9884. virtual bool noteEndOfInputChunk() { return true; }
  9885. virtual void noteEndOfInput() {}
  9886. } nullCallback;
  9887. public:
  9888. CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  9889. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), combiner(*this), helper((IHThorAggregateArg &)basehelper)
  9890. {
  9891. isInputGrouped = false;
  9892. abortEarly = false;
  9893. }
  9894. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  9895. {
  9896. CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
  9897. isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
  9898. abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
  9899. //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
  9900. //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
  9901. if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
  9902. strandOptions.numStrands = 1;
  9903. else if (!isInputGrouped)
  9904. combineStreams = true;
  9905. }
  9906. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  9907. {
  9908. PointerArrayOf<IEngineRowStream> localStreams;
  9909. //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
  9910. IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
  9911. Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
  9912. if (localStreams.ordinality() == 1)
  9913. combineStreams = false; // Select a more efficient/simpler code path
  9914. if (combineStreams)
  9915. {
  9916. assertex(!outJunction); // this needs more thought!
  9917. streams.append(&combiner);
  9918. }
  9919. else
  9920. {
  9921. streams.swapWith(localStreams);
  9922. }
  9923. return outJunction.getClear();
  9924. }
  9925. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  9926. {
  9927. if (traceLevel > 4)
  9928. DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
  9929. return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
  9930. }
  9931. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  9932. virtual bool needsAllocator() const { return true; }
  9933. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
  9934. {
  9935. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  9936. onStartStrands();
  9937. if (combineStreams)
  9938. {
  9939. barrier.setown(createStrandBarrier());
  9940. ForEachItemIn(i, strands)
  9941. barrier->startStrand(queryAggregate(i));
  9942. active.store(1);
  9943. }
  9944. else
  9945. active.store(0);
  9946. }
  9947. virtual void reset() override
  9948. {
  9949. CRoxieServerStrandedActivity::reset();
  9950. barrier.clear();
  9951. calculated = false;
  9952. }
  9953. //Helper functions for the single aggregate case
  9954. const void * getCombinedAggregate()
  9955. {
  9956. if (calculated)
  9957. return NULL;
  9958. calculated= true;
  9959. barrier->waitForStrands();
  9960. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  9961. size32_t finalSize = helper.clearAggregate(rowBuilder);
  9962. bool isFirst = true;
  9963. for (unsigned i=0; i < numStrands(); i++)
  9964. {
  9965. const void * next = queryAggregate(i).queryResult();
  9966. if (next)
  9967. {
  9968. if (isFirst)
  9969. {
  9970. finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
  9971. isFirst = false;
  9972. }
  9973. else
  9974. finalSize = helper.mergeAggregate(rowBuilder, next);
  9975. }
  9976. }
  9977. return rowBuilder.finalizeRowClear(finalSize);
  9978. }
  9979. void outputStopped()
  9980. {
  9981. //only called if generating a single result.
  9982. assertex(combineStreams);
  9983. if (barrier)
  9984. {
  9985. requestAbort(); // if strands are still running, abort them
  9986. barrier->waitForStrands();
  9987. }
  9988. else
  9989. {
  9990. ForEachItemIn(i, strands)
  9991. queryAggregate(i).stopStream();
  9992. }
  9993. CRoxieServerStrandedActivity::stop();
  9994. }
  9995. void noteStrandFinished(IRowStream * stream)
  9996. {
  9997. barrier->noteStrandFinished(stream);
  9998. }
  9999. virtual IOrderedOutputCallback * queryCallback(unsigned i)
  10000. {
  10001. //The non-ordered aggregate does not need to process the ordered call back information.
  10002. //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
  10003. //however it needs some care since the strands are not yet created. So cannot return strand(i).
  10004. return &nullCallback;
  10005. }
  10006. inline AggregateProcessor & queryAggregate(unsigned i)
  10007. {
  10008. return static_cast<AggregateProcessor &>(strands.item(i));
  10009. }
  10010. protected:
  10011. IHThorAggregateArg &helper;
  10012. Owned<IStrandBarrier> barrier;
  10013. IEngineRowStream * combinedStream = nullptr;
  10014. bool isInputGrouped;
  10015. bool abortEarly;
  10016. bool combineStreams = false;
  10017. bool calculated = false;
  10018. };
  10019. class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
  10020. {
  10021. StrandOptions strandOptions;
  10022. public:
  10023. CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10024. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  10025. {
  10026. Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
  10027. if (!(helper->getAggregateFlags() & TAForderedmerge))
  10028. optStableInput = false;
  10029. }
  10030. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10031. {
  10032. return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
  10033. }
  10034. };
  10035. IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10036. {
  10037. return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10038. }
  10039. //=================================================================================
  10040. typedef unsigned t_hashPrefix;
  10041. class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
  10042. {
  10043. IHThorHashAggregateArg &helper;
  10044. RowAggregator aggregated;
  10045. bool eof;
  10046. bool gathered;
  10047. bool isGroupedAggregate;
  10048. public:
  10049. CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
  10050. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
  10051. aggregated(helper, helper),
  10052. isGroupedAggregate(_isGroupedAggregate)
  10053. {
  10054. eof = false;
  10055. gathered = false;
  10056. }
  10057. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10058. {
  10059. eof = false;
  10060. gathered = false;
  10061. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10062. }
  10063. virtual void reset()
  10064. {
  10065. aggregated.reset();
  10066. CRoxieServerActivity::reset();
  10067. }
  10068. virtual bool needsAllocator() const { return true; }
  10069. virtual const void * nextRow()
  10070. {
  10071. ActivityTimer t(totalCycles, timeActivities);
  10072. if (eof)
  10073. return NULL;
  10074. if (!gathered)
  10075. {
  10076. aggregated.start(rowAllocator, ctx->queryCodeContext(), activityId);
  10077. bool eog = true;
  10078. for (;;)
  10079. {
  10080. const void * next = inputStream->nextRow();
  10081. if (!next)
  10082. {
  10083. if (isGroupedAggregate)
  10084. {
  10085. if (eog)
  10086. eof = true;
  10087. break;
  10088. }
  10089. next = inputStream->nextRow();
  10090. if (!next)
  10091. break;
  10092. }
  10093. eog = false;
  10094. aggregated.addRow(next);
  10095. ReleaseRoxieRow(next);
  10096. }
  10097. gathered = true;
  10098. }
  10099. Owned<AggregateRowBuilder> next = aggregated.nextResult();
  10100. if (next)
  10101. {
  10102. processed++;
  10103. return next->finalizeRowClear();
  10104. }
  10105. if (!isGroupedAggregate)
  10106. eof = true;
  10107. aggregated.reset();
  10108. gathered = false;
  10109. return NULL;
  10110. }
  10111. };
  10112. class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
  10113. {
  10114. public:
  10115. CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10116. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10117. {
  10118. isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
  10119. }
  10120. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10121. {
  10122. return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
  10123. }
  10124. protected:
  10125. bool isGroupedAggregate;
  10126. };
  10127. IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10128. {
  10129. return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10130. }
  10131. //=================================================================================
  10132. class CRoxieServerDegroupActivity : public CRoxieServerActivity
  10133. {
  10134. bool eof;
  10135. public:
  10136. CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10137. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10138. {
  10139. eof = false;
  10140. }
  10141. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10142. {
  10143. eof = false;
  10144. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10145. }
  10146. virtual const void * nextRow()
  10147. {
  10148. ActivityTimer t(totalCycles, timeActivities);
  10149. if (eof)
  10150. return NULL;
  10151. const void * ret = inputStream->ungroupedNextRow();
  10152. if (ret)
  10153. processed++;
  10154. else
  10155. eof = true;
  10156. return ret;
  10157. }
  10158. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  10159. {
  10160. ActivityTimer t(totalCycles, timeActivities);
  10161. if (eof)
  10162. return NULL;
  10163. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  10164. if (ret)
  10165. processed++;
  10166. else
  10167. eof = true;
  10168. return ret;
  10169. }
  10170. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  10171. {
  10172. return input->gatherConjunctions(collector);
  10173. }
  10174. virtual void resetEOF()
  10175. {
  10176. eof = false;
  10177. inputStream->resetEOF();
  10178. }
  10179. IInputSteppingMeta * querySteppingMeta()
  10180. {
  10181. return input->querySteppingMeta();
  10182. }
  10183. };
  10184. class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
  10185. {
  10186. public:
  10187. CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10188. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10189. {
  10190. }
  10191. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10192. {
  10193. return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
  10194. }
  10195. };
  10196. IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10197. {
  10198. return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10199. }
  10200. //=================================================================================
  10201. class CRoxieServerSpillReadActivity : public CRoxieServerActivity
  10202. {
  10203. IHThorDiskReadArg &helper;
  10204. bool needTransform;
  10205. bool eof;
  10206. bool anyThisGroup;
  10207. unsigned __int64 rowLimit;
  10208. unsigned __int64 choosenLimit;
  10209. public:
  10210. CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10211. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
  10212. {
  10213. needTransform = helper.needTransform();
  10214. rowLimit = (unsigned __int64) -1;
  10215. choosenLimit = 0;
  10216. eof = false;
  10217. anyThisGroup = false;
  10218. }
  10219. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10220. {
  10221. anyThisGroup = false;
  10222. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10223. if (helper.canMatchAny())
  10224. eof = false;
  10225. else
  10226. eof = true;
  10227. choosenLimit = helper.getChooseNLimit();
  10228. rowLimit = helper.getRowLimit();
  10229. helper.setCallback(NULL); // members should not be called - change if they are
  10230. }
  10231. virtual bool needsAllocator() const { return true; }
  10232. virtual const void * nextRow()
  10233. {
  10234. ActivityTimer t(totalCycles, timeActivities);
  10235. if (eof)
  10236. return NULL;
  10237. if (processed==choosenLimit)
  10238. {
  10239. eof = true;
  10240. return NULL;
  10241. }
  10242. if (needTransform)
  10243. {
  10244. for (;;)
  10245. {
  10246. OwnedConstRoxieRow in = inputStream->nextRow();
  10247. if (!in)
  10248. {
  10249. if (anyThisGroup)
  10250. {
  10251. anyThisGroup = false;
  10252. return NULL;
  10253. }
  10254. in.setown(inputStream->nextRow());
  10255. if (!in)
  10256. {
  10257. eof = true;
  10258. return NULL; // eof...
  10259. }
  10260. }
  10261. if (likely(helper.canMatch(in)))
  10262. {
  10263. unsigned outSize;
  10264. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  10265. try
  10266. {
  10267. outSize = helper.transform(rowBuilder, in);
  10268. }
  10269. catch (IException *E)
  10270. {
  10271. throw makeWrappedException(E);
  10272. }
  10273. if (outSize)
  10274. {
  10275. anyThisGroup = true;
  10276. processed++;
  10277. if (processed==rowLimit)
  10278. {
  10279. if (traceLevel > 4)
  10280. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10281. helper.onLimitExceeded();
  10282. }
  10283. return rowBuilder.finalizeRowClear(outSize);
  10284. }
  10285. }
  10286. }
  10287. }
  10288. else
  10289. {
  10290. const void *ret = inputStream->nextRow();
  10291. if (ret)
  10292. {
  10293. processed++;
  10294. if (processed==rowLimit)
  10295. {
  10296. if (traceLevel > 4)
  10297. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  10298. ReleaseClearRoxieRow(ret);
  10299. helper.onLimitExceeded(); // should not return
  10300. throwUnexpected();
  10301. }
  10302. }
  10303. return ret;
  10304. }
  10305. }
  10306. };
  10307. class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
  10308. {
  10309. public:
  10310. CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10311. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10312. {
  10313. }
  10314. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10315. {
  10316. return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
  10317. }
  10318. virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
  10319. {
  10320. if (sourceKind==TAKspill || sourceKind==TAKdiskwrite || sourceKind==TAKspillwrite) // Bit of a hack - codegen probably should differentiate
  10321. setInput(0, source, sourceIdx);
  10322. else
  10323. CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
  10324. }
  10325. };
  10326. IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10327. {
  10328. return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10329. }
  10330. //=================================================================================
  10331. class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
  10332. {
  10333. public:
  10334. CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10335. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  10336. {
  10337. }
  10338. ~CRoxieServerSpillWriteActivity()
  10339. {
  10340. }
  10341. virtual const void *nextRow()
  10342. {
  10343. ActivityTimer t(totalCycles, timeActivities);
  10344. return inputStream->nextRow();
  10345. }
  10346. };
  10347. //==================================================================================
  10348. class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10349. {
  10350. protected:
  10351. Owned<IExtRowWriter> outSeq;
  10352. Owned<IOutputRowSerializer> rowSerializer;
  10353. Linked<IFileIOStream> diskout;
  10354. bool blockcompressed;
  10355. bool extend;
  10356. bool overwrite;
  10357. bool encrypted;
  10358. bool grouped;
  10359. IHThorDiskWriteArg &helper;
  10360. Owned<IRecordSize> diskmeta;
  10361. Owned<IRoxieWriteHandler> writer;
  10362. bool tallycrc;
  10363. unsigned __int64 uncompressedBytesWritten;
  10364. CRC32 crc;
  10365. void updateWorkUnitResult(unsigned __int64 reccount)
  10366. {
  10367. assertex(writer);
  10368. // MORE - a lot of this is common with hthor
  10369. WorkunitUpdate wu = ctx->updateWorkUnit();
  10370. if (wu)
  10371. {
  10372. OwnedRoxieString rawLogicalName = helper.getFileName();
  10373. StringBuffer lfn; // logical filename
  10374. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10375. if (lfn.length())
  10376. {
  10377. unsigned flags = helper.getFlags();
  10378. WUFileKind fileKind;
  10379. if (TDXtemporary & flags)
  10380. fileKind = WUFileTemporary;
  10381. else if(TDXjobtemp & flags)
  10382. fileKind = WUFileJobOwned;
  10383. else if(TDWowned & flags)
  10384. fileKind = WUFileOwned;
  10385. else
  10386. fileKind = WUFileStandard;
  10387. StringArray clusters;
  10388. writer->getClusters(clusters);
  10389. wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
  10390. if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
  10391. {
  10392. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10393. if (result)
  10394. {
  10395. result->setResultTotalRowCount(reccount);
  10396. result->setResultStatus(ResultStatusCalculated);
  10397. if (helper.getFlags() & TDWresult)
  10398. result->setResultFilename(lfn.str());
  10399. else
  10400. result->setResultLogicalName(lfn.str());
  10401. }
  10402. }
  10403. }
  10404. }
  10405. }
  10406. void resolve()
  10407. {
  10408. OwnedRoxieString rawLogicalName = helper.getFileName();
  10409. assertex(rawLogicalName);
  10410. assertex((helper.getFlags() & TDXtemporary) == 0);
  10411. StringArray clusters;
  10412. unsigned clusterIdx = 0;
  10413. while(true)
  10414. {
  10415. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10416. if(!cluster)
  10417. break;
  10418. clusters.append(cluster);
  10419. clusterIdx++;
  10420. }
  10421. if (clusters.length())
  10422. {
  10423. if (extend)
  10424. throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
  10425. }
  10426. else
  10427. {
  10428. if (roxieName.length())
  10429. clusters.append(roxieName.str());
  10430. else
  10431. clusters.append(".");
  10432. }
  10433. writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
  10434. // MORE - need to check somewhere that single part if it's an existing file or an external one...
  10435. }
  10436. public:
  10437. CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10438. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &) basehelper)
  10439. {
  10440. extend = ((helper.getFlags() & TDWextend) != 0);
  10441. overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
  10442. grouped = (helper.getFlags() & TDXgrouped) != 0;
  10443. diskmeta.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  10444. if (grouped)
  10445. diskmeta.setown(createDeltaRecordSize(diskmeta, +1));
  10446. size32_t fixedSize = diskmeta->getFixedSize();
  10447. blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && ((0 == fixedSize) || (fixedSize >= MIN_ROWCOMPRESS_RECSIZE)))); //always use new compression
  10448. encrypted = false; // set later
  10449. tallycrc = true;
  10450. uncompressedBytesWritten = 0;
  10451. }
  10452. ~CRoxieServerDiskWriteActivity()
  10453. {
  10454. }
  10455. virtual bool needsAllocator() const
  10456. {
  10457. return true;
  10458. }
  10459. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10460. {
  10461. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10462. resolve();
  10463. Owned<IFileIO> io;
  10464. void *ekey;
  10465. size32_t ekeylen;
  10466. helper.getEncryptKey(ekeylen, ekey);
  10467. Owned<ICompressor> ecomp;
  10468. if (ekeylen!=0)
  10469. {
  10470. ecomp.setown(createAESCompressor256(ekeylen,ekey));
  10471. memset(ekey,0,ekeylen);
  10472. rtlFree(ekey);
  10473. encrypted = true;
  10474. blockcompressed = true;
  10475. }
  10476. if (blockcompressed)
  10477. io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta->isFixedSize() ? diskmeta->getFixedSize() : 0), extend, true, ecomp));
  10478. else
  10479. io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
  10480. if (!io)
  10481. throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
  10482. diskout.setown(createBufferedIOStream(io));
  10483. if (extend)
  10484. diskout->seek(0, IFSend);
  10485. tallycrc = !blockcompressed; // MORE: Should this be controlled by an activity hint/flag?
  10486. Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
  10487. rowSerializer.set(rowIf->queryRowSerializer());
  10488. unsigned rwFlags = rw_autoflush;
  10489. if(grouped)
  10490. rwFlags |= rw_grouped;
  10491. if(tallycrc)
  10492. rwFlags |= rw_crc;
  10493. outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
  10494. }
  10495. virtual void stop()
  10496. {
  10497. if (aborted)
  10498. {
  10499. if (writer)
  10500. writer->finish(false, this);
  10501. }
  10502. else
  10503. {
  10504. if (outSeq)
  10505. outSeq->flush(&crc);
  10506. if (outSeq)
  10507. uncompressedBytesWritten = outSeq->getPosition();
  10508. outSeq.clear();
  10509. diskout.clear(); // Make sure file is properly closed or date may not match published info
  10510. if (writer)
  10511. {
  10512. updateWorkUnitResult(processed);
  10513. writer->finish(true, this);
  10514. }
  10515. }
  10516. writer.clear();
  10517. CRoxieServerActivity::stop();
  10518. }
  10519. virtual void reset()
  10520. {
  10521. CRoxieServerActivity::reset();
  10522. diskout.clear();
  10523. outSeq.clear();
  10524. writer.clear();
  10525. uncompressedBytesWritten = 0;
  10526. crc.reset();
  10527. }
  10528. virtual void onExecute()
  10529. {
  10530. for (;;)
  10531. {
  10532. const void *row = inputStream->nextRow();
  10533. if (!row)
  10534. {
  10535. row = inputStream->nextRow();
  10536. if (!row)
  10537. break;
  10538. if (grouped)
  10539. outSeq->putRow(NULL);
  10540. }
  10541. processed++;
  10542. outSeq->putRow(row);
  10543. }
  10544. }
  10545. virtual void setFileProperties(IFileDescriptor *desc) const
  10546. {
  10547. IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
  10548. IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
  10549. if (blockcompressed)
  10550. {
  10551. // caller has already set @size from file size...
  10552. fileProps.setPropBool("@blockCompressed", true);
  10553. fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10554. partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
  10555. fileProps.setPropInt64("@size", uncompressedBytesWritten);
  10556. partProps.setPropInt64("@size", uncompressedBytesWritten);
  10557. }
  10558. else if (tallycrc && crc.get())
  10559. partProps.setPropInt64("@fileCrc", crc.get());
  10560. if (encrypted)
  10561. fileProps.setPropBool("@encrypted", true);
  10562. fileProps.setPropInt64("@recordCount", processed);
  10563. partProps.setPropInt64("@recordCount", processed);
  10564. unsigned flags = helper.getFlags();
  10565. if (flags & TDWpersist)
  10566. fileProps.setPropBool("@persistent", true);
  10567. if (grouped)
  10568. fileProps.setPropBool("@grouped", true);
  10569. if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
  10570. fileProps.setPropBool("@owned", true);
  10571. if (flags & TDWresult)
  10572. fileProps.setPropBool("@result", true);
  10573. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10574. if (workUnit)
  10575. {
  10576. fileProps.setProp("@owner", workUnit->queryUser());
  10577. fileProps.setProp("@workunit", workUnit->queryWuid());
  10578. fileProps.setProp("@job", workUnit->queryJobName());
  10579. }
  10580. if (flags & TDWexpires)
  10581. setExpiryTime(fileProps, helper.getExpiryDays());
  10582. if (flags & TDWupdate)
  10583. {
  10584. unsigned eclCRC;
  10585. unsigned __int64 totalCRC;
  10586. helper.getUpdateCRCs(eclCRC, totalCRC);
  10587. fileProps.setPropInt("@eclCRC", eclCRC);
  10588. fileProps.setPropInt64("@totalCRC", totalCRC);
  10589. }
  10590. fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
  10591. IRecordSize * inputMeta = input->queryOutputMeta();
  10592. if ((inputMeta->isFixedSize()) && !isOutputTransformed())
  10593. fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
  10594. const char *recordECL = helper.queryRecordECL();
  10595. if (recordECL && *recordECL)
  10596. fileProps.setProp("ECL", recordECL);
  10597. setRtlFormat(fileProps, helper.queryDiskRecordSize());
  10598. fileProps.setProp("@kind", "flat"); // default, derivitives may override
  10599. }
  10600. virtual IUserDescriptor *queryUserDescriptor() const
  10601. {
  10602. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  10603. if (workUnit)
  10604. return workUnit->queryUserDescriptor();//ad-hoc mode
  10605. else
  10606. {
  10607. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  10608. if (daliHelper)
  10609. return daliHelper->queryUserDescriptor();//predeployed query mode
  10610. }
  10611. return NULL;
  10612. }
  10613. virtual bool isOutputTransformed() const { return false; }
  10614. };
  10615. //=================================================================================
  10616. class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
  10617. {
  10618. IHThorCsvWriteArg &csvHelper;
  10619. CSVOutputStream csvOutput;
  10620. public:
  10621. CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10622. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
  10623. {
  10624. csvOutput.init(csvHelper.queryCsvParameters(), false);
  10625. }
  10626. virtual void onExecute()
  10627. {
  10628. OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
  10629. if (header)
  10630. {
  10631. csvOutput.beginLine();
  10632. csvOutput.writeHeaderLn(strlen(header), header);
  10633. diskout->write(csvOutput.length(), csvOutput.str());
  10634. }
  10635. for (;;)
  10636. {
  10637. const void *nextrec = inputStream->ungroupedNextRow();
  10638. if (!nextrec)
  10639. break;
  10640. processed++;
  10641. csvOutput.beginLine();
  10642. csvHelper.writeRow((const byte *)nextrec, &csvOutput);
  10643. csvOutput.endLine();
  10644. diskout->write(csvOutput.length(), csvOutput.str());
  10645. ReleaseRoxieRow(nextrec);
  10646. }
  10647. OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
  10648. if (footer)
  10649. {
  10650. csvOutput.beginLine();
  10651. csvOutput.writeHeaderLn(strlen(footer), footer);
  10652. diskout->write(csvOutput.length(), csvOutput.str());
  10653. }
  10654. }
  10655. virtual void setFileProperties(IFileDescriptor *desc) const
  10656. {
  10657. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10658. IPropertyTree &props = desc->queryProperties();
  10659. props.setProp("@format","utf8n");
  10660. ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
  10661. StringBuffer separator;
  10662. OwnedRoxieString rs(csvParameters->getSeparator(0));
  10663. const char *s = rs;
  10664. while (s && *s)
  10665. {
  10666. if (',' == *s)
  10667. separator.append("\\,");
  10668. else
  10669. separator.append(*s);
  10670. ++s;
  10671. }
  10672. props.setProp("@csvSeparate", separator.str());
  10673. props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
  10674. props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
  10675. props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
  10676. props.setProp("@kind", "csv");
  10677. }
  10678. virtual bool isOutputTransformed() const { return true; }
  10679. };
  10680. class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
  10681. {
  10682. IHThorXmlWriteArg &xmlHelper;
  10683. StringAttr rowTag;
  10684. ThorActivityKind kind;
  10685. unsigned headerLength;
  10686. unsigned footerLength;
  10687. public:
  10688. CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
  10689. : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
  10690. {
  10691. }
  10692. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10693. {
  10694. CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
  10695. OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
  10696. if (!xmlpath)
  10697. rowTag.set(DEFAULTXMLROWTAG);
  10698. else
  10699. {
  10700. const char *path = xmlpath;
  10701. if (*path == '/') path++;
  10702. if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
  10703. rowTag.set(path);
  10704. }
  10705. }
  10706. virtual void onExecute()
  10707. {
  10708. StringBuffer header;
  10709. OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
  10710. if (kind==TAKjsonwrite)
  10711. buildJsonHeader(header, suppliedHeader, rowTag);
  10712. else if (suppliedHeader)
  10713. header.set(suppliedHeader);
  10714. else
  10715. header.append(DEFAULTXMLHEADER).newline();
  10716. headerLength = header.length();
  10717. diskout->write(header.length(), header.str());
  10718. Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSONRootless : WTStandard);
  10719. writer->outputBeginArray(rowTag); //need to set this
  10720. writer->clear(); //but not output it
  10721. for (;;)
  10722. {
  10723. OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
  10724. if (!nextrec)
  10725. break;
  10726. processed++;
  10727. writer->clear().outputBeginNested(rowTag, false);
  10728. xmlHelper.toXML((const byte *)nextrec.get(), *writer);
  10729. writer->outputEndNested(rowTag);
  10730. diskout->write(writer->length(), writer->str());
  10731. }
  10732. OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
  10733. StringBuffer footer;
  10734. if (kind==TAKjsonwrite)
  10735. buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
  10736. else if (suppliedFooter)
  10737. footer.append(suppliedFooter);
  10738. else
  10739. footer.append(DEFAULTXMLFOOTER);
  10740. footerLength=footer.length();
  10741. diskout->write(footer.length(), footer);
  10742. }
  10743. virtual void reset()
  10744. {
  10745. CRoxieServerDiskWriteActivity::reset();
  10746. rowTag.clear();
  10747. }
  10748. virtual void setFileProperties(IFileDescriptor *desc) const
  10749. {
  10750. CRoxieServerDiskWriteActivity::setFileProperties(desc);
  10751. desc->queryProperties().setProp("@format","utf8n");
  10752. desc->queryProperties().setProp("@rowTag",rowTag.get());
  10753. desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
  10754. desc->queryProperties().setPropInt(FPheaderLength, headerLength);
  10755. desc->queryProperties().setPropInt(FPfooterLength, footerLength);
  10756. }
  10757. virtual bool isOutputTransformed() const { return true; }
  10758. };
  10759. class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
  10760. {
  10761. bool isTemp;
  10762. public:
  10763. CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10764. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  10765. {
  10766. Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
  10767. isTemp = (helper->getFlags() & TDXtemporary) != 0;
  10768. setNumOutputs(helper->getTempUsageCount());
  10769. if (_kind != TAKspillwrite)
  10770. assertex(numOutputs == 0);
  10771. }
  10772. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  10773. {
  10774. switch (numOutputs)
  10775. {
  10776. case 0:
  10777. switch (kind)
  10778. {
  10779. case TAKdiskwrite:
  10780. return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
  10781. case TAKcsvwrite:
  10782. return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
  10783. case TAKxmlwrite:
  10784. case TAKjsonwrite:
  10785. return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
  10786. case TAKspillwrite:
  10787. return new CRoxieServerNullSinkActivity(_ctx, this, _probeManager);
  10788. };
  10789. throwUnexpected();
  10790. case 1:
  10791. return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
  10792. default:
  10793. return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
  10794. }
  10795. }
  10796. virtual bool isSink() const
  10797. {
  10798. return numOutputs == 0 && (kind==TAKspillwrite || !isTemp); // MORE - check with Gavin if this is right if not a temp but reread in same job...
  10799. }
  10800. };
  10801. IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  10802. {
  10803. return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  10804. }
  10805. //=================================================================================
  10806. class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
  10807. {
  10808. IHThorIndexWriteArg &helper;
  10809. bool overwrite;
  10810. Owned<ClusterWriteHandler> clusterHandler;
  10811. Owned<IRoxieWriteHandler> writer;
  10812. unsigned __int64 reccount;
  10813. unsigned int fileCrc;
  10814. StringBuffer filename;
  10815. unsigned __int64 duplicateKeyCount = 0;
  10816. unsigned __int64 cummulativeDuplicateKeyCount = 0;
  10817. void updateWorkUnitResult()
  10818. {
  10819. // MORE - a lot of this is common with hthor
  10820. WorkunitUpdate wu = ctx->updateWorkUnit();
  10821. if (wu)
  10822. {
  10823. OwnedRoxieString rawLogicalName = helper.getFileName();
  10824. StringBuffer lfn; // logical filename
  10825. expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
  10826. if (lfn.length())
  10827. {
  10828. if (helper.getSequence() >= 0)
  10829. {
  10830. Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
  10831. if (result)
  10832. {
  10833. result->setResultTotalRowCount(reccount);
  10834. result->setResultStatus(ResultStatusCalculated);
  10835. result->setResultLogicalName(lfn.str());
  10836. }
  10837. }
  10838. if(clusterHandler)
  10839. clusterHandler->finish(writer->queryFile());
  10840. CTXLOG("Created roxie index file %s", lfn.str());
  10841. }
  10842. }
  10843. }
  10844. virtual void resolve()
  10845. {
  10846. StringArray clusters;
  10847. unsigned clusterIdx = 0;
  10848. while(true)
  10849. {
  10850. OwnedRoxieString cluster(helper.getCluster(clusterIdx));
  10851. if(!cluster)
  10852. break;
  10853. clusters.append(cluster);
  10854. clusterIdx++;
  10855. }
  10856. if (roxieName.length())
  10857. clusters.append(roxieName.str());
  10858. else
  10859. clusters.append(".");
  10860. OwnedRoxieString fname(helper.getFileName());
  10861. writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
  10862. filename.set(writer->queryFile()->queryFilename());
  10863. if (writer->queryFile()->exists())
  10864. {
  10865. if (overwrite)
  10866. {
  10867. CTXLOG("Removing existing %s from DFS",filename.str());
  10868. writer->queryFile()->remove();
  10869. }
  10870. else
  10871. throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
  10872. }
  10873. }
  10874. void buildUserMetadata(Owned<IPropertyTree> & metadata)
  10875. {
  10876. size32_t nameLen;
  10877. char * nameBuff;
  10878. size32_t valueLen;
  10879. char * valueBuff;
  10880. unsigned idx = 0;
  10881. while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
  10882. {
  10883. StringBuffer name(nameLen, nameBuff);
  10884. StringBuffer value(valueLen, valueBuff);
  10885. if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
  10886. {
  10887. OwnedRoxieString fname(helper.getFileName());
  10888. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
  10889. }
  10890. if(!validateXMLTag(name.str()))
  10891. {
  10892. OwnedRoxieString fname(helper.getFileName());
  10893. throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
  10894. }
  10895. if(!metadata)
  10896. metadata.setown(createPTree("metadata", ipt_fast));
  10897. metadata->setProp(name.str(), value.str());
  10898. }
  10899. }
  10900. void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
  10901. {
  10902. if(!metadata)
  10903. metadata.setown(createPTree("metadata", ipt_fast));
  10904. metadata->setProp("_record_ECL", helper.queryRecordECL());
  10905. setRtlFormat(*metadata, helper.queryDiskRecordSize());
  10906. }
  10907. public:
  10908. CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  10909. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
  10910. {
  10911. overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
  10912. reccount = 0;
  10913. fileCrc = 0;
  10914. }
  10915. ~CRoxieServerIndexWriteActivity()
  10916. {
  10917. }
  10918. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  10919. {
  10920. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  10921. resolve();
  10922. }
  10923. virtual void onExecute()
  10924. {
  10925. bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
  10926. size32_t fileposSize = hasTrailingFileposition(helper.queryDiskRecordSize()->queryTypeInfo()) ? sizeof(offset_t) : 0;
  10927. size32_t maxDiskRecordSize;
  10928. if (isVariable)
  10929. {
  10930. if (helper.getFlags() & TIWmaxlength)
  10931. maxDiskRecordSize = helper.getMaxKeySize();
  10932. else
  10933. maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
  10934. }
  10935. else
  10936. maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize()-fileposSize;
  10937. if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
  10938. throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
  10939. OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
  10940. fileCrc = -1;
  10941. {
  10942. Owned<IFileIO> io;
  10943. try
  10944. {
  10945. io.setown(writer->queryFile()->open(IFOcreate));
  10946. }
  10947. catch(IException * e)
  10948. {
  10949. e->Release();
  10950. clearKeyStoreCache(false);
  10951. io.setown(writer->queryFile()->open(IFOcreate));
  10952. }
  10953. if(!io)
  10954. throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
  10955. Owned<IFileIOStream> out = createIOStream(io);
  10956. unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
  10957. if (helper.getFlags() & TIWrowcompress)
  10958. flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
  10959. else if (!(helper.getFlags() & TIWnolzwcompress))
  10960. flags |= HTREE_COMPRESSED_KEY;
  10961. if (isVariable)
  10962. flags |= HTREE_VARSIZE;
  10963. Owned<IPropertyTree> metadata;
  10964. buildUserMetadata(metadata);
  10965. buildLayoutMetadata(metadata);
  10966. unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
  10967. Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0, &helper, true, false);
  10968. class BcWrapper : implements IBlobCreator
  10969. {
  10970. IKeyBuilder *builder;
  10971. public:
  10972. BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
  10973. virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
  10974. {
  10975. return builder->createBlob(size, (const char *) ptr);
  10976. }
  10977. } bc(builder);
  10978. // Loop thru the results
  10979. for (;;)
  10980. {
  10981. OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
  10982. if (!nextrec)
  10983. break;
  10984. try
  10985. {
  10986. unsigned __int64 fpos=0;
  10987. RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
  10988. size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
  10989. builder->processKeyData(rowBuffer, fpos, thisSize);
  10990. }
  10991. catch(IException * e)
  10992. {
  10993. throw makeWrappedException(e);
  10994. }
  10995. reccount++;
  10996. }
  10997. duplicateKeyCount = builder->getDuplicateCount();
  10998. cummulativeDuplicateKeyCount += duplicateKeyCount;
  10999. builder->finish(metadata, &fileCrc);
  11000. clearKeyStoreCache(false);
  11001. }
  11002. }
  11003. virtual void stop()
  11004. {
  11005. if (writer)
  11006. {
  11007. if (!aborted)
  11008. updateWorkUnitResult();
  11009. writer->finish(!aborted, this);
  11010. writer.clear();
  11011. }
  11012. CRoxieServerActivity::stop();
  11013. }
  11014. virtual void reset()
  11015. {
  11016. noteStatistic(StNumDuplicateKeys, cummulativeDuplicateKeyCount);
  11017. CRoxieServerActivity::reset();
  11018. writer.clear();
  11019. }
  11020. //interface IRoxiePublishCallback
  11021. virtual void setFileProperties(IFileDescriptor *desc) const
  11022. {
  11023. // Now publish to name services
  11024. StringBuffer dir,base;
  11025. offset_t indexFileSize = writer->queryFile()->size();
  11026. if(clusterHandler)
  11027. clusterHandler->splitPhysicalFilename(dir, base);
  11028. else
  11029. {
  11030. // Check filename is URL and get localpath, only actually necessary if force remote reads are are on
  11031. RemoteFilename rfn;
  11032. rfn.setRemotePath(filename);
  11033. StringBuffer localPath;
  11034. rfn.getLocalPath(localPath);
  11035. splitFilename(localPath, &dir, &dir, &base, &base);
  11036. }
  11037. desc->setDefaultDir(dir.str());
  11038. //properties of the first file part.
  11039. Owned<IPropertyTree> attrs;
  11040. if(clusterHandler)
  11041. attrs.setown(createPTree("Part", ipt_fast)); // clusterHandler is going to set attributes
  11042. else
  11043. {
  11044. // add cluster
  11045. StringBuffer mygroupname;
  11046. desc->setNumParts(1);
  11047. desc->setPartMask(base.str());
  11048. attrs.set(&desc->queryPart(0)->queryProperties());
  11049. }
  11050. attrs->setPropInt64("@size", indexFileSize);
  11051. attrs->setPropInt64("@recordCount", reccount);
  11052. CDateTime createTime, modifiedTime, accessedTime;
  11053. writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
  11054. // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
  11055. unsigned hour, min, sec, nanosec;
  11056. modifiedTime.getTime(hour, min, sec, nanosec);
  11057. modifiedTime.setTime(hour, min, sec, 0);
  11058. StringBuffer timestr;
  11059. modifiedTime.getString(timestr);
  11060. if(timestr.length())
  11061. attrs->setProp("@modified", timestr.str());
  11062. if(clusterHandler)
  11063. clusterHandler->setDescriptorParts(desc, base.str(), attrs);
  11064. // properties of the logical file
  11065. IPropertyTree & properties = desc->queryProperties();
  11066. properties.setProp("@kind", "key");
  11067. properties.setPropInt64("@size", indexFileSize);
  11068. properties.setPropInt64("@recordCount", reccount);
  11069. properties.setPropInt64("@duplicateKeyCount", duplicateKeyCount);
  11070. WorkunitUpdate workUnit = ctx->updateWorkUnit();
  11071. if (workUnit)
  11072. {
  11073. properties.setProp("@owner", workUnit->queryUser());
  11074. properties.setProp("@workunit", workUnit->queryWuid());
  11075. properties.setProp("@job", workUnit->queryJobName());
  11076. }
  11077. char const * rececl = helper.queryRecordECL();
  11078. if(rececl && *rececl)
  11079. properties.setProp("ECL", rececl);
  11080. if (helper.getFlags() & TIWexpires)
  11081. setExpiryTime(properties, helper.getExpiryDays());
  11082. if (helper.getFlags() & TIWupdate)
  11083. {
  11084. unsigned eclCRC;
  11085. unsigned __int64 totalCRC;
  11086. helper.getUpdateCRCs(eclCRC, totalCRC);
  11087. properties.setPropInt("@eclCRC", eclCRC);
  11088. properties.setPropInt64("@totalCRC", totalCRC);
  11089. }
  11090. properties.setPropInt("@fileCrc", fileCrc);
  11091. properties.setPropInt("@formatCrc", helper.getFormatCrc());
  11092. // Legacy record layout info
  11093. void * layoutMetaBuff;
  11094. size32_t layoutMetaSize;
  11095. if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
  11096. {
  11097. properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
  11098. rtlFree(layoutMetaBuff);
  11099. }
  11100. // New record layout info
  11101. setRtlFormat(properties, helper.queryDiskRecordSize());
  11102. // Bloom info
  11103. const IBloomBuilderInfo * const *bloomFilters = helper.queryBloomInfo();
  11104. while (bloomFilters && *bloomFilters)
  11105. {
  11106. const IBloomBuilderInfo *info = *bloomFilters++;
  11107. IPropertyTree *bloom = properties.addPropTree("Bloom");
  11108. bloom->setPropInt64("@bloomFieldMask", info->getBloomFields());
  11109. 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.
  11110. VStringBuffer pval("%f", info->getBloomProbability());
  11111. bloom->setProp("@bloomProbability", pval.str());
  11112. }
  11113. }
  11114. IUserDescriptor *queryUserDescriptor() const
  11115. {
  11116. IConstWorkUnit *workUnit = ctx->queryWorkUnit();
  11117. if (workUnit)
  11118. return workUnit->queryUserDescriptor();//ad-hoc mode
  11119. else
  11120. {
  11121. Owned<IRoxieDaliHelper> daliHelper = connectToDali(false);
  11122. if (daliHelper)
  11123. return daliHelper->queryUserDescriptor();//predeployed query mode
  11124. }
  11125. return NULL;
  11126. }
  11127. };
  11128. //=================================================================================
  11129. class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
  11130. {
  11131. public:
  11132. CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11133. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11134. {
  11135. setNumOutputs(0);
  11136. }
  11137. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11138. {
  11139. return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
  11140. }
  11141. virtual bool isSink() const
  11142. {
  11143. return true;
  11144. }
  11145. virtual const StatisticsMapping &queryStatsMapping() const
  11146. {
  11147. return indexWriteStatistics; // Overridden by anyone that needs more
  11148. }
  11149. };
  11150. IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  11151. {
  11152. return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  11153. }
  11154. //=================================================================================
  11155. static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
  11156. {
  11157. if((flags & JFmatchAbortLimitSkips) != 0)
  11158. {
  11159. limitFail = false;
  11160. limitOnFail = false;
  11161. }
  11162. else
  11163. {
  11164. limitOnFail = ((flags & JFonfail) != 0);
  11165. limitFail = !limitOnFail;
  11166. }
  11167. }
  11168. class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
  11169. {
  11170. enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
  11171. IHThorJoinArg &helper;
  11172. ICompare * collate;
  11173. ICompare * collateupper;
  11174. ThorActivityKind activityKind;
  11175. bool leftOuterJoin;
  11176. bool rightOuterJoin;
  11177. bool exclude;
  11178. bool limitFail;
  11179. bool limitOnFail;
  11180. bool forceSpill;
  11181. unsigned keepLimit;
  11182. unsigned joinLimit;
  11183. unsigned atmostLimit;
  11184. unsigned abortLimit;
  11185. unsigned atmostsTriggered;
  11186. bool betweenjoin;
  11187. OwnedRowArray right;
  11188. const void * left;
  11189. const void * pendingRight;
  11190. unsigned rightIndex;
  11191. unsigned joinCounter;
  11192. BoolArray matchedRight;
  11193. bool matchedLeft;
  11194. Owned<IException> failingLimit;
  11195. ConstPointerArray filteredRight;
  11196. Owned<IRHLimitedCompareHelper> limitedhelper;
  11197. OwnedConstRoxieRow defaultLeft;
  11198. OwnedConstRoxieRow defaultRight;
  11199. Owned<IEngineRowAllocator> defaultLeftAllocator;
  11200. Owned<IEngineRowAllocator> defaultRightAllocator;
  11201. Owned<IGroupedInput> sortedLeft;
  11202. Owned<IGroupedInput> groupedSortedRight;
  11203. bool cloneLeft;
  11204. void createDefaultLeft()
  11205. {
  11206. if (!defaultLeft)
  11207. {
  11208. if (!defaultLeftAllocator)
  11209. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  11210. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  11211. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  11212. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  11213. }
  11214. }
  11215. void createDefaultRight()
  11216. {
  11217. if (!defaultRight)
  11218. {
  11219. if (!defaultRightAllocator)
  11220. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  11221. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  11222. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  11223. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  11224. }
  11225. }
  11226. public:
  11227. CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  11228. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  11229. {
  11230. // MORE - some of this should be done in factory
  11231. unsigned joinFlags = helper.getJoinFlags();
  11232. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  11233. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  11234. exclude = (joinFlags & JFexclude) != 0;
  11235. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  11236. getLimitType(joinFlags, limitFail, limitOnFail);
  11237. if (joinFlags & JFslidingmatch)
  11238. {
  11239. betweenjoin = true;
  11240. collate = helper.queryCompareLeftRightLower();
  11241. collateupper = helper.queryCompareLeftRightUpper();
  11242. }
  11243. else
  11244. {
  11245. betweenjoin = false;
  11246. collate = collateupper = helper.queryCompareLeftRight();
  11247. }
  11248. rightIndex = 0;
  11249. joinCounter = 0;
  11250. state = JSfill;
  11251. matchedLeft = false;
  11252. joinLimit = 0;
  11253. keepLimit = 0; // wait until ctx available
  11254. atmostLimit = 0; // wait until ctx available
  11255. abortLimit = 0; // wait until ctx available
  11256. atmostsTriggered = 0;
  11257. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
  11258. left = NULL;
  11259. pendingRight = NULL;
  11260. activityKind = _factory->getKind();
  11261. }
  11262. virtual bool needsAllocator() const { return true; }
  11263. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11264. {
  11265. left = NULL;
  11266. rightIndex = 0;
  11267. joinCounter = 0;
  11268. state = JSfill;
  11269. matchedLeft = false;
  11270. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  11271. keepLimit = helper.getKeepLimit();
  11272. if (keepLimit == 0)
  11273. keepLimit = (unsigned)-1;
  11274. atmostsTriggered = 0;
  11275. atmostLimit = helper.getJoinLimit();
  11276. if(atmostLimit == 0)
  11277. atmostLimit = (unsigned)-1;
  11278. else
  11279. assertex(!rightOuterJoin && !betweenjoin);
  11280. abortLimit = helper.getMatchAbortLimit();
  11281. if (abortLimit == 0)
  11282. abortLimit = (unsigned)-1;
  11283. if (rightOuterJoin)
  11284. createDefaultLeft();
  11285. if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
  11286. createDefaultRight();
  11287. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  11288. RoxieSortAlgorithm sortAlgorithm;
  11289. if (forceSpill)
  11290. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  11291. else
  11292. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  11293. if (helper.isLeftAlreadySorted())
  11294. sortedLeft.setown(createDegroupedInputReader(inputStream));
  11295. else
  11296. sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11297. ICompare *compareRight = helper.queryCompareRight();
  11298. if (helper.isRightAlreadySorted())
  11299. groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
  11300. else
  11301. groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  11302. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  11303. { //limited match join (s[1..n])
  11304. limitedhelper.setown(createRHLimitedCompareHelper());
  11305. limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
  11306. }
  11307. }
  11308. virtual void reset()
  11309. {
  11310. if (atmostsTriggered)
  11311. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  11312. right.clear();
  11313. ReleaseClearRoxieRow(left);
  11314. ReleaseClearRoxieRow(pendingRight);
  11315. defaultRight.clear();
  11316. defaultLeft.clear();
  11317. sortedLeft.clear();
  11318. groupedSortedRight.clear();
  11319. CRoxieServerTwoInputActivity::reset();
  11320. }
  11321. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  11322. {
  11323. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  11324. {
  11325. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  11326. puller->setInput(0, _sourceIdx, _in);
  11327. _in = puller;
  11328. _sourceIdx = 0;
  11329. }
  11330. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  11331. }
  11332. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  11333. {
  11334. if (idx==(unsigned)-1)
  11335. idx = 0;
  11336. return idx ? NULL : this;
  11337. }
  11338. void fillLeft()
  11339. {
  11340. matchedLeft = false;
  11341. left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
  11342. if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
  11343. fillRight();
  11344. if (limitedhelper && 0==rightIndex)
  11345. {
  11346. rightIndex = 0;
  11347. joinCounter = 0;
  11348. right.clear();
  11349. matchedRight.kill();
  11350. if (left)
  11351. {
  11352. limitedhelper->getGroup(right,left);
  11353. ForEachItemIn(idx, right)
  11354. matchedRight.append(false);
  11355. }
  11356. }
  11357. }
  11358. void fillRight()
  11359. {
  11360. if (limitedhelper)
  11361. return;
  11362. failingLimit.clear();
  11363. if(betweenjoin && left)
  11364. {
  11365. aindex_t start = 0;
  11366. while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
  11367. start++;
  11368. if(start>0)
  11369. right.clearPart(0, start);
  11370. }
  11371. else
  11372. right.clear();
  11373. rightIndex = 0;
  11374. joinCounter = 0;
  11375. unsigned groupCount = 0;
  11376. const void * next;
  11377. while(true)
  11378. {
  11379. if(pendingRight)
  11380. {
  11381. next = pendingRight;
  11382. pendingRight = NULL;
  11383. }
  11384. else
  11385. {
  11386. next = groupedSortedRight->nextRow();
  11387. }
  11388. if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
  11389. {
  11390. while(next)
  11391. {
  11392. ReleaseClearRoxieRow(next);
  11393. next = groupedSortedRight->nextRow();
  11394. }
  11395. continue;
  11396. }
  11397. while(next)
  11398. {
  11399. if(groupCount==abortLimit)
  11400. {
  11401. if(limitFail)
  11402. failLimit();
  11403. if (ctx->queryDebugContext())
  11404. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  11405. if(limitOnFail)
  11406. {
  11407. assertex(!failingLimit);
  11408. try
  11409. {
  11410. failLimit();
  11411. }
  11412. catch(IException * except)
  11413. {
  11414. failingLimit.setown(except);
  11415. }
  11416. assertex(failingLimit != NULL);
  11417. }
  11418. right.append(next);
  11419. do
  11420. {
  11421. next = groupedSortedRight->nextRow();
  11422. ReleaseRoxieRow(next);
  11423. } while(next);
  11424. break;
  11425. }
  11426. else if(groupCount==atmostLimit)
  11427. {
  11428. atmostsTriggered++;
  11429. right.clear();
  11430. groupCount = 0;
  11431. while(next)
  11432. {
  11433. ReleaseRoxieRow(next);
  11434. next = groupedSortedRight->nextRow();
  11435. }
  11436. }
  11437. else
  11438. {
  11439. right.append(next);
  11440. groupCount++;
  11441. }
  11442. next = groupedSortedRight->nextRow();
  11443. }
  11444. // 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
  11445. if(betweenjoin && left)
  11446. {
  11447. pendingRight = groupedSortedRight->nextRow();
  11448. if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
  11449. break;
  11450. }
  11451. else
  11452. break;
  11453. }
  11454. matchedRight.kill();
  11455. ForEachItemIn(idx, right)
  11456. matchedRight.append(false);
  11457. }
  11458. const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter, unsigned flags)
  11459. {
  11460. if (cloneLeft)
  11461. {
  11462. LinkRoxieRow(curLeft);
  11463. return curLeft;
  11464. }
  11465. try
  11466. {
  11467. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11468. size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  11469. if (thisSize)
  11470. return rowBuilder.finalizeRowClear(thisSize);
  11471. else
  11472. return NULL;
  11473. }
  11474. catch (IException *E)
  11475. {
  11476. throw makeWrappedException(E);
  11477. }
  11478. }
  11479. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  11480. {
  11481. try
  11482. {
  11483. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11484. unsigned numRows = rows.ordinality();
  11485. const void * right = numRows ? rows.item(0) : defaultRight.get();
  11486. if (numRows>0)
  11487. flags |= JTFmatchedright;
  11488. size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray(), flags);
  11489. if (thisSize)
  11490. return rowBuilder.finalizeRowClear(thisSize);
  11491. else
  11492. return NULL;
  11493. }
  11494. catch (IException *E)
  11495. {
  11496. throw makeWrappedException(E);
  11497. }
  11498. }
  11499. const void * joinException(const void * curLeft, IException * except)
  11500. {
  11501. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11502. size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except, JTFmatchedleft);
  11503. return rowBuilder.finalizeRowClear(thisSize);
  11504. }
  11505. void failLimit()
  11506. {
  11507. helper.onMatchAbortLimitExceeded();
  11508. CommonXmlWriter xmlwrite(0);
  11509. if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  11510. {
  11511. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  11512. }
  11513. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  11514. }
  11515. virtual const void * nextRow()
  11516. {
  11517. ActivityTimer t(totalCycles, timeActivities);
  11518. for (;;)
  11519. {
  11520. switch (state)
  11521. {
  11522. case JSfill:
  11523. fillLeft();
  11524. state = JSfillright;
  11525. break;
  11526. case JSfillright:
  11527. fillRight();
  11528. state = JScollate;
  11529. break;
  11530. case JSfillleft:
  11531. fillLeft();
  11532. state = JScollate;
  11533. break;
  11534. case JScollate:
  11535. if (right.ordinality() == 0)
  11536. {
  11537. if (left == NULL)
  11538. return NULL;
  11539. state = JSleftonly;
  11540. }
  11541. else
  11542. {
  11543. if (!left)
  11544. state = JSrightonly;
  11545. else
  11546. {
  11547. int diff;
  11548. if(betweenjoin)
  11549. diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
  11550. else
  11551. diff = collate->docompare(left, right.item(0));
  11552. bool limitExceeded = right.ordinality()>abortLimit;
  11553. if (diff == 0)
  11554. {
  11555. if (limitExceeded)
  11556. {
  11557. const void * ret = NULL;
  11558. if(failingLimit)
  11559. ret = joinException(left, failingLimit);
  11560. ReleaseRoxieRow(left);
  11561. left = NULL;
  11562. state = JSfillleft;
  11563. ForEachItemIn(idx, right)
  11564. matchedRight.replace(true, idx);
  11565. if(ret)
  11566. {
  11567. processed++;
  11568. return ret;
  11569. }
  11570. }
  11571. else
  11572. {
  11573. state = JScompare;
  11574. joinLimit = keepLimit;
  11575. }
  11576. }
  11577. else if (diff < 0)
  11578. state = JSleftonly;
  11579. else if (limitExceeded)
  11580. {
  11581. // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
  11582. state = JSfillright;
  11583. }
  11584. else
  11585. state = JSrightonly;
  11586. }
  11587. }
  11588. break;
  11589. case JSrightonly:
  11590. if (rightOuterJoin)
  11591. {
  11592. switch (activityKind)
  11593. {
  11594. case TAKjoin:
  11595. {
  11596. while (right.isItem(rightIndex))
  11597. {
  11598. if (!matchedRight.item(rightIndex))
  11599. {
  11600. const void * rhs = right.item(rightIndex++);
  11601. const void *ret = joinRecords(defaultLeft, rhs, 0, JTFmatchedright);
  11602. if (ret)
  11603. {
  11604. processed++;
  11605. return ret;
  11606. }
  11607. }
  11608. else
  11609. rightIndex++;
  11610. }
  11611. break;
  11612. }
  11613. //Probably excessive to implement the following, but possibly useful
  11614. case TAKdenormalize:
  11615. {
  11616. OwnedConstRoxieRow newLeft;
  11617. newLeft.set(defaultLeft);
  11618. unsigned rowSize = 0;
  11619. unsigned leftCount = 0;
  11620. while (right.isItem(rightIndex))
  11621. {
  11622. if (!matchedRight.item(rightIndex))
  11623. {
  11624. const void * rhs = right.item(rightIndex);
  11625. try
  11626. {
  11627. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11628. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedright);
  11629. if (thisSize)
  11630. {
  11631. rowSize = thisSize;
  11632. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11633. }
  11634. }
  11635. catch (IException *E)
  11636. {
  11637. throw makeWrappedException(E);
  11638. }
  11639. }
  11640. rightIndex++;
  11641. }
  11642. state = JSfillright;
  11643. if (rowSize)
  11644. {
  11645. processed++;
  11646. return newLeft.getClear();
  11647. }
  11648. break;
  11649. }
  11650. case TAKdenormalizegroup:
  11651. {
  11652. filteredRight.kill();
  11653. while (right.isItem(rightIndex))
  11654. {
  11655. if (!matchedRight.item(rightIndex))
  11656. filteredRight.append(right.item(rightIndex));
  11657. rightIndex++;
  11658. }
  11659. state = JSfillright;
  11660. if (filteredRight.ordinality())
  11661. {
  11662. const void * ret = denormalizeRecords(defaultLeft, filteredRight, 0);
  11663. filteredRight.kill();
  11664. if (ret)
  11665. {
  11666. processed++;
  11667. return ret;
  11668. }
  11669. }
  11670. break;
  11671. }
  11672. }
  11673. }
  11674. state = JSfillright;
  11675. break;
  11676. case JSleftonly:
  11677. {
  11678. const void * ret = NULL;
  11679. if (!matchedLeft && leftOuterJoin)
  11680. {
  11681. switch (activityKind)
  11682. {
  11683. case TAKjoin:
  11684. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  11685. break;
  11686. case TAKdenormalize:
  11687. ret = left;
  11688. left = NULL;
  11689. break;
  11690. case TAKdenormalizegroup:
  11691. filteredRight.kill();
  11692. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11693. break;
  11694. }
  11695. }
  11696. ReleaseRoxieRow(left);
  11697. left = NULL;
  11698. state = JSfillleft;
  11699. if (ret)
  11700. {
  11701. processed++;
  11702. return ret;
  11703. }
  11704. break;
  11705. }
  11706. case JScompare:
  11707. if (joinLimit != 0)
  11708. {
  11709. switch (activityKind)
  11710. {
  11711. case TAKjoin:
  11712. {
  11713. while (right.isItem(rightIndex))
  11714. {
  11715. const void * rhs = right.item(rightIndex++);
  11716. if (helper.match(left, rhs))
  11717. {
  11718. matchedRight.replace(true, rightIndex-1);
  11719. matchedLeft = true;
  11720. if (!exclude)
  11721. {
  11722. const void *ret = joinRecords(left, rhs, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  11723. if (ret)
  11724. {
  11725. processed++;
  11726. joinLimit--;
  11727. return ret;
  11728. }
  11729. }
  11730. }
  11731. }
  11732. break;
  11733. }
  11734. case TAKdenormalize:
  11735. {
  11736. OwnedConstRoxieRow newLeft;
  11737. newLeft.set(left);
  11738. unsigned rowSize = 0;
  11739. unsigned leftCount = 0;
  11740. while (right.isItem(rightIndex) && joinLimit)
  11741. {
  11742. try
  11743. {
  11744. const void * rhs = right.item(rightIndex++);
  11745. if (helper.match(left, rhs))
  11746. {
  11747. matchedRight.replace(true, rightIndex-1);
  11748. matchedLeft = true;
  11749. if (!exclude)
  11750. {
  11751. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  11752. unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount, JTFmatchedleft|JTFmatchedright);
  11753. if (thisSize)
  11754. {
  11755. rowSize = thisSize;
  11756. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  11757. joinLimit--;
  11758. }
  11759. }
  11760. }
  11761. }
  11762. catch (IException *E)
  11763. {
  11764. throw makeWrappedException(E);
  11765. }
  11766. }
  11767. state = JSleftonly;
  11768. rightIndex = 0;
  11769. if (rowSize)
  11770. {
  11771. processed++;
  11772. return newLeft.getClear();
  11773. }
  11774. break;
  11775. }
  11776. case TAKdenormalizegroup:
  11777. {
  11778. filteredRight.kill();
  11779. while (right.isItem(rightIndex))
  11780. {
  11781. const void * rhs = right.item(rightIndex++);
  11782. if (helper.match(left, rhs))
  11783. {
  11784. matchedRight.replace(true, rightIndex-1);
  11785. filteredRight.append(rhs);
  11786. matchedLeft = true;
  11787. if (filteredRight.ordinality()==joinLimit)
  11788. break;
  11789. }
  11790. }
  11791. state = JSleftonly;
  11792. rightIndex = 0;
  11793. if (!exclude && filteredRight.ordinality())
  11794. {
  11795. const void * ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  11796. filteredRight.kill();
  11797. if (ret)
  11798. {
  11799. processed++;
  11800. return ret;
  11801. }
  11802. }
  11803. break;
  11804. }
  11805. }
  11806. }
  11807. state = JSleftonly;
  11808. rightIndex = 0;
  11809. joinCounter = 0;
  11810. break;
  11811. }
  11812. }
  11813. }
  11814. };
  11815. class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
  11816. {
  11817. unsigned input2;
  11818. unsigned input2idx;
  11819. bool forceSpill;
  11820. public:
  11821. CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11822. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  11823. {
  11824. forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
  11825. input2 = 0;
  11826. input2idx = 0;
  11827. }
  11828. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  11829. {
  11830. return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
  11831. }
  11832. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  11833. {
  11834. if (idx==1)
  11835. {
  11836. input2 = source;
  11837. input2idx = sourceidx;
  11838. }
  11839. else
  11840. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  11841. }
  11842. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  11843. {
  11844. switch (idx)
  11845. {
  11846. case 1:
  11847. sourceidx = input2idx;
  11848. return input2;
  11849. case 0:
  11850. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  11851. default:
  11852. return (unsigned) -1;
  11853. }
  11854. }
  11855. virtual unsigned numInputs() const { return 2; }
  11856. virtual const StatisticsMapping &queryStatsMapping() const
  11857. {
  11858. return joinStatistics;
  11859. }
  11860. };
  11861. IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  11862. {
  11863. return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  11864. }
  11865. //=================================================================================
  11866. #define CONCAT_READAHEAD 1000
  11867. class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
  11868. {
  11869. public:
  11870. IMPLEMENT_IINTERFACE;
  11871. CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
  11872. : puller(false), ready(_ready), atEog(true), eof(false), grouped(_grouped)
  11873. {
  11874. }
  11875. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
  11876. {
  11877. space.reinit(CONCAT_READAHEAD);
  11878. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
  11879. }
  11880. void stop()
  11881. {
  11882. space.interrupt();
  11883. puller.stop();
  11884. }
  11885. IFinalRoxieInput *queryInput() const
  11886. {
  11887. return puller.queryInput();
  11888. }
  11889. void reset()
  11890. {
  11891. puller.reset();
  11892. ForEachItemIn(idx, buffer)
  11893. ReleaseRoxieRow(buffer.item(idx));
  11894. buffer.clear();
  11895. eof = false;
  11896. atEog = true;
  11897. }
  11898. void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
  11899. {
  11900. puller.setInput(this, _sourceIdx, _in);
  11901. }
  11902. void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
  11903. {
  11904. puller.connectInputStreams(ctx, consumerOrdered);
  11905. }
  11906. virtual void processRow(const void *row)
  11907. {
  11908. buffer.enqueue(row);
  11909. ready.signal();
  11910. space.wait();
  11911. }
  11912. virtual void processGroup(const ConstPointerArray &rows)
  11913. {
  11914. // We use record-by-record input mode of the puller thread even in grouped mode.
  11915. throwUnexpected();
  11916. }
  11917. virtual void processEOG()
  11918. {
  11919. if (grouped)
  11920. processRow(NULL);
  11921. }
  11922. virtual void processDone()
  11923. {
  11924. processRow(NULL);
  11925. }
  11926. virtual bool fireException(IException *e)
  11927. {
  11928. // called from puller thread on failure
  11929. ready.interrupt(LINK(e));
  11930. space.interrupt(e);
  11931. return true;
  11932. }
  11933. bool peek(const void * &row, bool &anyActive)
  11934. {
  11935. if (!eof)
  11936. {
  11937. if (buffer.ordinality())
  11938. {
  11939. space.signal();
  11940. row = buffer.dequeue();
  11941. if (row==NULL)
  11942. {
  11943. if (atEog)
  11944. {
  11945. eof = true;
  11946. return false;
  11947. }
  11948. else
  11949. atEog = true;
  11950. }
  11951. else if (grouped)
  11952. atEog = false;
  11953. return true;
  11954. }
  11955. anyActive = true;
  11956. }
  11957. return false;
  11958. }
  11959. protected:
  11960. RecordPullerThread puller;
  11961. InterruptableSemaphore space;
  11962. InterruptableSemaphore &ready;
  11963. SafeQueueOf<const void, true> buffer;
  11964. bool atEog;
  11965. bool eof;
  11966. bool grouped;
  11967. };
  11968. typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
  11969. class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
  11970. {
  11971. InterruptableSemaphore ready;
  11972. ReaderArray pullers;
  11973. unsigned numInputs;
  11974. unsigned nextPuller; // for round robin
  11975. unsigned readyPending;
  11976. bool eof;
  11977. bool inGroup;
  11978. bool grouped;
  11979. public:
  11980. CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  11981. : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
  11982. {
  11983. numInputs = _numInputs;
  11984. eof = (numInputs==0);
  11985. inGroup = false;
  11986. nextPuller = 0;
  11987. readyPending = 0;
  11988. for (unsigned i = 0; i < numInputs; i++)
  11989. pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
  11990. }
  11991. ~CRoxieServerThreadedConcatActivity()
  11992. {
  11993. ForEachItemIn(idx, pullers)
  11994. delete &pullers.item(idx);
  11995. }
  11996. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  11997. {
  11998. eof = (numInputs==0);
  11999. inGroup = false;
  12000. nextPuller = 0;
  12001. readyPending = 0;
  12002. ready.reinit();
  12003. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12004. ForEachItemIn(idx, pullers)
  12005. {
  12006. pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
  12007. // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
  12008. // in the part of the subgraph that the thread uses has been started.
  12009. // Note that splitters are supposed to cope with being used when only some outputs have been started.
  12010. }
  12011. }
  12012. virtual void stop()
  12013. {
  12014. ready.interrupt();
  12015. ForEachItemIn(idx, pullers)
  12016. pullers.item(idx).stop();
  12017. CRoxieServerActivity::stop();
  12018. }
  12019. virtual unsigned __int64 queryLocalCycles() const
  12020. {
  12021. return 0;
  12022. }
  12023. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  12024. {
  12025. if (pullers.isItem(idx))
  12026. return pullers.item(idx).queryInput();
  12027. else
  12028. return NULL;
  12029. }
  12030. virtual void reset()
  12031. {
  12032. CRoxieServerActivity::reset();
  12033. ForEachItemIn(idx, pullers)
  12034. pullers.item(idx).reset();
  12035. eof = false;
  12036. inGroup = false;
  12037. nextPuller = 0;
  12038. readyPending = 0;
  12039. }
  12040. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  12041. {
  12042. if (pullers.isItem(idx))
  12043. pullers.item(idx).setInput(_sourceIdx, _in);
  12044. else
  12045. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  12046. }
  12047. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  12048. {
  12049. ForEachItemIn(i, pullers)
  12050. pullers.item(i).connectInputStreams(ctx, consumerOrdered);
  12051. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
  12052. }
  12053. virtual const void * nextRow()
  12054. {
  12055. ActivityTimer t(totalCycles, timeActivities);
  12056. if (eof)
  12057. return NULL;
  12058. for (;;)
  12059. {
  12060. if (readyPending && !inGroup)
  12061. {
  12062. if (readyPending > 1)
  12063. ready.signal(readyPending-1);
  12064. readyPending = 0;
  12065. }
  12066. else
  12067. ready.wait();
  12068. bool anyActive = false;
  12069. ForEachItemIn(unused_index, pullers)
  12070. {
  12071. // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
  12072. const void *ret;
  12073. bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
  12074. if (fetched)
  12075. {
  12076. inGroup = (ret != NULL);
  12077. return ret;
  12078. }
  12079. if (inGroup && grouped)
  12080. {
  12081. // Some other puller has data, but we can't consume it until the group we are reading is complete.
  12082. readyPending++;
  12083. anyActive = true;
  12084. break;
  12085. }
  12086. nextPuller++;
  12087. if (nextPuller==pullers.ordinality())
  12088. nextPuller = 0;
  12089. }
  12090. if (!anyActive)
  12091. break;
  12092. // A ready signal without anything being ready means someone reached end-of-file.
  12093. }
  12094. eof = true;
  12095. return NULL;
  12096. }
  12097. };
  12098. class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
  12099. {
  12100. IEngineRowStream *curStream;
  12101. bool eogSeen;
  12102. bool anyThisGroup;
  12103. bool grouped;
  12104. unsigned streamIdx;
  12105. public:
  12106. CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
  12107. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12108. {
  12109. eogSeen = false;
  12110. anyThisGroup = false;
  12111. grouped = _grouped;
  12112. streamIdx = 0;
  12113. curStream = NULL;
  12114. }
  12115. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12116. {
  12117. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12118. streamIdx = 0;
  12119. curStream = streamArray[streamIdx];
  12120. eogSeen = false;
  12121. anyThisGroup = false;
  12122. }
  12123. virtual const void * nextRow()
  12124. {
  12125. ActivityTimer t(totalCycles, timeActivities);
  12126. if (!curStream)
  12127. return NULL; // eof
  12128. const void * next = curStream->nextRow();
  12129. if (next)
  12130. {
  12131. anyThisGroup = true;
  12132. eogSeen = false;
  12133. processed++;
  12134. return next;
  12135. }
  12136. else if (!eogSeen)
  12137. {
  12138. eogSeen = true;
  12139. if (grouped)
  12140. {
  12141. if (anyThisGroup)
  12142. {
  12143. anyThisGroup = false;
  12144. return NULL;
  12145. }
  12146. else
  12147. return nextRow();
  12148. }
  12149. else
  12150. return nextRow();
  12151. }
  12152. else if (streamIdx < numStreams-1)
  12153. {
  12154. streamIdx++;
  12155. curStream = streamArray[streamIdx];
  12156. eogSeen = false;
  12157. return nextRow();
  12158. }
  12159. else
  12160. {
  12161. curStream = NULL;
  12162. return NULL;
  12163. }
  12164. }
  12165. };
  12166. class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
  12167. {
  12168. bool ordered;
  12169. bool grouped;
  12170. public:
  12171. CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12172. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12173. {
  12174. Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
  12175. ordered = helper->isOrdered();
  12176. grouped = helper->queryOutputMeta()->isGrouped();
  12177. }
  12178. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12179. {
  12180. if (ordered || (_probeManager && _probeManager->queryDebugManager()))
  12181. return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12182. else
  12183. return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
  12184. }
  12185. };
  12186. IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12187. {
  12188. return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12189. }
  12190. //=================================================================================
  12191. class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
  12192. {
  12193. IEngineRowStream* selectedStream;
  12194. unsigned savedParentExtractSize;
  12195. const byte * savedParentExtract;
  12196. bool foundInput;
  12197. bool unusedStopped;
  12198. public:
  12199. CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12200. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  12201. {
  12202. foundInput = false;
  12203. unusedStopped = false;
  12204. selectedStream = NULL;
  12205. savedParentExtractSize = 0;;
  12206. savedParentExtract = NULL;
  12207. }
  12208. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12209. {
  12210. //Don't start the inputs yet so we can short-circuit...
  12211. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  12212. savedParentExtractSize = parentExtractSize;
  12213. savedParentExtract = parentExtract;
  12214. }
  12215. virtual void stop()
  12216. {
  12217. if (unusedStopped)
  12218. {
  12219. if (selectedStream)
  12220. selectedStream->stop();
  12221. }
  12222. else
  12223. {
  12224. //May possibly call stop too many times if input->start() throws an exception (e.g. due to a dependency)
  12225. for (unsigned i = 0; i < numStreams; i++)
  12226. streamArray[i]->stop();
  12227. }
  12228. CRoxieServerMultiInputBaseActivity::stop();
  12229. }
  12230. virtual void reset()
  12231. {
  12232. CRoxieServerMultiInputBaseActivity::reset();
  12233. foundInput = false;
  12234. unusedStopped = false;
  12235. selectedStream = NULL;
  12236. }
  12237. virtual unsigned __int64 queryLocalCycles() const
  12238. {
  12239. return 0; // Can't easily calculate anything reliable but local processing is negligible
  12240. }
  12241. virtual const void * nextRow()
  12242. {
  12243. ActivityTimer t(totalCycles, timeActivities);
  12244. if (!foundInput)
  12245. {
  12246. foundInput = true;
  12247. assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
  12248. //If we get an exception in this loop then stop() will stop any started inputs
  12249. for (unsigned i=0; i < numStreams; i++)
  12250. {
  12251. selectedStream = streamArray[i];
  12252. inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
  12253. startJunction(junctionArray[i]);
  12254. const void * next = selectedStream->nextRow();
  12255. if (next)
  12256. {
  12257. //Found a row so stop remaining
  12258. for (unsigned j=i+1; j < numInputs; j++)
  12259. streamArray[j]->stop();
  12260. unusedStopped = true;
  12261. processed++;
  12262. return next;
  12263. }
  12264. selectedStream->stop();
  12265. }
  12266. unusedStopped = true;
  12267. selectedStream = NULL;
  12268. return NULL;
  12269. }
  12270. if (!selectedStream)
  12271. return NULL;
  12272. const void * next = selectedStream->nextRow();
  12273. if (next)
  12274. processed++;
  12275. return next;
  12276. }
  12277. };
  12278. class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
  12279. {
  12280. public:
  12281. CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12282. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12283. {
  12284. }
  12285. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12286. {
  12287. return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
  12288. }
  12289. };
  12290. IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12291. {
  12292. return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12293. }
  12294. //=================================================================================
  12295. class SingleNodeActivityContext : public IThorActivityContext
  12296. {
  12297. public:
  12298. SingleNodeActivityContext(unsigned _numStrands, unsigned _curStrand) : strands(_numStrands), curStrand(_curStrand) { assertex(curStrand < strands); }
  12299. virtual bool isLocal() const override { return false; }
  12300. virtual unsigned numSlaves() const override { return 1; }
  12301. virtual unsigned numStrands() const override { return strands; }
  12302. virtual unsigned querySlave() const override { return 0; }
  12303. virtual unsigned queryStrand() const override { return curStrand; }
  12304. protected:
  12305. unsigned strands;
  12306. unsigned curStrand;
  12307. };
  12308. class CRoxieServerExternalActivity : public CRoxieServerMultiInputActivity
  12309. {
  12310. Owned<IRowStream> rows;
  12311. SingleNodeActivityContext activityContext;
  12312. public:
  12313. CRoxieServerExternalActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12314. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), activityContext(1, 0)
  12315. {
  12316. }
  12317. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
  12318. {
  12319. Owned<IStrandJunction> junction = CRoxieServerMultiInputActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  12320. associateInputsWithHelper();
  12321. return junction.getClear();
  12322. }
  12323. virtual void connectInputStreams(bool consumerOrdered)
  12324. {
  12325. CRoxieServerMultiInputActivity::connectInputStreams(consumerOrdered);
  12326. associateInputsWithHelper();
  12327. }
  12328. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12329. {
  12330. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12331. if (factory->getKind() != TAKexternalsink)
  12332. {
  12333. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12334. rows.setown(helper.createOutput(&activityContext));
  12335. }
  12336. }
  12337. virtual void stop()
  12338. {
  12339. if (rows)
  12340. {
  12341. rows->stop();
  12342. rows.clear();
  12343. }
  12344. CRoxieServerMultiInputBaseActivity::stop();
  12345. }
  12346. virtual void reset()
  12347. {
  12348. rows.clear();
  12349. }
  12350. virtual const void * nextRow()
  12351. {
  12352. ActivityTimer t(totalCycles, timeActivities);
  12353. assertex(rows);
  12354. const void * next = rows->nextRow();
  12355. if (next)
  12356. processed++;
  12357. return next;
  12358. }
  12359. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  12360. {
  12361. try
  12362. {
  12363. start(parentExtractSize, parentExtract, false);
  12364. assertex(!rows);
  12365. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12366. helper.execute(&activityContext);
  12367. stop();
  12368. }
  12369. catch (IException * E)
  12370. {
  12371. ctx->notifyAbort(E);
  12372. abort();
  12373. throw;
  12374. }
  12375. }
  12376. protected:
  12377. void associateInputsWithHelper()
  12378. {
  12379. IHThorExternalArg & helper = static_cast<IHThorExternalArg &>(basehelper);
  12380. for (unsigned i = 0; i < numInputs; i++)
  12381. helper.setInput(i, streamArray[i]);
  12382. }
  12383. };
  12384. class CRoxieServerExternalActivityFactory : public CRoxieServerMultiInputFactory
  12385. {
  12386. bool isRoot;
  12387. public:
  12388. CRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12389. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  12390. {
  12391. }
  12392. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12393. {
  12394. return new CRoxieServerExternalActivity(_ctx, this, _probeManager, numInputs());
  12395. }
  12396. virtual bool isSink() const
  12397. {
  12398. return (kind == TAKexternalsink) && isRoot;
  12399. }
  12400. };
  12401. IRoxieServerActivityFactory *createRoxieServerExternalActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  12402. {
  12403. return new CRoxieServerExternalActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  12404. }
  12405. //=================================================================================
  12406. class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
  12407. {
  12408. IHThorMergeArg &helper;
  12409. unsigned *mergeheap;
  12410. unsigned activeInputs;
  12411. const void **pending;
  12412. bool first;
  12413. ICompare *compare;
  12414. bool dedup;
  12415. void permute()
  12416. {
  12417. assertex(activeInputs == 0);
  12418. for(unsigned i = 0; i < numStreams; i++)
  12419. if(pullInput(i))
  12420. mergeheap[activeInputs++] = i;
  12421. // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
  12422. // the heap property: no element should be smaller than its parent
  12423. // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
  12424. // 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
  12425. if (activeInputs >= 2)
  12426. for(unsigned p = (activeInputs-2)/2; p > 0; --p)
  12427. siftDown(p);
  12428. if(dedup)
  12429. siftDownDedupTop();
  12430. else
  12431. siftDown(0);
  12432. }
  12433. void readNext()
  12434. {
  12435. if(!pullInput(mergeheap[0]))
  12436. if(!promote(0))
  12437. return;
  12438. // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
  12439. if(dedup)
  12440. siftDownDedupTop();
  12441. else
  12442. siftDown(0);
  12443. }
  12444. bool pullInput(unsigned i)
  12445. {
  12446. const void *next = streamArray[i]->ungroupedNextRow();
  12447. pending[i] = next;
  12448. return (next != NULL);
  12449. }
  12450. bool promote(unsigned p)
  12451. {
  12452. activeInputs--;
  12453. if(activeInputs == p)
  12454. return false;
  12455. mergeheap[p] = mergeheap[activeInputs];
  12456. return true;
  12457. }
  12458. bool siftDown(unsigned p)
  12459. {
  12460. // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
  12461. bool nochange = true;
  12462. while(1)
  12463. {
  12464. unsigned c = p*2 + 1;
  12465. if(c >= activeInputs)
  12466. return nochange;
  12467. if(c+1 < activeInputs)
  12468. {
  12469. int childcmp = BuffCompare(c+1, c);
  12470. if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
  12471. ++c;
  12472. }
  12473. int cmp = BuffCompare(c, p);
  12474. if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
  12475. return nochange;
  12476. nochange = false;
  12477. unsigned r = mergeheap[c];
  12478. mergeheap[c] = mergeheap[p];
  12479. mergeheap[p] = r;
  12480. p = c;
  12481. }
  12482. }
  12483. void siftDownDedupTop()
  12484. {
  12485. // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
  12486. if(activeInputs < 2)
  12487. return;
  12488. unsigned c = 1;
  12489. int childcmp = 1;
  12490. if(activeInputs >= 3)
  12491. {
  12492. childcmp = BuffCompare(2, 1);
  12493. if(childcmp < 0)
  12494. c = 2;
  12495. }
  12496. int cmp = BuffCompare(c, 0);
  12497. if(cmp > 0)
  12498. return;
  12499. // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
  12500. while(cmp <= 0)
  12501. {
  12502. if(cmp == 0)
  12503. {
  12504. if(mergeheap[c] < mergeheap[0])
  12505. {
  12506. unsigned r = mergeheap[c];
  12507. mergeheap[c] = mergeheap[0];
  12508. mergeheap[0] = r;
  12509. }
  12510. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12511. if(!pullInput(mergeheap[c]))
  12512. if(!promote(c))
  12513. break;
  12514. siftDown(c);
  12515. }
  12516. else
  12517. {
  12518. unsigned r = mergeheap[c];
  12519. mergeheap[c] = mergeheap[0];
  12520. mergeheap[0] = r;
  12521. if(siftDown(c))
  12522. break;
  12523. }
  12524. cmp = BuffCompare(c, 0);
  12525. }
  12526. // the following loop ensures the uniqueness property holds on the other branch too
  12527. c = 3-c;
  12528. if(activeInputs <= c)
  12529. return;
  12530. while(childcmp == 0)
  12531. {
  12532. if(mergeheap[c] < mergeheap[0])
  12533. {
  12534. unsigned r = mergeheap[c];
  12535. mergeheap[c] = mergeheap[0];
  12536. mergeheap[0] = r;
  12537. }
  12538. ReleaseClearRoxieRow(pending[mergeheap[c]]);
  12539. if(!pullInput(mergeheap[c]))
  12540. if(!promote(c))
  12541. break;
  12542. siftDown(c);
  12543. childcmp = BuffCompare(c, 0);
  12544. }
  12545. }
  12546. inline int BuffCompare(unsigned a, unsigned b)
  12547. {
  12548. return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
  12549. }
  12550. public:
  12551. CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12552. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
  12553. {
  12554. activeInputs = 0;
  12555. first = true;
  12556. mergeheap = new unsigned[numInputs];
  12557. pending = new const void *[numStreams];
  12558. compare = helper.queryCompare();
  12559. dedup = helper.dedup();
  12560. for (unsigned i = 0; i < numStreams; i++)
  12561. pending[i] = NULL;
  12562. }
  12563. ~CRoxieServerMergeActivity()
  12564. {
  12565. delete [] mergeheap;
  12566. delete [] pending;
  12567. }
  12568. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12569. {
  12570. activeInputs = 0;
  12571. first = true;
  12572. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12573. }
  12574. virtual void reset()
  12575. {
  12576. for (unsigned i = 0; i < numStreams; i++)
  12577. ReleaseClearRoxieRow(pending[i]);
  12578. CRoxieServerMultiInputActivity::reset();
  12579. }
  12580. virtual const void * nextRow()
  12581. {
  12582. ActivityTimer t(totalCycles, timeActivities);
  12583. if (first)
  12584. {
  12585. permute();
  12586. first = false;
  12587. }
  12588. if (activeInputs)
  12589. {
  12590. const void *next = pending[mergeheap[0]];
  12591. readNext();
  12592. if (next)
  12593. processed++;
  12594. return next;
  12595. }
  12596. else
  12597. return NULL;
  12598. }
  12599. };
  12600. class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
  12601. {
  12602. public:
  12603. CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12604. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12605. {
  12606. }
  12607. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12608. {
  12609. return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
  12610. }
  12611. };
  12612. IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12613. {
  12614. return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12615. }
  12616. //=================================================================================
  12617. class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
  12618. {
  12619. unsigned streamIndex;
  12620. bool eof;
  12621. unsigned __int64 numProcessedLastGroup;
  12622. public:
  12623. CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12624. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
  12625. {
  12626. streamIndex = 0;
  12627. eof = false;
  12628. numProcessedLastGroup = 0;
  12629. }
  12630. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12631. {
  12632. streamIndex = 0;
  12633. eof = false;
  12634. numProcessedLastGroup = processed;
  12635. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12636. }
  12637. const void * nextFromInputs()
  12638. {
  12639. unsigned initialStream = streamIndex;
  12640. while (streamIndex < numStreams)
  12641. {
  12642. const void * next = streamArray[streamIndex]->nextRow();
  12643. if (next)
  12644. {
  12645. if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
  12646. {
  12647. ReleaseRoxieRow(next);
  12648. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12649. }
  12650. return next;
  12651. }
  12652. streamIndex++;
  12653. }
  12654. if ((initialStream != 0) && (initialStream+1 != numStreams))
  12655. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
  12656. streamIndex = 0;
  12657. return NULL;
  12658. }
  12659. virtual const void * nextRow()
  12660. {
  12661. ActivityTimer t(totalCycles, timeActivities);
  12662. if (eof)
  12663. return NULL;
  12664. const void * ret = nextFromInputs();
  12665. if (ret)
  12666. {
  12667. processed++;
  12668. return ret;
  12669. }
  12670. if (numProcessedLastGroup != processed)
  12671. {
  12672. numProcessedLastGroup = processed;
  12673. return NULL;
  12674. }
  12675. eof = true;
  12676. return NULL;
  12677. }
  12678. };
  12679. class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
  12680. {
  12681. public:
  12682. CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12683. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12684. {
  12685. }
  12686. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12687. {
  12688. return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
  12689. }
  12690. };
  12691. IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12692. {
  12693. return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12694. }
  12695. //=================================================================================
  12696. class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
  12697. {
  12698. IHThorCombineArg &helper;
  12699. unsigned __int64 numProcessedLastGroup;
  12700. public:
  12701. CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  12702. : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
  12703. {
  12704. numProcessedLastGroup = 0;
  12705. }
  12706. ~CRoxieServerCombineActivity()
  12707. {
  12708. }
  12709. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12710. {
  12711. numProcessedLastGroup = processed;
  12712. CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
  12713. }
  12714. void nextInputs(ConstPointerArray & out)
  12715. {
  12716. for (unsigned i=0; i < numStreams; i++)
  12717. {
  12718. const void * next = streamArray[i]->nextRow();
  12719. if (next)
  12720. out.append(next);
  12721. }
  12722. }
  12723. virtual bool needsAllocator() const { return true; }
  12724. virtual const void * nextRow()
  12725. {
  12726. ActivityTimer t(totalCycles, timeActivities);
  12727. for (;;)
  12728. {
  12729. ConstPointerArray group;
  12730. nextInputs(group);
  12731. if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
  12732. nextInputs(group);
  12733. if (group.ordinality() == 0)
  12734. {
  12735. numProcessedLastGroup = processed;
  12736. return NULL;
  12737. }
  12738. else if (group.ordinality() != numInputs)
  12739. {
  12740. ReleaseRoxieRows(group);
  12741. throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
  12742. }
  12743. try
  12744. {
  12745. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12746. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
  12747. ReleaseRoxieRows(group);
  12748. if (outSize)
  12749. {
  12750. processed++;
  12751. return rowBuilder.finalizeRowClear(outSize);
  12752. }
  12753. }
  12754. catch (IException *E)
  12755. {
  12756. ReleaseRoxieRows(group);
  12757. throw makeWrappedException(E);
  12758. }
  12759. }
  12760. }
  12761. };
  12762. class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
  12763. {
  12764. public:
  12765. CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12766. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12767. {
  12768. }
  12769. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12770. {
  12771. return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
  12772. }
  12773. };
  12774. IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12775. {
  12776. return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12777. }
  12778. //=================================================================================
  12779. class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
  12780. {
  12781. IHThorCombineGroupArg &helper;
  12782. unsigned __int64 numProcessedLastGroup;
  12783. public:
  12784. CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12785. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
  12786. {
  12787. numProcessedLastGroup = 0;
  12788. }
  12789. ~CRoxieServerCombineGroupActivity()
  12790. {
  12791. }
  12792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12793. {
  12794. numProcessedLastGroup = processed;
  12795. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  12796. }
  12797. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  12798. {
  12799. if (idx==(unsigned)-1)
  12800. idx = 0;
  12801. return idx ? NULL : this;
  12802. }
  12803. virtual bool needsAllocator() const { return true; }
  12804. virtual const void * nextRow()
  12805. {
  12806. ActivityTimer t(totalCycles, timeActivities);
  12807. for (;;)
  12808. {
  12809. const void * left = inputStream->nextRow();
  12810. if (!left && (numProcessedLastGroup == processed))
  12811. left = inputStream->nextRow();
  12812. if (!left)
  12813. {
  12814. if (numProcessedLastGroup == processed)
  12815. {
  12816. const void * nextRight = inputStream1->nextRow();
  12817. if (nextRight)
  12818. {
  12819. ReleaseRoxieRow(nextRight);
  12820. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
  12821. }
  12822. }
  12823. else
  12824. numProcessedLastGroup = processed;
  12825. return NULL;
  12826. }
  12827. ConstPointerArray group;
  12828. for (;;)
  12829. {
  12830. const void * in = inputStream1->nextRow();
  12831. if (!in)
  12832. break;
  12833. group.append(in);
  12834. }
  12835. if (group.ordinality() == 0)
  12836. {
  12837. ReleaseRoxieRow(left);
  12838. ReleaseRoxieRows(group);
  12839. throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
  12840. }
  12841. try
  12842. {
  12843. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12844. size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
  12845. ReleaseRoxieRow(left);
  12846. ReleaseRoxieRows(group);
  12847. if (outSize)
  12848. {
  12849. processed++;
  12850. return rowBuilder.finalizeRowClear(outSize);
  12851. }
  12852. }
  12853. catch (IException *E)
  12854. {
  12855. ReleaseRoxieRow(left);
  12856. ReleaseRoxieRows(group);
  12857. throw makeWrappedException(E);
  12858. }
  12859. }
  12860. }
  12861. };
  12862. class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
  12863. {
  12864. unsigned input2;
  12865. unsigned input2idx;
  12866. public:
  12867. CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12868. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12869. {
  12870. input2 = 0;
  12871. input2idx = 0;
  12872. }
  12873. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12874. {
  12875. return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
  12876. }
  12877. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  12878. {
  12879. if (idx==1)
  12880. {
  12881. input2 = source;
  12882. input2idx = sourceidx;
  12883. }
  12884. else
  12885. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  12886. }
  12887. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  12888. {
  12889. switch (idx)
  12890. {
  12891. case 1:
  12892. sourceidx = input2idx;
  12893. return input2;
  12894. case 0:
  12895. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  12896. default:
  12897. return (unsigned) -1;
  12898. }
  12899. }
  12900. virtual unsigned numInputs() const { return 2; }
  12901. };
  12902. IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12903. {
  12904. return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12905. }
  12906. //=================================================================================
  12907. class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
  12908. {
  12909. IHThorRollupGroupArg &helper;
  12910. bool eof;
  12911. public:
  12912. CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12913. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  12914. helper((IHThorRollupGroupArg &)basehelper)
  12915. {
  12916. eof = false;
  12917. }
  12918. ~CRoxieServerRollupGroupActivity()
  12919. {
  12920. }
  12921. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12922. {
  12923. eof = false;
  12924. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  12925. }
  12926. virtual bool needsAllocator() const { return true; }
  12927. virtual const void * nextRow()
  12928. {
  12929. ActivityTimer t(totalCycles, timeActivities);
  12930. if (eof)
  12931. return NULL;
  12932. for (;;)
  12933. {
  12934. ConstPointerArray group;
  12935. for (;;)
  12936. {
  12937. const void * in = inputStream->nextRow();
  12938. if (!in)
  12939. break;
  12940. group.append(in);
  12941. }
  12942. if (group.ordinality() == 0)
  12943. {
  12944. eof = true;
  12945. return NULL;
  12946. }
  12947. try
  12948. {
  12949. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  12950. size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
  12951. ReleaseRoxieRows(group);
  12952. if (outSize)
  12953. {
  12954. processed++;
  12955. return rowBuilder.finalizeRowClear(outSize);
  12956. }
  12957. }
  12958. catch (IException * E)
  12959. {
  12960. ReleaseRoxieRows(group);
  12961. throw makeWrappedException(E);
  12962. }
  12963. }
  12964. }
  12965. };
  12966. class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
  12967. {
  12968. public:
  12969. CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12970. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  12971. {
  12972. }
  12973. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  12974. {
  12975. return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
  12976. }
  12977. };
  12978. IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  12979. {
  12980. return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  12981. }
  12982. //=================================================================================
  12983. class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
  12984. {
  12985. IHThorFilterProjectArg &helper;
  12986. unsigned numProcessedLastGroup;
  12987. unsigned __int64 recordCount;
  12988. public:
  12989. CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  12990. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
  12991. {
  12992. numProcessedLastGroup = 0;
  12993. recordCount = 0;
  12994. }
  12995. ~CRoxieServerFilterProjectActivity()
  12996. {
  12997. }
  12998. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  12999. {
  13000. numProcessedLastGroup = 0;
  13001. recordCount = 0;
  13002. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  13003. lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
  13004. }
  13005. virtual bool needsAllocator() const { return true; }
  13006. virtual const void * nextRow()
  13007. {
  13008. ActivityTimer t(totalCycles, timeActivities);
  13009. if (eof)
  13010. return NULL;
  13011. for (;;)
  13012. {
  13013. const void * in = inputStream->nextRow();
  13014. if (!in)
  13015. {
  13016. recordCount = 0;
  13017. if (numProcessedLastGroup == processed)
  13018. in = inputStream->nextRow();
  13019. if (!in)
  13020. {
  13021. numProcessedLastGroup = processed;
  13022. return NULL;
  13023. }
  13024. }
  13025. try
  13026. {
  13027. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13028. size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
  13029. ReleaseRoxieRow(in);
  13030. if (outSize)
  13031. {
  13032. processed++;
  13033. return rowBuilder.finalizeRowClear(outSize);
  13034. }
  13035. }
  13036. catch (IException *E)
  13037. {
  13038. throw makeWrappedException(E);
  13039. }
  13040. }
  13041. }
  13042. };
  13043. class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
  13044. {
  13045. public:
  13046. CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13047. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13048. {
  13049. //MORE: Code generator needs to indicate if the count is used.
  13050. //optStableInput = false;
  13051. }
  13052. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13053. {
  13054. return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
  13055. }
  13056. };
  13057. IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13058. {
  13059. return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13060. }
  13061. //=====================================================
  13062. class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
  13063. {
  13064. class ProjectProcessor : public StrandProcessor
  13065. {
  13066. protected:
  13067. IHThorProjectArg &helper;
  13068. public:
  13069. ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
  13070. : StrandProcessor(_parent, _inputStream, true), helper(_helper)
  13071. {
  13072. }
  13073. virtual const void * nextRow()
  13074. {
  13075. ActivityTimer t(totalCycles, timeActivities);
  13076. for (;;)
  13077. {
  13078. OwnedConstRoxieRow in = inputStream->nextRow();
  13079. if (!in)
  13080. {
  13081. if (numProcessedLastGroup == processed)
  13082. in.setown(inputStream->nextRow());
  13083. if (!in)
  13084. {
  13085. numProcessedLastGroup = processed;
  13086. return NULL;
  13087. }
  13088. }
  13089. try
  13090. {
  13091. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13092. size32_t outSize;
  13093. outSize = helper.transform(rowBuilder, in);
  13094. if (outSize)
  13095. {
  13096. processed++;
  13097. return rowBuilder.finalizeRowClear(outSize);
  13098. }
  13099. }
  13100. catch (IException *E)
  13101. {
  13102. throw parent.makeWrappedException(E);
  13103. }
  13104. }
  13105. }
  13106. };
  13107. public:
  13108. CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
  13109. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
  13110. {
  13111. }
  13112. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13113. {
  13114. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  13115. onStartStrands();
  13116. }
  13117. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  13118. {
  13119. return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
  13120. }
  13121. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  13122. };
  13123. class CRoxieServerProjectActivity : public CRoxieServerActivity
  13124. {
  13125. unsigned numProcessedLastGroup;
  13126. unsigned __int64 recordCount;
  13127. bool count;
  13128. public:
  13129. CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
  13130. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13131. count(_count)
  13132. {
  13133. numProcessedLastGroup = 0;
  13134. recordCount = 0;
  13135. }
  13136. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13137. {
  13138. numProcessedLastGroup = 0;
  13139. recordCount = 0;
  13140. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13141. }
  13142. virtual bool needsAllocator() const { return true; }
  13143. virtual const void * nextRow()
  13144. {
  13145. ActivityTimer t(totalCycles, timeActivities);
  13146. for (;;)
  13147. {
  13148. OwnedConstRoxieRow in = inputStream->nextRow();
  13149. if (!in)
  13150. {
  13151. recordCount = 0;
  13152. if (numProcessedLastGroup == processed)
  13153. in.setown(inputStream->nextRow());
  13154. if (!in)
  13155. {
  13156. numProcessedLastGroup = processed;
  13157. return NULL;
  13158. }
  13159. }
  13160. try
  13161. {
  13162. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13163. size32_t outSize;
  13164. if (count)
  13165. outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
  13166. else
  13167. outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
  13168. if (outSize)
  13169. {
  13170. processed++;
  13171. return rowBuilder.finalizeRowClear(outSize);
  13172. }
  13173. }
  13174. catch (IException *E)
  13175. {
  13176. throw makeWrappedException(E);
  13177. }
  13178. }
  13179. }
  13180. };
  13181. class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
  13182. {
  13183. protected:
  13184. StrandOptions strandOptions;
  13185. bool count;
  13186. public:
  13187. CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13188. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  13189. {
  13190. count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
  13191. optStableInput = count;
  13192. }
  13193. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13194. {
  13195. // 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.
  13196. if (kind == TAKproject) // Not supported on prefetch or count projects
  13197. return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
  13198. else
  13199. return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
  13200. }
  13201. };
  13202. IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13203. {
  13204. return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13205. }
  13206. //=================================================================================
  13207. class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
  13208. {
  13209. unsigned numProcessedLastGroup;
  13210. bool eof;
  13211. bool allPulled;
  13212. bool isThreaded;
  13213. unsigned preload;
  13214. unsigned __int64 recordCount;
  13215. IHThorPrefetchProjectArg &helper;
  13216. RecordPullerThread puller;
  13217. InterruptableSemaphore ready;
  13218. InterruptableSemaphore space;
  13219. class PrefetchInfo : public CInterface
  13220. {
  13221. public:
  13222. inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
  13223. {
  13224. if (helper.preTransform(extract, _in, _recordCount))
  13225. {
  13226. in.setown(_in);
  13227. recordCount = _recordCount;
  13228. }
  13229. else
  13230. {
  13231. ReleaseRoxieRow(_in);
  13232. recordCount = 0;
  13233. }
  13234. }
  13235. OwnedConstRoxieRow in;
  13236. unsigned __int64 recordCount;
  13237. rtlRowBuilder extract;
  13238. };
  13239. QueueOf<PrefetchInfo, true> pulled;
  13240. CriticalSection pulledCrit;
  13241. public:
  13242. CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  13243. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13244. helper((IHThorPrefetchProjectArg &) basehelper),
  13245. puller(false)
  13246. {
  13247. numProcessedLastGroup = 0;
  13248. recordCount = 0;
  13249. eof = false;
  13250. allPulled = false;
  13251. isThreaded = (helper.getFlags() & PPFparallel) != 0;
  13252. preload = 0;
  13253. }
  13254. ~CRoxieServerPrefetchProjectActivity()
  13255. {
  13256. while (pulled.ordinality())
  13257. ::Release(pulled.dequeue());
  13258. }
  13259. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13260. {
  13261. if (idx)
  13262. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13263. puller.setInput(this, _sourceIdx, _in);
  13264. }
  13265. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13266. {
  13267. puller.connectInputStreams(ctx, consumerOrdered);
  13268. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  13269. }
  13270. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13271. {
  13272. if (idx==0)
  13273. return puller.queryInput();
  13274. else
  13275. return NULL;
  13276. }
  13277. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13278. {
  13279. numProcessedLastGroup = 0;
  13280. recordCount = 0;
  13281. eof = false;
  13282. allPulled = false;
  13283. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13284. preload = helper.getLookahead();
  13285. if (!preload)
  13286. preload = ctx->queryOptions().prefetchProjectPreload;
  13287. space.reinit(preload);
  13288. ready.reinit();
  13289. puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
  13290. }
  13291. virtual void stop()
  13292. {
  13293. space.interrupt();
  13294. ready.interrupt();
  13295. CRoxieServerActivity::stop();
  13296. puller.stop();
  13297. }
  13298. virtual void reset()
  13299. {
  13300. CRoxieServerActivity::reset();
  13301. puller.reset();
  13302. allPulled = false;
  13303. while (pulled.ordinality())
  13304. ::Release(pulled.dequeue());
  13305. }
  13306. virtual PrefetchInfo *readNextRecord()
  13307. {
  13308. if (!isThreaded)
  13309. {
  13310. if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
  13311. puller.pullRecords(1);
  13312. }
  13313. else
  13314. ready.wait();
  13315. CriticalBlock b(pulledCrit);
  13316. PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
  13317. space.signal();
  13318. return ret;
  13319. }
  13320. virtual bool needsAllocator() const { return true; }
  13321. virtual const void * nextRow()
  13322. {
  13323. ActivityTimer t(totalCycles, timeActivities);
  13324. if (eof)
  13325. return NULL;
  13326. for (;;)
  13327. {
  13328. Owned<PrefetchInfo> in = readNextRecord();
  13329. if (!in)
  13330. {
  13331. recordCount = 0;
  13332. if (numProcessedLastGroup == processed)
  13333. in.setown(readNextRecord());
  13334. if (!in)
  13335. {
  13336. numProcessedLastGroup = processed;
  13337. eof = true;
  13338. return NULL;
  13339. }
  13340. }
  13341. try
  13342. {
  13343. if (in->in)
  13344. {
  13345. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  13346. size32_t outSize;
  13347. IThorChildGraph *child = helper.queryChild();
  13348. Owned<IEclGraphResults> results;
  13349. if (child)
  13350. results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
  13351. outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
  13352. if (outSize)
  13353. {
  13354. processed++;
  13355. return rowBuilder.finalizeRowClear(outSize);
  13356. }
  13357. }
  13358. }
  13359. catch (IException *E)
  13360. {
  13361. throw makeWrappedException(E);
  13362. }
  13363. }
  13364. }
  13365. // interface IExceptionHandler
  13366. virtual bool fireException(IException *e)
  13367. {
  13368. // called from puller thread on failure
  13369. ready.interrupt(LINK(e));
  13370. space.interrupt(e);
  13371. return true;
  13372. }
  13373. // interface IRecordPullerCallback
  13374. virtual void processRow(const void *row)
  13375. {
  13376. {
  13377. CriticalBlock b(pulledCrit);
  13378. pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
  13379. }
  13380. if (isThreaded)
  13381. {
  13382. ready.signal();
  13383. space.wait();
  13384. }
  13385. }
  13386. virtual void processEOG()
  13387. {
  13388. {
  13389. CriticalBlock b(pulledCrit);
  13390. pulled.enqueue(NULL);
  13391. }
  13392. if (isThreaded)
  13393. {
  13394. ready.signal();
  13395. space.wait();
  13396. }
  13397. }
  13398. virtual void processGroup(const ConstPointerArray &rows)
  13399. {
  13400. throwUnexpected();
  13401. }
  13402. virtual void processDone()
  13403. {
  13404. CriticalBlock b(pulledCrit);
  13405. allPulled = true;
  13406. if (isThreaded)
  13407. ready.signal();
  13408. }
  13409. };
  13410. class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
  13411. {
  13412. public:
  13413. CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13414. : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  13415. {
  13416. }
  13417. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  13418. {
  13419. return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager);
  13420. }
  13421. };
  13422. extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  13423. {
  13424. return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  13425. }
  13426. //=================================================================================
  13427. class CPointerArrayRoxieInput : public CPseudoRoxieInput
  13428. {
  13429. public:
  13430. CPointerArrayRoxieInput()
  13431. {
  13432. rowset = NULL;
  13433. rowcount = 0;
  13434. curRow = 0;
  13435. }
  13436. void init(size32_t _rowcount, const byte **_rowset)
  13437. {
  13438. rowset = _rowset;
  13439. rowcount = _rowcount;
  13440. curRow = 0;
  13441. }
  13442. virtual const void * nextRow()
  13443. {
  13444. if (curRow < rowcount)
  13445. {
  13446. const void * ret = rowset[curRow];
  13447. if (ret)
  13448. LinkRoxieRow(ret);
  13449. curRow++;
  13450. return ret;
  13451. }
  13452. return NULL;
  13453. }
  13454. protected:
  13455. const byte **rowset;
  13456. size32_t rowcount;
  13457. size32_t curRow;
  13458. };
  13459. class CRoxieServerLoopActivity : public CRoxieServerActivity
  13460. {
  13461. protected:
  13462. IHThorLoopArg &helper;
  13463. ThorActivityKind activityKind;
  13464. unsigned maxIterations;
  13465. bool finishedLooping;
  13466. unsigned flags;
  13467. bool eof;
  13468. rtlRowBuilder loopExtractBuilder;
  13469. unsigned loopGraphId;
  13470. Linked<IOutputMetaData> counterMeta;
  13471. public:
  13472. CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13473. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  13474. helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
  13475. {
  13476. eof = false;
  13477. finishedLooping = false;
  13478. activityKind = factory->getKind();
  13479. flags = helper.getFlags();
  13480. maxIterations = 0;
  13481. }
  13482. virtual bool needsAllocator() const { return true; }
  13483. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13484. {
  13485. eof = false;
  13486. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  13487. int iterations = (int) helper.numIterations();
  13488. maxIterations = (iterations >= 0) ? iterations : 0;
  13489. finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
  13490. if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
  13491. finishedLooping = true;
  13492. loopExtractBuilder.clear();
  13493. helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
  13494. }
  13495. virtual void stop()
  13496. {
  13497. CRoxieServerActivity::stop();
  13498. loopExtractBuilder.clear();
  13499. }
  13500. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  13501. {
  13502. if (flags & IHThorLoopArg::LFcounter)
  13503. {
  13504. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  13505. *((thor_loop_counter_t *)counterRow) = counter;
  13506. RtlLinkedDatasetBuilder builder(rowAllocator);
  13507. builder.appendOwn(counterRow);
  13508. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  13509. graph->setInputResult(2, counterResult);
  13510. }
  13511. }
  13512. };
  13513. //=================================================================================
  13514. class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
  13515. {
  13516. Owned<IActivityGraph> loopQuery;
  13517. Owned<IRoxieServerChildGraph> loopGraph;
  13518. IEngineRowStream * curStream;
  13519. RtlLinkedDatasetBuilder *loopInputBuilder;
  13520. CPointerArrayRoxieInput arrayInput;
  13521. Linked<IEngineRowStream> resultStream;
  13522. unsigned loopCounter;
  13523. public:
  13524. CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13525. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
  13526. {
  13527. curStream = NULL;
  13528. loopCounter = 0;
  13529. loopInputBuilder = NULL;
  13530. }
  13531. virtual bool needsAllocator() const { return true; }
  13532. virtual void onCreate(IHThorArg *_colocalParent)
  13533. {
  13534. CRoxieServerLoopActivity::onCreate(_colocalParent);
  13535. loopQuery.set(ctx->queryChildGraph(loopGraphId));
  13536. }
  13537. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13538. {
  13539. curStream = inputStream;
  13540. loopCounter = 1;
  13541. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13542. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  13543. loopGraph.set(loopQuery->queryLoopGraph());
  13544. loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
  13545. }
  13546. virtual void stop()
  13547. {
  13548. delete loopInputBuilder;
  13549. loopInputBuilder = NULL;
  13550. CRoxieServerLoopActivity::stop();
  13551. }
  13552. virtual const void * nextRow()
  13553. {
  13554. ActivityTimer t(totalCycles, timeActivities);
  13555. if (eof)
  13556. return NULL;
  13557. unsigned emptyIterations = 0;
  13558. for (;;)
  13559. {
  13560. for (;;)
  13561. {
  13562. const void * ret = curStream->nextRow();
  13563. if (!ret)
  13564. {
  13565. ret = curStream->nextRow(); // more cope with groups somehow....
  13566. if (!ret)
  13567. {
  13568. if (finishedLooping)
  13569. {
  13570. eof = true;
  13571. return NULL;
  13572. }
  13573. break;
  13574. }
  13575. }
  13576. if (finishedLooping ||
  13577. ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
  13578. {
  13579. processed++;
  13580. return ret;
  13581. }
  13582. loopInputBuilder->appendOwn(ret);
  13583. }
  13584. switch (activityKind)
  13585. {
  13586. case TAKloopdataset:
  13587. {
  13588. if (!(flags & IHThorLoopArg::LFnewloopagain))
  13589. {
  13590. if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
  13591. {
  13592. if (loopInputBuilder->getcount() == 0)
  13593. {
  13594. eof = true;
  13595. return NULL;
  13596. }
  13597. arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13598. // MORE - should builder be cleared here?
  13599. curStream = &arrayInput;
  13600. finishedLooping = true;
  13601. continue; // back to the input loop again
  13602. }
  13603. }
  13604. break;
  13605. }
  13606. case TAKlooprow:
  13607. if (!loopInputBuilder->getcount())
  13608. {
  13609. finishedLooping = true;
  13610. eof = true;
  13611. return NULL;
  13612. }
  13613. break;
  13614. }
  13615. if (loopInputBuilder->getcount())
  13616. emptyIterations = 0;
  13617. else
  13618. {
  13619. //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
  13620. emptyIterations++;
  13621. if (emptyIterations > maxEmptyLoopIterations)
  13622. throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
  13623. if (emptyIterations % 32 == 0)
  13624. CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
  13625. }
  13626. checkAbort();
  13627. try
  13628. {
  13629. Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
  13630. resultStream.setown(results->createIterator(0));
  13631. if (flags & IHThorLoopArg::LFnewloopagain)
  13632. {
  13633. Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
  13634. OwnedConstRoxieRow row = againResult->nextRow();
  13635. assertex(row);
  13636. //Result is a row which contains a single boolean field.
  13637. if (!((const bool *)row.get())[0])
  13638. finishedLooping = true;
  13639. }
  13640. }
  13641. catch (IException *E)
  13642. {
  13643. throw makeWrappedException(E);
  13644. }
  13645. curStream = resultStream.get();
  13646. loopCounter++;
  13647. if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
  13648. finishedLooping = true;
  13649. }
  13650. }
  13651. IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  13652. {
  13653. try
  13654. {
  13655. loopGraph->beforeExecute();
  13656. Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
  13657. loopInputBuilder->clear();
  13658. loopGraph->setInputResult(1, inputRowsResult);
  13659. createCounterResult(loopGraph, counter);
  13660. Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
  13661. loopGraph->afterExecute();
  13662. return ret.getClear();
  13663. }
  13664. catch (...)
  13665. {
  13666. CTXLOG("Exception thrown in loop body - cleaning up");
  13667. loopGraph->afterExecute();
  13668. throw;
  13669. }
  13670. }
  13671. };
  13672. //=================================================================================
  13673. typedef SafeQueueOf<const void, true> SafeRowQueue;
  13674. class CRowQueuePseudoInput : public CPseudoRoxieInput
  13675. {
  13676. public:
  13677. CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
  13678. : input(_input), meta(_meta)
  13679. {
  13680. eof = false;
  13681. }
  13682. virtual const void * nextRow()
  13683. {
  13684. if (eof)
  13685. return NULL;
  13686. const void * ret = input.dequeue();
  13687. if (!ret)
  13688. eof = true;
  13689. return ret;
  13690. }
  13691. virtual IOutputMetaData * queryOutputMeta() const { return meta; }
  13692. protected:
  13693. SafeRowQueue & input;
  13694. IOutputMetaData * meta;
  13695. bool eof;
  13696. };
  13697. class CRoxieServerParallelLoopActivity;
  13698. class LoopFilterPseudoInput : public CIndirectRoxieInput
  13699. {
  13700. public:
  13701. LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
  13702. activity(_activity), counter(_counter)
  13703. {
  13704. }
  13705. virtual const void * nextRow();
  13706. protected:
  13707. CRoxieServerParallelLoopActivity * activity;
  13708. unsigned counter;
  13709. };
  13710. class LoopExecutorThread : public RestartableThread
  13711. {
  13712. protected:
  13713. Owned<CSafeRoxieInput> safeInput;
  13714. CRoxieServerParallelLoopActivity * activity;
  13715. bool eof;
  13716. CriticalSection crit;
  13717. unsigned flags;
  13718. SafeRowQueue tempResults[2];
  13719. unsigned savedParentExtractSize;
  13720. const byte * savedParentExtract;
  13721. IArrayOf<IActivityGraph> cachedGraphs;
  13722. IRoxieSlaveContext *ctx;
  13723. public:
  13724. LoopExecutorThread()
  13725. : RestartableThread("LoopExecutorThread")
  13726. {
  13727. activity = NULL;
  13728. eof = false;
  13729. flags = 0;
  13730. ctx = NULL;
  13731. savedParentExtract = NULL;
  13732. savedParentExtractSize = 0;
  13733. }
  13734. void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
  13735. {
  13736. activity = _activity;
  13737. flags = _flags;
  13738. // 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.
  13739. safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
  13740. }
  13741. void connectInputStreams(bool consumerOrdered)
  13742. {
  13743. safeInput->connectInputStreams(ctx, consumerOrdered);
  13744. }
  13745. IFinalRoxieInput *queryInput() const
  13746. {
  13747. return safeInput;
  13748. }
  13749. void onCreate(IRoxieSlaveContext * _ctx);
  13750. void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
  13751. void stop();
  13752. void reset();
  13753. virtual int run();
  13754. protected:
  13755. void executeLoop();
  13756. void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
  13757. IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
  13758. };
  13759. class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
  13760. {
  13761. friend class LoopFilterPseudoInput;
  13762. friend class LoopExecutorThread;
  13763. QueueOf<const void, true> ready;
  13764. CriticalSection helperCS;
  13765. CriticalSection cs;
  13766. unsigned defaultNumParallel;
  13767. LoopExecutorThread executor;
  13768. IProbeManager* probeManager;
  13769. CriticalSection canAccess;
  13770. CriticalSection scrit;
  13771. InterruptableSemaphore readySpace;
  13772. InterruptableSemaphore recordsReady;
  13773. protected:
  13774. bool includeInLoop(unsigned counter, const void * row)
  13775. {
  13776. CriticalBlock b(helperCS);
  13777. return helper.sendToLoop(counter, row);
  13778. }
  13779. public:
  13780. CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
  13781. : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
  13782. readySpace(parallelLoopFlowLimit)
  13783. {
  13784. probeManager = _probeManager;
  13785. defaultNumParallel = 0;
  13786. }
  13787. virtual void onCreate(IHThorArg *_colocalParent)
  13788. {
  13789. CRoxieServerActivity::onCreate(_colocalParent);
  13790. executor.onCreate(ctx);
  13791. }
  13792. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13793. {
  13794. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13795. readySpace.reinit(parallelLoopFlowLimit);
  13796. recordsReady.reinit();
  13797. CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
  13798. defaultNumParallel = helper.defaultParallelIterations();
  13799. if (!defaultNumParallel)
  13800. defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
  13801. //MORE: If numIterations <= number of parallel iterations[1],
  13802. //then we don't need to create a separate thread to do the processing, and the results will also avoid
  13803. //being transferred via a queue
  13804. executor.start(parentExtractSize, parentExtract, paused);
  13805. }
  13806. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  13807. {
  13808. if (idx)
  13809. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  13810. executor.setInput(this, _sourceIdx, _in, flags);
  13811. }
  13812. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  13813. {
  13814. executor.connectInputStreams(consumerOrdered);
  13815. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  13816. }
  13817. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  13818. {
  13819. if (idx==0)
  13820. return executor.queryInput();
  13821. else
  13822. return NULL;
  13823. }
  13824. virtual void stop()
  13825. {
  13826. CriticalBlock b(scrit); // can stop while still starting, if unlucky...
  13827. readySpace.interrupt();
  13828. recordsReady.interrupt();
  13829. executor.join(); // MORE - may not be needed given stop/reset split
  13830. CRoxieServerLoopActivity::stop();
  13831. }
  13832. virtual void reset()
  13833. {
  13834. while (ready.ordinality())
  13835. ReleaseRoxieRow(ready.dequeue());
  13836. executor.reset();
  13837. CRoxieServerActivity::reset();
  13838. }
  13839. virtual const void * nextRow()
  13840. {
  13841. ActivityTimer t(totalCycles, timeActivities);
  13842. for (;;)
  13843. {
  13844. if (eof)
  13845. return NULL;
  13846. recordsReady.wait();
  13847. CriticalBlock procedure(canAccess);
  13848. if (ready.ordinality())
  13849. {
  13850. const void *result = ready.dequeue();
  13851. readySpace.signal();
  13852. if (result)
  13853. processed++;
  13854. return result;
  13855. }
  13856. else
  13857. eof = true;
  13858. }
  13859. }
  13860. unsigned getNumParallel(unsigned iter)
  13861. {
  13862. return defaultNumParallel;
  13863. }
  13864. inline void enqueueResult(const void * row)
  13865. {
  13866. try
  13867. {
  13868. while(!readySpace.wait(1000))
  13869. {
  13870. CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
  13871. }
  13872. }
  13873. catch (...)
  13874. {
  13875. ReleaseRoxieRow(row);
  13876. throw;
  13877. }
  13878. CriticalBlock b2(canAccess);
  13879. ready.enqueue(row);
  13880. recordsReady.signal();
  13881. }
  13882. inline void finishResults()
  13883. {
  13884. recordsReady.signal();
  13885. }
  13886. virtual bool fireException(IException *e)
  13887. {
  13888. readySpace.interrupt(LINK(e));
  13889. recordsReady.interrupt(e);
  13890. return true;
  13891. }
  13892. IActivityGraph * createChildGraphInstance()
  13893. {
  13894. return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
  13895. }
  13896. IActivityGraph * queryChildGraph()
  13897. {
  13898. return ctx->queryChildGraph(loopGraphId);
  13899. }
  13900. };
  13901. //=================================================================================
  13902. const void * LoopFilterPseudoInput::nextRow()
  13903. {
  13904. for (;;)
  13905. {
  13906. const void * next = stream->nextRow();
  13907. if (!next || activity->includeInLoop(counter, next))
  13908. return next;
  13909. activity->enqueueResult(next);
  13910. }
  13911. }
  13912. void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
  13913. {
  13914. //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
  13915. ctx = _ctx;
  13916. cachedGraphs.append(*LINK(activity->queryChildGraph()));
  13917. }
  13918. void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  13919. {
  13920. savedParentExtractSize = parentExtractSize;
  13921. savedParentExtract = parentExtract;
  13922. eof = false;
  13923. StringBuffer logPrefix("[");
  13924. ctx->getLogPrefix(logPrefix).append("] ");
  13925. RestartableThread::start(logPrefix);
  13926. }
  13927. int LoopExecutorThread::run()
  13928. {
  13929. try
  13930. {
  13931. executeLoop();
  13932. }
  13933. catch (IException *e)
  13934. {
  13935. activity->fireException(e);
  13936. }
  13937. catch (...)
  13938. {
  13939. activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
  13940. }
  13941. return 0;
  13942. }
  13943. void LoopExecutorThread::stop()
  13944. {
  13945. safeInput->stop();
  13946. RestartableThread::join();
  13947. }
  13948. void LoopExecutorThread::reset()
  13949. {
  13950. safeInput->reset();
  13951. }
  13952. void LoopExecutorThread::executeLoop()
  13953. {
  13954. unsigned iterations = 0;
  13955. unsigned counter = 0;
  13956. unsigned outputIndex = 0;
  13957. //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
  13958. for (;;)
  13959. {
  13960. if (activity->activityKind == TAKloopcount)
  13961. {
  13962. if (counter == activity->maxIterations)
  13963. break;
  13964. }
  13965. else
  13966. {
  13967. //This condition isn't quite right because it needs to be whether the filtered
  13968. //input is empty. May be ok if we include that in the semantics,
  13969. if (tempResults[1-outputIndex].ordinality() == 0)
  13970. break;
  13971. }
  13972. unsigned numParallel = activity->getNumParallel(iterations);
  13973. Linked<IFinalRoxieInput> curInput;
  13974. if (iterations == 0)
  13975. curInput.set(safeInput);
  13976. else
  13977. {
  13978. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13979. inputQueue.enqueue(NULL);
  13980. curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
  13981. }
  13982. SafeRowQueue * curOutput = NULL;
  13983. if (counter+numParallel > activity->maxIterations)
  13984. numParallel = activity->maxIterations - counter;
  13985. else if (counter+numParallel < activity->maxIterations)
  13986. curOutput = &tempResults[outputIndex];
  13987. executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
  13988. outputIndex = 1-outputIndex;
  13989. counter += numParallel;
  13990. iterations++;
  13991. }
  13992. //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
  13993. SafeRowQueue & inputQueue = tempResults[1-outputIndex];
  13994. while (inputQueue.ordinality())
  13995. {
  13996. const void * next = inputQueue.dequeue();
  13997. activity->enqueueResult(next);
  13998. }
  13999. activity->finishResults();
  14000. }
  14001. void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
  14002. {
  14003. IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
  14004. Linked<IFinalRoxieInput> curInput = input;
  14005. unsigned i;
  14006. for (i= 0; i != numIterations; i++)
  14007. {
  14008. unsigned thisCounter = counter+i+1;
  14009. IFinalRoxieInput * filtered = curInput;
  14010. if (flags & IHThorLoopArg::LFfiltered)
  14011. {
  14012. LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
  14013. newFiltered->setInput(inputIdx, curInput);
  14014. filtered = newFiltered;
  14015. savedInputs.append(*filtered);
  14016. inputIdx = 0;
  14017. }
  14018. //graph is kept, so new curInput will be guaranteed to exist
  14019. curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
  14020. inputIdx = 0;
  14021. }
  14022. Owned<IStrandJunction> curJunction;
  14023. IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
  14024. Owned<IException> failure;
  14025. try
  14026. {
  14027. curInput->start(savedParentExtractSize, savedParentExtract, false);
  14028. if (spillOutput)
  14029. {
  14030. for (;;)
  14031. {
  14032. const void * next = curStream->nextRow();
  14033. if (!next)
  14034. break;
  14035. spillOutput->enqueue(next);
  14036. }
  14037. }
  14038. else
  14039. {
  14040. for (;;)
  14041. {
  14042. const void * next = curStream->nextRow();
  14043. if (!next)
  14044. break;
  14045. activity->enqueueResult(next);
  14046. }
  14047. }
  14048. }
  14049. catch (IException *E)
  14050. {
  14051. ctx->notifyAbort(E);
  14052. failure.setown(E);
  14053. }
  14054. for (i= 0; i != numIterations; i++)
  14055. {
  14056. IRoxieServerChildGraph * loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14057. loopGraph->afterExecute();
  14058. //NOTE: inputIdx is always 0 - the code above could be cleaned up.
  14059. loopGraph->querySetInputResult(1, 0, nullptr);
  14060. }
  14061. curStream->stop();
  14062. curInput->reset();
  14063. if (failure)
  14064. throw failure.getClear();
  14065. }
  14066. IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
  14067. {
  14068. if (!cachedGraphs.isItem(i))
  14069. cachedGraphs.append(*activity->createChildGraphInstance());
  14070. Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
  14071. loopGraph->beforeExecute();
  14072. if (!loopGraph->querySetInputResult(1, inputIdx, input))
  14073. throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
  14074. activity->createCounterResult(loopGraph, counter);
  14075. return loopGraph->selectOutput(0);
  14076. }
  14077. //=================================================================================
  14078. class CCounterRowMetaData : implements IOutputMetaData, public CInterface
  14079. {
  14080. public:
  14081. IMPLEMENT_IINTERFACE
  14082. virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
  14083. virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
  14084. virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
  14085. virtual void toXML(const byte * self, IXmlWriter & out) { }
  14086. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  14087. virtual unsigned getMetaFlags() { return 0; }
  14088. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  14089. virtual void destruct(byte * self) {}
  14090. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14091. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14092. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  14093. virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
  14094. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14095. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  14096. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  14097. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  14098. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  14099. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); } // could provide a static implementation if needed
  14100. };
  14101. class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
  14102. {
  14103. unsigned loopGraphId;
  14104. unsigned flags;
  14105. Linked<IOutputMetaData> counterMeta;
  14106. public:
  14107. CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14108. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14109. {
  14110. Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
  14111. flags = helper->getFlags();
  14112. counterMeta.setown(new CCounterRowMetaData);
  14113. }
  14114. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14115. {
  14116. if (flags & IHThorLoopArg::LFparallel)
  14117. return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14118. else
  14119. return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14120. }
  14121. };
  14122. IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14123. {
  14124. return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14125. }
  14126. //=================================================================================
  14127. class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
  14128. {
  14129. protected:
  14130. IHThorGraphLoopArg &helper;
  14131. unsigned maxIterations;
  14132. unsigned flags;
  14133. rtlRowBuilder GraphExtractBuilder;
  14134. unsigned loopGraphId;
  14135. Linked<IOutputMetaData> counterMeta;
  14136. public:
  14137. CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14138. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14139. helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
  14140. {
  14141. flags = helper.getFlags();
  14142. maxIterations = 0;
  14143. }
  14144. virtual bool needsAllocator() const { return true; }
  14145. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14146. {
  14147. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14148. int iterations = (int) helper.numIterations();
  14149. maxIterations = (iterations >= 0) ? iterations : 0;
  14150. if (maxIterations > maxGraphLoopIterations)
  14151. throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
  14152. if (maxIterations != 0)
  14153. {
  14154. GraphExtractBuilder.clear();
  14155. helper.createParentExtract(GraphExtractBuilder);
  14156. }
  14157. }
  14158. virtual void stop()
  14159. {
  14160. CRoxieServerActivity::stop();
  14161. GraphExtractBuilder.clear();
  14162. }
  14163. void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
  14164. {
  14165. if (flags & IHThorGraphLoopArg::GLFcounter)
  14166. {
  14167. void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
  14168. *((thor_loop_counter_t *)counterRow) = counter;
  14169. RtlLinkedDatasetBuilder builder(rowAllocator);
  14170. builder.appendOwn(counterRow);
  14171. Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
  14172. graph->setInputResult(0, counterResult);
  14173. }
  14174. }
  14175. };
  14176. //=================================================================================
  14177. class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
  14178. {
  14179. Owned<IActivityGraph> GraphQuery;
  14180. Owned<IRoxieServerChildGraph> loopGraph;
  14181. Linked<IEngineRowStream> resultStream;
  14182. bool evaluated;
  14183. public:
  14184. CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14185. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
  14186. {
  14187. evaluated = false;
  14188. }
  14189. virtual void onCreate(IHThorArg *_colocalParent)
  14190. {
  14191. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14192. GraphQuery.set(ctx->queryChildGraph(loopGraphId));
  14193. }
  14194. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14195. {
  14196. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
  14197. //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
  14198. loopGraph.set(GraphQuery->queryLoopGraph());
  14199. evaluated = false;
  14200. }
  14201. virtual void stop()
  14202. {
  14203. if (loopGraph)
  14204. loopGraph->clearGraphLoopResults();
  14205. CRoxieServerGraphLoopActivity::stop();
  14206. }
  14207. virtual const void * nextRow()
  14208. {
  14209. ActivityTimer t(totalCycles, timeActivities);
  14210. if (!evaluated)
  14211. {
  14212. executeEntireGraph();
  14213. evaluated = true;
  14214. }
  14215. const void * ret = resultStream->nextRow();
  14216. if (ret)
  14217. processed++;
  14218. return ret;
  14219. }
  14220. void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
  14221. {
  14222. try
  14223. {
  14224. loopGraph->beforeExecute();
  14225. createCounterResult(loopGraph, counter);
  14226. loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
  14227. loopGraph->afterExecute();
  14228. }
  14229. catch (...)
  14230. {
  14231. CTXLOG("Exception thrown in graph body - cleaning up");
  14232. loopGraph->afterExecute();
  14233. throw;
  14234. }
  14235. }
  14236. void createInitialGraphInput()
  14237. {
  14238. loopGraph->clearGraphLoopResults();
  14239. RtlLinkedDatasetBuilder builder(rowAllocator);
  14240. inputStream->readAll(builder);
  14241. Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
  14242. loopGraph->setGraphLoopResult(0, result);
  14243. }
  14244. void executeEntireGraph()
  14245. {
  14246. createInitialGraphInput();
  14247. for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
  14248. {
  14249. executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
  14250. }
  14251. resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
  14252. }
  14253. };
  14254. //=================================================================================
  14255. struct GraphOutputSplitterArg : public CThorSplitArg
  14256. {
  14257. public:
  14258. virtual unsigned numBranches()
  14259. {
  14260. return 0;
  14261. }
  14262. virtual IOutputMetaData * queryOutputMeta()
  14263. {
  14264. return NULL;// get it from the parent..
  14265. }
  14266. };
  14267. extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
  14268. class CGraphIterationInfo : public CInterface
  14269. {
  14270. private:
  14271. Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
  14272. unsigned sourceIdx;
  14273. Linked<IRoxieServerActivity> sourceAct;
  14274. Linked<IFinalRoxieInput> sourceInput;
  14275. unsigned numUses;
  14276. unsigned iteration;
  14277. public:
  14278. CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
  14279. : sourceIdx(_sourceIdx), sourceAct(_sourceAct), sourceInput(_input), iteration(_iteration)
  14280. {
  14281. numUses = 0;
  14282. }
  14283. inline void noteUsed()
  14284. {
  14285. numUses++;
  14286. }
  14287. void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14288. {
  14289. if (numUses > 1)
  14290. {
  14291. Owned<IPropertyTree> splitterNode = createPTree(ipt_fast);
  14292. factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
  14293. IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
  14294. splitter->onCreate(NULL);
  14295. IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
  14296. if (probeManager)
  14297. {
  14298. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
  14299. probes.append(*LINK(inputProbe));
  14300. input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14301. sourceIdx = 0;
  14302. }
  14303. sourceAct.setown(splitter);
  14304. sourceAct->setInput(0, sourceIdx, input);
  14305. sourceIdx = 0;
  14306. sourceInput.clear();
  14307. }
  14308. }
  14309. IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14310. {
  14311. // MORE - not really necessary to create splitters in separate pass, is it?
  14312. if (factory) // we created a splitter....
  14313. sourceInput.set(sourceAct->queryOutput(sourceIdx));
  14314. IFinalRoxieInput *ret = sourceInput;
  14315. if (probeManager)
  14316. {
  14317. IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
  14318. probes.append(*LINK(inputProbe));
  14319. ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  14320. // MORE - do we need to connect the stream in the probe?
  14321. }
  14322. if (factory) // we created a splitter....
  14323. sourceIdx++;
  14324. return ret;
  14325. }
  14326. };
  14327. class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
  14328. {
  14329. Owned<IActivityGraph> childGraph;
  14330. IFinalRoxieInput * resultInput;
  14331. IEngineRowStream * resultStream;
  14332. Owned<IStrandJunction> resultJunction;
  14333. CIArrayOf<CGraphIterationInfo> outputs;
  14334. IArrayOf<IRoxieServerChildGraph> iterationGraphs;
  14335. Owned<CExtractMapperInput> inputExtractMapper;
  14336. IProbeManager *probeManager;
  14337. Owned<IStatisticGatherer> childStats;
  14338. unsigned createLoopCounter;
  14339. IArrayOf<IRoxieProbe> probes;
  14340. public:
  14341. CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
  14342. : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
  14343. {
  14344. inputExtractMapper.setown(new CExtractMapperInput);
  14345. resultInput = NULL;
  14346. resultStream = NULL;
  14347. createLoopCounter = 0;
  14348. if (ctx && ctx->collectingDetailedStatistics())
  14349. {
  14350. StatsScopeId rootScope(SSTnone, 0U);
  14351. childStats.setown(createStatisticsGatherer(SCTroxie, "", rootScope));
  14352. }
  14353. }
  14354. virtual void onCreate(IHThorArg *_colocalParent)
  14355. {
  14356. CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
  14357. childGraph.set(ctx->queryChildGraph(loopGraphId));
  14358. }
  14359. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14360. {
  14361. CRoxieServerGraphLoopActivity::gatherStatistics(statsBuilder);
  14362. if (statsBuilder && childStats)
  14363. {
  14364. //Merge any stats collected from executed graphs into the full statistics
  14365. Owned<IStatisticCollection> childCollection = childStats->getResult();
  14366. childCollection->mergeInto(*statsBuilder);
  14367. }
  14368. }
  14369. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14370. {
  14371. //Input needs to be handled very carefully.....
  14372. //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
  14373. //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
  14374. //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
  14375. //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
  14376. assertex(idx == 0);
  14377. inputExtractMapper->setInput(_sourceIdx, _in);
  14378. }
  14379. virtual void connectInputStreams(bool consumerOrdered)
  14380. {
  14381. //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
  14382. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  14383. }
  14384. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14385. {
  14386. if (idx==0)
  14387. return inputExtractMapper->queryInput();
  14388. else
  14389. return NULL;
  14390. }
  14391. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14392. {
  14393. CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
  14394. inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
  14395. createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
  14396. resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
  14397. startJunction(resultJunction);
  14398. }
  14399. virtual void stop()
  14400. {
  14401. if (resultStream)
  14402. resultStream->stop();
  14403. CRoxieServerGraphLoopActivity::stop();
  14404. }
  14405. virtual void reset()
  14406. {
  14407. if (resultInput)
  14408. resultInput->reset();
  14409. resetJunction(resultJunction);
  14410. resultInput = NULL;
  14411. resultStream = NULL;
  14412. resultJunction.clear();
  14413. ForEachItemIn(i, iterationGraphs)
  14414. iterationGraphs.item(i).gatherStatistics(childStats);
  14415. outputs.kill();
  14416. iterationGraphs.kill(); // must be done after all activities killed
  14417. if (probeManager)
  14418. {
  14419. probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
  14420. probes.kill();
  14421. }
  14422. CRoxieServerGraphLoopActivity::reset();
  14423. }
  14424. virtual const void * nextRow()
  14425. {
  14426. ActivityTimer t(totalCycles, timeActivities);
  14427. const void * ret = resultStream->nextRow();
  14428. if (ret)
  14429. processed++;
  14430. return ret;
  14431. }
  14432. void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
  14433. {
  14434. //result(0) is the input to the graph.
  14435. resultInput = inputExtractMapper;
  14436. outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
  14437. for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
  14438. {
  14439. IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
  14440. graph->beforeExecute();
  14441. iterationGraphs.append(*graph);
  14442. graph->gatherIterationUsage(*this);
  14443. CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
  14444. outputs.append(*iteration);
  14445. }
  14446. createLoopCounter = 0;
  14447. createSplitters(probeManager, probes);
  14448. ForEachItemIn(i2, iterationGraphs)
  14449. iterationGraphs.item(i2).associateIterationOutputs(*this);
  14450. resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
  14451. resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
  14452. }
  14453. void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  14454. {
  14455. ForEachItemIn(i, outputs)
  14456. {
  14457. CGraphIterationInfo & next = outputs.item(i);
  14458. next.createSplitter(ctx, probeManager, probes);
  14459. }
  14460. }
  14461. //IRoxieServerLoopResultProcessor
  14462. virtual void noteUseIteration(unsigned _whichIteration)
  14463. {
  14464. int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
  14465. if (whichIteration >= 0)
  14466. {
  14467. if (!outputs.isItem(whichIteration))
  14468. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
  14469. outputs.item(whichIteration).noteUsed();
  14470. }
  14471. }
  14472. virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
  14473. {
  14474. if (outputs.isItem(whichIteration))
  14475. {
  14476. CGraphIterationInfo & next = outputs.item(whichIteration);
  14477. return next.connectOutput(probeManager, probes, targetAct, targetIdx);
  14478. }
  14479. return NULL;
  14480. }
  14481. };
  14482. //=================================================================================
  14483. class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
  14484. {
  14485. unsigned loopGraphId;
  14486. unsigned flags;
  14487. Linked<IOutputMetaData> counterMeta;
  14488. public:
  14489. CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14490. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
  14491. {
  14492. Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
  14493. flags = helper->getFlags();
  14494. counterMeta.setown(new CCounterRowMetaData);
  14495. }
  14496. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14497. {
  14498. if (kind == TAKparallelgraphloop)
  14499. return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14500. else
  14501. return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
  14502. }
  14503. };
  14504. IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
  14505. {
  14506. return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
  14507. }
  14508. //=====================================================================================================
  14509. class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
  14510. {
  14511. class OutputAdaptor : public CExtractMapperInput
  14512. {
  14513. bool stopped;
  14514. public:
  14515. CRoxieServerLibraryCallActivity *parent;
  14516. IOutputMetaData * meta = nullptr;
  14517. unsigned oid;
  14518. unsigned processed;
  14519. unsigned numStarts = 0;
  14520. public:
  14521. OutputAdaptor()
  14522. {
  14523. parent = NULL;
  14524. oid = 0;
  14525. init();
  14526. }
  14527. ~OutputAdaptor()
  14528. {
  14529. if (traceStartStop)
  14530. DBGLOG("%p ~OutputAdaptor %d", this, oid);
  14531. }
  14532. void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
  14533. {
  14534. parent = _parent;
  14535. meta = _meta;
  14536. oid = _oid;
  14537. }
  14538. void init()
  14539. {
  14540. processed = 0;
  14541. stopped = false;
  14542. }
  14543. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14544. {
  14545. parent->start(oid, parentExtractSize, parentExtract, paused);
  14546. CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
  14547. numStarts++;
  14548. }
  14549. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  14550. {
  14551. //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
  14552. if (!oid) // Only need to set up once
  14553. {
  14554. parent->connectInputStreams(true); // To handle dependencies etc
  14555. }
  14556. return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
  14557. }
  14558. //This override should not really be needed, but input is set up too late for the call to connect strands
  14559. virtual IOutputMetaData * queryOutputMeta() const
  14560. {
  14561. return meta;
  14562. }
  14563. virtual void stop()
  14564. {
  14565. if (!stopped)
  14566. {
  14567. stopped = true;
  14568. parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
  14569. CExtractMapperInput::stop();
  14570. }
  14571. };
  14572. virtual void reset()
  14573. {
  14574. parent->reset(oid);
  14575. CExtractMapperInput::reset();
  14576. init();
  14577. };
  14578. virtual void checkAbort()
  14579. {
  14580. parent->checkAbort();
  14581. }
  14582. };
  14583. IHThorLibraryCallArg &helper;
  14584. unsigned numInputs;
  14585. unsigned numOutputs;
  14586. unsigned numActiveOutputs;
  14587. bool started;
  14588. OutputAdaptor* outputAdaptors;
  14589. CExtractMapperInput * * inputAdaptors;
  14590. bool * inputUsed;
  14591. bool * outputUsed;
  14592. Owned<IException> error;
  14593. CriticalSection crit;
  14594. rtlRowBuilder libraryExtractBuilder;
  14595. Owned<IActivityGraph> libraryGraph;
  14596. const LibraryCallFactoryExtra & extra;
  14597. public:
  14598. CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
  14599. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  14600. helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
  14601. {
  14602. numInputs = _numInputs;
  14603. numOutputs = _numOutputs;
  14604. numActiveOutputs = numOutputs;
  14605. inputAdaptors = new CExtractMapperInput*[numInputs];
  14606. inputUsed = new bool[numInputs];
  14607. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14608. {
  14609. inputAdaptors[i1] = new CExtractMapperInput;
  14610. inputUsed[i1] = false;
  14611. }
  14612. outputAdaptors = new OutputAdaptor[numOutputs];
  14613. outputUsed = new bool[numOutputs];
  14614. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14615. {
  14616. outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
  14617. outputUsed[i2] = false;
  14618. }
  14619. started = false;
  14620. }
  14621. ~CRoxieServerLibraryCallActivity()
  14622. {
  14623. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14624. ::Release(inputAdaptors[i1]);
  14625. delete [] inputAdaptors;
  14626. delete [] inputUsed;
  14627. delete [] outputAdaptors;
  14628. delete [] outputUsed;
  14629. }
  14630. virtual void onCreate(IHThorArg *_colocalParent)
  14631. {
  14632. CRoxieServerActivity::onCreate(_colocalParent);
  14633. libraryGraph.setown(ctx->getLibraryGraph(extra, this));
  14634. libraryGraph->onCreate(_colocalParent);
  14635. //Now map the inputs and outputs to the adapters
  14636. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14637. for (unsigned i1=0; i1<numInputs; i1++)
  14638. inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
  14639. for (unsigned i2=0; i2<numOutputs; i2++)
  14640. {
  14641. unsigned outputIndex = extra.outputs.item(i2);
  14642. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
  14643. outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
  14644. outputAdaptors[i2].connectInputStreams(ctx, true);
  14645. }
  14646. }
  14647. virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14648. {
  14649. CriticalBlock b(crit);
  14650. if (error)
  14651. throw error.getLink();
  14652. if (collectFactoryStatistics)
  14653. factory->noteStarted(oid);
  14654. if (!started)
  14655. {
  14656. // even though it is not complete, we don't want to run this again if it fails.
  14657. started = true;
  14658. //see notes on splitter above
  14659. try
  14660. {
  14661. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14662. }
  14663. catch (IException *E)
  14664. {
  14665. #ifdef TRACE_SPLIT
  14666. CTXLOG("spill %d caught exception in start", activityId);
  14667. #endif
  14668. error.set(E);
  14669. throw;
  14670. }
  14671. catch (...)
  14672. {
  14673. IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
  14674. error.set(E);
  14675. throw E;
  14676. }
  14677. //recreate the parent extract, and use it to reinitialize the graphs...
  14678. libraryExtractBuilder.clear();
  14679. helper.createParentExtract(libraryExtractBuilder);
  14680. // 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
  14681. // some inputs before we see start on others.
  14682. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14683. {
  14684. if (inputUsed[i1])
  14685. inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
  14686. else
  14687. inputAdaptors[i1]->queryInput()->stopall();
  14688. }
  14689. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  14690. outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
  14691. //call stop on all the unused inputs.
  14692. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14693. graph->beforeExecute();
  14694. ForEachItemIn(i3, extra.unusedOutputs)
  14695. {
  14696. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14697. output->stopall();
  14698. }
  14699. }
  14700. }
  14701. virtual void stop(unsigned oid)
  14702. {
  14703. CriticalBlock b(crit);
  14704. if (--numActiveOutputs == 0)
  14705. {
  14706. //call stop on all the unused inputs.
  14707. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14708. graph->beforeExecute();
  14709. ForEachItemIn(i3, extra.unusedOutputs)
  14710. {
  14711. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14712. output->stopall();
  14713. }
  14714. CRoxieServerActivity::stop();
  14715. }
  14716. }
  14717. void reset(unsigned oid)
  14718. {
  14719. started = false;
  14720. error.clear();
  14721. numActiveOutputs = numOutputs;
  14722. if (state != STATEreset) // make sure input is only reset once
  14723. {
  14724. CRoxieServerActivity::reset();
  14725. libraryGraph->reset();
  14726. //Call reset on all unused inputs/outputs from the graph - no one else will.
  14727. for (unsigned i1 = 0; i1 < numInputs; i1++)
  14728. {
  14729. if (!inputUsed[i1])
  14730. inputAdaptors[i1]->reset();
  14731. }
  14732. IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
  14733. ForEachItemIn(i3, extra.unusedOutputs)
  14734. {
  14735. Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
  14736. output->reset();
  14737. }
  14738. }
  14739. };
  14740. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  14741. {
  14742. inputAdaptors[idx]->setInput(_sourceIdx, _in);
  14743. }
  14744. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14745. {
  14746. if (idx < numInputs && inputAdaptors[idx])
  14747. return inputAdaptors[idx]->queryInput();
  14748. else
  14749. return NULL;
  14750. }
  14751. public:
  14752. virtual const void *nextRow()
  14753. {
  14754. throwUnexpected(); // Internal logic error - we are not anybody's input
  14755. }
  14756. virtual IOutputMetaData * queryOutputMeta() const
  14757. {
  14758. throwUnexpected(); // should be called on outputs instead
  14759. }
  14760. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  14761. {
  14762. assertex(idx!=(unsigned)-1);
  14763. assertex(!outputUsed[idx]);
  14764. outputUsed[idx] = true;
  14765. return &outputAdaptors[idx];
  14766. }
  14767. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  14768. {
  14769. if (libraryGraph)
  14770. libraryGraph->gatherStatistics(statsBuilder);
  14771. CRoxieServerActivity::gatherStatistics(statsBuilder);
  14772. }
  14773. virtual void updateEdgeStats(IStatisticGatherer * statsBuilder) const
  14774. {
  14775. for (unsigned i = 0; i < numOutputs; i++)
  14776. addEdgeStats(statsBuilder, i, outputAdaptors[i].numStarts, outputAdaptors[i].processed, 0);
  14777. }
  14778. };
  14779. void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
  14780. {
  14781. ForEachItemIn(i1, _other.outputs)
  14782. outputs.append(_other.outputs.item(i1));
  14783. ForEachItemIn(i2, _other.unusedOutputs)
  14784. unusedOutputs.append(_other.unusedOutputs.item(i2));
  14785. maxOutputs = _other.maxOutputs;
  14786. graphid = _other.graphid;
  14787. libraryName.set(_other.libraryName);
  14788. embeddedGraphName.set(_other.embeddedGraphName);
  14789. interfaceHash = _other.interfaceHash;
  14790. embedded = _other.embedded;
  14791. }
  14792. void LibraryCallFactoryExtra::calcUnused()
  14793. {
  14794. for (unsigned i=0; i < maxOutputs; i++)
  14795. if (!outputs.contains(i))
  14796. unusedOutputs.append(i);
  14797. }
  14798. class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
  14799. {
  14800. private:
  14801. CRoxieServerMultiInputInfo inputs;
  14802. LibraryCallFactoryExtra extra;
  14803. public:
  14804. CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14805. : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14806. {
  14807. extra.set(_extra);
  14808. extra.calcUnused();
  14809. setNumOutputs(extra.outputs.ordinality());
  14810. }
  14811. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14812. {
  14813. return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
  14814. }
  14815. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  14816. {
  14817. inputs.set(idx, source, sourceidx);
  14818. }
  14819. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  14820. {
  14821. return inputs.get(idx, sourceidx);
  14822. }
  14823. virtual unsigned numInputs() const { return inputs.ordinality(); }
  14824. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  14825. {
  14826. addXrefLibraryInfo(reply, extra.libraryName);
  14827. }
  14828. };
  14829. IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
  14830. {
  14831. return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
  14832. }
  14833. //=====================================================================================================
  14834. // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
  14835. // Used to implement RANGE(<rowset-expression>, [set-of-indices])
  14836. class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
  14837. {
  14838. protected:
  14839. PointerArrayOf<IFinalRoxieInput> selectedInputs;
  14840. PointerArrayOf<IEngineRowStream> selectedStreams;
  14841. PointerArrayOf<IStrandJunction> selectedJunctions;
  14842. public:
  14843. CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14844. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  14845. {
  14846. }
  14847. virtual unsigned __int64 queryLocalCycles() const
  14848. {
  14849. __int64 localCycles = totalCycles.totalCycles;
  14850. ForEachItemIn(i, selectedInputs)
  14851. {
  14852. localCycles -= selectedInputs.item(i)->queryTotalCycles();
  14853. }
  14854. if (localCycles < 0)
  14855. localCycles = 0;
  14856. return localCycles;
  14857. }
  14858. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  14859. {
  14860. if (selectedInputs.isItem(idx))
  14861. return selectedInputs.item(idx);
  14862. else
  14863. return NULL;
  14864. }
  14865. virtual void reset()
  14866. {
  14867. ForEachItemIn(i, selectedInputs)
  14868. selectedInputs.item(i)->reset();
  14869. selectedInputs.kill();
  14870. selectedStreams.kill();
  14871. selectedJunctions.kill();
  14872. CRoxieServerMultiInputBaseActivity::reset();
  14873. }
  14874. virtual const void * nextRow()
  14875. {
  14876. throwUnexpected();
  14877. }
  14878. virtual unsigned numConcreteOutputs() const
  14879. {
  14880. return selectedInputs.ordinality();
  14881. }
  14882. virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
  14883. {
  14884. return queryInput(idx);
  14885. }
  14886. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
  14887. {
  14888. if (selectedStreams.isItem(whichInput))
  14889. return selectedStreams.item(whichInput);
  14890. return NULL;
  14891. }
  14892. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
  14893. {
  14894. if (selectedJunctions.isItem(idx))
  14895. return selectedJunctions.item(idx);
  14896. return NULL;
  14897. }
  14898. };
  14899. class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
  14900. {
  14901. IHThorNWayInputArg & helper;
  14902. public:
  14903. CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  14904. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
  14905. {
  14906. }
  14907. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14908. {
  14909. CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  14910. bool selectionIsAll;
  14911. size32_t selectionLen;
  14912. rtlDataAttr selection;
  14913. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  14914. selectedInputs.kill();
  14915. selectedStreams.kill();
  14916. selectedJunctions.kill();
  14917. assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
  14918. if (selectionIsAll)
  14919. {
  14920. for (unsigned i=0; i < numInputs; i++)
  14921. {
  14922. selectedInputs.append(inputArray[i]);
  14923. selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
  14924. selectedJunctions.append(junctionArray[i]);
  14925. }
  14926. }
  14927. else
  14928. {
  14929. const size32_t * selections = (const size32_t *)selection.getdata();
  14930. unsigned max = selectionLen/sizeof(size32_t);
  14931. for (unsigned i = 0; i < max; i++)
  14932. {
  14933. unsigned nextIndex = selections[i];
  14934. //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
  14935. for (unsigned j=i+1; j < max; j++)
  14936. {
  14937. if (nextIndex == selections[j])
  14938. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
  14939. }
  14940. if (nextIndex > numInputs || nextIndex > numStreams)
  14941. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
  14942. selectedInputs.append(inputArray[nextIndex-1]);
  14943. selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
  14944. selectedJunctions.append(junctionArray[nextIndex-1]);
  14945. }
  14946. }
  14947. // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
  14948. // But the N-Way input itself is now done with processing, and can stop itself/dependencies.
  14949. stop();
  14950. }
  14951. };
  14952. class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
  14953. {
  14954. public:
  14955. CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14956. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  14957. {
  14958. }
  14959. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  14960. {
  14961. return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
  14962. }
  14963. };
  14964. IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  14965. {
  14966. return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  14967. }
  14968. //=====================================================================================================
  14969. class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
  14970. {
  14971. IHThorNWayGraphLoopResultReadArg & helper;
  14972. IArrayOf<IRoxieServerActivity> resultReaders;
  14973. Owned<IStrandJunction> *resultJunctions;
  14974. unsigned graphId;
  14975. bool grouped;
  14976. bool selectionIsAll;
  14977. size32_t selectionLen;
  14978. rtlDataAttr selection;
  14979. public:
  14980. CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
  14981. : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
  14982. {
  14983. grouped = helper.isGrouped();
  14984. graphId = _graphId;
  14985. selectionIsAll = false;
  14986. selectionLen = 0;
  14987. resultJunctions = NULL;
  14988. }
  14989. ~CRoxieServerNWayGraphLoopResultReadActivity()
  14990. {
  14991. delete [] resultJunctions;
  14992. }
  14993. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  14994. {
  14995. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  14996. if (selectedInputs.ordinality() == 0)
  14997. {
  14998. initInputSelection();
  14999. unsigned max = selectionLen / sizeof(size32_t);
  15000. const size32_t * selections = (const size32_t *)selection.getdata();
  15001. IProbeManager * probeManager = NULL; // MORE!!
  15002. for (unsigned i = 0; i < max; i++)
  15003. {
  15004. CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
  15005. resultReaders.append(*resultInput);
  15006. selectedInputs.append(resultInput);
  15007. resultInput->onCreate(colocalParent);
  15008. resultInput->start(parentExtractSize, parentExtract, paused);
  15009. selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
  15010. selectedJunctions.append(resultJunctions[i]);
  15011. }
  15012. }
  15013. // I have done with my processing - note that this won't stop my inputs
  15014. stop();
  15015. }
  15016. virtual void reset()
  15017. {
  15018. resultReaders.kill();
  15019. CRoxieServerNWayInputBaseActivity::reset();
  15020. ForEachItemIn(i, selectedStreams)
  15021. resetJunction(resultJunctions[i]);
  15022. }
  15023. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
  15024. {
  15025. ensureCreated();
  15026. basehelper.onStart(parentExtract, NULL);
  15027. initInputSelection();
  15028. unsigned max = selectionLen / sizeof(size32_t);
  15029. const size32_t * selections = (const size32_t *)selection.getdata();
  15030. for (unsigned i = 0; i < max; i++)
  15031. processor.noteUseIteration(selections[i]);
  15032. }
  15033. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
  15034. {
  15035. //selection etc. already initialised from the gatherIterationUsage() call.
  15036. unsigned max = selectionLen / sizeof(size32_t);
  15037. const size32_t * selections = (const size32_t *)selection.getdata();
  15038. resultJunctions = new Owned<IStrandJunction> [max];
  15039. for (unsigned i = 0; i < max; i++)
  15040. {
  15041. IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
  15042. selectedInputs.append(in);
  15043. selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
  15044. selectedJunctions.append(resultJunctions[i]);
  15045. }
  15046. }
  15047. protected:
  15048. void initInputSelection()
  15049. {
  15050. helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
  15051. if (selectionIsAll)
  15052. throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
  15053. }
  15054. };
  15055. class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
  15056. {
  15057. unsigned graphId;
  15058. public:
  15059. CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
  15060. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
  15061. {
  15062. }
  15063. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15064. {
  15065. return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
  15066. }
  15067. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15068. {
  15069. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
  15070. }
  15071. };
  15072. IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
  15073. {
  15074. return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
  15075. }
  15076. //=================================================================================
  15077. class RoxieSteppedInput : implements ISteppedInput, public CInterface
  15078. {
  15079. public:
  15080. RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
  15081. IMPLEMENT_IINTERFACE
  15082. protected:
  15083. virtual const void * nextInputRow()
  15084. {
  15085. #ifdef TRACE_SEEK_REQUESTS
  15086. IRoxieContextLogger * logger = input->queryActivity();
  15087. const void * ret = doNextInputRow();
  15088. {
  15089. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15090. if (!ret)
  15091. xmlwrite.outputBool(true,"eof");
  15092. else if (input->queryOutputMeta()->hasXML())
  15093. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15094. logger->CTXLOG("next() returns (%s)", xmlwrite.str());
  15095. }
  15096. return ret;
  15097. #else
  15098. return inputStream->ungroupedNextRow();
  15099. #endif
  15100. }
  15101. virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15102. {
  15103. #ifdef TRACE_SEEK_REQUESTS
  15104. IRoxieContextLogger * logger = input->queryActivity();
  15105. {
  15106. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15107. if (input->queryOutputMeta()->hasXML())
  15108. input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
  15109. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
  15110. numFields,
  15111. stepExtra.readAheadManyResults() ? "readahead " : "",
  15112. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15113. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15114. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15115. xmlwrite.str());
  15116. }
  15117. const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15118. {
  15119. CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
  15120. if (!ret)
  15121. xmlwrite.outputBool(true,"eof");
  15122. else if (input->queryOutputMeta()->hasXML())
  15123. input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
  15124. logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
  15125. numFields,
  15126. stepExtra.readAheadManyResults() ? "readahead " : "",
  15127. stepExtra.returnMismatches() ? "mismatch" : "exact",
  15128. stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
  15129. stepExtra.queryExtraSeeks() ? "multi-seek":"",
  15130. xmlwrite.str());
  15131. }
  15132. return ret;
  15133. #else
  15134. return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15135. #endif
  15136. }
  15137. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15138. {
  15139. return input->gatherConjunctions(collector);
  15140. }
  15141. virtual void resetEOF()
  15142. {
  15143. inputStream->resetEOF();
  15144. }
  15145. virtual IInputSteppingMeta * queryInputSteppingMeta()
  15146. {
  15147. return input->querySteppingMeta();
  15148. }
  15149. inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15150. {
  15151. assertex(wasCompleteMatch);
  15152. return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15153. }
  15154. protected:
  15155. IFinalRoxieInput * input;
  15156. IEngineRowStream * inputStream;
  15157. };
  15158. //=================================================================================
  15159. class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
  15160. {
  15161. public:
  15162. CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15163. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15164. {
  15165. }
  15166. void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15167. {
  15168. ForEachItemIn(ei, expandedInputs)
  15169. expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
  15170. ForEachItemIn(idx, expandedInputs)
  15171. startJunction(expandedJunctions.item(idx));
  15172. }
  15173. virtual void stop()
  15174. {
  15175. ForEachItemIn(i, expandedStreams)
  15176. expandedStreams.item(i)->stop();
  15177. CRoxieServerMultiInputBaseActivity::stop();
  15178. }
  15179. virtual void reset()
  15180. {
  15181. ForEachItemIn(idx, expandedInputs)
  15182. resetJunction(expandedJunctions.item(idx));
  15183. expandedInputs.kill();
  15184. expandedStreams.kill();
  15185. expandedJunctions.kill();
  15186. CRoxieServerMultiInputBaseActivity::reset();
  15187. }
  15188. protected:
  15189. PointerArrayOf<IFinalRoxieInput> expandedInputs;
  15190. PointerArrayOf<IEngineRowStream> expandedStreams;
  15191. PointerArrayOf<IStrandJunction> expandedJunctions;
  15192. };
  15193. //=================================================================================
  15194. class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
  15195. {
  15196. public:
  15197. CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15198. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
  15199. {
  15200. }
  15201. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15202. {
  15203. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15204. for (unsigned i=0; i < numInputs; i++)
  15205. {
  15206. IFinalRoxieInput * cur = inputArray[i];
  15207. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15208. if (nWayInput)
  15209. {
  15210. nWayInput->start(parentExtractSize, parentExtract, paused);
  15211. unsigned numRealInputs = cur->numConcreteOutputs();
  15212. for (unsigned j = 0; j < numRealInputs; j++)
  15213. {
  15214. expandedInputs.append(cur->queryConcreteInput(j));
  15215. expandedStreams.append(cur->queryConcreteOutputStream(j));
  15216. expandedJunctions.append(cur->queryConcreteOutputJunction(j));
  15217. }
  15218. }
  15219. else
  15220. {
  15221. expandedInputs.append(cur);
  15222. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15223. expandedStreams.append(queryConcreteOutputStream(i));
  15224. expandedJunctions.append(queryConcreteOutputJunction(i));
  15225. }
  15226. }
  15227. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15228. }
  15229. };
  15230. //=================================================================================
  15231. class CRoxieStreamMerger : public CStreamMerger
  15232. {
  15233. public:
  15234. CRoxieStreamMerger() : CStreamMerger(true)
  15235. {
  15236. streamArray = NULL;
  15237. }
  15238. void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
  15239. {
  15240. CStreamMerger::initInputs(_numInputs);
  15241. streamArray = _streamArray;
  15242. }
  15243. virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
  15244. {
  15245. const void * next;
  15246. bool matches = true;
  15247. if (seek)
  15248. next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
  15249. else
  15250. next = streamArray[i]->ungroupedNextRow();
  15251. pending[i] = next;
  15252. pendingMatches[i] = matches;
  15253. return (next != NULL);
  15254. }
  15255. virtual void releaseRow(const void * row)
  15256. {
  15257. ReleaseRoxieRow(row);
  15258. }
  15259. protected:
  15260. IEngineRowStream **streamArray;
  15261. };
  15262. class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
  15263. {
  15264. public:
  15265. CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15266. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15267. helper((IHThorNWayMergeArg &)basehelper)
  15268. {
  15269. initializedMeta = false;
  15270. }
  15271. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15272. {
  15273. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15274. merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
  15275. merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
  15276. }
  15277. virtual void stop()
  15278. {
  15279. merger.done();
  15280. CRoxieServerNaryActivity::stop();
  15281. }
  15282. virtual void reset()
  15283. {
  15284. merger.cleanup();
  15285. CRoxieServerNaryActivity::reset();
  15286. initializedMeta = false;
  15287. }
  15288. virtual const void * nextRow()
  15289. {
  15290. ActivityTimer t(totalCycles, timeActivities);
  15291. const void * next = merger.nextRow();
  15292. if (next)
  15293. processed++;
  15294. return next;
  15295. }
  15296. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
  15297. {
  15298. ActivityTimer t(totalCycles, timeActivities);
  15299. const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15300. if (next)
  15301. processed++;
  15302. return next;
  15303. }
  15304. virtual IInputSteppingMeta * querySteppingMeta()
  15305. {
  15306. if (expandedStreams.ordinality() == 0)
  15307. return NULL;
  15308. if (!initializedMeta)
  15309. {
  15310. meta.init(helper.querySteppingMeta(), false);
  15311. ForEachItemIn(i, expandedStreams)
  15312. {
  15313. if (meta.getNumFields() == 0)
  15314. break;
  15315. IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
  15316. meta.intersect(inputMeta);
  15317. }
  15318. initializedMeta = true;
  15319. }
  15320. if (meta.getNumFields() == 0)
  15321. return NULL;
  15322. return &meta;
  15323. }
  15324. protected:
  15325. IHThorNWayMergeArg &helper;
  15326. CRoxieStreamMerger merger;
  15327. CSteppingMeta meta;
  15328. bool initializedMeta;
  15329. };
  15330. class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
  15331. {
  15332. public:
  15333. CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15334. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15335. {
  15336. }
  15337. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15338. {
  15339. return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
  15340. }
  15341. };
  15342. IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15343. {
  15344. return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15345. }
  15346. //=================================================================================
  15347. class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
  15348. {
  15349. public:
  15350. CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
  15351. : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
  15352. helper((IHThorNWayMergeJoinArg &)basehelper),
  15353. processor(_processor)
  15354. {
  15355. }
  15356. virtual void onCreate(IHThorArg *_colocalParent)
  15357. {
  15358. CRoxieServerNaryActivity::onCreate(_colocalParent);
  15359. inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
  15360. outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
  15361. }
  15362. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15363. {
  15364. CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
  15365. ForEachItemIn(i1, expandedInputs)
  15366. {
  15367. Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
  15368. processor.addInput(stepInput);
  15369. }
  15370. processor.beforeProcessing(inputAllocator, outputAllocator);
  15371. }
  15372. virtual void stop()
  15373. {
  15374. processor.afterProcessing();
  15375. CRoxieServerNaryActivity::stop();
  15376. }
  15377. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15378. {
  15379. return processor.gatherConjunctions(collector);
  15380. }
  15381. virtual void resetEOF()
  15382. {
  15383. processor.queryResetEOF();
  15384. }
  15385. virtual const void * nextRow()
  15386. {
  15387. ActivityTimer t(totalCycles, timeActivities);
  15388. const void * next = processor.nextRow();
  15389. if (next)
  15390. processed++;
  15391. return next;
  15392. }
  15393. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15394. {
  15395. ActivityTimer t(totalCycles, timeActivities);
  15396. const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
  15397. if (next)
  15398. processed++;
  15399. return next;
  15400. }
  15401. virtual IInputSteppingMeta * querySteppingMeta()
  15402. {
  15403. return processor.queryInputSteppingMeta();
  15404. }
  15405. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15406. {
  15407. CRoxieServerNaryActivity::gatherStats(merged);
  15408. if (inputAllocator)
  15409. inputAllocator->gatherStats(merged);
  15410. if (outputAllocator)
  15411. outputAllocator->gatherStats(merged);
  15412. }
  15413. protected:
  15414. IHThorNWayMergeJoinArg & helper;
  15415. CMergeJoinProcessor & processor;
  15416. Owned<IEngineRowAllocator> inputAllocator;
  15417. Owned<IEngineRowAllocator> outputAllocator;
  15418. };
  15419. class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15420. {
  15421. public:
  15422. CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15423. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
  15424. {
  15425. }
  15426. protected:
  15427. CAndMergeJoinProcessor andProcessor;
  15428. };
  15429. class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15430. {
  15431. public:
  15432. CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15433. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
  15434. {
  15435. }
  15436. protected:
  15437. CAndLeftMergeJoinProcessor andLeftProcessor;
  15438. };
  15439. class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15440. {
  15441. public:
  15442. CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15443. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
  15444. {
  15445. }
  15446. protected:
  15447. CMofNMergeJoinProcessor mofnProcessor;
  15448. };
  15449. class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
  15450. {
  15451. public:
  15452. CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15453. : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
  15454. {
  15455. }
  15456. protected:
  15457. CProximityJoinProcessor proximityProcessor;
  15458. };
  15459. class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
  15460. {
  15461. unsigned flags;
  15462. public:
  15463. CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15464. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15465. {
  15466. Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
  15467. flags = helper->getJoinFlags();
  15468. }
  15469. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15470. {
  15471. if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
  15472. return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
  15473. switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
  15474. {
  15475. case IHThorNWayMergeJoinArg::MJFinner:
  15476. return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15477. case IHThorNWayMergeJoinArg::MJFleftonly:
  15478. case IHThorNWayMergeJoinArg::MJFleftouter:
  15479. return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15480. case IHThorNWayMergeJoinArg::MJFmofn:
  15481. return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
  15482. default:
  15483. throwUnexpected();
  15484. }
  15485. }
  15486. };
  15487. IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15488. {
  15489. return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15490. }
  15491. //=================================================================================
  15492. class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
  15493. {
  15494. IHThorNWaySelectArg &helper;
  15495. public:
  15496. CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  15497. : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
  15498. helper((IHThorNWaySelectArg &)basehelper)
  15499. {
  15500. }
  15501. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15502. {
  15503. CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
  15504. unsigned whichInput = helper.getInputIndex();
  15505. selectedInput = nullptr;
  15506. selectedStream = nullptr;
  15507. if (whichInput--)
  15508. {
  15509. for (unsigned i=0; i < numInputs; i++)
  15510. {
  15511. IFinalRoxieInput * cur = inputArray[i];
  15512. CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
  15513. if (nWayInput)
  15514. {
  15515. nWayInput->start(parentExtractSize, parentExtract, paused);
  15516. unsigned numRealInputs = cur->numConcreteOutputs();
  15517. if (whichInput < numRealInputs)
  15518. {
  15519. expandedInputs.append(cur->queryConcreteInput(whichInput));
  15520. expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
  15521. expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
  15522. break;
  15523. }
  15524. whichInput -= numRealInputs;
  15525. }
  15526. else
  15527. {
  15528. if (whichInput == 0)
  15529. {
  15530. expandedInputs.append(cur);
  15531. // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
  15532. expandedStreams.append(queryConcreteOutputStream(i));
  15533. expandedJunctions.append(queryConcreteOutputJunction(i));
  15534. break;
  15535. }
  15536. whichInput -= 1;
  15537. }
  15538. }
  15539. }
  15540. if (expandedInputs.ordinality())
  15541. {
  15542. startExpandedInputs(parentExtractSize, parentExtract, paused);
  15543. selectedInput = expandedInputs.item(0);
  15544. selectedStream = expandedStreams.item(0);
  15545. }
  15546. }
  15547. const void * nextRow()
  15548. {
  15549. ActivityTimer t(totalCycles, timeActivities);
  15550. if (!selectedStream)
  15551. return NULL;
  15552. return selectedStream->nextRow();
  15553. }
  15554. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  15555. {
  15556. if (!selectedInput)
  15557. return false;
  15558. return selectedInput->gatherConjunctions(collector);
  15559. }
  15560. virtual void resetEOF()
  15561. {
  15562. if (selectedStream)
  15563. selectedStream->resetEOF();
  15564. }
  15565. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  15566. {
  15567. ActivityTimer t(totalCycles, timeActivities);
  15568. if (!selectedStream)
  15569. return NULL;
  15570. return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  15571. }
  15572. IInputSteppingMeta * querySteppingMeta()
  15573. {
  15574. if (selectedInput)
  15575. return selectedInput->querySteppingMeta();
  15576. return NULL;
  15577. }
  15578. protected:
  15579. IFinalRoxieInput * selectedInput = nullptr;
  15580. IEngineRowStream * selectedStream = nullptr;
  15581. Owned<IStrandJunction> selectedJunction;
  15582. };
  15583. class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
  15584. {
  15585. public:
  15586. CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15587. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15588. {
  15589. }
  15590. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15591. {
  15592. return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
  15593. }
  15594. };
  15595. IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15596. {
  15597. return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15598. }
  15599. //=================================================================================
  15600. class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  15601. {
  15602. protected:
  15603. IHThorRemoteArg &helper;
  15604. CRemoteResultAdaptor remote;
  15605. public:
  15606. CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
  15607. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15608. helper((IHThorRemoteArg &)basehelper),
  15609. remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
  15610. {
  15611. }
  15612. virtual const IResolvedFile *queryVarFileInfo() const
  15613. {
  15614. return NULL;
  15615. }
  15616. virtual void onCreate(IHThorArg *_colocalParent)
  15617. {
  15618. CRoxieServerActivity::onCreate(_colocalParent);
  15619. remote.onCreate(_colocalParent);
  15620. }
  15621. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15622. {
  15623. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15624. remote.onStart(parentExtractSize, parentExtract);
  15625. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  15626. unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
  15627. remote.getMem(0, fileNo, 0); // the cached context is all we need to send
  15628. remote.flush();
  15629. remote.senddone();
  15630. }
  15631. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  15632. {
  15633. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  15634. }
  15635. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  15636. {
  15637. if (idx==(unsigned)-1)
  15638. idx = 0;
  15639. return idx ? NULL: &remote;
  15640. }
  15641. virtual void reset()
  15642. {
  15643. processed = remote.processed;
  15644. remote.processed = 0;
  15645. CRoxieServerActivity::reset();
  15646. }
  15647. virtual void onLimitExceeded(bool isKeyed)
  15648. {
  15649. if (traceLevel > 4)
  15650. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  15651. helper.onLimitExceeded();
  15652. }
  15653. virtual const void *createLimitFailRow(bool isKeyed)
  15654. {
  15655. UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
  15656. }
  15657. virtual const void *nextRow()
  15658. {
  15659. throwUnexpected(); // I am nobody's input
  15660. }
  15661. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15662. {
  15663. CRoxieServerActivity::gatherStats(merged);
  15664. remote.gatherStats(merged);
  15665. }
  15666. };
  15667. class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
  15668. {
  15669. public:
  15670. RemoteActivityId remoteId;
  15671. bool isRoot;
  15672. CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15673. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
  15674. {
  15675. }
  15676. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15677. {
  15678. return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
  15679. }
  15680. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  15681. {
  15682. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  15683. }
  15684. virtual bool isSink() const
  15685. {
  15686. //I don't think the action version of this is implemented - but this would be the code
  15687. return isRoot && !meta.queryOriginal();
  15688. }
  15689. virtual const StatisticsMapping &queryStatsMapping() const
  15690. {
  15691. return allStatistics; // Child queries...
  15692. }
  15693. };
  15694. IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
  15695. {
  15696. return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
  15697. }
  15698. //=================================================================================
  15699. class CRoxieServerIterateActivity : public CRoxieServerActivity
  15700. {
  15701. IHThorIterateArg &helper;
  15702. OwnedConstRoxieRow defaultRecord;
  15703. OwnedConstRoxieRow left;
  15704. OwnedConstRoxieRow right;
  15705. unsigned counter;
  15706. public:
  15707. CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15708. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  15709. helper((IHThorIterateArg &)basehelper)
  15710. {
  15711. counter = 0;
  15712. }
  15713. virtual bool needsAllocator() const { return true; }
  15714. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15715. {
  15716. counter = 0;
  15717. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15718. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15719. size32_t thisSize = helper.createDefault(rowBuilder);
  15720. defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
  15721. }
  15722. virtual void reset()
  15723. {
  15724. defaultRecord.clear();
  15725. right.clear();
  15726. left.clear();
  15727. CRoxieServerActivity::reset();
  15728. }
  15729. virtual const void * nextRow()
  15730. {
  15731. ActivityTimer t(totalCycles, timeActivities);
  15732. for (;;)
  15733. {
  15734. right.setown(inputStream->nextRow());
  15735. if (!right)
  15736. {
  15737. bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
  15738. left.clear();
  15739. counter = 0;
  15740. if (skippedGroup) continue;
  15741. return NULL;
  15742. }
  15743. try
  15744. {
  15745. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15746. unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
  15747. if (outSize)
  15748. {
  15749. left.setown(rowBuilder.finalizeRowClear(outSize));
  15750. processed++;
  15751. return left.getLink();
  15752. }
  15753. }
  15754. catch (IException *E)
  15755. {
  15756. throw makeWrappedException(E);
  15757. }
  15758. }
  15759. }
  15760. };
  15761. class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
  15762. {
  15763. public:
  15764. CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15765. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15766. {
  15767. }
  15768. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15769. {
  15770. return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
  15771. }
  15772. };
  15773. IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15774. {
  15775. return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15776. }
  15777. //=================================================================================
  15778. class CRoxieServerProcessActivity : public CRoxieServerActivity
  15779. {
  15780. IHThorProcessArg &helper;
  15781. OwnedConstRoxieRow curRight;
  15782. OwnedConstRoxieRow initialRight;
  15783. unsigned counter;
  15784. Owned<IEngineRowAllocator> rightRowAllocator;
  15785. public:
  15786. CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15787. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
  15788. {
  15789. counter = 0;
  15790. }
  15791. virtual bool needsAllocator() const { return true; }
  15792. virtual void onCreate(IHThorArg *_colocalParent)
  15793. {
  15794. CRoxieServerActivity::onCreate(_colocalParent);
  15795. rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
  15796. }
  15797. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15798. {
  15799. counter = 0;
  15800. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15801. RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
  15802. size32_t thisSize = helper.createInitialRight(rowBuilder);
  15803. initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
  15804. curRight.set(initialRight);
  15805. }
  15806. virtual const void * nextRow()
  15807. {
  15808. ActivityTimer t(totalCycles, timeActivities);
  15809. try
  15810. {
  15811. for (;;)
  15812. {
  15813. const void * in = inputStream->nextRow();
  15814. if (!in)
  15815. {
  15816. bool eog = (curRight != initialRight); // processed any records?
  15817. counter = 0;
  15818. curRight.set(initialRight);
  15819. if (eog)
  15820. return NULL;
  15821. in = inputStream->nextRow();
  15822. if (!in)
  15823. return NULL;
  15824. }
  15825. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  15826. RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
  15827. size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
  15828. ReleaseRoxieRow(in);
  15829. if (outSize)
  15830. {
  15831. //MORE: This should be returned...
  15832. size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
  15833. curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
  15834. processed++;
  15835. return rowBuilder.finalizeRowClear(outSize);
  15836. }
  15837. }
  15838. }
  15839. catch (IException *E)
  15840. {
  15841. throw makeWrappedException(E);
  15842. }
  15843. }
  15844. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  15845. {
  15846. CRoxieServerActivity::gatherStats(merged);
  15847. if (rightRowAllocator)
  15848. rightRowAllocator->gatherStats(merged);
  15849. }
  15850. };
  15851. class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
  15852. {
  15853. public:
  15854. CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15855. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15856. {
  15857. }
  15858. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15859. {
  15860. return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
  15861. }
  15862. };
  15863. IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15864. {
  15865. return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15866. }
  15867. //=================================================================================
  15868. class CRoxieServerGroupActivity : public CRoxieServerActivity
  15869. {
  15870. IHThorGroupArg &helper;
  15871. bool endPending;
  15872. bool eof;
  15873. bool first;
  15874. unsigned numGroups;
  15875. unsigned numGroupMax;
  15876. unsigned numProcessedLastGroup;
  15877. const void *next;
  15878. public:
  15879. CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15880. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
  15881. {
  15882. next = NULL;
  15883. endPending = false;
  15884. eof = false;
  15885. first = true;
  15886. numGroups = 0;
  15887. numGroupMax = 0;
  15888. numProcessedLastGroup = 0;
  15889. }
  15890. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15891. {
  15892. endPending = false;
  15893. eof = false;
  15894. first = true;
  15895. numGroups = 0;
  15896. numGroupMax = 0;
  15897. numProcessedLastGroup = processed;
  15898. assertex(next == NULL);
  15899. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  15900. }
  15901. virtual void reset()
  15902. {
  15903. noteStatistic(StNumGroups, numGroups);
  15904. noteStatistic(StNumGroupMax, numGroupMax);
  15905. ReleaseClearRoxieRow(next);
  15906. CRoxieServerActivity::reset();
  15907. }
  15908. virtual const void * nextRow()
  15909. {
  15910. ActivityTimer t(totalCycles, timeActivities);
  15911. if (first)
  15912. {
  15913. next = inputStream->nextRow();
  15914. first = false;
  15915. }
  15916. if (eof || endPending)
  15917. {
  15918. endPending = false;
  15919. return NULL;
  15920. }
  15921. const void * prev = next;
  15922. next = inputStream->ungroupedNextRow();
  15923. if (next)
  15924. {
  15925. assertex(prev);
  15926. if (!helper.isSameGroup(prev, next))
  15927. {
  15928. noteEndOfGroup();
  15929. endPending = true;
  15930. }
  15931. }
  15932. else
  15933. {
  15934. noteEndOfGroup();
  15935. eof = true;
  15936. }
  15937. if (prev)
  15938. processed++;
  15939. return prev;
  15940. }
  15941. inline void noteEndOfGroup()
  15942. {
  15943. unsigned numThisGroup = processed - numProcessedLastGroup;
  15944. if (numThisGroup == 0)
  15945. return;
  15946. numProcessedLastGroup = processed;
  15947. if (numThisGroup > numGroupMax)
  15948. numGroupMax = numThisGroup;
  15949. numGroups++;
  15950. }
  15951. };
  15952. class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
  15953. {
  15954. public:
  15955. CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15956. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  15957. {
  15958. }
  15959. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  15960. {
  15961. return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
  15962. }
  15963. virtual const StatisticsMapping &queryStatsMapping() const
  15964. {
  15965. return groupStatistics;
  15966. }
  15967. };
  15968. IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  15969. {
  15970. return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  15971. }
  15972. //=================================================================================
  15973. class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
  15974. {
  15975. unsigned __int64 limit;
  15976. unsigned __int64 skip;
  15977. unsigned doneThisGroup;
  15978. IHThorFirstNArg &helper;
  15979. public:
  15980. CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  15981. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
  15982. {
  15983. doneThisGroup = 0;
  15984. limit = 0;
  15985. skip = 0;
  15986. }
  15987. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  15988. {
  15989. doneThisGroup = 0;
  15990. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  15991. limit = helper.getLimit();
  15992. skip = helper.numToSkip();
  15993. lateStart(parentExtractSize, parentExtract, limit > 0);
  15994. if (limit + skip >= limit)
  15995. limit += skip;
  15996. }
  15997. const void * nextRow()
  15998. {
  15999. ActivityTimer t(totalCycles, timeActivities);
  16000. if (eof)
  16001. return NULL;
  16002. const void *ret;
  16003. for (;;)
  16004. {
  16005. ret = inputStream->nextRow();
  16006. if (!ret)
  16007. {
  16008. if (meta.isGrouped())
  16009. {
  16010. if (doneThisGroup > skip)
  16011. {
  16012. doneThisGroup = 0;
  16013. return NULL;
  16014. }
  16015. doneThisGroup = 0;
  16016. }
  16017. ret = inputStream->nextRow();
  16018. if (!ret)
  16019. {
  16020. eof = true;
  16021. return NULL;
  16022. }
  16023. }
  16024. doneThisGroup++;
  16025. if (doneThisGroup > skip)
  16026. break;
  16027. ReleaseRoxieRow(ret);
  16028. }
  16029. if (doneThisGroup <= limit)
  16030. {
  16031. processed++;
  16032. return ret;
  16033. }
  16034. ReleaseRoxieRow(ret);
  16035. if (meta.isGrouped())
  16036. {
  16037. while ((ret = inputStream->nextRow()) != NULL)
  16038. ReleaseRoxieRow(ret);
  16039. doneThisGroup = 0;
  16040. }
  16041. else
  16042. eof = true;
  16043. return NULL;
  16044. }
  16045. };
  16046. class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
  16047. {
  16048. public:
  16049. CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16050. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16051. {
  16052. }
  16053. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16054. {
  16055. return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
  16056. }
  16057. };
  16058. IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16059. {
  16060. return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16061. }
  16062. //=================================================================================
  16063. class CRoxieServerSelectNActivity : public CRoxieServerActivity
  16064. {
  16065. bool done;
  16066. IHThorSelectNArg &helper;
  16067. public:
  16068. CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  16069. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
  16070. {
  16071. done = false;
  16072. }
  16073. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16074. {
  16075. done = false;
  16076. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16077. }
  16078. const void *defaultRow()
  16079. {
  16080. if (!rowAllocator)
  16081. ensureRowAllocator(); // We delay as often not needed...
  16082. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16083. size32_t thisSize = helper.createDefault(rowBuilder);
  16084. return rowBuilder.finalizeRowClear(thisSize);
  16085. }
  16086. virtual const void * nextRow()
  16087. {
  16088. ActivityTimer t(totalCycles, timeActivities);
  16089. if (done)
  16090. return NULL;
  16091. done = true;
  16092. processed++; // always going to return a row!
  16093. unsigned __int64 index = helper.getRowToSelect();
  16094. while (--index)
  16095. {
  16096. const void * next = inputStream->ungroupedNextRow();
  16097. if (!next)
  16098. return defaultRow();
  16099. ReleaseRoxieRow(next);
  16100. }
  16101. const void * next = inputStream->ungroupedNextRow();
  16102. if (!next)
  16103. next = defaultRow();
  16104. return next;
  16105. }
  16106. };
  16107. class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
  16108. {
  16109. public:
  16110. CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16111. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16112. {
  16113. }
  16114. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16115. {
  16116. return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
  16117. }
  16118. };
  16119. IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16120. {
  16121. return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16122. }
  16123. //=================================================================================
  16124. class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
  16125. {
  16126. IHThorJoinArg &helper;
  16127. ICompare *collate;
  16128. OwnedRowArray group;
  16129. bool matchedLeft;
  16130. BoolArray matchedRight;
  16131. bool eof;
  16132. bool first;
  16133. unsigned leftIndex;
  16134. unsigned rightIndex;
  16135. unsigned rightOuterIndex;
  16136. unsigned joinLimit;
  16137. unsigned atmostLimit;
  16138. unsigned atmostsTriggered;
  16139. unsigned abortLimit;
  16140. unsigned keepLimit;
  16141. unsigned joinCounter;
  16142. bool leftOuterJoin;
  16143. bool rightOuterJoin;
  16144. bool exclude;
  16145. bool limitFail;
  16146. bool limitOnFail;
  16147. bool cloneLeft;
  16148. bool forceSpill;
  16149. OwnedConstRoxieRow defaultLeft;
  16150. OwnedConstRoxieRow defaultRight;
  16151. OwnedConstRoxieRow lhs;
  16152. Owned<IException> failingLimit;
  16153. bool failingOuterAtmost;
  16154. Owned<IEngineRowAllocator> defaultAllocator;
  16155. Owned<IRHLimitedCompareHelper> limitedhelper;
  16156. Owned<CRHDualCache> dualcache;
  16157. Owned<IGroupedInput> groupedInput;
  16158. IRowStream *dualCacheInput;
  16159. bool fillGroup()
  16160. {
  16161. group.clear();
  16162. matchedLeft = false;
  16163. matchedRight.kill();
  16164. failingOuterAtmost = false;
  16165. const void * next;
  16166. unsigned groupCount = 0;
  16167. while((next = groupedInput->nextRow()) != NULL)
  16168. {
  16169. if(groupCount==abortLimit)
  16170. {
  16171. if(limitFail)
  16172. failLimit(next);
  16173. if (ctx->queryDebugContext())
  16174. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  16175. if(limitOnFail)
  16176. {
  16177. assertex(!failingLimit);
  16178. try
  16179. {
  16180. failLimit(next);
  16181. }
  16182. catch(IException * except)
  16183. {
  16184. failingLimit.setown(except);
  16185. }
  16186. assertex(failingLimit != NULL);
  16187. group.append(next);
  16188. groupCount++;
  16189. break;
  16190. }
  16191. group.clear();
  16192. groupCount = 0;
  16193. while(next)
  16194. {
  16195. ReleaseRoxieRow(next);
  16196. next = groupedInput->nextRow();
  16197. }
  16198. }
  16199. else if(groupCount==atmostLimit)
  16200. {
  16201. atmostsTriggered++;
  16202. if(leftOuterJoin)
  16203. {
  16204. group.append(next);
  16205. groupCount++;
  16206. failingOuterAtmost = true;
  16207. break;
  16208. }
  16209. else
  16210. {
  16211. group.clear();
  16212. groupCount = 0;
  16213. while (next)
  16214. {
  16215. ReleaseRoxieRow(next);
  16216. next = groupedInput->nextRow();
  16217. }
  16218. }
  16219. }
  16220. else
  16221. {
  16222. group.append(next);
  16223. groupCount++;
  16224. }
  16225. }
  16226. if(group.ordinality()==0)
  16227. {
  16228. eof = true;
  16229. return false;
  16230. }
  16231. leftIndex = 0;
  16232. rightIndex = 0;
  16233. rightOuterIndex = 0;
  16234. joinCounter = 0;
  16235. joinLimit = keepLimit;
  16236. ForEachItemIn(idx, group)
  16237. matchedRight.append(false);
  16238. return true;
  16239. }
  16240. void failLimit(const void * next)
  16241. {
  16242. helper.onMatchAbortLimitExceeded();
  16243. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  16244. if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  16245. {
  16246. input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
  16247. }
  16248. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  16249. }
  16250. virtual bool needsAllocator() const { return true; }
  16251. const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except, unsigned flags)
  16252. {
  16253. try
  16254. {
  16255. if (cloneLeft && !except)
  16256. {
  16257. LinkRoxieRow(curLeft);
  16258. return curLeft;
  16259. }
  16260. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  16261. size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except, flags) : helper.transform(rowBuilder, curLeft, curRight, counter, flags);
  16262. if (outsize)
  16263. return rowBuilder.finalizeRowClear(outsize);
  16264. else
  16265. return NULL;
  16266. }
  16267. catch (IException *E)
  16268. {
  16269. throw makeWrappedException(E);
  16270. }
  16271. }
  16272. void createDefaultLeft()
  16273. {
  16274. if (!defaultLeft)
  16275. {
  16276. if (!defaultAllocator)
  16277. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16278. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16279. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  16280. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  16281. }
  16282. }
  16283. void createDefaultRight()
  16284. {
  16285. if (!defaultRight)
  16286. {
  16287. if (!defaultAllocator)
  16288. defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  16289. RtlDynamicRowBuilder rowBuilder(defaultAllocator);
  16290. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16291. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16292. }
  16293. }
  16294. public:
  16295. CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
  16296. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
  16297. {
  16298. collate = helper.queryCompareLeftRight();
  16299. eof = false;
  16300. first = true;
  16301. keepLimit = 0;
  16302. atmostLimit = 0;
  16303. atmostsTriggered = 0;
  16304. unsigned joinFlags = helper.getJoinFlags();
  16305. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16306. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  16307. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16308. exclude = (joinFlags & JFexclude) != 0;
  16309. abortLimit = 0;
  16310. joinLimit = 0;
  16311. assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
  16312. getLimitType(joinFlags, limitFail, limitOnFail);
  16313. if((joinFlags & JFslidingmatch) != 0)
  16314. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
  16315. failingOuterAtmost = false;
  16316. matchedLeft = false;
  16317. leftIndex = 0;
  16318. rightIndex = 0;
  16319. rightOuterIndex = 0;
  16320. joinCounter = 0;
  16321. dualCacheInput = NULL;
  16322. }
  16323. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16324. {
  16325. eof = false;
  16326. first = true;
  16327. failingLimit.clear();
  16328. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  16329. keepLimit = helper.getKeepLimit();
  16330. if(keepLimit == 0)
  16331. keepLimit = (unsigned)-1;
  16332. atmostsTriggered = 0;
  16333. atmostLimit = helper.getJoinLimit();
  16334. if(atmostLimit == 0)
  16335. atmostLimit = (unsigned)-1;
  16336. else
  16337. assertex(!rightOuterJoin);
  16338. abortLimit = helper.getMatchAbortLimit();
  16339. if (abortLimit == 0)
  16340. abortLimit = (unsigned)-1;
  16341. if (rightOuterJoin)
  16342. createDefaultLeft();
  16343. if (leftOuterJoin || limitOnFail)
  16344. createDefaultRight();
  16345. ICompare *compareLeft = helper.queryCompareLeft();
  16346. if (helper.isLeftAlreadySorted())
  16347. groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
  16348. else
  16349. {
  16350. bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
  16351. RoxieSortAlgorithm sortAlgorithm;
  16352. if (forceSpill)
  16353. sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
  16354. else
  16355. sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
  16356. groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
  16357. }
  16358. if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
  16359. { //limited match join (s[1..n])
  16360. dualcache.setown(new CRHDualCache());
  16361. dualcache->init(groupedInput);
  16362. dualCacheInput = dualcache->queryOut1();
  16363. failingOuterAtmost = false;
  16364. matchedLeft = false;
  16365. leftIndex = 0;
  16366. rightOuterIndex = 0;
  16367. joinCounter = 0;
  16368. limitedhelper.setown(createRHLimitedCompareHelper());
  16369. limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
  16370. }
  16371. }
  16372. virtual void reset()
  16373. {
  16374. if (atmostsTriggered)
  16375. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16376. group.clear();
  16377. groupedInput.clear();
  16378. CRoxieServerActivity::reset();
  16379. defaultLeft.clear();
  16380. defaultRight.clear();
  16381. }
  16382. virtual const void * nextRow()
  16383. {
  16384. ActivityTimer t(totalCycles, timeActivities);
  16385. if (limitedhelper)
  16386. {
  16387. while(!eof) //limited match join
  16388. {
  16389. if (!group.isItem(rightIndex))
  16390. {
  16391. lhs.setown(dualCacheInput->nextRow());
  16392. if (lhs)
  16393. {
  16394. rightIndex = 0;
  16395. joinCounter = 0;
  16396. group.clear();
  16397. limitedhelper->getGroup(group,lhs);
  16398. }
  16399. else
  16400. {
  16401. eof = true;
  16402. }
  16403. }
  16404. if (group.isItem(rightIndex))
  16405. {
  16406. const void * rhs = group.item(rightIndex++);
  16407. if(helper.match(lhs, rhs))
  16408. {
  16409. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16410. if(ret)
  16411. {
  16412. processed++;
  16413. return ret;
  16414. }
  16415. }
  16416. }
  16417. }
  16418. return NULL;
  16419. }
  16420. else
  16421. {
  16422. if (first)
  16423. {
  16424. first = false;
  16425. fillGroup();
  16426. }
  16427. while(!eof)
  16428. {
  16429. if(failingOuterAtmost)
  16430. while(group.isItem(leftIndex))
  16431. {
  16432. const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL, JTFmatchedleft);
  16433. if(ret)
  16434. {
  16435. processed++;
  16436. return ret;
  16437. }
  16438. }
  16439. if((joinLimit == 0) || !group.isItem(rightIndex))
  16440. {
  16441. if(leftOuterJoin && !matchedLeft && !failingLimit)
  16442. {
  16443. const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL, JTFmatchedleft);
  16444. if(ret)
  16445. {
  16446. matchedLeft = true;
  16447. processed++;
  16448. return ret;
  16449. }
  16450. }
  16451. leftIndex++;
  16452. matchedLeft = false;
  16453. rightIndex = 0;
  16454. joinCounter = 0;
  16455. joinLimit = keepLimit;
  16456. }
  16457. if(!group.isItem(leftIndex))
  16458. {
  16459. if(failingLimit || failingOuterAtmost)
  16460. {
  16461. const void * lhs;
  16462. while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
  16463. {
  16464. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16465. ReleaseRoxieRow(lhs);
  16466. if(ret)
  16467. {
  16468. processed++;
  16469. return ret;
  16470. }
  16471. }
  16472. failingLimit.clear();
  16473. }
  16474. if(rightOuterJoin && !failingLimit)
  16475. while(group.isItem(rightOuterIndex))
  16476. if(!matchedRight.item(rightOuterIndex++))
  16477. {
  16478. const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL, JTFmatchedright);
  16479. if(ret)
  16480. {
  16481. processed++;
  16482. return ret;
  16483. }
  16484. }
  16485. if(!fillGroup())
  16486. return NULL;
  16487. continue;
  16488. }
  16489. const void * lhs = group.item(leftIndex);
  16490. if(failingLimit)
  16491. {
  16492. leftIndex++;
  16493. const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit, JTFmatchedleft);
  16494. if(ret)
  16495. {
  16496. processed++;
  16497. return ret;
  16498. }
  16499. }
  16500. else
  16501. {
  16502. const void * rhs = group.item(rightIndex++);
  16503. if(helper.match(lhs, rhs))
  16504. {
  16505. matchedLeft = true;
  16506. matchedRight.replace(true, rightIndex-1);
  16507. if(!exclude)
  16508. {
  16509. const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL, JTFmatchedleft|JTFmatchedright);
  16510. if(ret)
  16511. {
  16512. processed++;
  16513. joinLimit--;
  16514. return ret;
  16515. }
  16516. }
  16517. }
  16518. }
  16519. }
  16520. return NULL;
  16521. }
  16522. }
  16523. };
  16524. class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
  16525. {
  16526. bool forceSpill;
  16527. public:
  16528. CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16529. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  16530. {
  16531. forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
  16532. }
  16533. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  16534. {
  16535. return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
  16536. }
  16537. virtual const StatisticsMapping &queryStatsMapping() const
  16538. {
  16539. return joinStatistics;
  16540. }
  16541. };
  16542. IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  16543. {
  16544. return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  16545. }
  16546. //=====================================================================================================
  16547. class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
  16548. {
  16549. private:
  16550. class LookupTable : public CInterface
  16551. {
  16552. public:
  16553. LookupTable(IHThorHashJoinArg &helper)
  16554. : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
  16555. leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
  16556. {
  16557. size = 0;
  16558. }
  16559. virtual const void *find(const void * left) const = 0;
  16560. virtual const void *findNext(const void * left) const = 0;
  16561. protected:
  16562. ICompare * leftRightCompare;
  16563. ICompare * rightCompare;
  16564. IHash * leftHash;
  16565. IHash * rightHash;
  16566. unsigned size;
  16567. };
  16568. class DedupLookupTable : public LookupTable
  16569. {
  16570. public:
  16571. DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16572. : LookupTable(helper)
  16573. {
  16574. size = (4*rightRows.length())/3 + 1;
  16575. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
  16576. ForEachItemIn(idx, rightRows)
  16577. add(rightRows.item(idx));
  16578. }
  16579. ~DedupLookupTable()
  16580. {
  16581. roxiemem::ReleaseRoxieRowArray(size, table);
  16582. free(table);
  16583. }
  16584. virtual const void *find(const void * left) const
  16585. {
  16586. unsigned index = leftHash->hash(left) % size;
  16587. unsigned start = index;
  16588. while (table[index])
  16589. {
  16590. if(leftRightCompare->docompare(left, table[index]) == 0)
  16591. return table[index];
  16592. index++;
  16593. if (index==size)
  16594. index = 0;
  16595. if (index==start)
  16596. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16597. }
  16598. return NULL;
  16599. }
  16600. virtual const void *findNext(const void * left) const
  16601. {
  16602. return NULL;
  16603. }
  16604. protected:
  16605. void add(const void * right)
  16606. {
  16607. unsigned index = rightHash->hash(right) % size;
  16608. unsigned start = index;
  16609. while (table[index])
  16610. {
  16611. if (rightCompare->docompare(table[index], right) == 0)
  16612. {
  16613. ReleaseRoxieRow(right);
  16614. return;
  16615. }
  16616. index++;
  16617. if (index==size)
  16618. index = 0;
  16619. if (index==start)
  16620. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
  16621. }
  16622. table[index] = right;
  16623. }
  16624. const void * * table;
  16625. };
  16626. class FewLookupTable : public LookupTable
  16627. {
  16628. public:
  16629. FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16630. : LookupTable(helper)
  16631. {
  16632. size = (4*rightRows.length())/3 + 1;
  16633. table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
  16634. findex = fstart = BadIndex;
  16635. ForEachItemIn(idx, rightRows)
  16636. add(rightRows.item(idx));
  16637. }
  16638. ~FewLookupTable()
  16639. {
  16640. roxiemem::ReleaseRoxieRowArray(size, table);
  16641. free(table);
  16642. }
  16643. virtual const void *find(const void * left) const
  16644. {
  16645. fstart = leftHash->hash(left) % size;
  16646. findex = fstart;
  16647. return doFind(left);
  16648. }
  16649. virtual const void *findNext(const void * left) const
  16650. {
  16651. if (findex == BadIndex)
  16652. return NULL;
  16653. advance();
  16654. return doFind(left);
  16655. }
  16656. protected:
  16657. void add(const void * right)
  16658. {
  16659. unsigned start = rightHash->hash(right) % size;
  16660. unsigned index = start;
  16661. while (table[index])
  16662. {
  16663. index++;
  16664. if (index==size)
  16665. index = 0;
  16666. if (index==start)
  16667. throwUnexpected(); //table is full, should never happen
  16668. }
  16669. table[index] = right;
  16670. }
  16671. void advance() const
  16672. {
  16673. findex++;
  16674. if(findex==size)
  16675. findex = 0;
  16676. if(findex==fstart)
  16677. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16678. }
  16679. const void *doFind(const void * left) const
  16680. {
  16681. while(table[findex])
  16682. {
  16683. if (leftRightCompare->docompare(left, table[findex]) == 0)
  16684. return table[findex];
  16685. advance();
  16686. }
  16687. findex = BadIndex;
  16688. return NULL;
  16689. }
  16690. const void * * table;
  16691. unsigned mutable fstart;
  16692. unsigned mutable findex;
  16693. static unsigned const BadIndex;
  16694. };
  16695. class ManyLookupTable : public LookupTable
  16696. {
  16697. public:
  16698. ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
  16699. : LookupTable(helper)
  16700. {
  16701. rightRows.swapWith(rowtable);
  16702. UInt64Array groups;
  16703. unsigned numRows = rowtable.length();
  16704. if (numRows)
  16705. {
  16706. unsigned groupStart = 0;
  16707. const void *groupStartRow = rowtable.item(0);
  16708. for (unsigned i=1; i < numRows; i++)
  16709. {
  16710. const void *thisRow = rowtable.item(i);
  16711. if (rightCompare->docompare(groupStartRow, thisRow))
  16712. {
  16713. groups.append(makeint64(groupStart, i-groupStart));
  16714. groupStart = i;
  16715. groupStartRow = thisRow;
  16716. }
  16717. }
  16718. groups.append(makeint64(groupStart, numRows-groupStart));
  16719. }
  16720. size = (4*groups.length())/3 + 1;
  16721. table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
  16722. ForEachItemIn(idx, groups)
  16723. {
  16724. unsigned __int64 group = groups.item(idx);
  16725. unsigned groupstart = high(group);
  16726. const void *row = rowtable.item(groupstart);
  16727. add(row, group);
  16728. }
  16729. }
  16730. ~ManyLookupTable()
  16731. {
  16732. roxiemem::ReleaseRoxieRows(rowtable);
  16733. free(table);
  16734. }
  16735. void add(const void *row, unsigned __int64 group)
  16736. {
  16737. unsigned start = rightHash->hash(row) % size;
  16738. unsigned index = start;
  16739. while (table[index])
  16740. {
  16741. index++;
  16742. if (index==size)
  16743. index = 0;
  16744. if (index==start)
  16745. throwUnexpected(); //table is full, should never happen
  16746. }
  16747. table[index] = group;
  16748. }
  16749. virtual const void *find(const void * left) const
  16750. {
  16751. unsigned index = leftHash->hash(left) % size;
  16752. unsigned start = index;
  16753. while (table[index])
  16754. {
  16755. __uint64 group = table[index];
  16756. currentMatch = high(group);
  16757. const void *right = rowtable.item(currentMatch);
  16758. if (leftRightCompare->docompare(left, right) == 0)
  16759. {
  16760. currentMatch++;
  16761. matchCount = low(group) - 1;
  16762. return right;
  16763. }
  16764. index++;
  16765. if (index==size)
  16766. index = 0;
  16767. if (index==start)
  16768. throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
  16769. }
  16770. matchCount = 0;
  16771. return NULL;
  16772. }
  16773. virtual const void *findNext(const void * left) const
  16774. {
  16775. if (!matchCount)
  16776. return NULL;
  16777. matchCount--;
  16778. return rowtable.item(currentMatch++);
  16779. }
  16780. protected:
  16781. __uint64 *table;
  16782. ConstPointerArray rowtable;
  16783. mutable unsigned currentMatch = 0;
  16784. mutable unsigned matchCount = 0;
  16785. };
  16786. IHThorHashJoinArg &helper;
  16787. bool leftOuterJoin;
  16788. bool exclude;
  16789. bool eog;
  16790. bool many;
  16791. bool dedupRHS;
  16792. bool useFewTable;
  16793. bool matchedGroup;
  16794. const void *left;
  16795. OwnedConstRoxieRow defaultRight;
  16796. Owned<LookupTable> table;
  16797. unsigned keepLimit;
  16798. unsigned atmostLimit;
  16799. unsigned atmostsTriggered;
  16800. unsigned limitLimit;
  16801. unsigned joinCounter;
  16802. bool limitFail;
  16803. bool limitOnFail;
  16804. bool hasGroupLimit;
  16805. bool isSmartJoin;
  16806. unsigned keepCount;
  16807. bool gotMatch;
  16808. bool cloneLeft;
  16809. ConstPointerArray rightGroup;
  16810. aindex_t rightGroupIndex;
  16811. Owned<IException> failingLimit;
  16812. ConstPointerArray filteredRight;
  16813. ThorActivityKind activityKind;
  16814. Owned<IEngineRowAllocator> defaultRightAllocator;
  16815. void createDefaultRight()
  16816. {
  16817. if (!defaultRight)
  16818. {
  16819. if (!defaultRightAllocator)
  16820. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  16821. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  16822. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  16823. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  16824. }
  16825. }
  16826. public:
  16827. CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
  16828. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
  16829. {
  16830. unsigned joinFlags = helper.getJoinFlags();
  16831. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  16832. assertex((joinFlags & JFrightouter) == 0);
  16833. exclude = (joinFlags & JFexclude) != 0;
  16834. many = (joinFlags & JFmanylookup) != 0;
  16835. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  16836. dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
  16837. left = NULL;
  16838. activityKind = factory->getKind();
  16839. eog = false;
  16840. matchedGroup = false;
  16841. gotMatch = false;
  16842. keepLimit = 0;
  16843. keepCount = 0;
  16844. joinCounter = 0;
  16845. atmostLimit = 0;
  16846. atmostsTriggered = 0;
  16847. limitLimit = 0;
  16848. rightGroupIndex = 0;
  16849. hasGroupLimit = false;
  16850. isSmartJoin = (joinFlags & JFsmart) != 0;
  16851. getLimitType(joinFlags, limitFail, limitOnFail);
  16852. }
  16853. void loadRight()
  16854. {
  16855. ConstPointerArray rightset;
  16856. try
  16857. {
  16858. const void * next;
  16859. while(true)
  16860. {
  16861. next = inputStream1->ungroupedNextRow();
  16862. if(!next)
  16863. break;
  16864. rightset.append(next);
  16865. }
  16866. if (!dedupRHS)
  16867. {
  16868. if (useFewTable)
  16869. {
  16870. table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16871. }
  16872. else
  16873. {
  16874. if (!helper.isRightAlreadySorted())
  16875. {
  16876. if (helper.getJoinFlags() & JFunstable)
  16877. {
  16878. qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
  16879. }
  16880. else
  16881. {
  16882. unsigned rightord = rightset.ordinality();
  16883. MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
  16884. void **temp = (void **) tempAttr.bufferBase();
  16885. void **_rows = const_cast<void * *>(rightset.getArray());
  16886. msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
  16887. }
  16888. }
  16889. table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16890. }
  16891. }
  16892. else
  16893. {
  16894. table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
  16895. }
  16896. }
  16897. catch (...)
  16898. {
  16899. roxiemem::ReleaseRoxieRows(rightset);
  16900. throw;
  16901. }
  16902. };
  16903. virtual void reset()
  16904. {
  16905. if (atmostsTriggered)
  16906. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  16907. CRoxieServerTwoInputActivity::reset();
  16908. ReleaseClearRoxieRow(left);
  16909. defaultRight.clear();
  16910. table.clear();
  16911. }
  16912. virtual bool needsAllocator() const { return true; }
  16913. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  16914. {
  16915. eog = false;
  16916. matchedGroup = false;
  16917. left = NULL;
  16918. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  16919. keepLimit = helper.getKeepLimit();
  16920. if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
  16921. atmostsTriggered = 0;
  16922. atmostLimit = helper.getJoinLimit();
  16923. limitLimit = helper.getMatchAbortLimit();
  16924. hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
  16925. if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
  16926. if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
  16927. getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
  16928. switch (activityKind)
  16929. {
  16930. case TAKlookupjoin:
  16931. case TAKlookupdenormalizegroup:
  16932. case TAKsmartjoin:
  16933. case TAKsmartdenormalizegroup:
  16934. if (leftOuterJoin)
  16935. createDefaultRight();
  16936. break;
  16937. }
  16938. if (limitOnFail)
  16939. createDefaultRight();
  16940. }
  16941. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  16942. {
  16943. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  16944. {
  16945. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  16946. puller->setInput(0, _sourceIdx, _in);
  16947. _in = puller;
  16948. _sourceIdx = 0;
  16949. }
  16950. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  16951. }
  16952. virtual const void * nextRow()
  16953. {
  16954. ActivityTimer t(totalCycles, timeActivities);
  16955. if(!table)
  16956. loadRight();
  16957. switch (activityKind)
  16958. {
  16959. case TAKlookupjoin:
  16960. case TAKsmartjoin:
  16961. return nextRowJoin();
  16962. case TAKlookupdenormalize:
  16963. case TAKlookupdenormalizegroup:
  16964. case TAKsmartdenormalize:
  16965. case TAKsmartdenormalizegroup:
  16966. return nextRowDenormalize();
  16967. }
  16968. throwUnexpected();
  16969. }
  16970. private:
  16971. const void * nextRowJoin()
  16972. {
  16973. if(!table)
  16974. loadRight();
  16975. while(true)
  16976. {
  16977. const void * right = NULL;
  16978. if(!left)
  16979. {
  16980. left = inputStream->nextRow();
  16981. keepCount = keepLimit;
  16982. joinCounter = 0;
  16983. if(!left)
  16984. {
  16985. if (isSmartJoin)
  16986. left = inputStream->nextRow();
  16987. if (!left)
  16988. {
  16989. if(matchedGroup || eog)
  16990. {
  16991. matchedGroup = false;
  16992. eog = true;
  16993. return NULL;
  16994. }
  16995. eog = true;
  16996. continue;
  16997. }
  16998. }
  16999. eog = false;
  17000. gotMatch = false;
  17001. right = getRightFirst();
  17002. }
  17003. else
  17004. right = getRightNext();
  17005. const void * ret = NULL;
  17006. if(failingLimit)
  17007. {
  17008. ret = joinException(left, failingLimit);
  17009. }
  17010. else
  17011. {
  17012. while(right)
  17013. {
  17014. if(helper.match(left, right))
  17015. {
  17016. gotMatch = true;
  17017. if(exclude)
  17018. break;
  17019. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17020. if(ret)
  17021. {
  17022. processed++;
  17023. break;
  17024. }
  17025. }
  17026. right = getRightNext();
  17027. ret = NULL;
  17028. }
  17029. if(leftOuterJoin && !gotMatch)
  17030. {
  17031. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17032. gotMatch = true;
  17033. }
  17034. }
  17035. if(ret)
  17036. {
  17037. matchedGroup = true;
  17038. processed++;
  17039. if(!many || (--keepCount == 0) || failingLimit)
  17040. {
  17041. ReleaseClearRoxieRow(left);
  17042. failingLimit.clear();
  17043. }
  17044. return ret;
  17045. }
  17046. ReleaseClearRoxieRow(left);
  17047. }
  17048. }
  17049. const void * nextRowDenormalize()
  17050. {
  17051. while(true)
  17052. {
  17053. left = inputStream->nextRow();
  17054. if(!left)
  17055. {
  17056. if (!matchedGroup || isSmartJoin)
  17057. left = inputStream->nextRow();
  17058. if (!left)
  17059. {
  17060. matchedGroup = false;
  17061. return NULL;
  17062. }
  17063. }
  17064. gotMatch = false;
  17065. const void * right = getRightFirst();
  17066. const void * ret = NULL;
  17067. if (failingLimit)
  17068. ret = joinException(left, failingLimit);
  17069. else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
  17070. {
  17071. OwnedConstRoxieRow newLeft;
  17072. newLeft.set(left);
  17073. unsigned rowSize = 0;
  17074. unsigned leftCount = 0;
  17075. keepCount = keepLimit;
  17076. while (right)
  17077. {
  17078. try
  17079. {
  17080. if (helper.match(left, right))
  17081. {
  17082. gotMatch = true;
  17083. if (exclude)
  17084. break;
  17085. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17086. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17087. if (thisSize)
  17088. {
  17089. rowSize = thisSize;
  17090. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17091. }
  17092. if(!many || (--keepCount == 0))
  17093. break;
  17094. }
  17095. right = getRightNext();
  17096. }
  17097. catch (IException *E)
  17098. {
  17099. throw makeWrappedException(E);
  17100. }
  17101. }
  17102. if (rowSize)
  17103. ret = newLeft.getClear();
  17104. else if (leftOuterJoin && !gotMatch)
  17105. {
  17106. ret = left;
  17107. left = NULL;
  17108. }
  17109. }
  17110. else
  17111. {
  17112. filteredRight.kill();
  17113. keepCount = keepLimit;
  17114. while (right)
  17115. {
  17116. if (helper.match(left, right))
  17117. {
  17118. gotMatch = true;
  17119. if(exclude)
  17120. break;
  17121. filteredRight.append(right);
  17122. if(!many || (--keepCount == 0))
  17123. break;
  17124. }
  17125. right = getRightNext();
  17126. }
  17127. if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
  17128. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17129. filteredRight.kill();
  17130. }
  17131. ReleaseRoxieRow(left);
  17132. left = NULL;
  17133. failingLimit.clear();
  17134. if(ret)
  17135. {
  17136. matchedGroup = true;
  17137. processed++;
  17138. return ret;
  17139. }
  17140. }
  17141. }
  17142. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17143. {
  17144. if (cloneLeft)
  17145. {
  17146. LinkRoxieRow(left);
  17147. return left;
  17148. }
  17149. try
  17150. {
  17151. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17152. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17153. if (outSize)
  17154. return rowBuilder.finalizeRowClear(outSize);
  17155. else
  17156. return NULL;
  17157. }
  17158. catch (IException *E)
  17159. {
  17160. throw makeWrappedException(E);
  17161. }
  17162. }
  17163. const void * joinException(const void * left, IException * except)
  17164. {
  17165. try
  17166. {
  17167. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17168. unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except, JTFmatchedleft);
  17169. if (outSize)
  17170. return rowBuilder.finalizeRowClear(outSize);
  17171. else
  17172. return NULL;
  17173. }
  17174. catch (IException *E)
  17175. {
  17176. throw makeWrappedException(E);
  17177. }
  17178. }
  17179. const void * denormalizeRecords(const void * left, ConstPointerArray & rows, unsigned flags)
  17180. {
  17181. try
  17182. {
  17183. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17184. unsigned numRows = rows.ordinality();
  17185. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17186. if (numRows>0)
  17187. flags |= JTFmatchedright;
  17188. unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray(), flags);
  17189. if (outSize)
  17190. return rowBuilder.finalizeRowClear(outSize);
  17191. else
  17192. return NULL;
  17193. }
  17194. catch (IException *E)
  17195. {
  17196. throw makeWrappedException(E);
  17197. }
  17198. }
  17199. const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
  17200. const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
  17201. const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
  17202. const void *fillRightGroup()
  17203. {
  17204. rightGroup.kill();
  17205. for(const void * right = table->find(left); right; right = table->findNext(left))
  17206. {
  17207. rightGroup.append(right);
  17208. if(rightGroup.ordinality() > limitLimit)
  17209. {
  17210. if(limitFail)
  17211. failLimit();
  17212. gotMatch = true;
  17213. if (ctx->queryDebugContext())
  17214. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17215. if(limitOnFail)
  17216. {
  17217. assertex(!failingLimit);
  17218. try
  17219. {
  17220. failLimit();
  17221. }
  17222. catch(IException * e)
  17223. {
  17224. failingLimit.setown(e);
  17225. }
  17226. assertex(failingLimit != NULL);
  17227. }
  17228. else
  17229. {
  17230. rightGroup.kill();
  17231. }
  17232. break;
  17233. }
  17234. if(rightGroup.ordinality() > atmostLimit)
  17235. {
  17236. atmostsTriggered++;
  17237. rightGroup.kill();
  17238. break;
  17239. }
  17240. }
  17241. rightGroupIndex = 0;
  17242. return readRightGroup();
  17243. }
  17244. void failLimit()
  17245. {
  17246. helper.onMatchAbortLimitExceeded();
  17247. CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
  17248. if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  17249. {
  17250. input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
  17251. }
  17252. throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
  17253. }
  17254. };
  17255. unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
  17256. class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17257. {
  17258. public:
  17259. CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17260. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17261. {
  17262. Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
  17263. useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
  17264. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
  17265. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
  17266. }
  17267. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17268. {
  17269. return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
  17270. }
  17271. virtual const StatisticsMapping &queryStatsMapping() const
  17272. {
  17273. return joinStatistics;
  17274. }
  17275. protected:
  17276. bool useFewTable;
  17277. };
  17278. IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17279. {
  17280. return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17281. }
  17282. //=====================================================================================================
  17283. class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
  17284. {
  17285. private:
  17286. IHThorAllJoinArg &helper;
  17287. bool leftOuterJoin;
  17288. bool rightOuterJoin;
  17289. bool exclude;
  17290. OwnedConstRoxieRow defaultRight;
  17291. OwnedConstRoxieRow defaultLeft;
  17292. Owned<IEngineRowAllocator> defaultRightAllocator;
  17293. Owned<IEngineRowAllocator> defaultLeftAllocator;
  17294. const void *left;
  17295. unsigned countForLeft;
  17296. ConstPointerArray rightset;
  17297. BoolArray matchedRight; // MORE - could use a bitset...
  17298. unsigned keepLimit;
  17299. bool started;
  17300. bool eog;
  17301. bool eos;
  17302. bool matchedLeft;
  17303. bool matchedGroup;
  17304. bool leftIsGrouped;
  17305. bool cloneLeft;
  17306. unsigned rightIndex;
  17307. unsigned joinCounter;
  17308. unsigned rightOrdinality;
  17309. ThorActivityKind activityKind;
  17310. ConstPointerArray filteredRight;
  17311. void createDefaultLeft()
  17312. {
  17313. if (!defaultLeft)
  17314. {
  17315. if (!defaultLeftAllocator)
  17316. defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
  17317. RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
  17318. size32_t thisSize = helper.createDefaultLeft(rowBuilder);
  17319. defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
  17320. }
  17321. }
  17322. void createDefaultRight()
  17323. {
  17324. if (!defaultRight)
  17325. {
  17326. if (!defaultRightAllocator)
  17327. defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
  17328. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  17329. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  17330. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  17331. }
  17332. }
  17333. public:
  17334. CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17335. : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
  17336. {
  17337. unsigned joinFlags = helper.getJoinFlags();
  17338. leftOuterJoin = (joinFlags & JFleftouter) != 0;
  17339. rightOuterJoin = (joinFlags & JFrightouter) != 0;
  17340. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  17341. keepLimit = (unsigned) -1;
  17342. exclude = (joinFlags & JFexclude) != 0;
  17343. left = NULL;
  17344. started = true;
  17345. eog = false;
  17346. eos = false;
  17347. matchedLeft = false;
  17348. matchedGroup = false;
  17349. activityKind = factory->getKind();
  17350. rightIndex = 0;
  17351. rightOrdinality = 0;
  17352. leftIsGrouped = false;
  17353. countForLeft = 0;
  17354. joinCounter = 0;
  17355. }
  17356. virtual void reset()
  17357. {
  17358. defaultRight.clear();
  17359. defaultLeft.clear();
  17360. ReleaseRoxieRows(rightset);
  17361. matchedRight.kill();
  17362. CRoxieServerTwoInputActivity::reset();
  17363. }
  17364. virtual bool needsAllocator() const { return true; }
  17365. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17366. {
  17367. eog = false;
  17368. eos = false;
  17369. matchedLeft = false;
  17370. matchedGroup = false;
  17371. started = false;
  17372. left = NULL;
  17373. CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
  17374. keepLimit = helper.getKeepLimit();
  17375. if(keepLimit==0)
  17376. keepLimit = (unsigned) -1;
  17377. countForLeft = keepLimit;
  17378. joinCounter = 0;
  17379. leftIsGrouped = input->queryOutputMeta()->isGrouped();
  17380. if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
  17381. createDefaultRight();
  17382. if(rightOuterJoin)
  17383. createDefaultLeft();
  17384. }
  17385. void loadRight()
  17386. {
  17387. const void * next;
  17388. while(true)
  17389. {
  17390. next = inputStream1->ungroupedNextRow();
  17391. if(!next)
  17392. break;
  17393. rightset.append(next);
  17394. matchedRight.append(false);
  17395. }
  17396. rightIndex = 0;
  17397. joinCounter = 0;
  17398. rightOrdinality = rightset.ordinality();
  17399. }
  17400. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  17401. {
  17402. if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
  17403. {
  17404. puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
  17405. puller->setInput(0, _sourceIdx, _in);
  17406. _in = puller;
  17407. _sourceIdx = 0;
  17408. }
  17409. CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
  17410. }
  17411. const void * joinRecords(const void * left, const void * right, unsigned counter, unsigned flags)
  17412. {
  17413. // MORE - could share some code with lookup join
  17414. if (cloneLeft)
  17415. {
  17416. LinkRoxieRow(left);
  17417. return left;
  17418. }
  17419. try
  17420. {
  17421. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17422. unsigned outSize = helper.transform(rowBuilder, left, right, counter, flags);
  17423. if (outSize)
  17424. return rowBuilder.finalizeRowClear(outSize);
  17425. else
  17426. return NULL;
  17427. }
  17428. catch (IException *E)
  17429. {
  17430. throw makeWrappedException(E);
  17431. }
  17432. }
  17433. const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows, unsigned flags)
  17434. {
  17435. try
  17436. {
  17437. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17438. unsigned numRows = rows.ordinality();
  17439. const void * right = numRows ? rows.item(0) : defaultRight.get();
  17440. if (numRows>0)
  17441. flags |= JTFmatchedright;
  17442. unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray(), flags);
  17443. if (outSize)
  17444. return rowBuilder.finalizeRowClear(outSize);
  17445. else
  17446. return NULL;
  17447. }
  17448. catch (IException *E)
  17449. {
  17450. throw makeWrappedException(E);
  17451. }
  17452. }
  17453. virtual const void *nextRow()
  17454. {
  17455. ActivityTimer t(totalCycles, timeActivities);
  17456. if(!started)
  17457. {
  17458. started = true;
  17459. left = inputStream->nextRow();
  17460. matchedLeft = false;
  17461. countForLeft = keepLimit;
  17462. joinCounter = 0;
  17463. if(left == NULL)
  17464. {
  17465. eos = true;
  17466. return NULL;
  17467. }
  17468. loadRight();
  17469. }
  17470. const void * ret;
  17471. const void * right;
  17472. if(eos)
  17473. return NULL;
  17474. while(true)
  17475. {
  17476. ret = NULL;
  17477. if((rightIndex == rightOrdinality) || (countForLeft==0))
  17478. {
  17479. if(leftOuterJoin && left && !matchedLeft)
  17480. {
  17481. switch(activityKind)
  17482. {
  17483. case TAKalljoin:
  17484. ret = joinRecords(left, defaultRight, 0, JTFmatchedleft);
  17485. break;
  17486. case TAKalldenormalize:
  17487. ret = left;
  17488. left = NULL;
  17489. break;
  17490. case TAKalldenormalizegroup:
  17491. filteredRight.kill();
  17492. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17493. break;
  17494. default:
  17495. throwUnexpected();
  17496. }
  17497. }
  17498. rightIndex = 0;
  17499. joinCounter = 0;
  17500. ReleaseRoxieRow(left);
  17501. left = NULL;
  17502. if(ret)
  17503. {
  17504. matchedGroup = true;
  17505. processed++;
  17506. return ret;
  17507. }
  17508. }
  17509. if(!left)
  17510. {
  17511. left = inputStream->nextRow();
  17512. matchedLeft = false;
  17513. countForLeft = keepLimit;
  17514. joinCounter = 0;
  17515. }
  17516. if(!left)
  17517. {
  17518. if(eog)
  17519. {
  17520. eos = true;
  17521. matchedGroup = false;
  17522. return NULL;
  17523. }
  17524. eog = true;
  17525. if (matchedGroup && leftIsGrouped)
  17526. {
  17527. matchedGroup = false;
  17528. return NULL;
  17529. }
  17530. matchedGroup = false;
  17531. continue;
  17532. }
  17533. eog = false;
  17534. switch(activityKind)
  17535. {
  17536. case TAKalljoin:
  17537. while(rightIndex < rightOrdinality)
  17538. {
  17539. right = rightset.item(rightIndex);
  17540. if(helper.match(left, right))
  17541. {
  17542. matchedLeft = true;
  17543. matchedRight.replace(true, rightIndex);
  17544. if(!exclude)
  17545. ret = joinRecords(left, right, ++joinCounter, JTFmatchedleft|JTFmatchedright);
  17546. }
  17547. rightIndex++;
  17548. if(ret)
  17549. {
  17550. countForLeft--;
  17551. matchedGroup = true;
  17552. processed++;
  17553. return ret;
  17554. }
  17555. }
  17556. break;
  17557. case TAKalldenormalize:
  17558. {
  17559. OwnedConstRoxieRow newLeft;
  17560. newLeft.set(left);
  17561. unsigned rowSize = 0;
  17562. unsigned leftCount = 0;
  17563. while((rightIndex < rightOrdinality) && countForLeft)
  17564. {
  17565. right = rightset.item(rightIndex);
  17566. if(helper.match(left, right))
  17567. {
  17568. matchedLeft = true;
  17569. matchedRight.replace(true, rightIndex);
  17570. if(!exclude)
  17571. {
  17572. try
  17573. {
  17574. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17575. unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount, JTFmatchedleft|JTFmatchedright);
  17576. if(thisSize)
  17577. {
  17578. rowSize = thisSize;
  17579. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  17580. --countForLeft;
  17581. }
  17582. }
  17583. catch (IException *e)
  17584. {
  17585. throw makeWrappedException(e);
  17586. }
  17587. }
  17588. }
  17589. rightIndex++;
  17590. }
  17591. if(rowSize)
  17592. {
  17593. processed++;
  17594. return newLeft.getClear();
  17595. }
  17596. }
  17597. break;
  17598. case TAKalldenormalizegroup:
  17599. filteredRight.kill();
  17600. while((rightIndex < rightOrdinality) && countForLeft)
  17601. {
  17602. right = rightset.item(rightIndex);
  17603. if(helper.match(left, right))
  17604. {
  17605. matchedLeft = true;
  17606. matchedRight.replace(true, rightIndex);
  17607. filteredRight.append(right);
  17608. --countForLeft;
  17609. }
  17610. ++rightIndex;
  17611. }
  17612. if(!exclude && filteredRight.ordinality())
  17613. {
  17614. ret = denormalizeRecords(left, filteredRight, JTFmatchedleft);
  17615. filteredRight.kill();
  17616. if(ret)
  17617. {
  17618. processed++;
  17619. return ret;
  17620. }
  17621. }
  17622. break;
  17623. default:
  17624. throwUnexpected();
  17625. }
  17626. }
  17627. }
  17628. };
  17629. class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
  17630. {
  17631. public:
  17632. CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17633. : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17634. {
  17635. Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
  17636. if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
  17637. throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
  17638. }
  17639. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17640. {
  17641. return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
  17642. }
  17643. virtual const StatisticsMapping &queryStatsMapping() const
  17644. {
  17645. return joinStatistics;
  17646. }
  17647. };
  17648. IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17649. {
  17650. return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17651. }
  17652. //=====================================================================================================
  17653. class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
  17654. {
  17655. unsigned limit;
  17656. bool hasBest;
  17657. bool eoi;
  17658. const void **sorted;
  17659. unsigned sortedCount;
  17660. unsigned curIndex;
  17661. IHThorTopNArg &helper;
  17662. ICompare &compare;
  17663. public:
  17664. CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17665. : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
  17666. {
  17667. sorted = NULL;
  17668. sortedCount = 0;
  17669. curIndex = 0;
  17670. limit = 0;
  17671. eoi = false;
  17672. hasBest = false;
  17673. }
  17674. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17675. {
  17676. assertex(sorted == NULL);
  17677. sortedCount = 0;
  17678. curIndex = 0;
  17679. eoi = false;
  17680. CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
  17681. limit = (unsigned) helper.getLimit();
  17682. hasBest = helper.hasBest();
  17683. lateStart(parentExtractSize, parentExtract, limit > 0);
  17684. // MORE - should we use an expanding array instead?
  17685. if (limit > 0)
  17686. sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
  17687. }
  17688. virtual void reset()
  17689. {
  17690. if (sorted)
  17691. {
  17692. roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
  17693. curIndex = 0;
  17694. sortedCount = 0;
  17695. ReleaseRoxieRow(sorted);
  17696. sorted = NULL;
  17697. }
  17698. CRoxieServerLateStartActivity::reset();
  17699. }
  17700. bool abortEarly()
  17701. {
  17702. if (hasBest && (sortedCount == limit))
  17703. {
  17704. int compare = helper.compareBest(sorted[sortedCount-1]);
  17705. if (compare == 0)
  17706. {
  17707. if (meta.isGrouped())
  17708. {
  17709. //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
  17710. const void * next;
  17711. while ((next = inputStream->nextRow()) != NULL)
  17712. ReleaseRoxieRow(next);
  17713. }
  17714. else
  17715. eoi = true;
  17716. return true;
  17717. }
  17718. //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
  17719. if (compare < 0)
  17720. throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
  17721. }
  17722. return false;
  17723. }
  17724. void getSorted()
  17725. {
  17726. curIndex = 0;
  17727. sortedCount = 0;
  17728. if(eoi)
  17729. return;
  17730. const void * next;
  17731. while ((next = inputStream->nextRow()) != NULL)
  17732. {
  17733. if (sortedCount < limit)
  17734. {
  17735. binary_vec_insert_stable(next, sorted, sortedCount, compare);
  17736. sortedCount++;
  17737. if(abortEarly())
  17738. return;
  17739. }
  17740. else
  17741. {
  17742. if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
  17743. {
  17744. binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
  17745. ReleaseRoxieRow(sorted[sortedCount]);
  17746. if(abortEarly())
  17747. return;
  17748. }
  17749. else
  17750. {
  17751. ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
  17752. }
  17753. }
  17754. }
  17755. }
  17756. virtual const void * nextRow()
  17757. {
  17758. ActivityTimer t(totalCycles, timeActivities);
  17759. if (eof)
  17760. return NULL;
  17761. if (curIndex >= sortedCount)
  17762. {
  17763. bool eog = sortedCount != 0;
  17764. getSorted();
  17765. if(sortedCount == 0)
  17766. {
  17767. eof = true;
  17768. return NULL;
  17769. }
  17770. if (eog)
  17771. return NULL;
  17772. }
  17773. processed++;
  17774. return sorted[curIndex++];
  17775. }
  17776. };
  17777. class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
  17778. {
  17779. public:
  17780. CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17781. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17782. {
  17783. }
  17784. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17785. {
  17786. return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
  17787. }
  17788. };
  17789. IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17790. {
  17791. return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17792. }
  17793. //=================================================================================
  17794. class CRoxieServerLimitActivity : public CRoxieServerActivity
  17795. {
  17796. protected:
  17797. unsigned __int64 rowLimit;
  17798. IHThorLimitArg &helper;
  17799. public:
  17800. CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17801. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
  17802. {
  17803. rowLimit = 0;
  17804. }
  17805. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17806. {
  17807. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  17808. rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
  17809. }
  17810. virtual const void *nextRow()
  17811. {
  17812. ActivityTimer t(totalCycles, timeActivities);
  17813. const void * ret = inputStream->nextRow();
  17814. if (ret)
  17815. {
  17816. processed++;
  17817. if (processed > rowLimit)
  17818. {
  17819. ReleaseRoxieRow(ret);
  17820. if (traceLevel > 4)
  17821. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17822. helper.onLimitExceeded();
  17823. }
  17824. }
  17825. return ret;
  17826. }
  17827. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  17828. {
  17829. ActivityTimer t(totalCycles, timeActivities);
  17830. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  17831. if (ret)
  17832. {
  17833. if (wasCompleteMatch)
  17834. processed++;
  17835. if (processed > rowLimit)
  17836. {
  17837. ReleaseRoxieRow(ret);
  17838. if (traceLevel > 4)
  17839. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  17840. helper.onLimitExceeded();
  17841. }
  17842. }
  17843. return ret;
  17844. }
  17845. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  17846. {
  17847. return input->gatherConjunctions(collector);
  17848. }
  17849. virtual void resetEOF()
  17850. {
  17851. //Do not reset the rowLimit
  17852. inputStream->resetEOF();
  17853. }
  17854. IInputSteppingMeta * querySteppingMeta()
  17855. {
  17856. return input->querySteppingMeta();
  17857. }
  17858. };
  17859. class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
  17860. {
  17861. public:
  17862. CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17863. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17864. {
  17865. }
  17866. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17867. {
  17868. return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
  17869. }
  17870. };
  17871. IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17872. {
  17873. return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17874. }
  17875. //=====================================================================================================
  17876. class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
  17877. {
  17878. ConstPointerArray buff;
  17879. bool started = false;
  17880. unsigned index = 0;
  17881. bool isFail = false;
  17882. public:
  17883. CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
  17884. : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
  17885. {
  17886. started = false;
  17887. index = 0;
  17888. isFail = _onFail;
  17889. }
  17890. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  17891. {
  17892. started = false;
  17893. index = 0;
  17894. CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
  17895. }
  17896. virtual void reset()
  17897. {
  17898. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  17899. buff.kill();
  17900. index = 0;
  17901. started = false;
  17902. CRoxieServerLimitActivity::reset();
  17903. }
  17904. virtual const void *nextRow()
  17905. {
  17906. ActivityTimer t(totalCycles, timeActivities);
  17907. if (!started)
  17908. pullInput();
  17909. if (buff.isItem(index))
  17910. {
  17911. const void * next = buff.item(index++);
  17912. if(next)
  17913. processed++;
  17914. return next;
  17915. }
  17916. return NULL;
  17917. }
  17918. protected:
  17919. void pullInput()
  17920. {
  17921. unsigned count = 0;
  17922. for (;;)
  17923. {
  17924. const void * next = inputStream->nextRow();
  17925. if (next == NULL)
  17926. {
  17927. next = inputStream->nextRow();
  17928. if(next == NULL)
  17929. break;
  17930. buff.append(NULL);
  17931. }
  17932. count++;
  17933. if (count > rowLimit)
  17934. {
  17935. ReleaseRoxieRow(next);
  17936. ReleaseRoxieRows(buff);
  17937. if (ctx->queryDebugContext())
  17938. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  17939. if (isFail)
  17940. {
  17941. ensureRowAllocator();
  17942. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  17943. size32_t outSize = helper.transformOnLimitExceeded(rowBuilder);
  17944. if (outSize)
  17945. buff.append(rowBuilder.finalizeRowClear(outSize));
  17946. }
  17947. break;
  17948. }
  17949. buff.append(next);
  17950. }
  17951. started = true;
  17952. }
  17953. };
  17954. class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
  17955. {
  17956. public:
  17957. CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17958. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  17959. {
  17960. }
  17961. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  17962. {
  17963. return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
  17964. }
  17965. };
  17966. IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  17967. {
  17968. return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  17969. }
  17970. //=================================================================================
  17971. class CRoxieServerCatchActivity : public CRoxieServerActivity
  17972. {
  17973. IHThorCatchArg &helper;
  17974. public:
  17975. CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  17976. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
  17977. {
  17978. }
  17979. // MORE - you could argue we should catch exceptions in START too, though not clear what to do with them
  17980. // See CRoxieServerSkipCatchActivity::start
  17981. // This is less significant now that we properly distinguish start exceptions from read exceptions in ThroughSpill activity
  17982. virtual const void *nextRow()
  17983. {
  17984. ActivityTimer t(totalCycles, timeActivities);
  17985. try
  17986. {
  17987. const void *ret = inputStream->nextRow();
  17988. if (ret)
  17989. processed++;
  17990. return ret;
  17991. }
  17992. catch (IException *E)
  17993. {
  17994. E->Release();
  17995. helper.onExceptionCaught();
  17996. }
  17997. catch (...)
  17998. {
  17999. helper.onExceptionCaught();
  18000. }
  18001. throwUnexpected(); // onExceptionCaught should have thrown something
  18002. }
  18003. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18004. {
  18005. try
  18006. {
  18007. ActivityTimer t(totalCycles, timeActivities);
  18008. const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18009. if (ret && wasCompleteMatch)
  18010. processed++;
  18011. return ret;
  18012. }
  18013. catch (IException *E)
  18014. {
  18015. E->Release();
  18016. helper.onExceptionCaught();
  18017. }
  18018. catch (...)
  18019. {
  18020. helper.onExceptionCaught();
  18021. }
  18022. throwUnexpected(); // onExceptionCaught should have thrown something
  18023. }
  18024. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18025. {
  18026. return input->gatherConjunctions(collector);
  18027. }
  18028. virtual void resetEOF()
  18029. {
  18030. inputStream->resetEOF(); // MORE - why not in base class?
  18031. }
  18032. IInputSteppingMeta * querySteppingMeta()
  18033. {
  18034. return input->querySteppingMeta();
  18035. }
  18036. };
  18037. class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
  18038. {
  18039. ConstPointerArray buff;
  18040. bool started;
  18041. unsigned index;
  18042. IHThorCatchArg &helper;
  18043. bool createRow;
  18044. public:
  18045. CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
  18046. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
  18047. {
  18048. started = false;
  18049. index = 0;
  18050. }
  18051. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18052. {
  18053. started = false;
  18054. index = 0;
  18055. try
  18056. {
  18057. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18058. }
  18059. catch (IException *E)
  18060. {
  18061. ensureCreated();
  18062. onException(E);
  18063. started = true;
  18064. }
  18065. catch (...)
  18066. {
  18067. ensureCreated();
  18068. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18069. started = true;
  18070. }
  18071. }
  18072. virtual void reset()
  18073. {
  18074. roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
  18075. buff.kill();
  18076. index = 0;
  18077. started = false;
  18078. CRoxieServerActivity::reset();
  18079. }
  18080. virtual const void *nextRow()
  18081. {
  18082. ActivityTimer t(totalCycles, timeActivities);
  18083. if (!started)
  18084. pullInput();
  18085. if (buff.isItem(index))
  18086. {
  18087. const void * next = buff.item(index++);
  18088. if(next)
  18089. processed++;
  18090. return next;
  18091. }
  18092. return NULL;
  18093. }
  18094. protected:
  18095. void onException(IException *E)
  18096. {
  18097. inputStream->stop();
  18098. ReleaseRoxieRows(buff);
  18099. if (createRow)
  18100. {
  18101. ensureRowAllocator();
  18102. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  18103. size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
  18104. if (outSize)
  18105. buff.append(rowBuilder.finalizeRowClear(outSize));
  18106. }
  18107. E->Release();
  18108. }
  18109. void pullInput()
  18110. {
  18111. try
  18112. {
  18113. bool EOGseen = false;
  18114. for (;;)
  18115. {
  18116. const void * next = inputStream->nextRow();
  18117. buff.append(next);
  18118. if (next == NULL)
  18119. {
  18120. if (EOGseen)
  18121. break;
  18122. EOGseen = true;
  18123. }
  18124. else
  18125. EOGseen = false;
  18126. }
  18127. }
  18128. catch (IException *E)
  18129. {
  18130. onException(E);
  18131. }
  18132. catch (...)
  18133. {
  18134. onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
  18135. }
  18136. started = true;
  18137. }
  18138. };
  18139. class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
  18140. {
  18141. public:
  18142. CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18143. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18144. {
  18145. }
  18146. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18147. {
  18148. switch (kind)
  18149. {
  18150. case TAKcatch:
  18151. return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
  18152. case TAKskipcatch:
  18153. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
  18154. case TAKcreaterowcatch:
  18155. return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
  18156. default:
  18157. throwUnexpected();
  18158. }
  18159. }
  18160. };
  18161. IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18162. {
  18163. return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18164. }
  18165. //=================================================================================
  18166. class CRoxieServerPullActivity : public CRoxieServerActivity
  18167. {
  18168. ConstPointerArray buff;
  18169. bool started;
  18170. unsigned index;
  18171. public:
  18172. CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18173. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18174. {
  18175. started = false;
  18176. index = 0;
  18177. }
  18178. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18179. {
  18180. started = false;
  18181. index = 0;
  18182. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18183. }
  18184. virtual void reset()
  18185. {
  18186. while (buff.isItem(index))
  18187. ReleaseRoxieRow(buff.item(index++));
  18188. buff.kill();
  18189. started = false;
  18190. index = 0;
  18191. CRoxieServerActivity::reset();
  18192. }
  18193. virtual const void *nextRow()
  18194. {
  18195. ActivityTimer t(totalCycles, timeActivities);
  18196. if (!started)
  18197. pullInput();
  18198. if (buff.isItem(index))
  18199. {
  18200. const void * next = buff.item(index++);
  18201. if (next)
  18202. processed++;
  18203. return next;
  18204. }
  18205. return NULL;
  18206. }
  18207. protected:
  18208. void pullInput()
  18209. {
  18210. bool EOGseen = false;
  18211. for (;;)
  18212. {
  18213. const void * next = inputStream->nextRow();
  18214. buff.append(next);
  18215. if (next == NULL)
  18216. {
  18217. if (EOGseen)
  18218. break;
  18219. EOGseen = true;
  18220. }
  18221. else
  18222. EOGseen = false;
  18223. }
  18224. started = true;
  18225. }
  18226. };
  18227. class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
  18228. {
  18229. public:
  18230. CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18231. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18232. {
  18233. }
  18234. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18235. {
  18236. return new CRoxieServerPullActivity(_ctx, this, _probeManager);
  18237. }
  18238. };
  18239. IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18240. {
  18241. return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18242. }
  18243. //=================================================================================
  18244. class CRoxieServerTraceActivity : public CRoxieServerActivity
  18245. {
  18246. public:
  18247. CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18248. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
  18249. keepLimit(0), skip(0), sample(0)
  18250. {
  18251. assertex(meta.hasXML());
  18252. traceEnabled = defaultTraceEnabled && !isBlind();
  18253. }
  18254. virtual void onCreate(IHThorArg *_colocalParent)
  18255. {
  18256. CRoxieServerActivity::onCreate(_colocalParent);
  18257. if (ctx)
  18258. traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
  18259. }
  18260. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18261. {
  18262. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18263. if (traceEnabled && helper.canMatchAny())
  18264. {
  18265. keepLimit = helper.getKeepLimit();
  18266. if (keepLimit==(unsigned) -1)
  18267. keepLimit = ctx->queryOptions().traceLimit;
  18268. skip = helper.getSkip();
  18269. sample = helper.getSample();
  18270. if (sample)
  18271. sample--;
  18272. name.setown(helper.getName());
  18273. if (!name)
  18274. name.set("Row");
  18275. }
  18276. else
  18277. keepLimit = 0;
  18278. }
  18279. virtual void stop()
  18280. {
  18281. name.clear();
  18282. CRoxieServerActivity::stop();
  18283. }
  18284. virtual bool isPassThrough()
  18285. {
  18286. return true;
  18287. }
  18288. virtual const void *nextRow()
  18289. {
  18290. ActivityTimer t(totalCycles, timeActivities);
  18291. const void *row = inputStream->nextRow();
  18292. if (row)
  18293. {
  18294. onTrace(row);
  18295. processed++;
  18296. }
  18297. return row;
  18298. }
  18299. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  18300. {
  18301. // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
  18302. ActivityTimer t(totalCycles, timeActivities);
  18303. const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
  18304. if (row)
  18305. {
  18306. onTrace(row);
  18307. processed++;
  18308. }
  18309. return row;
  18310. }
  18311. virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
  18312. {
  18313. return input->gatherConjunctions(collector);
  18314. }
  18315. virtual void resetEOF()
  18316. {
  18317. inputStream->resetEOF();
  18318. }
  18319. IInputSteppingMeta * querySteppingMeta()
  18320. {
  18321. return input->querySteppingMeta();
  18322. }
  18323. protected:
  18324. void onTrace(const void *row)
  18325. {
  18326. if (keepLimit && helper.isValid(row))
  18327. {
  18328. if (skip)
  18329. skip--;
  18330. else if (sample)
  18331. sample--;
  18332. else
  18333. {
  18334. CommonXmlWriter xmlwrite(XWFnoindent);
  18335. meta.toXML((const byte *) row, xmlwrite);
  18336. CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
  18337. keepLimit--;
  18338. sample = helper.getSample();
  18339. if (sample)
  18340. sample--;
  18341. }
  18342. }
  18343. }
  18344. OwnedRoxieString name;
  18345. IHThorTraceArg &helper;
  18346. unsigned keepLimit;
  18347. unsigned skip;
  18348. unsigned sample;
  18349. bool traceEnabled;
  18350. };
  18351. class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
  18352. {
  18353. public:
  18354. CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18355. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18356. {
  18357. }
  18358. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18359. {
  18360. return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
  18361. }
  18362. };
  18363. IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18364. {
  18365. return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18366. }
  18367. //=================================================================================
  18368. class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
  18369. {
  18370. IHThorCaseArg &helper;
  18371. unsigned cond;
  18372. bool unusedStopped;
  18373. IEngineRowStream *active;
  18374. public:
  18375. CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
  18376. : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
  18377. {
  18378. unusedStopped = false;
  18379. cond = 0;
  18380. active = NULL;
  18381. }
  18382. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18383. {
  18384. CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
  18385. cond = helper.getBranch();
  18386. //CHOOSE defaults to the last argument if out of range.
  18387. if (cond >= numInputs)
  18388. cond = numInputs - 1;
  18389. inputArray[cond]->start(parentExtractSize, parentExtract, paused);
  18390. startJunction(junctionArray[cond]);
  18391. assertex(numInputs==numStreams);
  18392. for (unsigned idx = 0; idx < numStreams; idx++)
  18393. {
  18394. if (idx!=cond)
  18395. streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18396. }
  18397. active = streamArray[cond];
  18398. unusedStopped = true;
  18399. }
  18400. virtual void stop()
  18401. {
  18402. for (unsigned idx = 0; idx < numStreams; idx++)
  18403. {
  18404. if (idx==cond || !unusedStopped)
  18405. streamArray[idx]->stop();
  18406. }
  18407. CRoxieServerMultiInputBaseActivity::stop();
  18408. }
  18409. virtual void reset()
  18410. {
  18411. unusedStopped = false;
  18412. active = NULL;
  18413. CRoxieServerMultiInputBaseActivity::reset();
  18414. }
  18415. virtual const void *nextRow()
  18416. {
  18417. ActivityTimer t(totalCycles, timeActivities);
  18418. if (active)
  18419. {
  18420. const void *ret = active->nextRow();
  18421. if (ret)
  18422. processed++;
  18423. return ret;
  18424. }
  18425. return NULL;
  18426. }
  18427. };
  18428. class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
  18429. {
  18430. bool graphInvariant;
  18431. public:
  18432. CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18433. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18434. {
  18435. graphInvariant = _graphInvariant;
  18436. }
  18437. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18438. {
  18439. return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
  18440. }
  18441. virtual bool isGraphInvariant() const
  18442. {
  18443. return graphInvariant;
  18444. }
  18445. };
  18446. IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18447. {
  18448. return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18449. }
  18450. //=================================================================================
  18451. class CRoxieServerIfActivity : public CRoxieServerActivity
  18452. {
  18453. IHThorIfArg &helper;
  18454. IFinalRoxieInput *inputTrue;
  18455. IFinalRoxieInput *inputFalse;
  18456. IEngineRowStream *streamTrue;
  18457. IEngineRowStream *streamFalse;
  18458. unsigned sourceIdxFalse = 0;
  18459. unsigned sourceIdxTrue = 0;
  18460. Owned<IStrandJunction> junctionTrue;
  18461. Owned<IStrandJunction> junctionFalse;
  18462. bool cond;
  18463. bool unusedStopped;
  18464. public:
  18465. CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18466. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18467. {
  18468. inputFalse = NULL;
  18469. inputTrue = NULL;
  18470. streamTrue = NULL;
  18471. streamFalse = NULL;
  18472. unusedStopped = false;
  18473. cond = false;
  18474. }
  18475. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18476. {
  18477. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18478. cond = helper.getCondition();
  18479. if (cond)
  18480. {
  18481. if (inputTrue)
  18482. {
  18483. inputTrue->start(parentExtractSize, parentExtract, paused);
  18484. startJunction(junctionTrue);
  18485. }
  18486. if (streamFalse)
  18487. streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
  18488. }
  18489. else
  18490. {
  18491. if (inputFalse)
  18492. {
  18493. inputFalse->start(parentExtractSize, parentExtract, paused);
  18494. startJunction(junctionFalse);
  18495. }
  18496. if (streamTrue)
  18497. streamTrue->stop();
  18498. }
  18499. unusedStopped = true;
  18500. }
  18501. virtual void stop()
  18502. {
  18503. if (streamTrue && (!unusedStopped || cond))
  18504. streamTrue->stop();
  18505. if (streamFalse && (!unusedStopped || !cond))
  18506. streamFalse->stop();
  18507. CRoxieServerActivity::stop();
  18508. }
  18509. virtual unsigned __int64 queryLocalCycles() const
  18510. {
  18511. __int64 localCycles = totalCycles.totalCycles;
  18512. if (inputTrue) // if conditional input cannot assume inputTrue
  18513. localCycles -= inputTrue->queryTotalCycles();
  18514. if (inputFalse)
  18515. localCycles -= inputFalse->queryTotalCycles();
  18516. if (localCycles < 0)
  18517. localCycles = 0;
  18518. return localCycles;
  18519. }
  18520. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18521. {
  18522. switch (idx)
  18523. {
  18524. case 0:
  18525. return inputTrue;
  18526. case 1:
  18527. return inputFalse;
  18528. default:
  18529. return NULL;
  18530. }
  18531. }
  18532. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
  18533. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
  18534. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  18535. {
  18536. IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
  18537. if (in)
  18538. return in->queryIndexReadActivity();
  18539. return NULL;
  18540. }
  18541. virtual void reset()
  18542. {
  18543. CRoxieServerActivity::reset();
  18544. if (inputTrue)
  18545. inputTrue->reset();
  18546. if (inputFalse)
  18547. inputFalse->reset();
  18548. resetJunction(junctionTrue);
  18549. resetJunction(junctionFalse);
  18550. unusedStopped = false;
  18551. }
  18552. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  18553. {
  18554. if (idx==1)
  18555. {
  18556. inputFalse = _in;
  18557. sourceIdxFalse = _sourceIdx;
  18558. }
  18559. else
  18560. {
  18561. assertex(!idx);
  18562. inputTrue = _in;
  18563. sourceIdxTrue = _sourceIdx;
  18564. }
  18565. }
  18566. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  18567. {
  18568. //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
  18569. streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
  18570. streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
  18571. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
  18572. }
  18573. virtual const void *nextRow()
  18574. {
  18575. ActivityTimer t(totalCycles, timeActivities);
  18576. IEngineRowStream *in = cond ? streamTrue : streamFalse;
  18577. if (in)
  18578. {
  18579. const void * ret;
  18580. if ((ret = in->nextRow()) != NULL)
  18581. processed++;
  18582. return ret;
  18583. }
  18584. return NULL;
  18585. }
  18586. };
  18587. class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
  18588. {
  18589. unsigned input2;
  18590. unsigned input2idx;
  18591. bool graphInvariant;
  18592. public:
  18593. CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18594. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18595. {
  18596. graphInvariant = _graphInvariant;
  18597. input2 = (unsigned)-1;
  18598. input2idx = (unsigned)-1;
  18599. }
  18600. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18601. {
  18602. return new CRoxieServerIfActivity(_ctx, this, _probeManager);
  18603. }
  18604. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  18605. {
  18606. if (idx==1)
  18607. {
  18608. input2 = source;
  18609. input2idx = sourceidx;
  18610. }
  18611. else
  18612. CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
  18613. }
  18614. virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
  18615. {
  18616. switch (idx)
  18617. {
  18618. case 1:
  18619. sourceidx = input2idx;
  18620. return input2;
  18621. case 0:
  18622. return CRoxieServerActivityFactory::getInput(idx, sourceidx);
  18623. default:
  18624. return (unsigned) -1;
  18625. }
  18626. }
  18627. virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
  18628. virtual bool isGraphInvariant() const
  18629. {
  18630. return graphInvariant;
  18631. }
  18632. };
  18633. IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
  18634. {
  18635. return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
  18636. }
  18637. //=================================================================================
  18638. class CRoxieServerActionBaseActivity : public CRoxieServerActivity
  18639. {
  18640. CriticalSection ecrit;
  18641. Owned<IException> exception;
  18642. bool executed;
  18643. public:
  18644. CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18645. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18646. {
  18647. executed = false;
  18648. }
  18649. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
  18650. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  18651. {
  18652. CriticalBlock b(ecrit);
  18653. if (exception)
  18654. throw(exception.getLink());
  18655. if (!executed)
  18656. {
  18657. try
  18658. {
  18659. executed = true;
  18660. start(parentExtractSize, parentExtract, false);
  18661. doExecuteAction(parentExtractSize, parentExtract);
  18662. stop();
  18663. }
  18664. catch (IException * E)
  18665. {
  18666. ctx->notifyAbort(E);
  18667. abort();
  18668. exception.set(E);
  18669. throw;
  18670. }
  18671. }
  18672. }
  18673. virtual void reset()
  18674. {
  18675. executed = false;
  18676. exception.clear();
  18677. CRoxieServerActivity::reset();
  18678. }
  18679. virtual const void *nextRow()
  18680. {
  18681. throwUnexpected(); // I am nobody's input
  18682. }
  18683. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  18684. {
  18685. return NULL;
  18686. }
  18687. };
  18688. class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
  18689. {
  18690. IHThorIfArg &helper;
  18691. public:
  18692. CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18693. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
  18694. {
  18695. }
  18696. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18697. {
  18698. bool cond;
  18699. {
  18700. ActivityTimer t(totalCycles, timeActivities);
  18701. cond = helper.getCondition();
  18702. }
  18703. stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
  18704. executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
  18705. }
  18706. };
  18707. class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
  18708. {
  18709. bool isRoot;
  18710. public:
  18711. CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18712. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18713. {
  18714. }
  18715. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18716. {
  18717. return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
  18718. }
  18719. virtual bool isSink() const
  18720. {
  18721. return isRoot;
  18722. }
  18723. };
  18724. IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18725. {
  18726. return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18727. }
  18728. //=================================================================================
  18729. class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
  18730. {
  18731. public:
  18732. CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18733. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18734. {
  18735. }
  18736. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18737. {
  18738. #ifdef PARALLEL_EXECUTE
  18739. CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
  18740. afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
  18741. #else
  18742. ForEachItemIn(idx, dependencies)
  18743. {
  18744. dependencies.item(idx).execute(parentExtractSize, parentExtract);
  18745. }
  18746. #endif
  18747. }
  18748. };
  18749. class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
  18750. {
  18751. bool isRoot;
  18752. public:
  18753. CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18754. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18755. {
  18756. assertex(!isRoot); // non-internal should be expanded out..
  18757. }
  18758. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18759. {
  18760. return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
  18761. }
  18762. virtual bool isSink() const
  18763. {
  18764. return isRoot;
  18765. }
  18766. };
  18767. IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18768. {
  18769. return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18770. }
  18771. //=================================================================================
  18772. class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
  18773. {
  18774. IHThorSequentialArg &helper;
  18775. public:
  18776. CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18777. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
  18778. {
  18779. }
  18780. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18781. {
  18782. unsigned numBranches = helper.numBranches();
  18783. for (unsigned branch=1; branch <= numBranches; branch++)
  18784. executeDependencies(parentExtractSize, parentExtract, branch);
  18785. }
  18786. };
  18787. class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
  18788. {
  18789. bool isRoot;
  18790. public:
  18791. CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18792. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18793. {
  18794. }
  18795. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18796. {
  18797. return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
  18798. }
  18799. virtual bool isSink() const
  18800. {
  18801. return isRoot;
  18802. }
  18803. };
  18804. IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18805. {
  18806. return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18807. }
  18808. //=================================================================================
  18809. class CRoxieServerWhenActivity : public CRoxieServerActivity
  18810. {
  18811. public:
  18812. CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18813. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  18814. {
  18815. savedExtractSize = 0;
  18816. savedExtract = NULL;
  18817. eofseen = false;
  18818. eogseen = false;
  18819. }
  18820. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18821. {
  18822. savedExtractSize = parentExtractSize;
  18823. savedExtract = parentExtract;
  18824. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  18825. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18826. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18827. eofseen = false;
  18828. eogseen = false;
  18829. }
  18830. virtual void stop()
  18831. {
  18832. if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
  18833. {
  18834. stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
  18835. stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
  18836. }
  18837. else if (state != STATEstopped)
  18838. {
  18839. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
  18840. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
  18841. }
  18842. CRoxieServerActivity::stop();
  18843. }
  18844. virtual const void *nextRow()
  18845. {
  18846. try
  18847. {
  18848. ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
  18849. const void *ret = inputStream->nextRow();
  18850. if (!ret)
  18851. {
  18852. if (eogseen)
  18853. eofseen = true;
  18854. else
  18855. eogseen = true;
  18856. }
  18857. else
  18858. eogseen = false;
  18859. return ret;
  18860. }
  18861. catch (...)
  18862. {
  18863. aborted = true;
  18864. throw;
  18865. }
  18866. }
  18867. protected:
  18868. const byte *savedExtract;
  18869. unsigned savedExtractSize;
  18870. bool eofseen;
  18871. bool eogseen;
  18872. };
  18873. class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
  18874. {
  18875. public:
  18876. CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18877. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  18878. {
  18879. }
  18880. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18881. {
  18882. return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
  18883. }
  18884. };
  18885. extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  18886. {
  18887. return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  18888. }
  18889. //=================================================================================
  18890. class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
  18891. {
  18892. public:
  18893. CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  18894. : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
  18895. {
  18896. savedExtractSize = 0;
  18897. savedExtract = NULL;
  18898. }
  18899. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  18900. {
  18901. savedExtractSize = parentExtractSize;
  18902. savedExtract = parentExtract;
  18903. CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
  18904. executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
  18905. executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
  18906. }
  18907. virtual void stop()
  18908. {
  18909. if (state != STATEstopped)
  18910. {
  18911. stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
  18912. executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
  18913. }
  18914. CRoxieServerActionBaseActivity::stop();
  18915. }
  18916. virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
  18917. {
  18918. executeDependencies(parentExtractSize, parentExtract, 1);
  18919. }
  18920. protected:
  18921. unsigned savedExtractSize;
  18922. const byte *savedExtract;
  18923. };
  18924. class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
  18925. {
  18926. public:
  18927. CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18928. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  18929. {
  18930. }
  18931. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  18932. {
  18933. return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
  18934. }
  18935. virtual bool isSink() const
  18936. {
  18937. return isRoot;
  18938. }
  18939. private:
  18940. bool isRoot;
  18941. };
  18942. extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  18943. {
  18944. return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  18945. }
  18946. //=================================================================================
  18947. class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
  18948. {
  18949. INlpParseAlgorithm * algorithm;
  18950. class ParseProcessor : public StrandProcessor, implements IMatchedAction
  18951. {
  18952. protected:
  18953. IHThorParseArg &helper;
  18954. INlpParser * parser;
  18955. INlpResultIterator * rowIter;
  18956. const void * in;
  18957. char * curSearchText;
  18958. size32_t curSearchTextLen;
  18959. bool processRecord(const void * inRec)
  18960. {
  18961. if (helper.searchTextNeedsFree())
  18962. rtlFree(curSearchText);
  18963. curSearchTextLen = 0;
  18964. curSearchText = NULL;
  18965. helper.getSearchText(curSearchTextLen, curSearchText, inRec);
  18966. return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
  18967. }
  18968. public:
  18969. ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
  18970. : StrandProcessor(_parent, _inputStream, false), helper(_helper)
  18971. {
  18972. parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
  18973. rowIter = parser->queryResultIter();
  18974. in = NULL;
  18975. curSearchText = NULL;
  18976. curSearchTextLen = 0;
  18977. }
  18978. ~ParseProcessor()
  18979. {
  18980. ::Release(parser);
  18981. }
  18982. virtual void start()
  18983. {
  18984. StrandProcessor::start();
  18985. numProcessedLastGroup = 0;
  18986. curSearchTextLen = 0;
  18987. curSearchText = NULL;
  18988. in = NULL;
  18989. parser->reset();
  18990. }
  18991. virtual void reset()
  18992. {
  18993. if (helper.searchTextNeedsFree())
  18994. rtlFree(curSearchText);
  18995. curSearchText = NULL;
  18996. ReleaseClearRoxieRow(in);
  18997. StrandProcessor::reset();
  18998. }
  18999. virtual const void * nextRow()
  19000. {
  19001. ActivityTimer t(totalCycles, timeActivities);
  19002. for (;;)
  19003. {
  19004. if (rowIter->isValid())
  19005. {
  19006. OwnedConstRoxieRow out = rowIter->getRow();
  19007. rowIter->next();
  19008. processed++;
  19009. return out.getClear();
  19010. }
  19011. ReleaseClearRoxieRow(in);
  19012. in = inputStream->nextRow();
  19013. if (!in)
  19014. {
  19015. if (processed == numProcessedLastGroup)
  19016. in = inputStream->nextRow();
  19017. if (!in)
  19018. {
  19019. processed = numProcessedLastGroup;
  19020. return NULL;
  19021. }
  19022. in = inputStream->nextRow();
  19023. if (!in)
  19024. return NULL;
  19025. }
  19026. processRecord(in);
  19027. rowIter->first();
  19028. }
  19029. }
  19030. virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
  19031. {
  19032. try
  19033. {
  19034. return helper.transform(self, curRecord, results, walker);
  19035. }
  19036. catch (IException *E)
  19037. {
  19038. throw parent.makeWrappedException(E);
  19039. }
  19040. }
  19041. };
  19042. public:
  19043. CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
  19044. : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
  19045. {
  19046. }
  19047. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19048. {
  19049. CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
  19050. onStartStrands();
  19051. }
  19052. virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
  19053. {
  19054. return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
  19055. }
  19056. virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
  19057. };
  19058. class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
  19059. {
  19060. Owned<INlpParseAlgorithm> algorithm;
  19061. Owned<IHThorParseArg> helper;
  19062. StrandOptions strandOptions;
  19063. public:
  19064. CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19065. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
  19066. {
  19067. helper.setown((IHThorParseArg *) helperFactory());
  19068. algorithm.setown(createThorParser(rc, *helper));
  19069. optStableInput = false;
  19070. }
  19071. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19072. {
  19073. return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
  19074. }
  19075. };
  19076. IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
  19077. {
  19078. return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
  19079. }
  19080. //=====================================================================================================
  19081. class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
  19082. {
  19083. IHThorWorkUnitWriteArg &helper;
  19084. bool isReread;
  19085. bool grouped;
  19086. IRoxieServerContext *serverContext;
  19087. int sequence;
  19088. public:
  19089. CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
  19090. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
  19091. {
  19092. grouped = (helper.getFlags() & POFgrouped) != 0;
  19093. serverContext = ctx->queryServerContext();
  19094. if (!serverContext)
  19095. {
  19096. throw MakeStringException(ROXIE_PIPE_ERROR, "Workunit output activity cannot be executed in slave context");
  19097. }
  19098. sequence = helper.getSequence();
  19099. if (sequence >= LibraryBaseSequence)
  19100. {
  19101. IConstWorkUnit *workunit = serverContext->queryQueryFactory()->queryWorkUnit();
  19102. assertex(workunit);
  19103. const char *storedName = helper.queryName();
  19104. assertex(storedName);
  19105. Owned<IConstWUResult> queryRes = workunit->getQueryResultByName(storedName);
  19106. if (!queryRes)
  19107. throw makeStringExceptionV(0, "Library cannot write to result %s that does not exist in calling query", storedName);
  19108. Owned<IConstWUResult> libraryRes = factory->queryQueryFactory().queryWorkUnit()->getResultBySequence(sequence);
  19109. if (libraryRes) // Should always be present, but rather than assert, just ignore if not
  19110. {
  19111. SCMStringBuffer queryFormat;
  19112. SCMStringBuffer libraryFormat;
  19113. queryRes->getResultEclSchema(queryFormat);
  19114. libraryRes->getResultEclSchema(libraryFormat);
  19115. if (!streq(queryFormat.str(), libraryFormat.str()))
  19116. {
  19117. DBGLOG("Query format: %s", queryFormat.str());
  19118. DBGLOG("Library format: %s", libraryFormat.str());
  19119. throw makeStringExceptionV(0, "Library cannot write to result %s: result type in query does not match", storedName);
  19120. }
  19121. }
  19122. sequence = queryRes->getResultSequence();
  19123. }
  19124. }
  19125. virtual bool needsAllocator() const { return true; }
  19126. virtual void onExecute()
  19127. {
  19128. MemoryBuffer result;
  19129. bool saveInContext = (int) sequence < 0 || isReread;
  19130. if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
  19131. meta.set(input->queryOutputMeta());
  19132. Owned<IOutputRowSerializer> rowSerializer;
  19133. Owned<IXmlWriter> xmlwriter;
  19134. bool appendRaw = false;
  19135. IHpccProtocolResultsWriter *results = NULL;
  19136. IHpccNativeProtocolResultsWriter *nativeResults = NULL;
  19137. IHpccProtocolResponse *protocol = serverContext->queryProtocol();
  19138. unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
  19139. if ((int) sequence >= 0)
  19140. {
  19141. results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
  19142. if (results)
  19143. {
  19144. nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
  19145. xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
  19146. }
  19147. }
  19148. size32_t outputLimitBytes = 0;
  19149. IConstWorkUnit *workunit = serverContext->queryWorkUnit();
  19150. if (workunit)
  19151. {
  19152. size32_t outputLimit;
  19153. if (helper.getFlags() & POFmaxsize)
  19154. outputLimit = helper.getMaxSize();
  19155. else
  19156. {
  19157. // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
  19158. outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
  19159. }
  19160. if (outputLimit>defaultDaliResultOutputMax)
  19161. 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);
  19162. assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
  19163. outputLimitBytes = outputLimit * 0x100000;
  19164. }
  19165. if (workunit != NULL || (results && (protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW)))
  19166. {
  19167. ensureRowAllocator();
  19168. rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
  19169. }
  19170. __int64 initialProcessed = processed;
  19171. RtlLinkedDatasetBuilder builder(rowAllocator);
  19172. for (;;)
  19173. {
  19174. const void *row = inputStream->nextRow();
  19175. if (saveInContext)
  19176. {
  19177. if (row || grouped)
  19178. builder.append(row);
  19179. }
  19180. if (grouped && (processed != initialProcessed))
  19181. {
  19182. if (workunit)
  19183. result.append(row == NULL);
  19184. if (results)
  19185. {
  19186. if ((protocolFlags & HPCC_PROTOCOL_NATIVE_RAW) && nativeResults)
  19187. {
  19188. char val = (char)(row == NULL);
  19189. nativeResults->appendRaw(sequence, 1, &val);
  19190. }
  19191. else if (xmlwriter)
  19192. {
  19193. xmlwriter->outputBeginNested("Row", false);
  19194. xmlwriter->outputCString("1", "@__GroupBreak__");
  19195. xmlwriter->outputEndNested("Row");
  19196. }
  19197. }
  19198. }
  19199. if (!row)
  19200. {
  19201. row = inputStream->nextRow();
  19202. if (!row)
  19203. break;
  19204. if (saveInContext)
  19205. builder.append(row);
  19206. }
  19207. processed++;
  19208. if (workunit)
  19209. {
  19210. CThorDemoRowSerializer serializerTarget(result);
  19211. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19212. }
  19213. if ((int) sequence >= 0)
  19214. {
  19215. if (appendRaw && nativeResults)
  19216. {
  19217. // MORE - should be able to serialize straight to the response...
  19218. MemoryBuffer rowbuff;
  19219. CThorDemoRowSerializer serializerTarget(rowbuff);
  19220. rowSerializer->serialize(serializerTarget, (const byte *) row);
  19221. nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
  19222. }
  19223. else if (xmlwriter)
  19224. {
  19225. xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
  19226. helper.serializeXml((byte *) row, *xmlwriter);
  19227. xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
  19228. results->finalizeXmlRow(sequence);
  19229. }
  19230. else if (nativeResults)
  19231. {
  19232. SimpleOutputWriter x;
  19233. helper.serializeXml((byte *) row, x);
  19234. x.newline();
  19235. nativeResults->appendSimpleRow(sequence, x.str());
  19236. }
  19237. }
  19238. ReleaseRoxieRow(row);
  19239. if (outputLimitBytes && result.length() > outputLimitBytes)
  19240. {
  19241. StringBuffer errMsg("Dataset too large to output to workunit (limit ");
  19242. errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
  19243. const char *name = helper.queryName();
  19244. if (name)
  19245. errMsg.append("name=").append(name);
  19246. else
  19247. errMsg.append("sequence=").append(helper.getSequence());
  19248. errMsg.append(")");
  19249. throw MakeStringExceptionDirect(0, errMsg.str());
  19250. }
  19251. }
  19252. if (xmlwriter)
  19253. xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
  19254. const char *storedName = helper.queryName();
  19255. if (!storedName)
  19256. storedName = "Dataset";
  19257. if (saveInContext)
  19258. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19259. if (workunit)
  19260. serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
  19261. }
  19262. };
  19263. class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
  19264. {
  19265. bool isReread;
  19266. public:
  19267. CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19268. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19269. {
  19270. isReread = usageCount > 0;
  19271. Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
  19272. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19273. }
  19274. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19275. {
  19276. return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
  19277. }
  19278. };
  19279. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19280. {
  19281. return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19282. }
  19283. //=====================================================================================================
  19284. class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
  19285. {
  19286. IHThorDictionaryWorkUnitWriteArg &helper;
  19287. IRoxieServerContext *serverContext;
  19288. public:
  19289. CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
  19290. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
  19291. {
  19292. serverContext = NULL;
  19293. }
  19294. virtual void onCreate(IHThorArg *_colocalParent)
  19295. {
  19296. CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
  19297. serverContext = ctx->queryServerContext();
  19298. if (!serverContext)
  19299. {
  19300. throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
  19301. }
  19302. }
  19303. virtual bool needsAllocator() const { return true; }
  19304. virtual void onExecute()
  19305. {
  19306. int sequence = helper.getSequence();
  19307. const char *storedName = helper.queryName();
  19308. assertex(storedName && *storedName);
  19309. assertex(sequence < 0);
  19310. RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
  19311. for (;;)
  19312. {
  19313. const void *row = inputStream->ungroupedNextRow();
  19314. if (!row)
  19315. break;
  19316. builder.appendOwn(row);
  19317. processed++;
  19318. }
  19319. serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
  19320. }
  19321. };
  19322. class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
  19323. {
  19324. public:
  19325. CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19326. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19327. {
  19328. Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
  19329. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19330. }
  19331. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19332. {
  19333. return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
  19334. }
  19335. };
  19336. IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19337. {
  19338. return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19339. }
  19340. //=================================================================================
  19341. class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
  19342. {
  19343. IHThorRemoteResultArg &helper;
  19344. public:
  19345. CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
  19346. : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
  19347. {
  19348. }
  19349. virtual void onExecute()
  19350. {
  19351. OwnedConstRoxieRow row = inputStream->nextRow();
  19352. helper.sendResult(row); // should be only one row or something has gone wrong!
  19353. }
  19354. };
  19355. class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
  19356. {
  19357. public:
  19358. CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19359. : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
  19360. {
  19361. Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
  19362. isInternal = (helper->getSequence()==ResultSequenceInternal);
  19363. }
  19364. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19365. {
  19366. return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
  19367. }
  19368. virtual bool isSink() const override
  19369. {
  19370. return CRoxieServerInternalSinkFactory::isSink() || dependentCount == 0; // Codegen normally optimizes these away, but if it doesn't we need to treat as a sink rather than a dependency or upstream activities are not stopped properly
  19371. }
  19372. };
  19373. IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
  19374. {
  19375. return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
  19376. }
  19377. //=================================================================================
  19378. class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
  19379. {
  19380. IHThorXmlParseArg &helper;
  19381. Owned<IXMLParse> xmlParser;
  19382. const void * in;
  19383. char * srchStr;
  19384. unsigned numProcessedLastGroup;
  19385. bool srchStrNeedsFree;
  19386. Owned<IColumnProvider> lastMatch;
  19387. public:
  19388. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19389. CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  19390. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19391. helper((IHThorXmlParseArg &)basehelper)
  19392. {
  19393. srchStrNeedsFree = helper.searchTextNeedsFree();
  19394. numProcessedLastGroup = 0;
  19395. srchStr = NULL;
  19396. in = NULL;
  19397. }
  19398. ~CRoxieServerXmlParseActivity()
  19399. {
  19400. }
  19401. virtual bool needsAllocator() const { return true; }
  19402. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19403. {
  19404. numProcessedLastGroup = 0;
  19405. srchStr = NULL;
  19406. in = NULL;
  19407. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19408. }
  19409. virtual void reset()
  19410. {
  19411. if (helper.searchTextNeedsFree())
  19412. rtlFree(srchStr);
  19413. srchStr = NULL;
  19414. ReleaseClearRoxieRow(in);
  19415. xmlParser.clear();
  19416. CRoxieServerActivity::reset();
  19417. }
  19418. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19419. {
  19420. lastMatch.set(&entry);
  19421. }
  19422. virtual const void *nextRow()
  19423. {
  19424. ActivityTimer t(totalCycles, timeActivities);
  19425. for (;;)
  19426. {
  19427. if(xmlParser)
  19428. {
  19429. for (;;)
  19430. {
  19431. if(!xmlParser->next())
  19432. {
  19433. if (srchStrNeedsFree)
  19434. {
  19435. rtlFree(srchStr);
  19436. srchStr = NULL;
  19437. }
  19438. xmlParser.clear();
  19439. break;
  19440. }
  19441. if(lastMatch)
  19442. {
  19443. try
  19444. {
  19445. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19446. size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
  19447. lastMatch.clear();
  19448. if (outSize)
  19449. {
  19450. processed++;
  19451. return rowBuilder.finalizeRowClear(outSize);
  19452. }
  19453. }
  19454. catch (IException *E)
  19455. {
  19456. throw makeWrappedException(E);
  19457. }
  19458. }
  19459. }
  19460. }
  19461. ReleaseClearRoxieRow(in);
  19462. in = inputStream->nextRow();
  19463. if(!in)
  19464. {
  19465. if(numProcessedLastGroup == processed)
  19466. in = inputStream->nextRow();
  19467. if(!in)
  19468. {
  19469. numProcessedLastGroup = processed;
  19470. return NULL;
  19471. }
  19472. }
  19473. size32_t srchLen;
  19474. helper.getSearchText(srchLen, srchStr, in);
  19475. OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
  19476. xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
  19477. }
  19478. }
  19479. };
  19480. class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
  19481. {
  19482. public:
  19483. CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19484. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  19485. {
  19486. }
  19487. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  19488. {
  19489. return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
  19490. }
  19491. };
  19492. IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  19493. {
  19494. return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  19495. }
  19496. //=====================================================================================================
  19497. class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
  19498. {
  19499. protected:
  19500. IHThorDiskReadBaseArg &helper;
  19501. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  19502. IHThorCompoundExtra * compoundHelper;
  19503. RemoteActivityId remoteId; // Note we copy it rather than reference
  19504. Owned<CSkippableRemoteResultAdaptor> remote;
  19505. unsigned numParts;
  19506. unsigned __int64 rowLimit;
  19507. unsigned __int64 stopAfter;
  19508. Linked<IInMemoryIndexManager> manager;
  19509. Linked<ITranslatorSet> translators;
  19510. ScoredRowFilter postFilter;
  19511. Owned<IDirectReader> reader;
  19512. bool eof;
  19513. bool variableFileName;
  19514. bool isOpt;
  19515. bool sorted;
  19516. bool maySkip;
  19517. bool isLocal;
  19518. bool forceRemote;
  19519. bool isGrouped = false;
  19520. CachedOutputMetaData diskSize;
  19521. Owned<const IResolvedFile> varFileInfo;
  19522. inline bool useRemote()
  19523. {
  19524. return remote != NULL && (forceRemote || numParts > 1);
  19525. }
  19526. public:
  19527. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  19528. CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19529. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19530. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  19531. helper((IHThorDiskReadBaseArg &)basehelper),
  19532. remoteId(_remoteId),
  19533. numParts(_numParts),
  19534. manager(_manager),
  19535. translators(_translators),
  19536. sorted(_sorted),
  19537. maySkip(_maySkip),
  19538. isLocal(_isLocal)
  19539. {
  19540. forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
  19541. if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
  19542. remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
  19543. compoundHelper = NULL;
  19544. eof = false;
  19545. rowLimit = (unsigned __int64) -1;
  19546. stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
  19547. diskSize.set(helper.queryDiskRecordSize()->querySerializedDiskMeta());
  19548. isGrouped = diskSize.isGrouped();
  19549. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  19550. isOpt = (helper.getFlags() & TDRoptional) != 0;
  19551. }
  19552. virtual const IResolvedFile *queryVarFileInfo() const
  19553. {
  19554. return varFileInfo;
  19555. }
  19556. virtual void onCreate(IHThorArg *_colocalParent)
  19557. {
  19558. CRoxieServerActivity::onCreate(_colocalParent);
  19559. if (remote)
  19560. remote->onCreate(_colocalParent);
  19561. }
  19562. virtual bool needsAllocator() const { return true; }
  19563. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19564. {
  19565. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  19566. if (compoundHelper)
  19567. {
  19568. rowLimit = compoundHelper->getRowLimit();
  19569. stopAfter = compoundHelper->getChooseNLimit();
  19570. }
  19571. if (!helper.canMatchAny())
  19572. eof = true;
  19573. else
  19574. {
  19575. if (variableFileName)
  19576. {
  19577. OwnedRoxieString fileName(helper.getFileName());
  19578. varFileInfo.setown(resolveLFNFlat(fileName, isOpt));
  19579. numParts = 0;
  19580. if (varFileInfo)
  19581. numParts = varFileInfo->getNumParts();
  19582. }
  19583. if (!numParts)
  19584. {
  19585. eof = true;
  19586. }
  19587. else if (useRemote())
  19588. {
  19589. remote->onStart(parentExtractSize, parentExtract);
  19590. remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
  19591. unsigned fileNo = 0;
  19592. // Translation into a message per channel done elsewhere....
  19593. remote->getMem(0, fileNo, 0);
  19594. remote->flush();
  19595. remote->senddone();
  19596. }
  19597. else
  19598. {
  19599. if (variableFileName)
  19600. {
  19601. unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
  19602. unsigned expectedFormatCrc = helper.getDiskFormatCrc();
  19603. unsigned projectedFormatCrc = helper.getProjectedFormatCrc();
  19604. translators.setown(varFileInfo->getTranslators(projectedFormatCrc, helper.queryProjectedDiskRecordSize(), expectedFormatCrc, helper.queryDiskRecordSize(), getEnableFieldTranslation(), false));
  19605. manager.setown(varFileInfo->getIndexManager(isOpt, channel, translators->queryActualLayout(0), false));
  19606. }
  19607. assertex(manager != NULL);
  19608. postFilter.clear();
  19609. helper.createSegmentMonitors(this);
  19610. const IKeyTranslator *keyTranslator = translators->queryKeyTranslator(0); // any part would do - in-memory requires all actuals to have same layout
  19611. if (keyTranslator)
  19612. keyTranslator->translate(postFilter);
  19613. reader.setown(manager->selectKey(postFilter, translators, *this));
  19614. if (!reader)
  19615. reader.setown(manager->createReader(postFilter, isGrouped, 0, 0, 1, translators));
  19616. assertex(reader);
  19617. helper.setCallback(reader);
  19618. }
  19619. }
  19620. }
  19621. virtual void append(IKeySegmentMonitor *segment)
  19622. {
  19623. segment->Release();
  19624. throwUnexpected();
  19625. }
  19626. virtual void append(FFoption option, const IFieldFilter * filter)
  19627. {
  19628. if (filter->isWild())
  19629. filter->Release();
  19630. else
  19631. postFilter.addFilter(*filter);
  19632. }
  19633. virtual void stop()
  19634. {
  19635. if (useRemote())
  19636. remote->onStop();
  19637. CRoxieServerActivity::stop();
  19638. }
  19639. virtual void reset()
  19640. {
  19641. if (useRemote())
  19642. {
  19643. processed = remote->processed;
  19644. remote->processed = 0;
  19645. remote->onReset();
  19646. }
  19647. varFileInfo.clear();
  19648. eof = false;
  19649. reader.clear();
  19650. CRoxieServerActivity::reset();
  19651. }
  19652. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  19653. {
  19654. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  19655. }
  19656. virtual void onLimitExceeded(bool isKeyed)
  19657. {
  19658. if (traceLevel > 4)
  19659. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  19660. assertex(compoundHelper);
  19661. if (isKeyed) // MORE does this exist for diskread? should it?
  19662. {
  19663. if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
  19664. {
  19665. if (ctx->queryDebugContext())
  19666. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19667. throw makeLimitSkipException(true);
  19668. }
  19669. else
  19670. {
  19671. UNIMPLEMENTED;
  19672. //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
  19673. }
  19674. }
  19675. else
  19676. {
  19677. if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
  19678. {
  19679. if (ctx->queryDebugContext())
  19680. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19681. throw makeLimitSkipException(false);
  19682. }
  19683. else
  19684. compoundHelper->onLimitExceeded();
  19685. }
  19686. }
  19687. virtual const void * createLimitFailRow(bool isKeyed)
  19688. {
  19689. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19690. assertex(limitTransformExtra);
  19691. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  19692. if (outSize)
  19693. return rowBuilder.finalizeRowClear(outSize);
  19694. return NULL;
  19695. }
  19696. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  19697. {
  19698. CRoxieServerActivity::gatherStats(merged);
  19699. if (remote)
  19700. remote->gatherStats(merged);
  19701. }
  19702. };
  19703. class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
  19704. {
  19705. IHThorDiskReadArg * readHelper;
  19706. ConstPointerArray readrows;
  19707. bool readAheadDone;
  19708. unsigned readIndex;
  19709. unsigned lastGroupProcessed;
  19710. bool someInGroup = false;
  19711. public:
  19712. CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19713. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19714. {
  19715. compoundHelper = (IHThorDiskReadArg *)&helper;
  19716. readHelper = (IHThorDiskReadArg *)&helper;
  19717. limitTransformExtra = readHelper;
  19718. readAheadDone = false;
  19719. readIndex = 0;
  19720. lastGroupProcessed = processed;
  19721. }
  19722. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19723. {
  19724. rowLimit = compoundHelper->getRowLimit();
  19725. stopAfter = compoundHelper->getChooseNLimit();
  19726. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19727. readAheadDone = false;
  19728. readIndex = 0;
  19729. lastGroupProcessed = processed;
  19730. someInGroup = false;
  19731. }
  19732. virtual void reset()
  19733. {
  19734. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19735. readrows.kill();
  19736. readAheadDone = false;
  19737. readIndex = 0;
  19738. lastGroupProcessed = processed;
  19739. someInGroup = false;
  19740. CRoxieServerDiskReadBaseActivity::reset();
  19741. }
  19742. virtual const void *nextRow()
  19743. {
  19744. ActivityTimer t(totalCycles, timeActivities);
  19745. if (eof)
  19746. return NULL;
  19747. else if (useRemote())
  19748. return remote->nextRow();
  19749. else if (maySkip)
  19750. {
  19751. if (!readAheadDone)
  19752. {
  19753. unsigned preprocessed = 0;
  19754. while (!eof)
  19755. {
  19756. const void *row = _nextRow();
  19757. if (row)
  19758. preprocessed++;
  19759. if (preprocessed > rowLimit)
  19760. {
  19761. ReleaseRoxieRow(row);
  19762. roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
  19763. readrows.kill();
  19764. readIndex = 0;
  19765. eof = true;
  19766. if (ctx->queryDebugContext())
  19767. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  19768. if (helper.getFlags() & TDRlimitskips)
  19769. return NULL;
  19770. else if (helper.getFlags() & TDRlimitcreates)
  19771. return createLimitFailRow(false);
  19772. else
  19773. throwUnexpected();
  19774. }
  19775. if (preprocessed > stopAfter) // MORE - bit of a strange place to check
  19776. {
  19777. eof = true;
  19778. ReleaseRoxieRow(row);
  19779. break;
  19780. }
  19781. readrows.append(row);
  19782. }
  19783. readAheadDone = true;
  19784. }
  19785. if (readrows.isItem(readIndex))
  19786. {
  19787. const void *ret = readrows.item(readIndex++);
  19788. if (ret)
  19789. processed++;
  19790. return ret;
  19791. }
  19792. else
  19793. {
  19794. eof = true;
  19795. return NULL;
  19796. }
  19797. }
  19798. else
  19799. {
  19800. const void *ret = _nextRow();
  19801. if (ret)
  19802. {
  19803. processed++;
  19804. if (processed > rowLimit)
  19805. {
  19806. if (traceLevel > 4)
  19807. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19808. ReleaseRoxieRow(ret);
  19809. compoundHelper->onLimitExceeded();
  19810. throwUnexpected(); // onLimitExceeded is not supposed to return
  19811. }
  19812. if (processed > stopAfter) // MORE - bit of a strange place to check
  19813. {
  19814. eof = true;
  19815. ReleaseRoxieRow(ret);
  19816. return NULL;
  19817. }
  19818. }
  19819. return ret;
  19820. }
  19821. }
  19822. const void *_nextRow()
  19823. {
  19824. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19825. unsigned transformedSize = 0;
  19826. for (;;)
  19827. {
  19828. const byte *nextRec = reader->nextRow();
  19829. if (nextRec)
  19830. {
  19831. someInGroup = true;
  19832. if (likely(readHelper->canMatch(nextRec)))
  19833. {
  19834. transformedSize = readHelper->transform(rowBuilder, nextRec);
  19835. reader->finishedRow();
  19836. if (transformedSize)
  19837. break;
  19838. }
  19839. else
  19840. reader->finishedRow();
  19841. }
  19842. else if (isGrouped)
  19843. {
  19844. if (lastGroupProcessed != processed)
  19845. {
  19846. someInGroup = false;
  19847. lastGroupProcessed = processed;
  19848. return nullptr;
  19849. }
  19850. else if (!someInGroup)
  19851. {
  19852. eof = true;
  19853. return nullptr;
  19854. }
  19855. }
  19856. else
  19857. {
  19858. eof = true;
  19859. return nullptr;
  19860. }
  19861. }
  19862. return rowBuilder.finalizeRowClear(transformedSize);
  19863. }
  19864. };
  19865. class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
  19866. {
  19867. IHThorXmlReadArg * readHelper;
  19868. Owned<IXmlToRowTransformer> rowTransformer;
  19869. Owned<IXMLParse> xmlParser;
  19870. Owned<IColumnProvider> lastMatch;
  19871. unsigned __int64 fileoffset;
  19872. IDirectStreamReader *streamReader = nullptr;
  19873. public:
  19874. IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
  19875. CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19876. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  19877. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators)
  19878. {
  19879. compoundHelper = NULL;
  19880. readHelper = (IHThorXmlReadArg *)&helper;
  19881. fileoffset = 0;
  19882. }
  19883. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  19884. {
  19885. rowLimit = readHelper->getRowLimit();
  19886. stopAfter = readHelper->getChooseNLimit();
  19887. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  19888. if (!useRemote())
  19889. {
  19890. rowTransformer.set(readHelper->queryTransformer());
  19891. assertex(reader != NULL);
  19892. streamReader = reader->queryDirectStreamReader();
  19893. assertex(streamReader != NULL);
  19894. OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
  19895. if (factory->getKind()==TAKjsonread)
  19896. xmlParser.setown(createJSONParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19897. else
  19898. xmlParser.setown(createXMLParse(*streamReader, xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
  19899. }
  19900. }
  19901. virtual void reset()
  19902. {
  19903. CRoxieServerDiskReadBaseActivity::reset();
  19904. rowTransformer.clear();
  19905. xmlParser.clear();
  19906. }
  19907. virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
  19908. {
  19909. fileoffset = startOffset;
  19910. lastMatch.set(&entry);
  19911. }
  19912. //interface IThorDiskCallback
  19913. virtual unsigned __int64 getFilePosition(const void * row)
  19914. {
  19915. return fileoffset;
  19916. }
  19917. virtual unsigned __int64 getLocalFilePosition(const void * row)
  19918. {
  19919. return streamReader->makeFilePositionLocal(fileoffset);
  19920. }
  19921. virtual const char * queryLogicalFilename(const void * row)
  19922. {
  19923. return reader->queryLogicalFilename(row);
  19924. }
  19925. virtual const byte * lookupBlob(unsigned __int64 id) { UNIMPLEMENTED; }
  19926. virtual const void *nextRow()
  19927. {
  19928. ActivityTimer t(totalCycles, timeActivities);
  19929. if (eof)
  19930. return NULL;
  19931. else if (useRemote())
  19932. return remote->nextRow();
  19933. assertex(xmlParser != NULL);
  19934. try
  19935. {
  19936. while (!eof)
  19937. {
  19938. //call to next() will callback on the IXmlSelect interface
  19939. bool gotNext = false;
  19940. gotNext = xmlParser->next();
  19941. if(!gotNext)
  19942. eof = true;
  19943. else if (lastMatch)
  19944. {
  19945. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  19946. unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
  19947. lastMatch.clear();
  19948. fileoffset = 0;
  19949. if (sizeGot)
  19950. {
  19951. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
  19952. if (processed > rowLimit)
  19953. {
  19954. if (traceLevel > 4)
  19955. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  19956. readHelper->onLimitExceeded();
  19957. throwUnexpected(); // onLimitExceeded is not supposed to return
  19958. }
  19959. processed++;
  19960. if (processed > stopAfter) // MORE - bit of a strange place to check
  19961. {
  19962. eof = true;
  19963. return NULL;
  19964. }
  19965. return ret.getClear();
  19966. }
  19967. }
  19968. }
  19969. return NULL;
  19970. }
  19971. catch(IException *E)
  19972. {
  19973. throw makeWrappedException(E);
  19974. }
  19975. }
  19976. };
  19977. class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
  19978. {
  19979. IHThorCsvReadArg *readHelper;
  19980. ICsvParameters * csvInfo;
  19981. unsigned headerLines;
  19982. unsigned maxDiskSize;
  19983. CSVSplitter csvSplitter;
  19984. unsigned __int64 localOffset;
  19985. IDirectStreamReader *streamReader = nullptr;
  19986. const char *quotes;
  19987. const char *separators;
  19988. const char *terminators;
  19989. const char *escapes;
  19990. size32_t maxRowSize;
  19991. public:
  19992. CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  19993. unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager, ITranslatorSet *_translators,
  19994. const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
  19995. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager, _translators),
  19996. quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
  19997. {
  19998. compoundHelper = NULL;
  19999. readHelper = (IHThorCsvReadArg *)&helper;
  20000. rowLimit = readHelper->getRowLimit();
  20001. stopAfter = readHelper->getChooseNLimit();
  20002. csvInfo = readHelper->queryCsvParameters();
  20003. maxDiskSize = csvInfo->queryMaxSize();
  20004. localOffset = 0;
  20005. headerLines = 0;
  20006. }
  20007. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20008. {
  20009. rowLimit = readHelper->getRowLimit();
  20010. stopAfter = readHelper->getChooseNLimit();
  20011. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20012. if (!useRemote())
  20013. {
  20014. if (!eof)
  20015. {
  20016. assertex(reader != nullptr);
  20017. streamReader = reader->queryDirectStreamReader();
  20018. assertex(streamReader != nullptr);
  20019. headerLines = csvInfo->queryHeaderLen();
  20020. if (headerLines && isLocal && streamReader->queryFilePart() != 1)
  20021. 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...
  20022. if (varFileInfo)
  20023. {
  20024. const IPropertyTree *options = varFileInfo->queryProperties();
  20025. if (options)
  20026. {
  20027. quotes = options->queryProp("@csvQuote");
  20028. separators = options->queryProp("@csvSeparate");
  20029. terminators = options->queryProp("@csvTerminate");
  20030. escapes = options->queryProp("@csvEscape");
  20031. }
  20032. }
  20033. csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
  20034. }
  20035. }
  20036. }
  20037. virtual const void *nextRow()
  20038. {
  20039. ActivityTimer t(totalCycles, timeActivities);
  20040. if (eof)
  20041. return NULL;
  20042. else if (useRemote())
  20043. return remote->nextRow();
  20044. try
  20045. {
  20046. while (!eof)
  20047. {
  20048. size32_t thisLineLength = csvSplitter.splitLine(streamReader, maxRowSize);
  20049. if (!thisLineLength)
  20050. break;
  20051. if (headerLines)
  20052. {
  20053. headerLines--;
  20054. streamReader->skip(thisLineLength);
  20055. }
  20056. else
  20057. {
  20058. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20059. unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
  20060. streamReader->skip(thisLineLength);
  20061. if (transformedSize)
  20062. {
  20063. OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
  20064. if (processed > rowLimit)
  20065. {
  20066. readHelper->onLimitExceeded();
  20067. throwUnexpected(); // onLimitExceeded is not supposed to return
  20068. }
  20069. processed++;
  20070. if (processed > stopAfter) // MORE - bit of a strange place to check
  20071. {
  20072. eof = true;
  20073. return NULL;
  20074. }
  20075. return ret.getClear();
  20076. }
  20077. }
  20078. }
  20079. return NULL;
  20080. }
  20081. catch(IException *E)
  20082. {
  20083. throw makeWrappedException(E);
  20084. }
  20085. }
  20086. virtual void reset()
  20087. {
  20088. CRoxieServerDiskReadBaseActivity::reset();
  20089. csvSplitter.reset();
  20090. localOffset = 0;
  20091. }
  20092. virtual unsigned __int64 getFilePosition(const void * row)
  20093. {
  20094. UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
  20095. }
  20096. virtual unsigned __int64 getLocalFilePosition(const void * row)
  20097. {
  20098. UNIMPLEMENTED;
  20099. }
  20100. };
  20101. class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
  20102. {
  20103. IHThorDiskNormalizeArg *normalizeHelper;
  20104. bool firstPending;
  20105. public:
  20106. CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20107. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager, _translators)
  20108. {
  20109. compoundHelper = (IHThorDiskNormalizeArg *)&helper;
  20110. normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
  20111. limitTransformExtra = normalizeHelper;
  20112. firstPending = true;
  20113. }
  20114. virtual void reset()
  20115. {
  20116. firstPending = true;
  20117. CRoxieServerDiskReadBaseActivity::reset();
  20118. }
  20119. virtual const void *nextRow()
  20120. {
  20121. ActivityTimer t(totalCycles, timeActivities);
  20122. if (eof)
  20123. return NULL;
  20124. else if (useRemote())
  20125. return remote->nextRow();
  20126. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20127. unsigned transformedSize = 0;
  20128. for (;;)
  20129. {
  20130. while (firstPending)
  20131. {
  20132. const byte *nextRec = reader->nextRow();
  20133. if (!nextRec)
  20134. {
  20135. eof = true;
  20136. return NULL;
  20137. }
  20138. if (normalizeHelper->first(nextRec))
  20139. firstPending = false;
  20140. reader->finishedRow();
  20141. }
  20142. transformedSize = normalizeHelper->transform(rowBuilder);
  20143. firstPending = !normalizeHelper->next();
  20144. if (transformedSize)
  20145. break;
  20146. }
  20147. OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
  20148. processed++;
  20149. if (processed > rowLimit)
  20150. {
  20151. compoundHelper->onLimitExceeded();
  20152. throwUnexpected(); // onLimitExceeded is not supposed to return
  20153. }
  20154. if (processed > stopAfter) // MORE - bit of a strange place to check
  20155. {
  20156. eof = true;
  20157. return NULL;
  20158. }
  20159. return recBuffer.getClear();
  20160. }
  20161. };
  20162. class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
  20163. {
  20164. protected:
  20165. bool done;
  20166. public:
  20167. CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20168. : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager, _translators),
  20169. done(false)
  20170. {
  20171. }
  20172. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20173. {
  20174. done = false;
  20175. CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20176. }
  20177. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  20178. {
  20179. if (idx==(unsigned)-1)
  20180. idx = 0;
  20181. return idx ? NULL: this;
  20182. }
  20183. };
  20184. class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
  20185. {
  20186. IHThorDiskCountArg & countHelper;
  20187. unsigned __int64 choosenLimit;
  20188. unsigned __int64 getSkippedCount()
  20189. {
  20190. unsigned flags = countHelper.getFlags();
  20191. if (flags & TDRlimitskips)
  20192. return 0;
  20193. else if (flags & TDRlimitcreates)
  20194. return 1;
  20195. else
  20196. {
  20197. countHelper.onLimitExceeded();
  20198. throwUnexpected(); // onLimitExceeded should always throw exception
  20199. }
  20200. }
  20201. public:
  20202. CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20203. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20204. countHelper((IHThorDiskCountArg &)basehelper)
  20205. {
  20206. choosenLimit = 0;
  20207. }
  20208. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20209. {
  20210. choosenLimit = countHelper.getChooseNLimit();
  20211. rowLimit = countHelper.getRowLimit();
  20212. // keyedLimit = countHelper->getKeyedLimit(); // more - should there be one?
  20213. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20214. }
  20215. virtual const void *nextRow()
  20216. {
  20217. ActivityTimer t(totalCycles, timeActivities);
  20218. if (done) return NULL;
  20219. done = true;
  20220. unsigned __int64 totalCount = 0;
  20221. if (helper.canMatchAny() && !eof)
  20222. {
  20223. if (useRemote())
  20224. {
  20225. for (;;)
  20226. {
  20227. const void * next = remote->nextRow();
  20228. if (!next)
  20229. break;
  20230. if (meta.getFixedSize() == 1)
  20231. totalCount += *(byte *)next;
  20232. else
  20233. totalCount += *(unsigned __int64 *)next;
  20234. ReleaseRoxieRow(next);
  20235. if (totalCount > rowLimit)
  20236. {
  20237. totalCount = getSkippedCount();
  20238. break;
  20239. }
  20240. else if (totalCount >= choosenLimit)
  20241. {
  20242. totalCount = choosenLimit;
  20243. break;
  20244. }
  20245. }
  20246. }
  20247. else
  20248. {
  20249. for (;;)
  20250. {
  20251. const byte *nextRec = reader->nextRow();
  20252. if (!nextRec)
  20253. break;
  20254. totalCount += countHelper.numValid(nextRec);
  20255. reader->finishedRow();
  20256. if (totalCount > rowLimit)
  20257. {
  20258. totalCount = getSkippedCount();
  20259. break;
  20260. }
  20261. else if (totalCount >= choosenLimit)
  20262. {
  20263. totalCount = choosenLimit;
  20264. break;
  20265. }
  20266. }
  20267. }
  20268. }
  20269. processed++;
  20270. size32_t rowSize = meta.getFixedSize();
  20271. void * result = rowAllocator->createRow();
  20272. if (rowSize == 1)
  20273. *(byte *)result = (byte)totalCount;
  20274. else
  20275. {
  20276. assertex(rowSize == sizeof(unsigned __int64));
  20277. *(unsigned __int64 *)result = totalCount;
  20278. }
  20279. return rowAllocator->finalizeRow(rowSize, result, rowSize);
  20280. }
  20281. };
  20282. class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20283. {
  20284. IHThorCompoundAggregateExtra & aggregateHelper;
  20285. public:
  20286. CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20287. unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20288. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20289. aggregateHelper((IHThorDiskAggregateArg &)basehelper)
  20290. {
  20291. }
  20292. const void * gatherMerged()
  20293. {
  20294. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  20295. size32_t finalSize = 0;
  20296. if (useRemote())
  20297. {
  20298. const void * firstRow = remote->nextRow();
  20299. if (!firstRow)
  20300. {
  20301. rowBuilder.ensureRow();
  20302. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  20303. }
  20304. else
  20305. {
  20306. // NOTE need to clone this because going to modify below, could special case 1 row only
  20307. finalSize = cloneRow(rowBuilder, firstRow, meta);
  20308. ReleaseRoxieRow(firstRow);
  20309. }
  20310. for (;;)
  20311. {
  20312. const void * next = remote->nextRow();
  20313. if (!next)
  20314. break;
  20315. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  20316. ReleaseRoxieRow(next);
  20317. }
  20318. }
  20319. else
  20320. {
  20321. aggregateHelper.clearAggregate(rowBuilder);
  20322. if (helper.canMatchAny() && !eof)
  20323. {
  20324. for (;;)
  20325. {
  20326. const byte *nextRec = reader->nextRow();
  20327. if (!nextRec)
  20328. break;
  20329. aggregateHelper.processRow(rowBuilder, nextRec);
  20330. reader->finishedRow();
  20331. }
  20332. }
  20333. finalSize = meta.getRecordSize(rowBuilder.getSelf());
  20334. }
  20335. return rowBuilder.finalizeRowClear(finalSize);
  20336. }
  20337. virtual const void *nextRow()
  20338. {
  20339. ActivityTimer t(totalCycles, timeActivities);
  20340. if (done) return NULL;
  20341. const void * ret = gatherMerged();
  20342. processed++;
  20343. done = true;
  20344. return ret;
  20345. }
  20346. };
  20347. class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
  20348. {
  20349. IHThorDiskGroupAggregateArg & aggregateHelper;
  20350. RowAggregator resultAggregator;
  20351. bool gathered;
  20352. public:
  20353. CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager, ITranslatorSet *_translators)
  20354. : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager, _translators),
  20355. aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
  20356. resultAggregator(aggregateHelper, aggregateHelper),
  20357. gathered(false)
  20358. {
  20359. }
  20360. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20361. {
  20362. gathered= false;
  20363. CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
  20364. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  20365. }
  20366. virtual void reset()
  20367. {
  20368. resultAggregator.reset();
  20369. CRoxieServerDiskAggregateBaseActivity::reset();
  20370. }
  20371. void gatherMerged()
  20372. {
  20373. if (useRemote())
  20374. {
  20375. for (;;)
  20376. {
  20377. const void * next = remote->nextRow();
  20378. if (!next)
  20379. break;
  20380. resultAggregator.mergeElement(next);
  20381. ReleaseRoxieRow(next);
  20382. }
  20383. }
  20384. else
  20385. {
  20386. if (helper.canMatchAny() && !eof)
  20387. {
  20388. Owned<IInMemoryFileProcessor> processor = createGroupAggregateRecordProcessor(resultAggregator, aggregateHelper, reader);
  20389. processor->doQuery(NULL, 0, 0, 0);
  20390. }
  20391. }
  20392. gathered = true;
  20393. }
  20394. virtual const void *nextRow()
  20395. {
  20396. ActivityTimer t(totalCycles, timeActivities);
  20397. if (done)
  20398. return NULL;
  20399. if (!gathered)
  20400. gatherMerged();
  20401. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  20402. if (next)
  20403. {
  20404. processed++;
  20405. return next->finalizeRowClear();
  20406. }
  20407. done = true;
  20408. return NULL;
  20409. }
  20410. };
  20411. class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
  20412. {
  20413. public:
  20414. RemoteActivityId remoteId;
  20415. bool isLocal;
  20416. bool sorted;
  20417. bool maySkip;
  20418. bool variableFileName;
  20419. Owned<ITranslatorSet> translators;
  20420. Owned<IInMemoryIndexManager> manager;
  20421. Owned<const IResolvedFile> datafile;
  20422. const char *quotes;
  20423. const char *separators;
  20424. const char *terminators;
  20425. const char *escapes;
  20426. size32_t maxCsvRowSize;
  20427. CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20428. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20429. {
  20430. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20431. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20432. sorted = (helper->getFlags() & TDRunsorted) == 0;
  20433. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
  20434. maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
  20435. quotes = separators = terminators = escapes = NULL;
  20436. if (!variableFileName)
  20437. {
  20438. bool isOpt = (helper->getFlags() & TDRoptional) != 0;
  20439. OwnedRoxieString fileName(helper->getFileName());
  20440. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
  20441. bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
  20442. if (isLocal || isSimple)
  20443. {
  20444. if (datafile)
  20445. {
  20446. unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
  20447. unsigned expectedFormatCrc = helper->getDiskFormatCrc();
  20448. unsigned projectedFormatCrc = helper->getProjectedFormatCrc();
  20449. translators.setown(datafile->getTranslators(projectedFormatCrc, helper->queryProjectedDiskRecordSize(), expectedFormatCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  20450. manager.setown(datafile->getIndexManager(isOpt, channel, translators->queryActualLayout(0), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false)));
  20451. const IPropertyTree *options = datafile->queryProperties();
  20452. if (options)
  20453. {
  20454. quotes = options->queryProp("@csvQuote");
  20455. separators = options->queryProp("@csvSeparate");
  20456. terminators = options->queryProp("@csvTerminate");
  20457. escapes = options->queryProp("@csvEscape");
  20458. }
  20459. }
  20460. else
  20461. manager.setown(createInMemoryIndexManager(helper->queryProjectedDiskRecordSize()->queryRecordAccessor(true), true, nullptr));
  20462. }
  20463. }
  20464. switch (kind)
  20465. {
  20466. case TAKcsvread:
  20467. {
  20468. maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
  20469. IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
  20470. if (workunit)
  20471. maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
  20472. break;
  20473. }
  20474. default:
  20475. maxCsvRowSize = 0; // unused
  20476. }
  20477. }
  20478. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  20479. {
  20480. unsigned numParts = datafile ? datafile->getNumParts() : 0;
  20481. switch (kind)
  20482. {
  20483. case TAKcsvread:
  20484. return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators,
  20485. quotes, separators, terminators, escapes, maxCsvRowSize);
  20486. case TAKxmlread:
  20487. case TAKjsonread:
  20488. return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20489. case TAKdiskread:
  20490. case TAKspillread:
  20491. return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager, translators);
  20492. case TAKdisknormalize:
  20493. return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager, translators);
  20494. case TAKdiskcount:
  20495. return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20496. case TAKdiskaggregate:
  20497. return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20498. case TAKdiskgroupaggregate:
  20499. return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager, translators);
  20500. }
  20501. throwUnexpected();
  20502. }
  20503. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20504. {
  20505. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
  20506. }
  20507. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20508. {
  20509. if (datafile)
  20510. addXrefFileInfo(reply, datafile);
  20511. else
  20512. {
  20513. // Temporarily resolve the file
  20514. Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
  20515. if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
  20516. {
  20517. OwnedRoxieString fileName(helper->getFileName());
  20518. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  20519. if (temp)
  20520. addXrefFileInfo(reply, temp);
  20521. }
  20522. }
  20523. }
  20524. virtual const StatisticsMapping &queryStatsMapping() const
  20525. {
  20526. return diskStatistics;
  20527. }
  20528. };
  20529. IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20530. {
  20531. return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  20532. }
  20533. //=================================================================================
  20534. class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
  20535. {
  20536. public:
  20537. Owned<IKeyArray> keySet;
  20538. Owned<ITranslatorSet> translators;
  20539. RemoteActivityId remoteId;
  20540. bool isSimple;
  20541. bool isLocal;
  20542. bool maySkip;
  20543. bool sorted;
  20544. bool variableFileName;
  20545. unsigned maxSeekLookahead;
  20546. Owned<const IResolvedFile> indexfile;
  20547. CRoxieServerSideCache *cache;
  20548. CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  20549. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  20550. {
  20551. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20552. unsigned flags = indexHelper->getFlags();
  20553. sorted = (flags & TIRunordered) == 0;
  20554. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  20555. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20556. if (!variableFileName)
  20557. {
  20558. bool isOpt = (flags & TIRoptional) != 0;
  20559. OwnedRoxieString indexName(indexHelper->getFileName());
  20560. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  20561. if (indexfile)
  20562. {
  20563. unsigned projectedCrc = indexHelper->getProjectedFormatCrc();
  20564. unsigned expectedCrc = indexHelper->getDiskFormatCrc();
  20565. IOutputMetaData *projectedMeta = indexHelper->queryProjectedDiskRecordSize();
  20566. IOutputMetaData *expectedMeta = indexHelper->queryDiskRecordSize();
  20567. translators.setown(indexfile->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  20568. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  20569. }
  20570. }
  20571. isSimple = isLocal;
  20572. maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
  20573. if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
  20574. {
  20575. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  20576. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  20577. isSimple = true;
  20578. }
  20579. int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
  20580. cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
  20581. maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
  20582. }
  20583. ~CRoxieServerBaseIndexActivityFactory()
  20584. {
  20585. delete cache;
  20586. }
  20587. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  20588. {
  20589. if (indexfile)
  20590. addXrefFileInfo(reply, indexfile);
  20591. else
  20592. {
  20593. Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
  20594. if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
  20595. {
  20596. OwnedRoxieString indexName(indexHelper->getFileName());
  20597. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
  20598. if (temp)
  20599. addXrefFileInfo(reply, temp);
  20600. }
  20601. }
  20602. }
  20603. virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
  20604. {
  20605. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
  20606. }
  20607. virtual IRoxieServerSideCache *queryServerSideCache() const
  20608. {
  20609. return cache;
  20610. }
  20611. virtual const StatisticsMapping &queryStatsMapping() const
  20612. {
  20613. return indexStatistics;
  20614. }
  20615. };
  20616. class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
  20617. {
  20618. protected:
  20619. IHThorIndexReadBaseArg &indexHelper;
  20620. IHThorSteppedSourceExtra *steppedExtra;
  20621. Linked<IKeyArray> keySet;
  20622. Linked<ITranslatorSet> translators;
  20623. CSkippableRemoteResultAdaptor remote;
  20624. CIndexTransformCallback callback;
  20625. bool sorted;
  20626. bool variableFileName;
  20627. bool variableInfoPending;
  20628. bool isOpt;
  20629. bool isLocal;
  20630. unsigned __int64 rowLimit;
  20631. unsigned __int64 keyedLimit;
  20632. unsigned __int64 choosenLimit;
  20633. unsigned accepted;
  20634. unsigned rejected;
  20635. unsigned seekGEOffset;
  20636. Owned<IKeyManager> tlk;
  20637. Owned<const IResolvedFile> varFileInfo;
  20638. const RemoteActivityId &remoteId;
  20639. void setVariableFileInfo()
  20640. {
  20641. OwnedRoxieString indexName(indexHelper.getFileName());
  20642. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  20643. if (varFileInfo)
  20644. {
  20645. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  20646. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  20647. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  20648. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  20649. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  20650. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  20651. }
  20652. variableInfoPending = false;
  20653. }
  20654. public:
  20655. CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20656. bool _sorted, bool _isLocal, bool _maySkip)
  20657. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  20658. indexHelper((IHThorIndexReadBaseArg &)basehelper),
  20659. keySet(_factory->keySet),
  20660. translators(_factory->translators),
  20661. remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
  20662. sorted(_sorted),
  20663. isLocal(_isLocal) ,
  20664. remoteId(_remoteId)
  20665. {
  20666. indexHelper.setCallback(&callback);
  20667. steppedExtra = indexHelper.querySteppingExtra();
  20668. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
  20669. variableInfoPending = false;
  20670. isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
  20671. seekGEOffset = 0;
  20672. // started = false;
  20673. rejected = accepted = 0;
  20674. rowLimit = choosenLimit = keyedLimit = 0;
  20675. }
  20676. virtual const IResolvedFile *queryVarFileInfo() const
  20677. {
  20678. return varFileInfo;
  20679. }
  20680. virtual void onCreate(IHThorArg *_colocalParent)
  20681. {
  20682. CRoxieServerActivity::onCreate(_colocalParent);
  20683. remote.onCreate(_colocalParent);
  20684. }
  20685. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20686. {
  20687. accepted = 0;
  20688. rejected = 0;
  20689. rowLimit = (unsigned __int64) -1;
  20690. keyedLimit = (unsigned __int64 ) -1;
  20691. choosenLimit = I64C(0x7fffffffffffffff);
  20692. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  20693. remote.onStart(parentExtractSize, parentExtract);
  20694. variableInfoPending = variableFileName;
  20695. }
  20696. void processAllKeys()
  20697. {
  20698. try
  20699. {
  20700. bool noLocal = factory->queryQueryFactory().queryOptions().disableLocalOptimizations || seekGEOffset > 0;
  20701. if (indexHelper.canMatchAny())
  20702. {
  20703. if (variableInfoPending)
  20704. setVariableFileInfo();
  20705. remote.setLimits(rowLimit, keyedLimit, choosenLimit);
  20706. if (keySet)
  20707. {
  20708. // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
  20709. // 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
  20710. // However order is probably better to iterate fileno's inside partnos
  20711. // A superkey that mixes single and multipart or tlk and roroot keys might be hard
  20712. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  20713. {
  20714. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  20715. if (thisBase)
  20716. {
  20717. unsigned fileNo = 0;
  20718. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  20719. if (!thisKey->isTopLevelKey())
  20720. {
  20721. if (keyedLimit != (unsigned __int64) -1)
  20722. {
  20723. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  20724. {
  20725. Owned<IKeyManager> countKey;
  20726. countKey.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20727. countKey->setLayoutTranslator(translators->queryTranslator(fileNo));
  20728. createSegmentMonitors(countKey);
  20729. unsigned __int64 count = countKey->checkCount(keyedLimit);
  20730. if (count > keyedLimit)
  20731. {
  20732. if (traceLevel > 4)
  20733. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  20734. onLimitExceeded(true);
  20735. }
  20736. }
  20737. }
  20738. }
  20739. if (seekGEOffset && !thisKey->isTopLevelKey())
  20740. {
  20741. tlk.setown(createSingleKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, seekGEOffset, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20742. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20743. }
  20744. else
  20745. {
  20746. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), thisKey, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  20747. if (!thisKey->isTopLevelKey())
  20748. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20749. else
  20750. tlk->setLayoutTranslator(nullptr);
  20751. }
  20752. createSegmentMonitors(tlk);
  20753. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  20754. {
  20755. StringBuffer out;
  20756. tlk->describeFilter(out);
  20757. CTXLOG("Using filter %s", out.str());
  20758. if (ctx->queryProbeManager())
  20759. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  20760. }
  20761. tlk->reset();
  20762. for (;;) // for each file part
  20763. {
  20764. //block for TransformCallbackAssociation
  20765. {
  20766. TransformCallbackAssociation associate(callback, tlk);
  20767. if (thisKey->isTopLevelKey())
  20768. {
  20769. if (thisKey->isFullySorted())
  20770. {
  20771. while (tlk->lookup(false))
  20772. {
  20773. unsigned slavePart = (unsigned)extractFpos(tlk);
  20774. if (slavePart)
  20775. {
  20776. accepted++;
  20777. remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
  20778. if (sorted && numChannels>1)
  20779. remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
  20780. }
  20781. }
  20782. }
  20783. else
  20784. {
  20785. unsigned slavePart = tlk->getPartition(); // Returns 0 if no partition info, or filter cannot be partitioned
  20786. remote.getMem(slavePart, fileNo, 0);
  20787. }
  20788. }
  20789. else
  20790. {
  20791. // Single - part key. We process locally unless smart-stepping is involved, in which case we need to ensure that
  20792. // we do the proper two-stage merge.
  20793. // Unfortunately processSingleKey will not use the merger we carefully set up before,
  20794. // so we disable the local processing in that case
  20795. if (noLocal)
  20796. remote.getMem(1, fileNo, 0); // 1 because it's a single part key
  20797. else if (processSingleKey(thisKey, translators->queryTranslator(fileNo)))
  20798. break;
  20799. }
  20800. }
  20801. if (++fileNo < thisBase->numParts())
  20802. {
  20803. thisKey = thisBase->queryPart(fileNo);
  20804. tlk->setKey(thisKey);
  20805. if (!thisKey->isTopLevelKey())
  20806. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  20807. else
  20808. tlk->setLayoutTranslator(nullptr);
  20809. tlk->reset();
  20810. }
  20811. else
  20812. break;
  20813. }
  20814. tlk->releaseSegmentMonitors();
  20815. tlk->setKey(NULL);
  20816. }
  20817. }
  20818. }
  20819. }
  20820. remote.flush();
  20821. remote.senddone();
  20822. }
  20823. catch (IException *E)
  20824. {
  20825. remote.setException(E);
  20826. }
  20827. }
  20828. virtual void createSegmentMonitors(IKeyManager *key)
  20829. {
  20830. indexHelper.createSegmentMonitors(key);
  20831. key->finishSegmentMonitors();
  20832. }
  20833. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) = 0;
  20834. virtual void reset()
  20835. {
  20836. if (accepted)
  20837. noteStatistic(StNumIndexAccepted, accepted);
  20838. if (rejected)
  20839. noteStatistic(StNumIndexRejected, rejected);
  20840. remote.onReset();
  20841. CRoxieServerActivity::reset();
  20842. if (varFileInfo)
  20843. {
  20844. keySet.clear();
  20845. varFileInfo.clear();
  20846. }
  20847. variableInfoPending = false;
  20848. }
  20849. virtual void stop()
  20850. {
  20851. remote.onStop();
  20852. CRoxieServerActivity::stop();
  20853. }
  20854. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  20855. {
  20856. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  20857. }
  20858. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  20859. {
  20860. CRoxieServerActivity::gatherStats(merged);
  20861. remote.gatherStats(merged);
  20862. }
  20863. };
  20864. class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
  20865. {
  20866. protected:
  20867. IHThorSourceLimitTransformExtra * limitTransformExtra = nullptr;
  20868. public:
  20869. CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20870. bool _sorted, bool _isLocal, bool _maySkip)
  20871. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip)
  20872. {
  20873. }
  20874. virtual void reset()
  20875. {
  20876. remote.onReset();
  20877. CRoxieServerIndexActivity::reset();
  20878. }
  20879. virtual const void *nextRow()
  20880. {
  20881. ActivityTimer t(totalCycles, timeActivities);
  20882. try
  20883. {
  20884. const void *ret = remote.nextRow();
  20885. if (ret)
  20886. processed++;
  20887. return ret;
  20888. }
  20889. catch (IException *E)
  20890. {
  20891. throw makeWrappedException(E);
  20892. }
  20893. }
  20894. protected:
  20895. virtual const void * createLimitFailRow(bool isKeyed)
  20896. {
  20897. ensureRowAllocator();
  20898. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  20899. assertex(limitTransformExtra);
  20900. size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
  20901. if (outSize)
  20902. return rowBuilder.finalizeRowClear(outSize);
  20903. return NULL;
  20904. }
  20905. };
  20906. class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
  20907. {
  20908. protected:
  20909. IHThorIndexReadArg & readHelper;
  20910. ISteppingMeta *rawMeta = nullptr;
  20911. CSteppingMeta steppingMeta;
  20912. unsigned * seekSizes = nullptr;
  20913. bool optimizeSteppedPostFilter;
  20914. ISteppingMeta * projectedMeta = nullptr;
  20915. unsigned maxSeekLookahead;
  20916. public:
  20917. CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  20918. bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
  20919. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, _maySkip),
  20920. readHelper((IHThorIndexReadArg &)basehelper)
  20921. {
  20922. limitTransformExtra = &readHelper;
  20923. rawMeta = readHelper.queryRawSteppingMeta();
  20924. unsigned flags = indexHelper.getFlags();
  20925. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  20926. seekSizes = NULL;
  20927. maxSeekLookahead = _maxSeekLookahead;
  20928. if (rawMeta)
  20929. {
  20930. const CFieldOffsetSize * fields = rawMeta->queryFields();
  20931. unsigned maxFields = rawMeta->getNumFields();
  20932. seekGEOffset = fields[0].offset;
  20933. seekSizes = new unsigned[maxFields];
  20934. seekSizes[0] = fields[0].size;
  20935. for (unsigned i=1; i < maxFields; i++)
  20936. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  20937. projectedMeta = readHelper.queryProjectedSteppingMeta();
  20938. ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
  20939. remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
  20940. bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
  20941. steppingMeta.init(useMeta, hasPostFilter);
  20942. }
  20943. }
  20944. ~CRoxieServerIndexReadActivity()
  20945. {
  20946. delete [] seekSizes;
  20947. }
  20948. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  20949. {
  20950. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  20951. steppingMeta.setDistributed();
  20952. if (steppedExtra)
  20953. steppingMeta.setExtra(steppedExtra);
  20954. rowLimit = readHelper.getRowLimit();
  20955. keyedLimit = readHelper.getKeyedLimit();
  20956. choosenLimit = readHelper.getChooseNLimit();
  20957. if (!paused)
  20958. processAllKeys();
  20959. }
  20960. class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
  20961. {
  20962. public:
  20963. IMPLEMENT_IINTERFACE;
  20964. virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
  20965. {
  20966. Link();
  20967. return const_cast<LazyLocalKeyReader*> (this);
  20968. }
  20969. virtual const void *getMessageHeader(unsigned &length) const
  20970. {
  20971. length = 0;
  20972. return NULL;
  20973. }
  20974. virtual const void *getMessageMetadata(unsigned &length) const
  20975. {
  20976. length = 0;
  20977. return NULL;
  20978. }
  20979. virtual void discard() const
  20980. {
  20981. // nothing to do.
  20982. }
  20983. unsigned keyedCount;
  20984. unsigned matched;
  20985. bool EOFseen;
  20986. Owned<IKeyIndexSet> keySet;
  20987. Owned<IKeyManager> tlk;
  20988. CRoxieServerIndexReadActivity &owner;
  20989. LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, const IDynamicTransform * trans)
  20990. : owner(_owner)
  20991. {
  20992. keyedCount = 0;
  20993. matched = 0;
  20994. EOFseen = false;
  20995. keySet.setown(createKeyIndexSet());
  20996. keySet->addIndex(LINK(key));
  20997. if (owner.seekGEOffset)
  20998. tlk.setown(createKeyMerger(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet, owner.seekGEOffset, &owner, owner.indexHelper.hasNewSegmentMonitors(), !owner.isBlind()));
  20999. else
  21000. tlk.setown(createLocalKeyManager(owner.indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keySet->queryPart(0), &owner, owner.indexHelper.hasNewSegmentMonitors(), !owner.isBlind()));
  21001. if (!key->isTopLevelKey())
  21002. tlk->setLayoutTranslator(trans);
  21003. owner.indexHelper.createSegmentMonitors(tlk);
  21004. tlk->finishSegmentMonitors();
  21005. tlk->reset();
  21006. }
  21007. virtual const void *getNext(int length)
  21008. {
  21009. TransformCallbackAssociation associate(owner.callback, tlk);
  21010. while (tlk->lookup(true))
  21011. {
  21012. keyedCount++;
  21013. if (keyedCount > owner.keyedLimit)
  21014. {
  21015. owner.onLimitExceeded(true); // Should throw exception
  21016. throwUnexpected();
  21017. }
  21018. size32_t transformedSize;
  21019. RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
  21020. byte const * keyRow = tlk->queryKeyBuffer();
  21021. if (likely(owner.readHelper.canMatch(keyRow)))
  21022. {
  21023. try
  21024. {
  21025. transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
  21026. owner.callback.finishedRow();
  21027. }
  21028. catch (IException *E)
  21029. {
  21030. throw owner.makeWrappedException(E);
  21031. }
  21032. if (transformedSize)
  21033. {
  21034. OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
  21035. matched++;
  21036. if (matched > owner.rowLimit)
  21037. {
  21038. owner.onLimitExceeded(false); // Should throw exception
  21039. throwUnexpected();
  21040. }
  21041. if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
  21042. {
  21043. break;
  21044. }
  21045. owner.accepted++;
  21046. return result.getClear();
  21047. }
  21048. else
  21049. owner.rejected++;
  21050. }
  21051. else
  21052. {
  21053. owner.callback.finishedRow(); // since filter might have accessed a blob
  21054. owner.rejected++;
  21055. }
  21056. }
  21057. EOFseen = true;
  21058. return NULL;
  21059. }
  21060. virtual bool atEOF() const
  21061. {
  21062. return EOFseen;
  21063. }
  21064. virtual bool isSerialized() const
  21065. {
  21066. return false;
  21067. }
  21068. };
  21069. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21070. {
  21071. ensureRowAllocator();
  21072. remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
  21073. return false;
  21074. }
  21075. virtual void onLimitExceeded(bool isKeyed)
  21076. {
  21077. if (traceLevel > 4)
  21078. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21079. if (isKeyed)
  21080. {
  21081. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21082. {
  21083. if (ctx->queryDebugContext())
  21084. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21085. throw makeLimitSkipException(true);
  21086. }
  21087. else
  21088. readHelper.onKeyedLimitExceeded();
  21089. }
  21090. else
  21091. {
  21092. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21093. {
  21094. if (ctx->queryDebugContext())
  21095. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21096. throw makeLimitSkipException(false);
  21097. }
  21098. else
  21099. readHelper.onLimitExceeded();
  21100. }
  21101. }
  21102. virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
  21103. {
  21104. out.append((unsigned short) numFields);
  21105. out.append((unsigned short) seekLen);
  21106. out.append((unsigned short) stepExtra.queryFlags());
  21107. IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
  21108. if (seeks)
  21109. {
  21110. unsigned lookahead = 40000/seekLen;
  21111. if (maxSeekLookahead && (lookahead > maxSeekLookahead))
  21112. lookahead = maxSeekLookahead;
  21113. seeks->ensureFilled(seek, numFields, lookahead);
  21114. out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
  21115. unsigned serialized = 1; // rawseek is always serialized...
  21116. unsigned patchLength = out.length();
  21117. out.append(serialized); // NOTE - we come back and patch with the actual value...
  21118. out.append(seekLen, rawSeek);
  21119. if (seeks->ordinality())
  21120. {
  21121. const void *lastSeek = rawSeek;
  21122. byte *nextSeek = NULL;
  21123. if (projectedMeta)
  21124. nextSeek = (byte *) alloca(seekLen);
  21125. for (unsigned i = 0; i < seeks->ordinality(); i++)
  21126. {
  21127. if (projectedMeta)
  21128. {
  21129. RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
  21130. readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21131. }
  21132. else
  21133. nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
  21134. int diff = memcmp(nextSeek, lastSeek, seekLen);
  21135. if (diff > 0)
  21136. {
  21137. serialized++;
  21138. out.append(seekLen, nextSeek);
  21139. lastSeek = (const byte *) out.reserve(0) - seekLen;
  21140. }
  21141. }
  21142. unsigned length = out.length();
  21143. out.setWritePos(patchLength);
  21144. out.append(serialized);
  21145. out.setWritePos(length);
  21146. }
  21147. }
  21148. else
  21149. {
  21150. out.append(false);
  21151. out.append(1);
  21152. out.append(seekLen, rawSeek);
  21153. }
  21154. }
  21155. virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21156. {
  21157. ActivityTimer t(totalCycles, timeActivities);
  21158. try
  21159. {
  21160. unsigned seeklen = 0;
  21161. const void *rawSeek = NULL;
  21162. if (seek && numFields)
  21163. {
  21164. seeklen = seekSizes[numFields-1];
  21165. rawSeek = (const byte *)seek + seekGEOffset;
  21166. if (projectedMeta)
  21167. {
  21168. byte * temp = (byte *) alloca(seeklen);
  21169. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
  21170. readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21171. rawSeek = (byte *)temp;
  21172. }
  21173. }
  21174. const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
  21175. if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
  21176. processed++;
  21177. return ret;
  21178. }
  21179. catch (IException *E)
  21180. {
  21181. throw makeWrappedException(E);
  21182. }
  21183. }
  21184. virtual IInputSteppingMeta * querySteppingMeta()
  21185. {
  21186. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21187. return &steppingMeta;
  21188. return NULL;
  21189. }
  21190. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21191. {
  21192. if (variableInfoPending)
  21193. setVariableFileInfo();
  21194. return this;
  21195. }
  21196. virtual IKeyArray *getKeySet() const
  21197. {
  21198. return keySet.getLink();
  21199. }
  21200. virtual const IResolvedFile *getVarFileInfo() const
  21201. {
  21202. return varFileInfo.getLink();
  21203. }
  21204. virtual ITranslatorSet *getTranslators() const override
  21205. {
  21206. return translators.getLink();
  21207. }
  21208. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21209. {
  21210. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21211. }
  21212. virtual IRoxieServerActivity *queryActivity() { return this; }
  21213. virtual const RemoteActivityId& queryRemoteId() const
  21214. {
  21215. return remoteId;
  21216. }
  21217. };
  21218. class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
  21219. {
  21220. IHThorIndexReadArg & indexHelper;
  21221. IHThorSteppedSourceExtra * steppedExtra;
  21222. bool eof;
  21223. Linked<IKeyArray>keySet;
  21224. Owned<IKeyIndexSet>keyIndexSet;
  21225. Owned<IKeyManager> tlk;
  21226. Linked<ITranslatorSet> translators;
  21227. CIndexTransformCallback callback;
  21228. unsigned __int64 keyedLimit;
  21229. unsigned rowLimit;
  21230. unsigned chooseNLimit;
  21231. unsigned accepted;
  21232. unsigned rejected;
  21233. unsigned keyedCount;
  21234. ISteppingMeta * rawMeta;
  21235. ISteppingMeta * projectedMeta;
  21236. size32_t seekGEOffset;
  21237. unsigned * seekSizes;
  21238. CSteppingMeta steppingMeta;
  21239. Owned<const IResolvedFile> varFileInfo;
  21240. const RemoteActivityId &remoteId;
  21241. bool firstRead;
  21242. bool variableFileName;
  21243. bool variableInfoPending;
  21244. bool isOpt;
  21245. bool isLocal;
  21246. bool optimizeSteppedPostFilter;
  21247. // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
  21248. void initKeySet()
  21249. {
  21250. if (keySet->length() > 1 || rawMeta != NULL)
  21251. {
  21252. if (translators->isTranslatingKeyed())
  21253. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Keyed Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
  21254. if (!translators->hasConsistentTranslation())
  21255. throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Mixture of layout translation is not available when merging key parts or smart-stepping");
  21256. }
  21257. keyIndexSet.setown(createKeyIndexSet());
  21258. for (unsigned part = 0; part < keySet->length(); part++)
  21259. {
  21260. IKeyIndexBase *kib = keySet->queryKeyPart(part);
  21261. if (kib)
  21262. {
  21263. for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
  21264. {
  21265. IKeyIndex *k = kib->queryPart(subpart);
  21266. if (k)
  21267. {
  21268. assertex(!k->isTopLevelKey());
  21269. keyIndexSet->addIndex(LINK(k));
  21270. }
  21271. }
  21272. }
  21273. }
  21274. }
  21275. void setVariableFileInfo()
  21276. {
  21277. OwnedRoxieString indexName(indexHelper.getFileName());
  21278. varFileInfo.setown(resolveLFNIndex(indexName, isOpt));
  21279. unsigned projectedCrc = indexHelper.getProjectedFormatCrc();
  21280. unsigned expectedCrc = indexHelper.getDiskFormatCrc();
  21281. IOutputMetaData *projectedMeta = indexHelper.queryProjectedDiskRecordSize();
  21282. IOutputMetaData *expectedMeta = indexHelper.queryDiskRecordSize();
  21283. translators.setown(varFileInfo->getTranslators(projectedCrc, projectedMeta, expectedCrc, expectedMeta, getEnableFieldTranslation(), true));
  21284. keySet.setown(varFileInfo->getKeyArray(isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  21285. initKeySet();
  21286. variableInfoPending = false;
  21287. }
  21288. void onEOF()
  21289. {
  21290. callback.setManager(NULL);
  21291. eof = true;
  21292. tlk.clear();
  21293. }
  21294. public:
  21295. CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21296. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21297. indexHelper((IHThorIndexReadArg &)basehelper),
  21298. keySet(_factory->keySet),
  21299. translators(_factory->translators),
  21300. remoteId(_remoteId),
  21301. isLocal(_isLocal)
  21302. {
  21303. rowLimit = 0;
  21304. keyedLimit = 0;
  21305. chooseNLimit = 0;
  21306. indexHelper.setCallback(&callback);
  21307. steppedExtra = indexHelper.querySteppingExtra();
  21308. unsigned flags = indexHelper.getFlags();
  21309. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
  21310. variableInfoPending = false;
  21311. isOpt = (flags & TIRoptional) != 0;
  21312. optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
  21313. firstRead = true;
  21314. accepted = 0;
  21315. rejected = 0;
  21316. keyedCount = 0;
  21317. eof = false;
  21318. rawMeta = indexHelper.queryRawSteppingMeta();
  21319. projectedMeta = indexHelper.queryProjectedSteppingMeta();
  21320. seekGEOffset = 0;
  21321. seekSizes = NULL;
  21322. if (rawMeta)
  21323. {
  21324. // MORE - should check all keys in maxFields list can actually be keyed.
  21325. const CFieldOffsetSize * fields = rawMeta->queryFields();
  21326. unsigned maxFields = rawMeta->getNumFields();
  21327. seekGEOffset = fields[0].offset;
  21328. seekSizes = new unsigned[maxFields];
  21329. seekSizes[0] = fields[0].size;
  21330. for (unsigned i=1; i < maxFields; i++)
  21331. seekSizes[i] = seekSizes[i-1] + fields[i].size;
  21332. bool hasPostFilter = indexHelper.transformMayFilter() && optimizeSteppedPostFilter;
  21333. if (projectedMeta)
  21334. steppingMeta.init(projectedMeta, hasPostFilter);
  21335. else
  21336. steppingMeta.init(rawMeta, hasPostFilter);
  21337. }
  21338. }
  21339. virtual const IResolvedFile *queryVarFileInfo() const
  21340. {
  21341. return varFileInfo;
  21342. }
  21343. ~CRoxieServerSimpleIndexReadActivity()
  21344. {
  21345. delete [] seekSizes;
  21346. }
  21347. virtual bool needsAllocator() const { return true; }
  21348. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21349. {
  21350. firstRead = true;
  21351. accepted = 0;
  21352. rejected = 0;
  21353. keyedCount = 0;
  21354. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21355. if (steppedExtra)
  21356. steppingMeta.setExtra(steppedExtra);
  21357. eof = !indexHelper.canMatchAny();
  21358. if (variableFileName)
  21359. variableInfoPending = true;
  21360. else
  21361. {
  21362. variableInfoPending = false;
  21363. if (!keyIndexSet)
  21364. initKeySet();
  21365. }
  21366. }
  21367. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  21368. {
  21369. if (variableInfoPending)
  21370. setVariableFileInfo();
  21371. return this;
  21372. }
  21373. virtual IKeyArray *getKeySet() const
  21374. {
  21375. return keySet.getLink();
  21376. }
  21377. virtual const IResolvedFile *getVarFileInfo() const
  21378. {
  21379. return varFileInfo.getLink();
  21380. }
  21381. virtual ITranslatorSet *getTranslators() const override
  21382. {
  21383. return translators.getLink();
  21384. }
  21385. virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
  21386. {
  21387. indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
  21388. }
  21389. virtual IRoxieServerActivity *queryActivity() { return this; }
  21390. virtual const RemoteActivityId& queryRemoteId() const
  21391. {
  21392. return remoteId;
  21393. }
  21394. const void *nextRow()
  21395. {
  21396. bool matched = true;
  21397. return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
  21398. }
  21399. unsigned __int64 checkCount(unsigned __int64 limit)
  21400. {
  21401. unsigned numParts = keyIndexSet->numParts();
  21402. unsigned __int64 result = 0;
  21403. for (unsigned i = 0; i < numParts; i++)
  21404. {
  21405. Owned<IKeyManager> countTlk = createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(i), this, indexHelper.hasNewSegmentMonitors(), !isBlind());
  21406. countTlk->setLayoutTranslator(translators->queryTranslator(i));
  21407. indexHelper.createSegmentMonitors(countTlk);
  21408. countTlk->finishSegmentMonitors();
  21409. result += countTlk->checkCount(limit-result);
  21410. if (result > limit)
  21411. break;
  21412. }
  21413. return result;
  21414. }
  21415. virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
  21416. {
  21417. ActivityTimer t(totalCycles, timeActivities);
  21418. if (eof)
  21419. return NULL;
  21420. if (firstRead)
  21421. {
  21422. if (variableInfoPending)
  21423. setVariableFileInfo();
  21424. rowLimit = (unsigned) indexHelper.getRowLimit();
  21425. chooseNLimit = (unsigned) indexHelper.getChooseNLimit();
  21426. unsigned numParts = keyIndexSet->numParts();
  21427. if (!numParts)
  21428. {
  21429. onEOF();
  21430. return NULL;
  21431. }
  21432. if (numParts > 1 || seekGEOffset)
  21433. {
  21434. tlk.setown(createKeyMerger(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet, seekGEOffset, this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  21435. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21436. }
  21437. else
  21438. {
  21439. tlk.setown(createLocalKeyManager(indexHelper.queryDiskRecordSize()->queryRecordAccessor(true), keyIndexSet->queryPart(0), this, indexHelper.hasNewSegmentMonitors(), !isBlind()));
  21440. tlk->setLayoutTranslator(translators->queryTranslator(0));
  21441. }
  21442. indexHelper.createSegmentMonitors(tlk);
  21443. tlk->finishSegmentMonitors();
  21444. if (queryTraceLevel() > 3 || ctx->queryProbeManager())
  21445. {
  21446. StringBuffer out;
  21447. tlk->describeFilter(out);
  21448. CTXLOG("Using filter %s", out.str());
  21449. if (ctx->queryProbeManager())
  21450. ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
  21451. }
  21452. tlk->reset();
  21453. callback.setManager(tlk);
  21454. keyedLimit = indexHelper.getKeyedLimit();
  21455. if (keyedLimit != (unsigned __int64) -1)
  21456. {
  21457. if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
  21458. {
  21459. unsigned __int64 count = checkCount(keyedLimit);
  21460. if (count > keyedLimit)
  21461. {
  21462. if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
  21463. indexHelper.onKeyedLimitExceeded();
  21464. const void * ret = NULL;
  21465. if (indexHelper.getFlags() & TIRkeyedlimitcreates)
  21466. ret = createKeyedLimitOnFailRow();
  21467. onEOF();
  21468. return ret;
  21469. }
  21470. keyedLimit = (unsigned __int64) -1;
  21471. }
  21472. }
  21473. firstRead = false;
  21474. }
  21475. if (accepted == chooseNLimit)
  21476. {
  21477. onEOF();
  21478. return NULL;
  21479. }
  21480. const byte * rawSeek = NULL;
  21481. unsigned seekSize = 0;
  21482. if (seek)
  21483. {
  21484. seekSize = seekSizes[numFields-1];
  21485. rawSeek = (const byte *)seek + seekGEOffset;
  21486. if (projectedMeta)
  21487. {
  21488. byte *temp = (byte *) alloca(seekSize);
  21489. RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
  21490. indexHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
  21491. rawSeek = (byte *)temp;
  21492. }
  21493. #ifdef _DEBUG
  21494. // StringBuffer seekStr;
  21495. // for (unsigned i = 0; i < seekSize; i++)
  21496. // {
  21497. // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
  21498. // }
  21499. // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
  21500. #endif
  21501. }
  21502. const byte * originalRawSeek = rawSeek;
  21503. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21504. while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
  21505. {
  21506. checkAbort();
  21507. keyedCount++;
  21508. if (keyedCount > keyedLimit)
  21509. {
  21510. indexHelper.onKeyedLimitExceeded();
  21511. break;
  21512. }
  21513. byte const * keyRow = tlk->queryKeyBuffer();
  21514. if (likely(indexHelper.canMatch(keyRow)))
  21515. {
  21516. #ifdef _DEBUG
  21517. // StringBuffer recstr;
  21518. // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
  21519. // for (unsigned i = 0; i < size; i++)
  21520. // {
  21521. // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
  21522. // }
  21523. // DBGLOG("nextRowGE Got %s", recstr.str());
  21524. if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
  21525. assertex(!"smart seek failure");
  21526. #endif
  21527. size32_t transformedSize;
  21528. rowBuilder.ensureRow();
  21529. try
  21530. {
  21531. transformedSize =indexHelper.transform(rowBuilder, keyRow);
  21532. //if the post filter causes a mismatch, and the stepping condition no longer matches
  21533. //then return a mismatch record - so the join code can start seeking on the other input.
  21534. if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
  21535. {
  21536. if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
  21537. {
  21538. transformedSize = indexHelper.unfilteredTransform(rowBuilder, keyRow);
  21539. if (transformedSize != 0)
  21540. wasCompleteMatch = false;
  21541. }
  21542. }
  21543. callback.finishedRow();
  21544. }
  21545. catch (IException *E)
  21546. {
  21547. throw makeWrappedException(E);
  21548. }
  21549. if (transformedSize)
  21550. {
  21551. accepted++;
  21552. if (accepted > rowLimit)
  21553. {
  21554. if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
  21555. {
  21556. throwUnexpected(); // should not have used simple variant if maySkip set...
  21557. }
  21558. if (traceLevel > 4)
  21559. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  21560. indexHelper.onLimitExceeded();
  21561. break;
  21562. }
  21563. processed++;
  21564. #ifdef _DEBUG
  21565. // const byte *ret = (const byte *) out.get();
  21566. // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
  21567. // queryOutputMeta()->toXML(ret, xmlwrite);
  21568. // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
  21569. #endif
  21570. return rowBuilder.finalizeRowClear(transformedSize);
  21571. }
  21572. else
  21573. rejected++;
  21574. }
  21575. else
  21576. {
  21577. callback.finishedRow(); // since filter might have accessed a blob
  21578. rejected++;
  21579. }
  21580. rawSeek = NULL;
  21581. }
  21582. onEOF();
  21583. return NULL;
  21584. }
  21585. virtual void reset()
  21586. {
  21587. onEOF();
  21588. if (accepted)
  21589. noteStatistic(StNumIndexAccepted, accepted);
  21590. if (rejected)
  21591. noteStatistic(StNumIndexRejected, rejected);
  21592. if (variableFileName)
  21593. {
  21594. varFileInfo.clear();
  21595. translators.clear();
  21596. }
  21597. variableInfoPending = false;
  21598. CRoxieServerActivity::reset();
  21599. }
  21600. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  21601. {
  21602. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
  21603. }
  21604. virtual IInputSteppingMeta * querySteppingMeta()
  21605. {
  21606. if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
  21607. return &steppingMeta;
  21608. return NULL;
  21609. }
  21610. protected:
  21611. const void * createKeyedLimitOnFailRow()
  21612. {
  21613. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21614. size32_t outSize = indexHelper.transformOnKeyedLimitExceeded(rowBuilder);
  21615. if (outSize)
  21616. return rowBuilder.finalizeRowClear(outSize);
  21617. return NULL;
  21618. }
  21619. };
  21620. class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21621. {
  21622. public:
  21623. CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21624. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21625. {
  21626. }
  21627. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21628. {
  21629. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21630. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  21631. else if (isSimple && !maySkip)
  21632. return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21633. else
  21634. return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal, maySkip, maxSeekLookahead);
  21635. }
  21636. };
  21637. IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21638. {
  21639. return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21640. }
  21641. //--------------------------------------------------------------------------------------------------------------------------
  21642. class CRoxieServerNullCountActivity : public CRoxieServerActivity
  21643. {
  21644. bool done;
  21645. public:
  21646. CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21647. : CRoxieServerActivity(_ctx, _factory, _probeManager)
  21648. {
  21649. done = false;
  21650. }
  21651. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21652. {
  21653. done = false;
  21654. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21655. }
  21656. virtual bool needsAllocator() const { return true; }
  21657. virtual const void *nextRow()
  21658. {
  21659. ActivityTimer t(totalCycles, timeActivities);
  21660. if (done) return NULL;
  21661. done = true;
  21662. size32_t rowSize = meta.getFixedSize();
  21663. void * nullRow = rowAllocator->createRow();
  21664. if (rowSize == 1)
  21665. *(byte *)nullRow = 0;
  21666. else
  21667. {
  21668. assertex(rowSize == sizeof(unsigned __int64));
  21669. *(unsigned __int64 *)nullRow = 0;
  21670. }
  21671. return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
  21672. }
  21673. };
  21674. class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
  21675. {
  21676. IHThorIndexCountArg & countHelper;
  21677. bool done;
  21678. public:
  21679. CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, bool _isLocal)
  21680. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21681. countHelper((IHThorIndexCountArg &)basehelper),
  21682. done(false)
  21683. {
  21684. }
  21685. virtual bool needsAllocator() const { return true; }
  21686. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21687. {
  21688. done = false;
  21689. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21690. choosenLimit = countHelper.getChooseNLimit();
  21691. rowLimit = countHelper.getRowLimit();
  21692. keyedLimit = countHelper.getKeyedLimit();
  21693. if (!paused)
  21694. processAllKeys();
  21695. }
  21696. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21697. {
  21698. unsigned __int64 count = 0;
  21699. if (countHelper.hasFilter())
  21700. {
  21701. while (tlk->lookup(true))
  21702. {
  21703. try
  21704. {
  21705. count += countHelper.numValid(tlk->queryKeyBuffer());
  21706. callback.finishedRow();
  21707. }
  21708. catch (IException *E)
  21709. {
  21710. throw makeWrappedException(E);
  21711. }
  21712. accepted++;
  21713. if (count >= choosenLimit) // MORE - what about limit?
  21714. break;
  21715. }
  21716. }
  21717. else
  21718. count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
  21719. if (count)
  21720. {
  21721. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  21722. if (count > choosenLimit)
  21723. count = choosenLimit;
  21724. void * recBuffer = rowAllocator->createRow();
  21725. if (meta.getFixedSize() == 1)
  21726. *(byte *)recBuffer = (byte)count;
  21727. else
  21728. {
  21729. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21730. *(unsigned __int64 *)recBuffer = count;
  21731. }
  21732. recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
  21733. result->append(recBuffer);
  21734. remote.injectResult(result.getClear());
  21735. //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
  21736. if (count >= choosenLimit)
  21737. return true;
  21738. }
  21739. return false;
  21740. }
  21741. virtual void onLimitExceeded(bool isKeyed)
  21742. {
  21743. if (traceLevel > 4)
  21744. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21745. if (isKeyed)
  21746. {
  21747. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  21748. {
  21749. if (ctx->queryDebugContext())
  21750. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21751. throw makeLimitSkipException(true);
  21752. }
  21753. else
  21754. {
  21755. countHelper.onKeyedLimitExceeded();
  21756. }
  21757. }
  21758. else
  21759. {
  21760. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  21761. {
  21762. if (ctx->queryDebugContext())
  21763. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  21764. throw makeLimitSkipException(false);
  21765. }
  21766. else
  21767. {
  21768. countHelper.onLimitExceeded();
  21769. }
  21770. }
  21771. }
  21772. virtual const void *createLimitFailRow(bool isKeyed)
  21773. {
  21774. throwUnexpected();
  21775. }
  21776. virtual const void *nextRow()
  21777. {
  21778. ActivityTimer t(totalCycles, timeActivities);
  21779. if (done) return NULL;
  21780. done = true;
  21781. unsigned __int64 totalCount = 0;
  21782. bool hasLimit = rowLimit != (unsigned __int64) -1;
  21783. try
  21784. {
  21785. for (;;)
  21786. {
  21787. const void * next = remote.nextRow();
  21788. if (!next)
  21789. break;
  21790. if (meta.getFixedSize() == 1)
  21791. totalCount += *(byte *)next;
  21792. else
  21793. totalCount += *(unsigned __int64 *) next;
  21794. ReleaseRoxieRow(next);
  21795. if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
  21796. break;
  21797. }
  21798. if (totalCount > rowLimit)
  21799. {
  21800. unsigned flags = indexHelper.getFlags();
  21801. if (flags & TIRlimitskips)
  21802. totalCount = 0;
  21803. else if (flags & TIRlimitcreates)
  21804. totalCount = 1;
  21805. else
  21806. countHelper.onLimitExceeded();
  21807. }
  21808. else if (totalCount > choosenLimit)
  21809. totalCount = choosenLimit;
  21810. }
  21811. catch (IException *E)
  21812. {
  21813. if (QUERYINTERFACE(E, LimitSkipException))
  21814. {
  21815. totalCount = 0;
  21816. unsigned flags = indexHelper.getFlags();
  21817. if (E->errorCode() == KeyedLimitSkipErrorCode)
  21818. {
  21819. if (flags & TIRkeyedlimitcreates)
  21820. totalCount++;
  21821. }
  21822. else
  21823. {
  21824. if (flags & TIRlimitcreates)
  21825. totalCount++;
  21826. }
  21827. if (totalCount > choosenLimit)
  21828. totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
  21829. E->Release();
  21830. }
  21831. else
  21832. throw ;
  21833. }
  21834. processed++;
  21835. void * result = rowAllocator->createRow();
  21836. if (meta.getFixedSize() == 1)
  21837. *(byte *)result = (byte)totalCount;
  21838. else
  21839. {
  21840. assertex(meta.getFixedSize() == sizeof(unsigned __int64));
  21841. *(unsigned __int64 *)result = totalCount;
  21842. }
  21843. return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
  21844. }
  21845. };
  21846. class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21847. {
  21848. public:
  21849. CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21850. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21851. {
  21852. }
  21853. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  21854. {
  21855. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  21856. return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
  21857. // else if (isSimple)
  21858. // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  21859. else
  21860. return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, isLocal);
  21861. }
  21862. };
  21863. IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21864. {
  21865. return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  21866. }
  21867. //--------------------------------------------------------------------------------------------------------------------------
  21868. class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
  21869. {
  21870. IHThorIndexAggregateArg &aggregateHelper;
  21871. bool done;
  21872. public:
  21873. CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  21874. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  21875. aggregateHelper((IHThorIndexAggregateArg &)basehelper)
  21876. {
  21877. done = false;
  21878. }
  21879. virtual bool needsAllocator() const { return true; }
  21880. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21881. {
  21882. done = false;
  21883. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  21884. }
  21885. virtual const void *nextRow()
  21886. {
  21887. ActivityTimer t(totalCycles, timeActivities);
  21888. if (done) return NULL;
  21889. done = true;
  21890. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  21891. size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
  21892. return rowBuilder.finalizeRowClear(thisSize);
  21893. }
  21894. };
  21895. class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
  21896. {
  21897. IHThorCompoundAggregateExtra & aggregateHelper;
  21898. bool done;
  21899. public:
  21900. CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  21901. const RemoteActivityId &_remoteId, bool _isLocal)
  21902. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  21903. aggregateHelper((IHThorIndexAggregateArg &)basehelper),
  21904. done(false)
  21905. {
  21906. }
  21907. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  21908. {
  21909. done = false;
  21910. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  21911. if (!paused)
  21912. processAllKeys();
  21913. }
  21914. virtual bool needsAllocator() const { return true; }
  21915. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  21916. {
  21917. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21918. while (tlk->lookup(true))
  21919. {
  21920. if (!rowBuilder.exists())
  21921. {
  21922. rowBuilder.ensureRow();
  21923. aggregateHelper.clearAggregate(rowBuilder);
  21924. }
  21925. try
  21926. {
  21927. aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer());
  21928. callback.finishedRow();
  21929. }
  21930. catch (IException *E)
  21931. {
  21932. throw makeWrappedException(E);
  21933. }
  21934. accepted++;
  21935. }
  21936. if (aggregateHelper.processedAnyRows())
  21937. {
  21938. size32_t size = meta.getRecordSize(rowBuilder.getSelf());
  21939. const void * recBuffer = rowBuilder.finalizeRowClear(size);
  21940. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  21941. result->append(recBuffer);
  21942. remote.injectResult(result.getClear());
  21943. }
  21944. return false;
  21945. }
  21946. virtual void onLimitExceeded(bool isKeyed)
  21947. {
  21948. if (traceLevel > 4)
  21949. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  21950. throwUnexpected();
  21951. }
  21952. virtual const void *createLimitFailRow(bool isKeyed)
  21953. {
  21954. throwUnexpected();
  21955. }
  21956. const void * gatherMerged()
  21957. {
  21958. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  21959. const void * firstRow = remote.nextRow();
  21960. size32_t finalSize = 0;
  21961. if (!firstRow)
  21962. {
  21963. rowBuilder.ensureRow();
  21964. finalSize = aggregateHelper.clearAggregate(rowBuilder);
  21965. }
  21966. else
  21967. {
  21968. // NOTE need to clone this because going to modify below, could special case 1 row only
  21969. finalSize = cloneRow(rowBuilder, firstRow, meta);
  21970. ReleaseRoxieRow(firstRow);
  21971. }
  21972. for (;;)
  21973. {
  21974. const void * next = remote.nextRow();
  21975. if (!next)
  21976. break;
  21977. finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
  21978. ReleaseRoxieRow(next);
  21979. }
  21980. return rowBuilder.finalizeRowClear(finalSize);
  21981. }
  21982. virtual const void *nextRow()
  21983. {
  21984. ActivityTimer t(totalCycles, timeActivities);
  21985. if (done) return NULL;
  21986. const void * ret = gatherMerged();
  21987. processed++;
  21988. done = true;
  21989. return ret;
  21990. }
  21991. };
  21992. class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  21993. {
  21994. public:
  21995. CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  21996. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  21997. {
  21998. }
  21999. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22000. {
  22001. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22002. return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
  22003. // else if (isSimple)
  22004. // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22005. else
  22006. return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22007. }
  22008. };
  22009. IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22010. {
  22011. return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22012. }
  22013. //--------------------------------------------------------------------------------------------------------------------------
  22014. class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
  22015. {
  22016. IHThorCompoundGroupAggregateExtra & aggregateHelper;
  22017. RowAggregator singleAggregator;
  22018. RowAggregator resultAggregator;
  22019. unsigned groupSegCount;
  22020. bool gathered;
  22021. bool eof;
  22022. public:
  22023. CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager,
  22024. const RemoteActivityId &_remoteId, bool _isLocal)
  22025. : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, false, _isLocal, false),
  22026. aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
  22027. singleAggregator(aggregateHelper, aggregateHelper),
  22028. resultAggregator(aggregateHelper, aggregateHelper),
  22029. gathered(false), eof(true)
  22030. {
  22031. groupSegCount = 0;
  22032. }
  22033. IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
  22034. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22035. {
  22036. eof = false;
  22037. gathered= false;
  22038. CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
  22039. groupSegCount = 0;
  22040. if (!paused)
  22041. processAllKeys();
  22042. resultAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  22043. }
  22044. virtual bool needsAllocator() const { return true; }
  22045. virtual void reset()
  22046. {
  22047. resultAggregator.reset();
  22048. CRoxieServerIndexActivity::reset();
  22049. }
  22050. virtual void processRow(const void * next)
  22051. {
  22052. singleAggregator.addRow(next);
  22053. }
  22054. virtual void createSegmentMonitors(IKeyManager *key)
  22055. {
  22056. ThorActivityKind kind = factory->getKind();
  22057. CRoxieServerIndexActivity::createSegmentMonitors(key);
  22058. if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
  22059. groupSegCount = aggregateHelper.getGroupingMaxField();
  22060. else
  22061. groupSegCount = 0;
  22062. }
  22063. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22064. {
  22065. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  22066. singleAggregator.start(rowAllocator, ctx->queryCodeContext(), activityId);
  22067. ThorActivityKind kind = factory->getKind();
  22068. while (tlk->lookup(true))
  22069. {
  22070. try
  22071. {
  22072. if (groupSegCount && !trans)
  22073. {
  22074. AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer());
  22075. callback.finishedRow();
  22076. if (kind==TAKindexgroupcount)
  22077. {
  22078. unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
  22079. aggregateHelper.processCountGrouping(rowBuilder, count-1);
  22080. }
  22081. if (!tlk->nextRange(groupSegCount))
  22082. break;
  22083. }
  22084. else
  22085. {
  22086. aggregateHelper.processRow(tlk->queryKeyBuffer(), this);
  22087. callback.finishedRow();
  22088. }
  22089. }
  22090. catch (IException *E)
  22091. {
  22092. throw makeWrappedException(E);
  22093. }
  22094. accepted++;
  22095. }
  22096. for (;;)
  22097. {
  22098. Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
  22099. if (!next)
  22100. break;
  22101. result->append(next->finalizeRowClear());
  22102. }
  22103. remote.injectResult(result.getClear());
  22104. singleAggregator.reset();
  22105. return false;
  22106. }
  22107. virtual void onLimitExceeded(bool isKeyed)
  22108. {
  22109. if (traceLevel > 4)
  22110. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22111. throwUnexpected();
  22112. }
  22113. virtual const void *createLimitFailRow(bool isKeyed)
  22114. {
  22115. throwUnexpected();
  22116. }
  22117. void gatherMerged()
  22118. {
  22119. gathered = true;
  22120. for (;;)
  22121. {
  22122. const void * next = remote.nextRow();
  22123. if (!next)
  22124. break;
  22125. resultAggregator.mergeElement(next);
  22126. ReleaseRoxieRow(next);
  22127. }
  22128. }
  22129. virtual const void *nextRow()
  22130. {
  22131. ActivityTimer t(totalCycles, timeActivities);
  22132. if (eof)
  22133. return NULL;
  22134. if (!gathered)
  22135. gatherMerged();
  22136. Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
  22137. if (next)
  22138. {
  22139. processed++;
  22140. return next->finalizeRowClear();
  22141. }
  22142. eof = true;
  22143. return NULL;
  22144. }
  22145. };
  22146. class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22147. {
  22148. public:
  22149. CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22150. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22151. {
  22152. }
  22153. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22154. {
  22155. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22156. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22157. // else if (isSimple)
  22158. // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
  22159. else
  22160. return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, isLocal);
  22161. }
  22162. };
  22163. IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22164. {
  22165. return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22166. }
  22167. //--------------------------------------------------------------------------------------------------------------------------
  22168. class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
  22169. {
  22170. IHThorIndexNormalizeArg & readHelper;
  22171. public:
  22172. CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const CRoxieServerBaseIndexActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
  22173. bool _sorted, bool _isLocal)
  22174. : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _sorted, _isLocal, false),
  22175. readHelper((IHThorIndexNormalizeArg &)basehelper)
  22176. {
  22177. limitTransformExtra = &readHelper;
  22178. }
  22179. virtual bool needsAllocator() const { return true; }
  22180. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22181. {
  22182. CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
  22183. rowLimit = readHelper.getRowLimit();
  22184. keyedLimit = readHelper.getKeyedLimit();
  22185. choosenLimit = readHelper.getChooseNLimit();
  22186. if (!paused)
  22187. processAllKeys();
  22188. }
  22189. virtual bool processSingleKey(IKeyIndex *key, const IDynamicTransform * trans) override
  22190. {
  22191. unsigned keyedCount = 0;
  22192. RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
  22193. while (tlk->lookup(true))
  22194. {
  22195. keyedCount++;
  22196. if (keyedCount > keyedLimit)
  22197. {
  22198. if (traceLevel > 4)
  22199. DBGLOG("activityid = %d line = %d", activityId, __LINE__);
  22200. onLimitExceeded(true);
  22201. break;
  22202. }
  22203. size32_t transformedSize;
  22204. if (readHelper.first(tlk->queryKeyBuffer()))
  22205. {
  22206. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  22207. do
  22208. {
  22209. if (accepted>=choosenLimit)
  22210. break;
  22211. rowBuilder.ensureRow();
  22212. try
  22213. {
  22214. transformedSize = readHelper.transform(rowBuilder);
  22215. }
  22216. catch (IException *E)
  22217. {
  22218. throw makeWrappedException(E);
  22219. }
  22220. if (transformedSize)
  22221. {
  22222. // MORE - would be a good idea to stop these asap if rowlimit exceeded
  22223. result->append(rowBuilder.finalizeRowClear(transformedSize));
  22224. accepted++;
  22225. }
  22226. else
  22227. rejected++;
  22228. } while (readHelper.next());
  22229. remote.injectResult(result.getClear());
  22230. callback.finishedRow();
  22231. if (accepted>=choosenLimit)
  22232. return true;
  22233. }
  22234. }
  22235. return false;
  22236. }
  22237. virtual void onLimitExceeded(bool isKeyed)
  22238. {
  22239. if (traceLevel > 4)
  22240. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22241. if (isKeyed)
  22242. {
  22243. if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
  22244. {
  22245. if (ctx->queryDebugContext())
  22246. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22247. throw makeLimitSkipException(true);
  22248. }
  22249. else
  22250. readHelper.onKeyedLimitExceeded();
  22251. }
  22252. else
  22253. {
  22254. if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
  22255. {
  22256. if (ctx->queryDebugContext())
  22257. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  22258. throw makeLimitSkipException(false);
  22259. }
  22260. else
  22261. readHelper.onLimitExceeded();
  22262. }
  22263. }
  22264. virtual const void *createLimitFailRow(bool isKeyed)
  22265. {
  22266. UNIMPLEMENTED;
  22267. }
  22268. };
  22269. class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
  22270. {
  22271. public:
  22272. CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22273. : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
  22274. {
  22275. }
  22276. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22277. {
  22278. if (!variableFileName && (keySet==NULL || keySet->length()==0))
  22279. return new CRoxieServerNullActivity(_ctx, this, _probeManager);
  22280. else
  22281. return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, sorted, isLocal);
  22282. }
  22283. };
  22284. IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22285. {
  22286. return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22287. }
  22288. //=================================================================================
  22289. class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22290. {
  22291. IHThorFetchBaseArg &helper;
  22292. Linked<IFilePartMap> map;
  22293. CRemoteResultAdaptor remote;
  22294. RecordPullerThread puller;
  22295. bool needsRHS;
  22296. bool variableFileName;
  22297. bool isOpt;
  22298. Owned<const IResolvedFile> varFileInfo;
  22299. Owned<IEngineRowAllocator> extractAllocator;
  22300. public:
  22301. CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
  22302. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
  22303. {
  22304. needsRHS = helper.transformNeedsRhs();
  22305. if (needsRHS)
  22306. extractAllocator.setown(createRowAllocator(helper.queryExtractedSize()));
  22307. variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22308. isOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  22309. }
  22310. virtual const IResolvedFile *queryVarFileInfo() const
  22311. {
  22312. return varFileInfo;
  22313. }
  22314. virtual void onCreate(IHThorArg *_colocalParent)
  22315. {
  22316. CRoxieServerActivity::onCreate(_colocalParent);
  22317. remote.onCreate(_colocalParent);
  22318. }
  22319. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22320. {
  22321. if (idx)
  22322. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22323. puller.setInput(this, _sourceIdx, _in);
  22324. }
  22325. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22326. {
  22327. puller.connectInputStreams(ctx, consumerOrdered);
  22328. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22329. }
  22330. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22331. {
  22332. if (idx==0)
  22333. return puller.queryInput();
  22334. else
  22335. return NULL;
  22336. }
  22337. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  22338. {
  22339. CRoxieServerActivity::gatherStats(merged);
  22340. remote.gatherStats(merged);
  22341. }
  22342. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22343. {
  22344. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  22345. remote.onStart(parentExtractSize, parentExtract);
  22346. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  22347. if (variableFileName)
  22348. {
  22349. OwnedRoxieString fname(helper.getFileName());
  22350. varFileInfo.setown(resolveLFNFlat(fname, isOpt));
  22351. if (varFileInfo)
  22352. map.setown(varFileInfo->getFileMap());
  22353. }
  22354. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
  22355. }
  22356. virtual void stop()
  22357. {
  22358. // Called from remote, so no need to call back to it....
  22359. puller.stop();
  22360. CRoxieServerActivity::stop();
  22361. }
  22362. virtual void reset()
  22363. {
  22364. processed = remote.processed;
  22365. remote.processed = 0;
  22366. puller.reset();
  22367. if (variableFileName)
  22368. {
  22369. varFileInfo.clear();
  22370. map.clear();
  22371. }
  22372. CRoxieServerActivity::reset();
  22373. }
  22374. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  22375. {
  22376. if (idx==(unsigned)-1)
  22377. idx = 0;
  22378. return idx ? NULL : &remote;
  22379. }
  22380. virtual void processRow(const void *row)
  22381. {
  22382. // called from puller thread
  22383. offset_t rp = helper.extractPosition(row);
  22384. unsigned partNo;
  22385. if (isLocalFpos(rp))
  22386. partNo = getLocalFposPart(rp) + 1;
  22387. else
  22388. partNo = map->mapOffset(rp);
  22389. if (needsRHS)
  22390. {
  22391. RtlDynamicRowBuilder rb(extractAllocator, true);
  22392. unsigned rhsSize = helper.extractJoinFields(rb, row);
  22393. char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
  22394. *(offset_t *) block = rp;
  22395. block += sizeof(rp);
  22396. *(unsigned *) block = rhsSize;
  22397. block += sizeof(rhsSize);
  22398. memcpy(block, rb.row(), rhsSize);
  22399. }
  22400. else
  22401. *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
  22402. ReleaseRoxieRow(row);
  22403. }
  22404. void processEOG()
  22405. {
  22406. #ifdef FETCH_PRESERVES_GROUPING
  22407. UNIMPLEMENTED;
  22408. #endif
  22409. // else discard is correct
  22410. }
  22411. void processGroup(const ConstPointerArray &)
  22412. {
  22413. throwUnexpected();
  22414. }
  22415. void processDone()
  22416. {
  22417. // called from puller thread
  22418. remote.flush();
  22419. remote.senddone();
  22420. }
  22421. virtual bool fireException(IException *e)
  22422. {
  22423. return remote.fireException(e);
  22424. }
  22425. virtual void onLimitExceeded(bool isKeyed)
  22426. {
  22427. if (traceLevel > 4)
  22428. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  22429. if (isKeyed)
  22430. throwUnexpected();
  22431. helper.onLimitExceeded();
  22432. }
  22433. virtual const void *createLimitFailRow(bool isKeyed)
  22434. {
  22435. UNIMPLEMENTED;
  22436. }
  22437. virtual const void *nextRow()
  22438. {
  22439. throwUnexpected(); // I am nobody's input
  22440. }
  22441. };
  22442. class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
  22443. {
  22444. RemoteActivityId remoteId;
  22445. Owned<IFilePartMap> map;
  22446. bool variableFileName;
  22447. Owned<const IResolvedFile> datafile;
  22448. public:
  22449. CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22450. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
  22451. {
  22452. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22453. variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  22454. if (!variableFileName)
  22455. {
  22456. OwnedRoxieString fname(helper->getFileName());
  22457. datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
  22458. (helper->getFetchFlags() & FFdatafileoptional) != 0,
  22459. true, true,
  22460. _queryFactory.queryWorkUnit(), true));
  22461. if (datafile)
  22462. map.setown(datafile->getFileMap());
  22463. }
  22464. }
  22465. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  22466. {
  22467. return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
  22468. }
  22469. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22470. {
  22471. if (datafile)
  22472. addXrefFileInfo(reply, datafile);
  22473. else
  22474. {
  22475. // Temporarily resolve the file
  22476. Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
  22477. if ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
  22478. {
  22479. OwnedRoxieString fileName(helper->getFileName());
  22480. Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
  22481. if (temp)
  22482. addXrefFileInfo(reply, temp);
  22483. }
  22484. }
  22485. }
  22486. virtual const StatisticsMapping &queryStatsMapping() const
  22487. {
  22488. return diskStatistics;
  22489. }
  22490. };
  22491. IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
  22492. {
  22493. return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
  22494. }
  22495. // MORE - is there any point keeping this now?
  22496. class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
  22497. {
  22498. public:
  22499. Owned<const IResolvedFile> indexfile;
  22500. Owned<const IResolvedFile> datafile;
  22501. StringAttr fileName;
  22502. StringAttr indexName;
  22503. Owned<IKeyArray> keySet;
  22504. Owned<IFileIOArray> files;
  22505. CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22506. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  22507. {
  22508. try // does not want any missing file errors to be fatal, or throw traps - just log it
  22509. {
  22510. if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
  22511. return; // ignore 'spills'
  22512. bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  22513. ThorActivityKind kind = getActivityKind(_graphNode);
  22514. if (kind != TAKdiskwrite && kind != TAKspillwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
  22515. {
  22516. fileName.set(queryNodeFileName(_graphNode, kind));
  22517. indexName.set(queryNodeIndexName(_graphNode, kind));
  22518. if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
  22519. {
  22520. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
  22521. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22522. if (indexfile)
  22523. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  22524. }
  22525. if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
  22526. {
  22527. bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
  22528. datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  22529. if (datafile)
  22530. {
  22531. if (isLocal)
  22532. files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
  22533. }
  22534. }
  22535. }
  22536. }
  22537. catch(IException *E)
  22538. {
  22539. StringBuffer errors;
  22540. E->errorMessage(errors);
  22541. OERRLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
  22542. E->Release();
  22543. }
  22544. }
  22545. 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__); }
  22546. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  22547. {
  22548. if (!allFilesDynamic)
  22549. {
  22550. if (datafile)
  22551. addXrefFileInfo(reply, datafile);
  22552. if (indexfile)
  22553. addXrefFileInfo(reply, indexfile);
  22554. }
  22555. else
  22556. {
  22557. Owned<const IResolvedFile> temp;
  22558. if (fileName.length())
  22559. {
  22560. temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
  22561. if (temp)
  22562. addXrefFileInfo(reply, temp);
  22563. }
  22564. if (indexName.length())
  22565. {
  22566. temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
  22567. if (temp)
  22568. addXrefFileInfo(reply, temp);
  22569. }
  22570. }
  22571. }
  22572. };
  22573. IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
  22574. {
  22575. return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
  22576. }
  22577. //=====================================================================================================
  22578. // Keyed joins...
  22579. //
  22580. // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
  22581. // may have RHS matches on, and sends the relevant fields to the relevant slaves.
  22582. // 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
  22583. // the transform and returns rows that are created.
  22584. // 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)
  22585. //
  22586. //=====================================================================================================
  22587. class CJoinGroup;
  22588. interface IJoinProcessor
  22589. {
  22590. virtual void processEOG() = 0;
  22591. virtual CJoinGroup *createJoinGroup(const void *row) = 0;
  22592. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
  22593. virtual bool fireException(IException *E) = 0;
  22594. virtual void processCompletedGroups() = 0;
  22595. };
  22596. //------------------------------------------------------------------------------------------------------
  22597. // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
  22598. // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
  22599. // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
  22600. // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
  22601. // per-query limits etc (Note that the pointer array block is not though).
  22602. // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
  22603. //
  22604. // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
  22605. // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
  22606. // initial count when created.
  22607. // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
  22608. // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
  22609. // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
  22610. // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
  22611. // remaining reference and the JoinGroup will be processed and destroyed.
  22612. //
  22613. //------------------------------------------------------------------------------------------------------
  22614. class CJoinGroup : public CInterface
  22615. {
  22616. protected:
  22617. const void *left; // LHS row
  22618. PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
  22619. atomic_t endMarkersPending; // How many slave responses still waiting for
  22620. CJoinGroup *groupStart; // Head of group, or NULL if not grouping
  22621. unsigned lastPartNo;
  22622. unsigned pos;
  22623. unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
  22624. public:
  22625. void *operator new(size_t size, IRowManager *a, unsigned activityId)
  22626. {
  22627. return a->allocate(size, activityId);
  22628. }
  22629. void operator delete(void *ptr, IRowManager *a, unsigned activityId)
  22630. {
  22631. ReleaseRoxieRow(ptr);
  22632. }
  22633. void operator delete(void *ptr)
  22634. {
  22635. ReleaseRoxieRow(ptr);
  22636. }
  22637. public:
  22638. CJoinGroup(const void *_left, CJoinGroup *_groupStart)
  22639. {
  22640. #ifdef TRACE_JOINGROUPS
  22641. DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
  22642. #endif
  22643. candidates = 0;
  22644. lastPartNo = 0;
  22645. pos = 0;
  22646. left = _left;
  22647. groupStart = _groupStart;
  22648. if (_groupStart)
  22649. {
  22650. atomic_inc(&_groupStart->endMarkersPending);
  22651. }
  22652. atomic_set(&endMarkersPending, 1);
  22653. }
  22654. ~CJoinGroup()
  22655. {
  22656. #ifdef TRACE_JOINGROUPS
  22657. DBGLOG("Destroying joinGroup %p", this);
  22658. #endif
  22659. if (left)
  22660. {
  22661. ReleaseRoxieRow(left);
  22662. roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
  22663. rows.kill();
  22664. }
  22665. }
  22666. inline bool isHeadRecord() const
  22667. {
  22668. return left==NULL;
  22669. }
  22670. inline bool complete() const
  22671. {
  22672. return atomic_read(&endMarkersPending) == 0;
  22673. }
  22674. #ifdef TRACE_JOINGROUPS
  22675. inline void notePending(unsigned lineNo)
  22676. #else
  22677. inline void notePending()
  22678. #endif
  22679. {
  22680. assert(!complete());
  22681. atomic_inc(&endMarkersPending);
  22682. #ifdef TRACE_JOINGROUPS
  22683. DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
  22684. #endif
  22685. }
  22686. inline bool inGroup(CJoinGroup *leader) const
  22687. {
  22688. return groupStart==leader;
  22689. }
  22690. inline const KeyedJoinHeader *queryRow(unsigned idx) const
  22691. {
  22692. // Single threaded by now
  22693. assert(complete());
  22694. return rows.item(idx);
  22695. }
  22696. #ifdef TRACE_JOINGROUPS
  22697. bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
  22698. #else
  22699. bool noteEndReceived(unsigned candidateCount)
  22700. #endif
  22701. {
  22702. assert(!complete());
  22703. if (candidateCount)
  22704. {
  22705. candidates += candidateCount;
  22706. }
  22707. #ifdef TRACE_JOINGROUPS
  22708. 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);
  22709. #endif
  22710. // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
  22711. // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
  22712. // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
  22713. CJoinGroup *localGroupStart = groupStart;
  22714. if (atomic_dec_and_test(&endMarkersPending))
  22715. {
  22716. if (localGroupStart)
  22717. return atomic_dec_and_test(&localGroupStart->endMarkersPending);
  22718. else
  22719. return true;
  22720. }
  22721. else
  22722. return false;
  22723. }
  22724. inline const void *queryLeft() const
  22725. {
  22726. return left;
  22727. }
  22728. void addRightMatch(KeyedJoinHeader *right)
  22729. {
  22730. assert(!complete());
  22731. unsigned short partNo = right->partNo;
  22732. if (partNo != lastPartNo)
  22733. {
  22734. // MORE - should we binchop? If we did we would need to be careful to find LAST match
  22735. if (partNo > lastPartNo)
  22736. pos = rows.length();
  22737. while (pos>0)
  22738. {
  22739. if (rows.item(pos-1)->partNo <= partNo)
  22740. break;
  22741. pos--;
  22742. }
  22743. lastPartNo = partNo;
  22744. }
  22745. rows.add(right, pos);
  22746. pos++;
  22747. }
  22748. inline unsigned rowsSeen() const
  22749. {
  22750. assert(complete());
  22751. return rows.length();
  22752. }
  22753. inline unsigned candidateCount() const
  22754. {
  22755. assert(complete());
  22756. return candidates;
  22757. }
  22758. };
  22759. #ifdef TRACE_JOINGROUPS
  22760. #define notePending() notePending(__LINE__)
  22761. #define noteEndReceived(a) noteEndReceived(a, __LINE__)
  22762. #endif
  22763. class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
  22764. {
  22765. private:
  22766. SafeQueueOf<const void, true> ready;
  22767. public:
  22768. IHThorKeyedJoinArg &helper;
  22769. unsigned joinProcessed;
  22770. bool isFullKey;
  22771. bool eof;
  22772. bool isSimple;
  22773. bool allPulled;
  22774. ActivityTimeAccumulator totalCycles;
  22775. unsigned activityId;
  22776. RecordPullerThread &puller;
  22777. SafeQueueOf<const void, true> injected; // Used in isSimple mode
  22778. Owned<IEngineRowAllocator> ccdRecordAllocator;
  22779. IJoinProcessor &processor;
  22780. KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
  22781. IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
  22782. RecordPullerThread &_puller, IJoinProcessor &_processor)
  22783. : CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
  22784. helper(_helper),
  22785. isFullKey(_isFullKey),
  22786. isSimple(_isSimple),
  22787. activityId(_activity.queryId()),
  22788. puller(_puller),
  22789. processor(_processor)
  22790. {
  22791. joinProcessed = 0;
  22792. allPulled = false;
  22793. eof = false;
  22794. }
  22795. virtual void onCreate(IHThorArg *_colocalArg)
  22796. {
  22797. CRemoteResultAdaptor::onCreate(_colocalArg);
  22798. ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
  22799. }
  22800. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  22801. {
  22802. eof = false;
  22803. joinProcessed = 0;
  22804. totalCycles.totalCycles = 0;
  22805. allPulled = false;
  22806. assertex(ready.ordinality()==0);
  22807. CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
  22808. }
  22809. virtual void reset()
  22810. {
  22811. CRemoteResultAdaptor::reset();
  22812. while (ready.ordinality())
  22813. {
  22814. const void *goer = ready.dequeue();
  22815. if (goer)
  22816. ReleaseRoxieRow(goer);
  22817. }
  22818. while (injected.ordinality())
  22819. {
  22820. const void *goer = injected.dequeue();
  22821. if (goer)
  22822. ReleaseRoxieRow(goer);
  22823. }
  22824. }
  22825. inline void addResult(const void *row)
  22826. {
  22827. ready.enqueue(row);
  22828. }
  22829. virtual unsigned __int64 queryTotalCycles() const
  22830. {
  22831. return totalCycles.totalCycles;
  22832. }
  22833. virtual const void *nextRow()
  22834. {
  22835. ActivityTimer t(totalCycles, timeActivities);
  22836. for (;;)
  22837. {
  22838. if (eof)
  22839. return NULL;
  22840. processSlaveResults();
  22841. if (ready.ordinality())
  22842. {
  22843. const void *result = ready.dequeue();
  22844. if (result)
  22845. joinProcessed++;
  22846. return result;
  22847. }
  22848. else
  22849. eof = true;
  22850. }
  22851. }
  22852. void gatherStats(CRuntimeStatisticCollection & merged) const
  22853. {
  22854. CRemoteResultAdaptor::gatherStats(merged);
  22855. if (ccdRecordAllocator)
  22856. ccdRecordAllocator->gatherStats(merged);
  22857. }
  22858. private:
  22859. void processSlaveResults()
  22860. {
  22861. while (!ready.ordinality())
  22862. {
  22863. KeyedJoinHeader *fetchedData;
  22864. if (isSimple)
  22865. {
  22866. while (!allPulled && !injected.ordinality())
  22867. {
  22868. if (!puller.pullRecords(1))
  22869. {
  22870. puller.done();
  22871. allPulled = true;
  22872. }
  22873. }
  22874. fetchedData = (KeyedJoinHeader *) injected.dequeue();
  22875. }
  22876. else
  22877. fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
  22878. if (fetchedData)
  22879. {
  22880. CJoinGroup *thisGroup = fetchedData->thisGroup;
  22881. if (fetchedData->partNo == (unsigned short) -1)
  22882. {
  22883. #ifdef TRACE_JOINGROUPS
  22884. CTXLOG("Got end for group %p", thisGroup);
  22885. #endif
  22886. unsigned candidateCount = (unsigned) fetchedData->fpos;
  22887. ReleaseRoxieRow(fetchedData);
  22888. processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
  22889. }
  22890. else
  22891. {
  22892. #ifdef TRACE_JOINGROUPS
  22893. CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
  22894. #endif
  22895. thisGroup->addRightMatch(fetchedData);
  22896. if (isFullKey)
  22897. {
  22898. #ifdef TRACE_JOINGROUPS
  22899. CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
  22900. #endif
  22901. processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
  22902. }
  22903. }
  22904. }
  22905. else
  22906. break;
  22907. }
  22908. }
  22909. };
  22910. class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
  22911. {
  22912. IHThorKeyedJoinArg &helper;
  22913. Owned<IKeyManager> tlk;
  22914. Linked<IKeyArray> keySet;
  22915. Linked<ITranslatorSet> translators;
  22916. CRemoteResultAdaptor remote;
  22917. RecordPullerThread puller;
  22918. IOutputMetaData *indexReadMeta;
  22919. IJoinProcessor *joinHandler;
  22920. bool variableIndexFileName;
  22921. bool indexReadInputRecordVariable;
  22922. bool isLocal;
  22923. Owned<IEngineRowAllocator> indexReadAllocator;
  22924. Owned<const IResolvedFile> varFileInfo;
  22925. IFinalRoxieInput *indexReadInput;
  22926. unsigned indexReadIdx = 0;
  22927. IIndexReadActivityInfo *rootIndex;
  22928. public:
  22929. CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
  22930. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  22931. helper((IHThorKeyedJoinArg &)basehelper),
  22932. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors(), !isBlind())),
  22933. keySet(_keySet),
  22934. translators(_translators),
  22935. remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
  22936. puller(false),
  22937. indexReadMeta(_indexReadMeta),
  22938. joinHandler(_joinHandler),
  22939. isLocal(_isLocal)
  22940. {
  22941. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  22942. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  22943. indexReadInput = NULL;
  22944. rootIndex = NULL;
  22945. }
  22946. virtual const IResolvedFile *queryVarFileInfo() const
  22947. {
  22948. return varFileInfo;
  22949. }
  22950. virtual void onCreate(IHThorArg *_colocalParent)
  22951. {
  22952. CRoxieServerActivity::onCreate(_colocalParent);
  22953. remote.onCreate(_colocalParent);
  22954. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  22955. }
  22956. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  22957. {
  22958. if (!idx)
  22959. puller.setInput(this, _sourceIdx, _in);
  22960. else if (idx==1)
  22961. {
  22962. indexReadInput = _in;
  22963. indexReadIdx = _sourceIdx;
  22964. }
  22965. else
  22966. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  22967. }
  22968. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  22969. {
  22970. puller.connectInputStreams(ctx, consumerOrdered);
  22971. //No rows are read from indexReadInput, so no need to extract the streams
  22972. return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  22973. }
  22974. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  22975. {
  22976. switch (idx)
  22977. {
  22978. case 0:
  22979. return puller.queryInput();
  22980. case 1:
  22981. return indexReadInput;
  22982. default:
  22983. return NULL;
  22984. }
  22985. }
  22986. virtual void serializeExtra(MemoryBuffer &out)
  22987. {
  22988. if (helper.getJoinFlags() & JFindexfromactivity)
  22989. {
  22990. assertex(rootIndex);
  22991. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  22992. indexId.serialize(out);
  22993. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  22994. MemoryBuffer tmp;
  22995. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  22996. if (rootIndex->queryActivity()->queryVarFileInfo())
  22997. {
  22998. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  22999. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23000. }
  23001. unsigned ctxlen = tmp.length();
  23002. out.append(ctxlen).append(tmp);
  23003. }
  23004. }
  23005. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23006. {
  23007. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23008. if (indexReadInput)
  23009. {
  23010. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23011. rootIndex = indexReadInput->queryIndexReadActivity();
  23012. if (!rootIndex)
  23013. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23014. }
  23015. remote.onStart(parentExtractSize, parentExtract);
  23016. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23017. if (rootIndex)
  23018. {
  23019. varFileInfo.setown(rootIndex->getVarFileInfo());
  23020. translators.setown(rootIndex->getTranslators());
  23021. keySet.setown(rootIndex->getKeySet());
  23022. }
  23023. else if (variableIndexFileName)
  23024. {
  23025. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23026. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23027. if (varFileInfo)
  23028. {
  23029. unsigned expectedCrc = helper.getIndexFormatCrc();
  23030. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23031. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23032. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23033. }
  23034. }
  23035. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
  23036. }
  23037. virtual void stop()
  23038. {
  23039. puller.stop();
  23040. CRoxieServerActivity::stop();
  23041. }
  23042. virtual void reset()
  23043. {
  23044. CRoxieServerActivity::reset();
  23045. puller.reset();
  23046. if (varFileInfo)
  23047. {
  23048. keySet.clear();
  23049. varFileInfo.clear();
  23050. }
  23051. }
  23052. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23053. {
  23054. if (idx==(unsigned)-1)
  23055. idx = 0;
  23056. return idx ? NULL : &remote;
  23057. }
  23058. virtual void processRow(const void *row)
  23059. {
  23060. // MORE - this code seems to be pretty much duplicated below in half-keyed....
  23061. // called from front puller thread
  23062. // buffer up an IndexRead request
  23063. if (keySet && helper.leftCanMatch(row))
  23064. {
  23065. RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
  23066. unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
  23067. OwnedConstRoxieRow extracted;
  23068. if (indexReadSize)
  23069. extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
  23070. CJoinGroup *jg = joinHandler->createJoinGroup(row);
  23071. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23072. {
  23073. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23074. if (thisBase)
  23075. {
  23076. unsigned fileNo = 0;
  23077. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23078. try
  23079. {
  23080. tlk->setKey(thisKey);
  23081. if (!thisKey->isTopLevelKey())
  23082. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23083. else
  23084. tlk->setLayoutTranslator(nullptr);
  23085. helper.createSegmentMonitors(tlk, extracted);
  23086. if (rootIndex)
  23087. rootIndex->mergeSegmentMonitors(tlk);
  23088. tlk->finishSegmentMonitors();
  23089. tlk->reset();
  23090. for (;;)
  23091. {
  23092. typedef const void * cvp;
  23093. if (thisKey->isTopLevelKey())
  23094. {
  23095. bool locallySorted = !thisKey->isFullySorted();
  23096. while (locallySorted || tlk->lookup(false))
  23097. {
  23098. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23099. if (locallySorted || slavePart)
  23100. {
  23101. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23102. *outputBuffer++ = jg;
  23103. if (indexReadInputRecordVariable)
  23104. {
  23105. *(unsigned *) outputBuffer = indexReadSize;
  23106. outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
  23107. }
  23108. jg->notePending();
  23109. memcpy(outputBuffer, extracted, indexReadSize);
  23110. if (!slavePart)
  23111. {
  23112. for (unsigned i = 1; i < numChannels; i++)
  23113. jg->notePending();
  23114. }
  23115. if (locallySorted)
  23116. break;
  23117. }
  23118. }
  23119. }
  23120. else
  23121. {
  23122. // MORE - this code seems to be duplicated in half keyed
  23123. unsigned accepted = 0;
  23124. unsigned rejected = 0;
  23125. Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult();
  23126. jg->notePending();
  23127. unsigned candidateCount = 0;
  23128. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23129. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23130. while (tlk->lookup(true))
  23131. {
  23132. candidateCount++;
  23133. indexRecordsRead++;
  23134. KLBlobProviderAdapter adapter(tlk);
  23135. const byte *indexRow = tlk->queryKeyBuffer();
  23136. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23137. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23138. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23139. {
  23140. KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23141. rhs->fpos = fpos;
  23142. rhs->thisGroup = jg;
  23143. rhs->partNo = partNo;
  23144. result->append(rhs);
  23145. }
  23146. else
  23147. {
  23148. rejected++;
  23149. postFiltered++;
  23150. }
  23151. }
  23152. // output an end marker for the matches to this group
  23153. KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23154. endMarker->fpos = (offset_t) candidateCount;
  23155. endMarker->thisGroup = jg;
  23156. endMarker->partNo = (unsigned short) -1;
  23157. result->append(endMarker);
  23158. remote.injectResult(result.getClear());
  23159. if (accepted)
  23160. noteStatistic(StNumIndexAccepted, accepted);
  23161. if (rejected)
  23162. noteStatistic(StNumIndexRejected, rejected);
  23163. }
  23164. if (++fileNo < thisBase->numParts())
  23165. {
  23166. thisKey = thisBase->queryPart(fileNo);
  23167. tlk->setKey(thisKey);
  23168. if (!thisKey->isTopLevelKey())
  23169. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23170. else
  23171. tlk->setLayoutTranslator(nullptr);
  23172. tlk->reset();
  23173. }
  23174. else
  23175. break;
  23176. }
  23177. tlk->releaseSegmentMonitors();
  23178. tlk->setKey(NULL);
  23179. }
  23180. catch (...)
  23181. {
  23182. tlk->releaseSegmentMonitors();
  23183. tlk->setKey(NULL);
  23184. throw;
  23185. }
  23186. }
  23187. }
  23188. joinHandler->noteEndReceived(jg, 0);
  23189. }
  23190. else
  23191. {
  23192. joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
  23193. }
  23194. }
  23195. void processGroup(const ConstPointerArray &)
  23196. {
  23197. throwUnexpected();
  23198. }
  23199. virtual void processEOG()
  23200. {
  23201. joinHandler->processEOG();
  23202. }
  23203. virtual void processDone()
  23204. {
  23205. // called from puller thread
  23206. remote.flush();
  23207. remote.senddone();
  23208. }
  23209. virtual void onLimitExceeded(bool isKeyed)
  23210. {
  23211. if (traceLevel > 4)
  23212. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23213. if (isKeyed)
  23214. throwUnexpected();
  23215. helper.onLimitExceeded();
  23216. }
  23217. virtual const void *createLimitFailRow(bool isKeyed)
  23218. {
  23219. throwUnexpected();
  23220. }
  23221. virtual bool fireException(IException *e)
  23222. {
  23223. // called from puller thread on failure
  23224. remote.fireException(LINK(e));
  23225. return joinHandler->fireException(e);
  23226. }
  23227. virtual const void *nextRow()
  23228. {
  23229. throwUnexpected(); // I am nobody's input
  23230. }
  23231. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23232. {
  23233. CRoxieServerActivity::gatherStats(merged);
  23234. remote.gatherStats(merged);
  23235. if (indexReadAllocator)
  23236. indexReadAllocator->gatherStats(merged);
  23237. }
  23238. };
  23239. class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
  23240. {
  23241. protected:
  23242. IHThorKeyedJoinArg &helper;
  23243. KeyedJoinRemoteAdaptor remote;
  23244. RecordPullerThread puller;
  23245. OwnedConstRoxieRow defaultRight;
  23246. Owned<IEngineRowAllocator> defaultRightAllocator;
  23247. unsigned joinFlags;
  23248. unsigned atMost;
  23249. unsigned atmostsTriggered;
  23250. unsigned abortLimit;
  23251. unsigned keepLimit;
  23252. bool limitFail;
  23253. bool limitOnFail;
  23254. bool preserveGroups;
  23255. bool cloneLeft;
  23256. bool isSimple;
  23257. bool isLocal;
  23258. ThorActivityKind activityKind;
  23259. CJoinGroup *groupStart;
  23260. CriticalSection groupsCrit;
  23261. QueueOf<CJoinGroup, false> groups;
  23262. IFinalRoxieInput *indexReadInput;
  23263. unsigned indexReadIdx = 0;
  23264. Owned<IStrandJunction> indexReadJunction;
  23265. IEngineRowStream *indexReadStream = NULL; // Never actually pulled
  23266. IIndexReadActivityInfo *rootIndex;
  23267. void createDefaultRight()
  23268. {
  23269. if (!defaultRight)
  23270. {
  23271. if (!defaultRightAllocator)
  23272. defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
  23273. RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
  23274. size32_t thisSize = helper.createDefaultRight(rowBuilder);
  23275. defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
  23276. }
  23277. }
  23278. public:
  23279. CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
  23280. , bool isFull, bool _isSimple, bool _isLocal)
  23281. : CRoxieServerActivity(_ctx, _factory, _probeManager),
  23282. helper((IHThorKeyedJoinArg &)basehelper),
  23283. remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
  23284. puller(false),
  23285. joinFlags(_joinFlags),
  23286. atMost(0),
  23287. abortLimit(0),
  23288. keepLimit(0),
  23289. limitFail(false),
  23290. limitOnFail(false),
  23291. preserveGroups(meta.isGrouped()),
  23292. cloneLeft(false),
  23293. isSimple(_isSimple),
  23294. isLocal(_isLocal)
  23295. {
  23296. groupStart = NULL;
  23297. activityKind = _factory->getKind();
  23298. indexReadInput = NULL;
  23299. rootIndex = NULL;
  23300. atmostsTriggered = 0;
  23301. // MORE - code would be easier to read if I got more values from helper rather than passing from factory
  23302. }
  23303. virtual void onCreate(IHThorArg *_colocalParent)
  23304. {
  23305. CRoxieServerActivity::onCreate(_colocalParent);
  23306. remote.onCreate(_colocalParent);
  23307. }
  23308. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23309. {
  23310. if (!idx)
  23311. puller.setInput(this, _sourceIdx, _in);
  23312. else if (idx==1)
  23313. {
  23314. indexReadInput = _in;
  23315. indexReadIdx = _sourceIdx;
  23316. }
  23317. else
  23318. throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
  23319. }
  23320. virtual void connectInputStreams(bool consumerOrdered)
  23321. {
  23322. CRoxieServerActivity::connectInputStreams(consumerOrdered);
  23323. puller.connectInputStreams(ctx, consumerOrdered);
  23324. if (indexReadInput)
  23325. indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
  23326. }
  23327. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23328. {
  23329. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  23330. if (indexReadInput)
  23331. {
  23332. indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
  23333. rootIndex = indexReadInput->queryIndexReadActivity();
  23334. if (!rootIndex)
  23335. throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
  23336. }
  23337. remote.onStart(parentExtractSize, parentExtract);
  23338. remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
  23339. atmostsTriggered = 0;
  23340. atMost = helper.getJoinLimit();
  23341. if (atMost == 0) atMost = (unsigned)-1;
  23342. abortLimit = helper.getMatchAbortLimit();
  23343. if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
  23344. keepLimit = helper.getKeepLimit();
  23345. if (keepLimit == 0) keepLimit = (unsigned)-1;
  23346. getLimitType(joinFlags, limitFail, limitOnFail);
  23347. cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
  23348. if ((joinFlags & JFleftouter) || limitOnFail)
  23349. createDefaultRight();
  23350. }
  23351. virtual void stop()
  23352. {
  23353. puller.stop();
  23354. if (indexReadStream)
  23355. indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
  23356. CRoxieServerActivity::stop();
  23357. }
  23358. virtual unsigned __int64 queryLocalCycles() const
  23359. {
  23360. __int64 localCycles = remote.totalCycles.totalCycles;
  23361. localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
  23362. if (localCycles < 0)
  23363. localCycles = 0;
  23364. return localCycles;
  23365. }
  23366. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23367. {
  23368. CRoxieServerActivity::gatherStats(merged);
  23369. remote.gatherStats(merged);
  23370. }
  23371. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23372. {
  23373. if (idx==0)
  23374. return puller.queryInput();
  23375. else if (idx==1)
  23376. return indexReadInput;
  23377. else
  23378. return NULL;
  23379. }
  23380. virtual void reset()
  23381. {
  23382. totalCycles.totalCycles = remote.totalCycles.totalCycles;
  23383. remote.totalCycles.totalCycles = 0;
  23384. processed = remote.joinProcessed;
  23385. remote.joinProcessed = 0;
  23386. defaultRight.clear();
  23387. if (indexReadInput)
  23388. indexReadInput->reset();
  23389. if (atmostsTriggered)
  23390. noteStatistic(StNumAtmostTriggered, atmostsTriggered);
  23391. CRoxieServerActivity::reset();
  23392. puller.reset();
  23393. while (groups.ordinality())
  23394. {
  23395. ::Release(groups.dequeue());
  23396. }
  23397. }
  23398. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  23399. {
  23400. if (idx==(unsigned)-1)
  23401. idx = 0;
  23402. return idx ? NULL : &remote;
  23403. }
  23404. virtual CJoinGroup *createJoinGroup(const void *row)
  23405. {
  23406. // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
  23407. CriticalBlock c(groupsCrit);
  23408. if (preserveGroups && !groupStart)
  23409. {
  23410. groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
  23411. groups.enqueue(groupStart);
  23412. }
  23413. CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
  23414. groups.enqueue(jg);
  23415. return jg;
  23416. }
  23417. void endGroup()
  23418. {
  23419. CriticalBlock c(groupsCrit);
  23420. if (groupStart)
  23421. noteEndReceived(groupStart, 0);
  23422. groupStart = NULL;
  23423. }
  23424. virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
  23425. {
  23426. if (jg->noteEndReceived(candidateCount))
  23427. processCompletedGroups();
  23428. }
  23429. void processCompletedGroups()
  23430. {
  23431. CriticalBlock c(groupsCrit);
  23432. while (groups.ordinality())
  23433. {
  23434. if (!groups.head()->complete())
  23435. break;
  23436. Owned<CJoinGroup> head = groups.dequeue();
  23437. if (preserveGroups)
  23438. {
  23439. assert(head->isHeadRecord());
  23440. assert(groups.head()->inGroup(head));
  23441. unsigned joinGroupSize = 0;
  23442. while (groups.ordinality() && groups.head()->inGroup(head))
  23443. {
  23444. Owned<CJoinGroup> finger = groups.dequeue();
  23445. joinGroupSize += doJoinGroup(finger);
  23446. }
  23447. if (joinGroupSize)
  23448. remote.addResult(NULL);
  23449. }
  23450. else
  23451. doJoinGroup(head);
  23452. }
  23453. }
  23454. void failLimit(const void * left)
  23455. {
  23456. helper.onMatchAbortLimitExceeded();
  23457. CommonXmlWriter xmlwrite(0);
  23458. if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
  23459. {
  23460. input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
  23461. }
  23462. throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
  23463. }
  23464. virtual bool needsAllocator() const { return true; }
  23465. unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
  23466. {
  23467. if (cloneLeft && !except)
  23468. {
  23469. LinkRoxieRow(left);
  23470. remote.addResult((void *) left);
  23471. return 1;
  23472. }
  23473. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23474. unsigned outSize;
  23475. try
  23476. {
  23477. outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
  23478. (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned)fpos_or_count, group) :
  23479. helper.transform(rowBuilder, left, right, fpos_or_count, counter);
  23480. }
  23481. catch (IException *E)
  23482. {
  23483. throw makeWrappedException(E);
  23484. }
  23485. if (outSize)
  23486. {
  23487. const void *shrunk = rowBuilder.finalizeRowClear(outSize);
  23488. remote.addResult(shrunk);
  23489. return 1;
  23490. }
  23491. else
  23492. return 0;
  23493. }
  23494. unsigned doJoinGroup(CJoinGroup *jg)
  23495. {
  23496. unsigned matched = jg->rowsSeen();
  23497. unsigned added = 0;
  23498. const void *left = jg->queryLeft();
  23499. if (jg->candidateCount() > abortLimit)
  23500. {
  23501. if (limitFail)
  23502. failLimit(left);
  23503. if (ctx->queryDebugContext())
  23504. ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
  23505. if (limitOnFail)
  23506. {
  23507. Owned<IException> except;
  23508. try
  23509. {
  23510. failLimit(left);
  23511. }
  23512. catch(IException * e)
  23513. {
  23514. except.setown(e);
  23515. }
  23516. added = doTransform(left, defaultRight, 0, except, NULL, 0);
  23517. }
  23518. }
  23519. else if (!matched || jg->candidateCount() > atMost)
  23520. {
  23521. if (jg->candidateCount() > atMost)
  23522. atmostsTriggered++;
  23523. switch (joinFlags & JFtypemask)
  23524. {
  23525. case JFleftouter:
  23526. case JFleftonly:
  23527. switch (activityKind)
  23528. {
  23529. case TAKkeyedjoin:
  23530. case TAKkeyeddenormalizegroup:
  23531. added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
  23532. break;
  23533. case TAKkeyeddenormalize:
  23534. LinkRoxieRow(left);
  23535. remote.addResult((void *) left);
  23536. added++;
  23537. break;
  23538. }
  23539. break;
  23540. }
  23541. }
  23542. else if (!(joinFlags & JFexclude))
  23543. {
  23544. unsigned idx = 0;
  23545. switch (activityKind)
  23546. {
  23547. case TAKkeyedjoin:
  23548. while (idx < matched)
  23549. {
  23550. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23551. added += doTransform(left, &rhs->rhsdata, 0, NULL, NULL, idx+1);
  23552. if (added==keepLimit)
  23553. break;
  23554. idx++;
  23555. }
  23556. break;
  23557. case TAKkeyeddenormalize:
  23558. {
  23559. OwnedConstRoxieRow newLeft;
  23560. newLeft.set(left);
  23561. unsigned rowSize = 0;
  23562. unsigned rightAdded = 0;
  23563. while (idx < matched)
  23564. {
  23565. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23566. try
  23567. {
  23568. RtlDynamicRowBuilder rowBuilder(rowAllocator);
  23569. size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
  23570. if (transformedSize)
  23571. {
  23572. rowSize = transformedSize;
  23573. newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
  23574. rightAdded++;
  23575. if (rightAdded==keepLimit)
  23576. break;
  23577. }
  23578. idx++;
  23579. }
  23580. catch (IException *E)
  23581. {
  23582. throw makeWrappedException(E);
  23583. }
  23584. }
  23585. if (rowSize)
  23586. {
  23587. remote.addResult(newLeft.getClear());
  23588. added++;
  23589. }
  23590. }
  23591. break;
  23592. case TAKkeyeddenormalizegroup:
  23593. {
  23594. ConstPointerArray extractedRows;
  23595. while (idx < matched && idx < keepLimit)
  23596. {
  23597. const KeyedJoinHeader *rhs = jg->queryRow(idx);
  23598. extractedRows.append((void *) &rhs->rhsdata);
  23599. idx++;
  23600. }
  23601. added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
  23602. }
  23603. break;
  23604. }
  23605. }
  23606. return added;
  23607. }
  23608. virtual void processDone()
  23609. {
  23610. // called from puller thread
  23611. remote.flush();
  23612. remote.senddone();
  23613. }
  23614. virtual void onLimitExceeded(bool isKeyed)
  23615. {
  23616. if (traceLevel > 4)
  23617. DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
  23618. if (isKeyed)
  23619. throwUnexpected();
  23620. helper.onLimitExceeded();
  23621. }
  23622. virtual const void *createLimitFailRow(bool isKeyed)
  23623. {
  23624. throwUnexpected();
  23625. }
  23626. virtual bool fireException(IException *e)
  23627. {
  23628. // called from puller thread on failure
  23629. return remote.fireException(e);
  23630. }
  23631. virtual const void *nextRow()
  23632. {
  23633. throwUnexpected(); // I am nobody's input
  23634. }
  23635. };
  23636. #ifdef _MSC_VER
  23637. #pragma warning ( push )
  23638. #pragma warning ( disable: 4355 )
  23639. #endif
  23640. class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23641. {
  23642. CRoxieServerFullKeyedJoinHead head;
  23643. Owned<IEngineRowAllocator> fetchInputAllocator;
  23644. Linked<IFilePartMap> map;
  23645. bool variableFetchFileName;
  23646. Owned<const IResolvedFile> varFetchFileInfo;
  23647. CachedOutputMetaData fetchInputFields;
  23648. public:
  23649. CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, ITranslatorSet *_keyTranslators, IOutputMetaData *_indexReadMeta,
  23650. const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
  23651. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
  23652. head(_ctx, _factory, _probeManager, _headId, _key, _keyTranslators, _indexReadMeta, this, _isLocal),
  23653. map(_map)
  23654. {
  23655. CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
  23656. variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  23657. }
  23658. virtual const IResolvedFile *queryVarFileInfo() const
  23659. {
  23660. return varFetchFileInfo;
  23661. }
  23662. virtual void onCreate(IHThorArg *_colocalParent)
  23663. {
  23664. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23665. head.onCreate(_colocalParent);
  23666. fetchInputFields.set(helper.queryFetchInputRecordSize());
  23667. fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
  23668. }
  23669. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23670. {
  23671. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23672. if (variableFetchFileName)
  23673. {
  23674. bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
  23675. OwnedRoxieString fname(helper.getFileName());
  23676. varFetchFileInfo.setown(resolveLFNFlat(fname, isFetchOpt));
  23677. if (varFetchFileInfo)
  23678. {
  23679. // Note - we don't need to do any translation on the disk part of full-keyed joins
  23680. map.setown(varFetchFileInfo->getFileMap());
  23681. }
  23682. }
  23683. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
  23684. }
  23685. virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
  23686. {
  23687. head.setInput(idx, _sourceIdx, _in);
  23688. }
  23689. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  23690. {
  23691. connectInputStreams(consumerOrdered);
  23692. return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
  23693. }
  23694. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  23695. {
  23696. return head.queryInput(idx);
  23697. }
  23698. virtual void processRow(const void *_rhs)
  23699. {
  23700. // called from puller thread
  23701. KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
  23702. CJoinGroup *jg = rhs->thisGroup;
  23703. if (rhs->partNo != (unsigned short) -1)
  23704. {
  23705. unsigned partNo = map->mapOffset(rhs->fpos);
  23706. RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
  23707. size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
  23708. if (fetchInputFields.isVariableSize())
  23709. {
  23710. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
  23711. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23712. ReleaseRoxieRow(rhs);
  23713. jg->notePending();
  23714. memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
  23715. memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
  23716. }
  23717. else
  23718. {
  23719. KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
  23720. memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
  23721. ReleaseRoxieRow(rhs);
  23722. jg->notePending();
  23723. memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
  23724. }
  23725. }
  23726. else
  23727. {
  23728. unsigned candidateCount = (unsigned) rhs->fpos;
  23729. // CTXLOG("Full keyed join - all results back from index");
  23730. ReleaseRoxieRow(rhs);
  23731. noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
  23732. }
  23733. }
  23734. virtual void processEOG()
  23735. {
  23736. // called from front puller thread
  23737. if (preserveGroups)
  23738. endGroup();
  23739. }
  23740. void processGroup(const ConstPointerArray &)
  23741. {
  23742. throwUnexpected();
  23743. }
  23744. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  23745. {
  23746. CRoxieServerKeyedJoinBase::gatherStats(merged);
  23747. if (fetchInputAllocator)
  23748. fetchInputAllocator->gatherStats(merged);
  23749. }
  23750. };
  23751. #ifdef _MSC_VER
  23752. #pragma warning ( pop )
  23753. #endif
  23754. class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
  23755. {
  23756. IOutputMetaData *indexReadMeta;
  23757. Owned<IEngineRowAllocator> indexReadAllocator;
  23758. Owned<IKeyManager> tlk;
  23759. bool variableIndexFileName;
  23760. bool indexReadInputRecordVariable;
  23761. Owned<const IResolvedFile> varFileInfo;
  23762. Linked<ITranslatorSet> translators;
  23763. Linked<IKeyArray> keySet;
  23764. Owned<IOutputMetaData> joinPrefixedMeta;
  23765. Owned<IEngineRowAllocator> joinFieldsAllocator;
  23766. public:
  23767. CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, ITranslatorSet *_translators,
  23768. IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
  23769. : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
  23770. indexReadMeta(_indexReadMeta),
  23771. tlk(createLocalKeyManager(helper.queryIndexRecordSize()->queryRecordAccessor(true), NULL, this, helper.hasNewSegmentMonitors(), !isBlind())),
  23772. translators(_translators),
  23773. keySet(_keySet)
  23774. {
  23775. variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  23776. indexReadInputRecordVariable = indexReadMeta->isVariableSize();
  23777. }
  23778. virtual void serializeExtra(MemoryBuffer &out)
  23779. {
  23780. if (helper.getJoinFlags() & JFindexfromactivity)
  23781. {
  23782. assertex(rootIndex);
  23783. const RemoteActivityId& indexId = rootIndex->queryRemoteId();
  23784. indexId.serialize(out);
  23785. // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
  23786. MemoryBuffer tmp;
  23787. rootIndex->queryActivity()->serializeCreateStartContext(tmp);
  23788. if (rootIndex->queryActivity()->queryVarFileInfo())
  23789. {
  23790. rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
  23791. tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
  23792. }
  23793. unsigned ctxlen = tmp.length();
  23794. out.append(ctxlen).append(tmp);
  23795. }
  23796. }
  23797. virtual void onCreate(IHThorArg *_colocalParent)
  23798. {
  23799. CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
  23800. indexReadAllocator.setown(createRowAllocator(indexReadMeta));
  23801. IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
  23802. joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
  23803. joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
  23804. }
  23805. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  23806. {
  23807. CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
  23808. if (rootIndex)
  23809. {
  23810. varFileInfo.setown(rootIndex->getVarFileInfo());
  23811. translators.setown(rootIndex->getTranslators());
  23812. keySet.setown(rootIndex->getKeySet());
  23813. }
  23814. else if (variableIndexFileName)
  23815. {
  23816. OwnedRoxieString indexFileName(helper.getIndexFileName());
  23817. varFileInfo.setown(resolveLFNIndex(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
  23818. if (varFileInfo)
  23819. {
  23820. unsigned expectedCrc = helper.getIndexFormatCrc();
  23821. unsigned projectedCrc = helper.getProjectedIndexFormatCrc();
  23822. translators.setown(varFileInfo->getTranslators(projectedCrc, helper.queryProjectedIndexRecordSize(), expectedCrc, helper.queryIndexRecordSize(), getEnableFieldTranslation(), true));
  23823. keySet.setown(varFileInfo->getKeyArray(false, isLocal ? factory->queryQueryFactory().queryChannel() : 0));
  23824. }
  23825. }
  23826. puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
  23827. }
  23828. virtual const IResolvedFile *queryVarFileInfo() const
  23829. {
  23830. return varFileInfo;
  23831. }
  23832. virtual void reset()
  23833. {
  23834. CRoxieServerKeyedJoinBase::reset();
  23835. if (varFileInfo)
  23836. {
  23837. keySet.clear();
  23838. varFileInfo.clear();
  23839. }
  23840. }
  23841. virtual void processRow(const void *row)
  23842. {
  23843. // called from front puller thread
  23844. // buffer up an IndexRead request
  23845. if (keySet && helper.leftCanMatch(row))
  23846. {
  23847. RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
  23848. unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
  23849. OwnedConstRoxieRow extracted;
  23850. if (indexReadRecordSize)
  23851. extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
  23852. CJoinGroup *jg = createJoinGroup(row);
  23853. for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
  23854. {
  23855. IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
  23856. if (thisBase)
  23857. {
  23858. unsigned fileNo = 0;
  23859. IKeyIndex *thisKey = thisBase->queryPart(fileNo);
  23860. tlk->setKey(thisKey);
  23861. if (thisKey && !thisKey->isTopLevelKey())
  23862. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23863. else
  23864. tlk->setLayoutTranslator(nullptr);
  23865. helper.createSegmentMonitors(tlk, extracted);
  23866. if (rootIndex)
  23867. rootIndex->mergeSegmentMonitors(tlk);
  23868. tlk->finishSegmentMonitors();
  23869. try
  23870. {
  23871. tlk->reset();
  23872. for (;;)
  23873. {
  23874. typedef const void * cvp;
  23875. if (thisKey && thisKey->isTopLevelKey())
  23876. {
  23877. bool locallySorted = (!thisKey->isFullySorted());
  23878. while (locallySorted || tlk->lookup(false))
  23879. {
  23880. unsigned slavePart = locallySorted ? tlk->getPartition() : (unsigned)extractFpos(tlk);
  23881. if (locallySorted || slavePart)
  23882. {
  23883. cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
  23884. *outputBuffer++ = jg;
  23885. if (indexReadInputRecordVariable)
  23886. {
  23887. *(unsigned *) outputBuffer = indexReadRecordSize;
  23888. outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
  23889. }
  23890. jg->notePending();
  23891. memcpy(outputBuffer, extracted, indexReadRecordSize);
  23892. if (!slavePart)
  23893. {
  23894. for (unsigned i = 1; i < numChannels; i++)
  23895. jg->notePending();
  23896. }
  23897. if (locallySorted)
  23898. break;
  23899. }
  23900. }
  23901. }
  23902. else
  23903. {
  23904. unsigned accepted = 0;
  23905. unsigned rejected = 0;
  23906. Owned<CRowArrayMessageResult> result;
  23907. if (!isSimple)
  23908. result.setown(new CRowArrayMessageResult());
  23909. // MORE - This code seems to be duplicated in keyedJoinHead
  23910. jg->notePending();
  23911. unsigned candidateCount = 0;
  23912. ScopedAtomic<unsigned> indexRecordsRead(::indexRecordsRead);
  23913. ScopedAtomic<unsigned> postFiltered(::postFiltered);
  23914. while (tlk->lookup(true))
  23915. {
  23916. candidateCount++;
  23917. indexRecordsRead++;
  23918. KLBlobProviderAdapter adapter(tlk);
  23919. const byte *indexRow = tlk->queryKeyBuffer();
  23920. size_t fposOffset = tlk->queryRowSize() - sizeof(offset_t);
  23921. offset_t fpos = rtlReadBigUInt8(indexRow + fposOffset);
  23922. if (helper.indexReadMatch(extracted, indexRow, &adapter))
  23923. {
  23924. RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
  23925. CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
  23926. accepted++;
  23927. KLBlobProviderAdapter adapter(tlk);
  23928. helper.extractJoinFields(pb, indexRow, &adapter);
  23929. KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
  23930. rec->fpos = fpos;
  23931. rec->thisGroup = jg;
  23932. rec->partNo = partNo;
  23933. if (isSimple)
  23934. remote.injected.enqueue(rec);
  23935. else
  23936. result->append(rec);
  23937. }
  23938. else
  23939. {
  23940. rejected++;
  23941. postFiltered++;
  23942. }
  23943. }
  23944. // output an end marker for the matches to this group
  23945. KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
  23946. rec->fpos = (offset_t) candidateCount;
  23947. rec->thisGroup = jg;
  23948. rec->partNo = (unsigned short) -1;
  23949. if (isSimple)
  23950. remote.injected.enqueue(rec);
  23951. else
  23952. {
  23953. result->append(rec);
  23954. remote.injectResult(result.getClear());
  23955. }
  23956. if (accepted)
  23957. noteStatistic(StNumIndexAccepted, accepted);
  23958. if (rejected)
  23959. noteStatistic(StNumIndexRejected, rejected);
  23960. }
  23961. if (++fileNo < thisBase->numParts())
  23962. {
  23963. thisKey = thisBase->queryPart(fileNo);
  23964. tlk->setKey(thisKey);
  23965. if (thisKey && !thisKey->isTopLevelKey())
  23966. tlk->setLayoutTranslator(translators->queryTranslator(fileNo));
  23967. else
  23968. tlk->setLayoutTranslator(nullptr);
  23969. tlk->reset();
  23970. }
  23971. else
  23972. break;
  23973. }
  23974. tlk->releaseSegmentMonitors();
  23975. tlk->setKey(NULL);
  23976. }
  23977. catch (...)
  23978. {
  23979. tlk->releaseSegmentMonitors();
  23980. tlk->setKey(NULL);
  23981. throw;
  23982. }
  23983. }
  23984. }
  23985. noteEndReceived(jg, 0);
  23986. }
  23987. else
  23988. {
  23989. noteEndReceived(createJoinGroup(row), 0);
  23990. }
  23991. }
  23992. virtual void processEOG()
  23993. {
  23994. // called from front puller thread
  23995. if (preserveGroups)
  23996. endGroup();
  23997. }
  23998. void processGroup(const ConstPointerArray &)
  23999. {
  24000. throwUnexpected();
  24001. }
  24002. virtual void gatherStats(CRuntimeStatisticCollection & merged) const override
  24003. {
  24004. CRoxieServerKeyedJoinBase::gatherStats(merged);
  24005. if (indexReadAllocator)
  24006. indexReadAllocator->gatherStats(merged);
  24007. if (joinFieldsAllocator)
  24008. joinFieldsAllocator->gatherStats(merged);
  24009. }
  24010. };
  24011. class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
  24012. {
  24013. Owned<const IResolvedFile> indexfile;
  24014. Owned<const IResolvedFile> datafile;
  24015. Owned<IKeyArray> keySet;
  24016. Owned<ITranslatorSet> keyTranslators; // For the indexes
  24017. RemoteActivityId headId;
  24018. RemoteActivityId tailId;
  24019. IOutputMetaData *indexReadMeta;
  24020. Owned<IFilePartMap> map;
  24021. Owned<ITranslatorSet> translators; // for the disk files on local full keyed joins
  24022. Owned<IFileIOArray> files;
  24023. unsigned joinFlags;
  24024. bool isHalfKeyed;
  24025. bool isLocal;
  24026. bool variableFetchFileName;
  24027. bool variableIndexFileName;
  24028. bool isSimple;
  24029. public:
  24030. CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
  24031. : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
  24032. {
  24033. Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
  24034. isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
  24035. isSimple = isLocal;
  24036. rtlDataAttr indexLayoutMeta;
  24037. size32_t indexLayoutSize = 0;
  24038. if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
  24039. assertex(indexLayoutSize== 0);
  24040. joinFlags = helper->getJoinFlags();
  24041. variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
  24042. variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
  24043. if (!variableIndexFileName)
  24044. {
  24045. bool isOpt = (joinFlags & JFindexoptional) != 0;
  24046. OwnedRoxieString indexFileName(helper->getIndexFileName());
  24047. indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
  24048. if (indexfile)
  24049. {
  24050. unsigned expectedCrc = helper->getIndexFormatCrc();
  24051. unsigned projectedCrc = helper->getProjectedIndexFormatCrc();
  24052. keyTranslators.setown(indexfile->getTranslators(projectedCrc, helper->queryProjectedIndexRecordSize(), expectedCrc, helper->queryIndexRecordSize(), getEnableFieldTranslation(), true));
  24053. keySet.setown(indexfile->getKeyArray(isOpt, isLocal ? queryFactory.queryChannel() : 0));
  24054. }
  24055. }
  24056. if (keySet && keySet->length()==1 && !isSimple)
  24057. {
  24058. IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
  24059. if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
  24060. isSimple = true;
  24061. // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
  24062. }
  24063. if (!simpleLocalKeyedJoins)
  24064. isSimple = false;
  24065. isHalfKeyed = !helper->diskAccessRequired();
  24066. indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
  24067. if (!isHalfKeyed && !variableFetchFileName)
  24068. {
  24069. bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
  24070. datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
  24071. if (datafile)
  24072. {
  24073. if (isLocal) // Not sure this works
  24074. {
  24075. unsigned expectedCrc = helper->getDiskFormatCrc();
  24076. unsigned projectedCrc = helper->getProjectedFormatCrc();
  24077. translators.setown(datafile->getTranslators(expectedCrc, helper->queryProjectedDiskRecordSize(), projectedCrc, helper->queryDiskRecordSize(), getEnableFieldTranslation(), false));
  24078. files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
  24079. }
  24080. else
  24081. map.setown(datafile->getFileMap());
  24082. }
  24083. }
  24084. }
  24085. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24086. {
  24087. if (isHalfKeyed)
  24088. return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
  24089. headId, keySet, keyTranslators, indexReadMeta, joinFlags, isSimple, isLocal);
  24090. else
  24091. return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
  24092. headId, keySet, keyTranslators, indexReadMeta,
  24093. tailId, map, joinFlags, isLocal); // MORE - not sure local variant actually works - should be using files not map, for example?
  24094. }
  24095. virtual const StatisticsMapping &queryStatsMapping() const
  24096. {
  24097. return keyedJoinStatistics;
  24098. }
  24099. virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
  24100. {
  24101. if (datafile)
  24102. addXrefFileInfo(reply, datafile);
  24103. if (indexfile)
  24104. addXrefFileInfo(reply, indexfile);
  24105. }
  24106. };
  24107. IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
  24108. {
  24109. return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
  24110. }
  24111. //=================================================================================
  24112. class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
  24113. {
  24114. protected:
  24115. Owned<ISoapCallHelper> soaphelper;
  24116. IHThorSoapActionArg & helper;
  24117. StringBuffer authToken;
  24118. bool eof;
  24119. CriticalSection crit;
  24120. ClientCertificate *pClientCert;
  24121. public:
  24122. IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
  24123. CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24124. : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
  24125. {
  24126. eof = false;
  24127. if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
  24128. pClientCert = &clientCert;
  24129. else
  24130. pClientCert = NULL;
  24131. }
  24132. // ISoapCallRowProvider
  24133. virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
  24134. virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
  24135. virtual const void * getNextRow() { return NULL; };
  24136. virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
  24137. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24138. {
  24139. eof = false;
  24140. CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
  24141. authToken.append(ctx->queryAuthToken());
  24142. }
  24143. virtual void reset()
  24144. {
  24145. // MORE - Shouldn't we make sure thread is stopped etc???
  24146. soaphelper.clear();
  24147. CRoxieServerActivity::reset();
  24148. }
  24149. // IRoxieAbortMonitor
  24150. virtual void checkForAbort() { checkAbort(); }
  24151. };
  24152. //---------------------------------------------------------------------------
  24153. class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
  24154. {
  24155. IHThorSoapCallArg & callHelper;
  24156. public:
  24157. CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24158. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24159. {
  24160. }
  24161. virtual IHThorSoapCallArg * queryCallHelper()
  24162. {
  24163. return &callHelper;
  24164. }
  24165. virtual bool needsAllocator() const { return true; }
  24166. virtual const void *nextRow()
  24167. {
  24168. ActivityTimer t(totalCycles, timeActivities);
  24169. if(eof) return NULL;
  24170. if (soaphelper == NULL)
  24171. {
  24172. if (factory->getKind()==TAKhttp_rowdataset)
  24173. soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24174. else
  24175. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
  24176. soaphelper->start();
  24177. }
  24178. OwnedConstRoxieRow ret = soaphelper->getRow();
  24179. if (!ret)
  24180. {
  24181. eof = true;
  24182. return NULL;
  24183. }
  24184. ++processed;
  24185. return ret.getClear();
  24186. }
  24187. };
  24188. class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
  24189. {
  24190. public:
  24191. CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24192. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24193. {
  24194. }
  24195. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24196. {
  24197. return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
  24198. }
  24199. virtual const StatisticsMapping &queryStatsMapping() const
  24200. {
  24201. return soapStatistics;
  24202. }
  24203. };
  24204. IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24205. {
  24206. return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24207. }
  24208. //---------------------------------------------------------------------------
  24209. class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
  24210. {
  24211. public:
  24212. CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24213. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24214. {}
  24215. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24216. {
  24217. //MORE: parentExtract not passed to start - although shouldn't be a problem.
  24218. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
  24219. soaphelper->start();
  24220. soaphelper->waitUntilDone();
  24221. IException *e = soaphelper->getError();
  24222. soaphelper.clear();
  24223. if (e)
  24224. throw e;
  24225. }
  24226. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24227. {
  24228. return NULL;
  24229. }
  24230. virtual const void *nextRow()
  24231. {
  24232. throwUnexpected(); // I am nobody's input
  24233. }
  24234. };
  24235. class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
  24236. {
  24237. bool isRoot;
  24238. public:
  24239. CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24240. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24241. {
  24242. }
  24243. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24244. {
  24245. return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
  24246. }
  24247. virtual bool isSink() const
  24248. {
  24249. return isRoot;
  24250. }
  24251. virtual const StatisticsMapping &queryStatsMapping() const
  24252. {
  24253. return soapStatistics;
  24254. }
  24255. };
  24256. IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24257. {
  24258. return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24259. }
  24260. //---------------------------------------------------------------------------
  24261. class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
  24262. {
  24263. IHThorSoapCallArg & callHelper;
  24264. public:
  24265. CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24266. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
  24267. {
  24268. }
  24269. virtual IHThorSoapCallArg * queryCallHelper()
  24270. {
  24271. return &callHelper;
  24272. }
  24273. virtual const void *getNextRow()
  24274. {
  24275. CriticalBlock b(crit); // MORE - why ?
  24276. return inputStream->ungroupedNextRow();
  24277. }
  24278. virtual bool needsAllocator() const { return true; }
  24279. virtual const void *nextRow()
  24280. {
  24281. ActivityTimer t(totalCycles, timeActivities);
  24282. if(eof) return NULL;
  24283. if (soaphelper == NULL)
  24284. {
  24285. soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
  24286. soaphelper->start();
  24287. }
  24288. OwnedConstRoxieRow ret = soaphelper->getRow();
  24289. if (!ret)
  24290. {
  24291. eof = true;
  24292. return NULL;
  24293. }
  24294. ++processed;
  24295. return ret.getClear();
  24296. }
  24297. };
  24298. class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
  24299. {
  24300. public:
  24301. CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24302. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
  24303. {
  24304. }
  24305. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24306. {
  24307. return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
  24308. }
  24309. virtual const StatisticsMapping &queryStatsMapping() const
  24310. {
  24311. return soapStatistics;
  24312. }
  24313. };
  24314. IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
  24315. {
  24316. return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
  24317. }
  24318. //---------------------------------------------------------------------------
  24319. class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
  24320. {
  24321. public:
  24322. CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
  24323. : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
  24324. {}
  24325. virtual const void *getNextRow()
  24326. {
  24327. CriticalBlock b(crit); // MORE - Why?
  24328. const void *nextrec = inputStream->ungroupedNextRow();
  24329. if (nextrec)
  24330. processed++;
  24331. return nextrec;
  24332. }
  24333. virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
  24334. {
  24335. try
  24336. {
  24337. start(parentExtractSize, parentExtract, false);
  24338. soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
  24339. soaphelper->start();
  24340. soaphelper->waitUntilDone();
  24341. IException *e = soaphelper->getError();
  24342. soaphelper.clear();
  24343. if (e)
  24344. throw e;
  24345. stop();
  24346. }
  24347. catch (IException *E)
  24348. {
  24349. ctx->notifyAbort(E);
  24350. abort();
  24351. throw;
  24352. }
  24353. catch(...)
  24354. {
  24355. Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
  24356. ctx->notifyAbort(E);
  24357. abort();
  24358. throw;
  24359. }
  24360. }
  24361. virtual IFinalRoxieInput *queryOutput(unsigned idx)
  24362. {
  24363. return NULL;
  24364. }
  24365. virtual const void *nextRow()
  24366. {
  24367. throwUnexpected(); // I am nobody's input
  24368. }
  24369. };
  24370. class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
  24371. {
  24372. bool isRoot;
  24373. public:
  24374. CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24375. : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
  24376. {
  24377. }
  24378. virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
  24379. {
  24380. return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
  24381. }
  24382. virtual bool isSink() const
  24383. {
  24384. return isRoot;
  24385. }
  24386. virtual const StatisticsMapping &queryStatsMapping() const
  24387. {
  24388. return soapStatistics;
  24389. }
  24390. };
  24391. IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
  24392. {
  24393. return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
  24394. }
  24395. //=====================================================================================================
  24396. class CGraphResults : implements IRoxieGraphResults, public CInterface
  24397. {
  24398. IArrayOf<IGraphResult> results;
  24399. CriticalSection cs;
  24400. IGraphResult & select(unsigned idx)
  24401. {
  24402. CriticalBlock procedure(cs);
  24403. if (idx >= results.ordinality())
  24404. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
  24405. return results.item(idx);
  24406. }
  24407. public:
  24408. IMPLEMENT_IINTERFACE
  24409. void clear()
  24410. {
  24411. CriticalBlock procedure(cs);
  24412. results.kill();
  24413. }
  24414. virtual IEngineRowStream * createIterator(unsigned id)
  24415. {
  24416. return select(id).createIterator();
  24417. }
  24418. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24419. {
  24420. select(id).getLinkedResult(count, ret);
  24421. }
  24422. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24423. {
  24424. select(id).getLinkedResult(count, ret);
  24425. }
  24426. virtual const void * getLinkedRowResult(unsigned id)
  24427. {
  24428. return select(id).getLinkedRowResult();
  24429. }
  24430. void setResult(unsigned id, IGraphResult * result)
  24431. {
  24432. CriticalBlock procedure(cs);
  24433. if (results.ordinality() <= id)
  24434. {
  24435. while (results.ordinality() < id)
  24436. results.append(*new CGraphResult);
  24437. results.append(*LINK(result));
  24438. }
  24439. else
  24440. results.replace(*LINK(result), id);
  24441. }
  24442. void appendResult(IGraphResult * result)
  24443. {
  24444. CriticalBlock procedure(cs);
  24445. results.append(*LINK(result));
  24446. }
  24447. };
  24448. //===================================================================================================================
  24449. class CPseudoArg : implements CThorSinkArgOf<IHThorArg>
  24450. {
  24451. };
  24452. class CPseudoActivity : public CRoxieServerActivity
  24453. {
  24454. public:
  24455. CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
  24456. virtual const void *nextRow()
  24457. {
  24458. throwUnexpected(); // I am nobody's input
  24459. }
  24460. };
  24461. class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
  24462. {
  24463. protected:
  24464. class ActivityGraphSlaveContext : public IndirectSlaveContext
  24465. {
  24466. SpinLock abortLock;
  24467. bool aborted;
  24468. Owned<IException> exception;
  24469. public:
  24470. ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
  24471. {
  24472. aborted = false;
  24473. }
  24474. // Note - we must track exceptions at the child level in case there is a CATCH in parent
  24475. virtual void notifyAbort(IException *E)
  24476. {
  24477. if (QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
  24478. {
  24479. SpinBlock b(abortLock);
  24480. if (!aborted)
  24481. {
  24482. aborted = true;
  24483. exception.set(E);
  24484. }
  24485. }
  24486. }
  24487. virtual void checkAbort()
  24488. {
  24489. if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
  24490. {
  24491. SpinBlock b(abortLock);
  24492. if (!exception)
  24493. exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
  24494. throw exception.getLink();
  24495. }
  24496. IndirectSlaveContext::checkAbort();
  24497. }
  24498. virtual ICodeContext *queryCodeContext()
  24499. {
  24500. return codeContext;
  24501. }
  24502. void setCodeContext(ICodeContext * _codeContext)
  24503. {
  24504. codeContext = _codeContext;
  24505. }
  24506. void setLoopCounter(unsigned _loopCounter)
  24507. {
  24508. loopCounter = _loopCounter;
  24509. }
  24510. virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
  24511. {
  24512. childGraphs.setValue(id, childGraph);
  24513. }
  24514. virtual IActivityGraph * queryChildGraph(unsigned id)
  24515. {
  24516. if (queryTraceLevel() > 10)
  24517. CTXLOG("resolveChildGraph %d", id);
  24518. IActivityGraph *childGraph = childGraphs.getValue(id);
  24519. assertex(childGraph);
  24520. return childGraph;
  24521. }
  24522. // 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
  24523. virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
  24524. {
  24525. logctx.getLogPrefix(ret);
  24526. if (loopCounter)
  24527. ret.appendf("{%u}", loopCounter);
  24528. return ret;
  24529. }
  24530. protected:
  24531. const IRoxieContextLogger &logctx;
  24532. unsigned loopCounter;
  24533. ICodeContext * codeContext;
  24534. MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
  24535. } graphSlaveContext;
  24536. class ActivityGraphCodeContext : public IndirectCodeContext
  24537. {
  24538. public:
  24539. virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
  24540. {
  24541. if ((unsigned) activityId == container->queryId())
  24542. return container;
  24543. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24544. if (match)
  24545. return match->queryLocalGraph();
  24546. return IndirectCodeContext::resolveLocalQuery(activityId);
  24547. }
  24548. virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
  24549. {
  24550. IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
  24551. return LINK(match->queryChildGraph());
  24552. }
  24553. virtual unsigned getGraphLoopCounter() const
  24554. {
  24555. return container->queryLoopCounter(); // only called if value is valid
  24556. }
  24557. void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
  24558. {
  24559. slaveContext = _slaveContext;
  24560. container = _container;
  24561. }
  24562. protected:
  24563. IRoxieSlaveContext * slaveContext;
  24564. CActivityGraph * container;
  24565. } graphCodeContext;
  24566. class SinkThread : public CInterface, implements IThreaded
  24567. {
  24568. public:
  24569. SinkThread(IActivityGraph &_parent, IRoxieServerActivity &_sink)
  24570. : thread("SinkThread", this), parent(_parent), sink(_sink)
  24571. {}
  24572. virtual void threadmain() override
  24573. {
  24574. try
  24575. {
  24576. sink.execute(parentExtractSize, parentExtract);
  24577. }
  24578. catch (IException *E)
  24579. {
  24580. parent.noteException(E);
  24581. throw;
  24582. }
  24583. }
  24584. void start(unsigned _parentExtractSize, const byte * _parentExtract)
  24585. {
  24586. parentExtract = _parentExtract;
  24587. parentExtractSize = _parentExtractSize;
  24588. thread.start();
  24589. }
  24590. inline void join()
  24591. {
  24592. thread.join(INFINITE);
  24593. }
  24594. private:
  24595. CThreadedPersistent thread;
  24596. IActivityGraph &parent;
  24597. IRoxieServerActivity &sink;
  24598. const byte * parentExtract = nullptr;
  24599. unsigned parentExtractSize = 0;
  24600. };
  24601. // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
  24602. IArrayOf<IRoxieServerActivity> activities;
  24603. IArrayOf<IRoxieProbe> probes;
  24604. CIArrayOf<SinkThread> threads;
  24605. IRoxieServerActivityCopyArray sinks;
  24606. StringAttr graphName;
  24607. Owned<CGraphResults> results;
  24608. CGraphResults graphLoopResults;
  24609. const ActivityArray & graphDefinition;
  24610. CriticalSection evaluateCrit;
  24611. IProbeManager *probeManager;
  24612. IRoxieServerActivity *parentActivity;
  24613. unsigned id;
  24614. unsigned loopCounter;
  24615. public:
  24616. IMPLEMENT_IINTERFACE;
  24617. CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, const ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
  24618. : graphSlaveContext(_ctx, _logctx), graphName(_graphName), graphDefinition(x), probeManager(_probeManager), parentActivity(_parentActivity)
  24619. {
  24620. id = x.getLibraryGraphId();
  24621. if (!id)
  24622. id = _id;
  24623. loopCounter = 0;
  24624. graphSlaveContext.setCodeContext(&graphCodeContext);
  24625. graphCodeContext.setContainer(&graphSlaveContext, this);
  24626. }
  24627. ~CActivityGraph()
  24628. {
  24629. if (probeManager)
  24630. probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
  24631. }
  24632. virtual const char *queryName() const
  24633. {
  24634. return graphName.get();
  24635. }
  24636. void createGraph(IRoxieSlaveContext *_ctx)
  24637. {
  24638. if (graphDefinition.isMultiInstance())
  24639. {
  24640. graphCodeContext.set(_ctx->queryCodeContext());
  24641. _ctx = &graphSlaveContext;
  24642. }
  24643. ForEachItemIn(idx, graphDefinition)
  24644. {
  24645. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
  24646. IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
  24647. activities.append(activity);
  24648. if (donor.isSink())
  24649. {
  24650. sinks.append(activity);
  24651. if (probeManager)
  24652. probeManager->noteSink(&activity);
  24653. }
  24654. }
  24655. ForEachItemIn(idx1, graphDefinition)
  24656. {
  24657. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
  24658. IRoxieServerActivity &activity = activities.item(idx1);
  24659. unsigned inputidx = 0;
  24660. for (;;)
  24661. {
  24662. unsigned outputidx;
  24663. unsigned source = donor.getInput(inputidx, outputidx);
  24664. if (source==(unsigned) -1)
  24665. break;
  24666. connectInput(idx1, inputidx, source, outputidx, 0);
  24667. inputidx++;
  24668. }
  24669. IntArray &dependencies = donor.queryDependencies();
  24670. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  24671. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  24672. StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
  24673. ForEachItemIn(idx2, dependencies)
  24674. {
  24675. IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
  24676. unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
  24677. unsigned dependencyControlId = dependencyControlIds.item(idx2);
  24678. activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
  24679. if (probeManager)
  24680. probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
  24681. }
  24682. }
  24683. ForEachItemIn(idx2, sinks)
  24684. {
  24685. IRoxieServerActivity &sink = sinks.item(idx2);
  24686. sink.connectInputStreams(true);
  24687. }
  24688. }
  24689. void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
  24690. {
  24691. IRoxieServerActivity &targetActivity = activities.item(target);
  24692. IRoxieServerActivity &sourceActivity = activities.item(source);
  24693. IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
  24694. if (probeManager)
  24695. {
  24696. IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
  24697. probes.append(*LINK(inputProbe));
  24698. output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
  24699. }
  24700. targetActivity.setInput(targetIdx, sourceIdx, output);
  24701. }
  24702. virtual void onCreate(IHThorArg *_colocalParent)
  24703. {
  24704. ForEachItemIn(idx, activities)
  24705. {
  24706. IRoxieServerActivity *activity = &activities.item(idx);
  24707. if (activity)
  24708. activity->onCreate(_colocalParent);
  24709. }
  24710. }
  24711. virtual void abort()
  24712. {
  24713. ForEachItemIn(idx, sinks)
  24714. {
  24715. IRoxieServerActivity &sink = sinks.item(idx);
  24716. sink.abort();
  24717. }
  24718. }
  24719. virtual void reset()
  24720. {
  24721. ForEachItemIn(idx, sinks)
  24722. {
  24723. IRoxieServerActivity &sink = sinks.item(idx);
  24724. sink.reset();
  24725. }
  24726. }
  24727. Linked<IException> exception;
  24728. CriticalSection eCrit;
  24729. virtual void noteException(IException *E)
  24730. {
  24731. CriticalBlock b(eCrit);
  24732. if (!exception)
  24733. {
  24734. if (graphSlaveContext.queryDebugContext())
  24735. {
  24736. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
  24737. }
  24738. exception.set(E);
  24739. }
  24740. }
  24741. virtual void checkAbort()
  24742. {
  24743. CriticalBlock b(eCrit);
  24744. if (exception)
  24745. throw exception.getLink();
  24746. }
  24747. virtual void execute()
  24748. {
  24749. results.setown(new CGraphResults);
  24750. doExecute(0, NULL);
  24751. }
  24752. //New child query code...
  24753. virtual IThorChildGraph * queryChildGraph()
  24754. {
  24755. return this;
  24756. }
  24757. virtual IEclGraphResults * queryLocalGraph()
  24758. {
  24759. return this;
  24760. }
  24761. virtual IRoxieServerChildGraph * queryLoopGraph()
  24762. {
  24763. return this;
  24764. }
  24765. inline unsigned queryId() const
  24766. {
  24767. return id;
  24768. }
  24769. inline unsigned queryLoopCounter() const
  24770. {
  24771. return loopCounter;
  24772. }
  24773. void doExecute(unsigned parentExtractSize, const byte * parentExtract)
  24774. {
  24775. if (sinks.ordinality()==1)
  24776. sinks.item(0).execute(parentExtractSize, parentExtract);
  24777. #ifdef PARALLEL_EXECUTE
  24778. else if (!probeManager && !graphDefinition.isSequential())
  24779. {
  24780. #ifdef PARALLEL_PERSISTANT_THREADS
  24781. if (!threads.ordinality())
  24782. {
  24783. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24784. {
  24785. threads.append(*new SinkThread(*this, sinks.item(i)));
  24786. }
  24787. }
  24788. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24789. threads.item(i).start(parentExtractSize, parentExtract);
  24790. try
  24791. {
  24792. sinks.item(sinks.ordinality()-1).execute(parentExtractSize, parentExtract);
  24793. }
  24794. catch (IException *E)
  24795. {
  24796. noteException(E);
  24797. E->Release();
  24798. }
  24799. for (unsigned i = 0; i < sinks.ordinality()-1; i++)
  24800. {
  24801. try
  24802. {
  24803. threads.item(i).join();
  24804. }
  24805. catch (IException *E)
  24806. {
  24807. noteException(E);
  24808. E->Release();
  24809. }
  24810. }
  24811. checkAbort();
  24812. #else
  24813. class casyncfor: public CAsyncFor
  24814. {
  24815. public:
  24816. IActivityGraph &parent;
  24817. unsigned parentExtractSize;
  24818. const byte * parentExtract;
  24819. casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
  24820. sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
  24821. void Do(unsigned i)
  24822. {
  24823. try
  24824. {
  24825. sinks.item(i).execute(parentExtractSize, parentExtract);
  24826. }
  24827. catch (IException *E)
  24828. {
  24829. parent.noteException(E);
  24830. throw;
  24831. }
  24832. }
  24833. private:
  24834. IRoxieServerActivityCopyArray &sinks;
  24835. } afor(sinks, *this, parentExtractSize, parentExtract);
  24836. afor.For(sinks.ordinality(), sinks.ordinality());
  24837. #endif
  24838. }
  24839. #endif
  24840. else
  24841. {
  24842. ForEachItemIn(idx, sinks)
  24843. {
  24844. IRoxieServerActivity &sink = sinks.item(idx);
  24845. sink.execute(parentExtractSize, parentExtract);
  24846. }
  24847. }
  24848. }
  24849. virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
  24850. {
  24851. CriticalBlock block(evaluateCrit);
  24852. results.setown(new CGraphResults);
  24853. try
  24854. {
  24855. doExecute(parentExtractSize, parentExtract);
  24856. }
  24857. catch (...)
  24858. {
  24859. DBGLOG("Exception thrown in child query - cleaning up");
  24860. reset();
  24861. throw;
  24862. }
  24863. reset();
  24864. return results.getClear();
  24865. }
  24866. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  24867. {
  24868. if (id && statsBuilder)
  24869. {
  24870. statsBuilder->beginSubGraphScope(parentActivity->querySubgraphId());
  24871. statsBuilder->beginActivityScope(parentActivity->queryId());
  24872. statsBuilder->beginChildGraphScope(id);
  24873. }
  24874. ForEachItemIn(i, activities)
  24875. activities.item(i).gatherStatistics(statsBuilder);
  24876. if (id && statsBuilder)
  24877. {
  24878. statsBuilder->endScope();
  24879. statsBuilder->endScope();
  24880. statsBuilder->endScope();
  24881. }
  24882. }
  24883. //interface IRoxieServerChildGraph
  24884. virtual void beforeExecute()
  24885. {
  24886. results.setown(new CGraphResults);
  24887. }
  24888. virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
  24889. {
  24890. IFinalRoxieInput * ret = selectOutput(id);
  24891. ret->start(parentExtractSize, parentExtract, paused);
  24892. return ret;
  24893. }
  24894. virtual IFinalRoxieInput * selectOutput(unsigned id)
  24895. {
  24896. ForEachItemIn(i, sinks)
  24897. {
  24898. IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
  24899. if (ret)
  24900. return ret;
  24901. }
  24902. throwUnexpected();
  24903. return NULL;
  24904. }
  24905. virtual void setInputResult(unsigned id, IGraphResult * result)
  24906. {
  24907. results->setResult(id, result);
  24908. }
  24909. virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
  24910. {
  24911. ForEachItemIn(i, activities)
  24912. {
  24913. if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
  24914. return true;
  24915. }
  24916. return false;
  24917. }
  24918. virtual void stopUnusedOutputs()
  24919. {
  24920. //Hmm not sure how to do this...
  24921. }
  24922. virtual void afterExecute()
  24923. {
  24924. ForEachItemIn(i, sinks)
  24925. {
  24926. sinks.item(i).stop();
  24927. }
  24928. if (graphSlaveContext.queryDebugContext())
  24929. {
  24930. graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
  24931. }
  24932. reset();
  24933. }
  24934. virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
  24935. {
  24936. doExecute(parentExtractSize, parentExtract);
  24937. return LINK(results);
  24938. }
  24939. virtual void getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) override
  24940. {
  24941. results->getLinkedResult(count, ret, id);
  24942. }
  24943. virtual void getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) override
  24944. {
  24945. results->getLinkedResult(count, ret, id);
  24946. }
  24947. virtual const void * getLinkedRowResult(unsigned id)
  24948. {
  24949. return results->getLinkedRowResult(id);
  24950. }
  24951. virtual void setResult(unsigned id, IGraphResult * result)
  24952. {
  24953. results->setResult(id, result);
  24954. }
  24955. virtual IEngineRowStream * createResultIterator(unsigned id)
  24956. {
  24957. return results->createIterator(id);
  24958. }
  24959. virtual void setGraphLoopResult(IGraphResult * result)
  24960. {
  24961. graphLoopResults.appendResult(result);
  24962. }
  24963. virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
  24964. {
  24965. try
  24966. {
  24967. return graphLoopResults.createIterator(id);
  24968. }
  24969. catch (IException * e)
  24970. {
  24971. e->Release();
  24972. throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
  24973. }
  24974. }
  24975. virtual void clearGraphLoopResults()
  24976. {
  24977. graphLoopResults.clear();
  24978. }
  24979. virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
  24980. {
  24981. doExecute(parentExtractSize, parentExtract);
  24982. }
  24983. virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
  24984. {
  24985. graphLoopResults.setResult(id, result);
  24986. }
  24987. virtual IEngineRowStream * getGraphLoopResult(unsigned id)
  24988. {
  24989. return graphLoopResults.createIterator(id);
  24990. }
  24991. virtual void getProbeResponse(IPropertyTree *query)
  24992. {
  24993. if (probeManager)
  24994. probeManager->getProbeResponse(query);
  24995. }
  24996. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
  24997. {
  24998. throwUnexpected();
  24999. }
  25000. virtual CGraphIterationInfo *selectGraphLoopOutput()
  25001. {
  25002. return NULL;
  25003. }
  25004. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  25005. {
  25006. throwUnexpected();
  25007. }
  25008. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  25009. {
  25010. throwUnexpected();
  25011. }
  25012. };
  25013. class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
  25014. {
  25015. public:
  25016. IMPLEMENT_IINTERFACE;
  25017. CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
  25018. : ctx(_ctx), parentActivity(_parentActivity), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
  25019. {
  25020. }
  25021. virtual void abort() override { throwUnexpected(); }
  25022. virtual void reset() override { throwUnexpected(); }
  25023. virtual void execute() override { throwUnexpected(); }
  25024. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  25025. virtual void onCreate(IHThorArg *_colocalArg) override
  25026. {
  25027. colocalArg = _colocalArg;
  25028. }
  25029. virtual void noteException(IException *E) override { throwUnexpected(); }
  25030. virtual void checkAbort() override { throwUnexpected(); }
  25031. virtual IThorChildGraph * queryChildGraph() override { return this; }
  25032. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25033. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25034. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override { throwUnexpected(); }
  25035. virtual const char *queryName() const override { throwUnexpected(); }
  25036. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override
  25037. {
  25038. CriticalBlock b(graphCrit);
  25039. ForEachItemIn(i, stack)
  25040. stack.item(i).gatherStatistics(statsBuilder);
  25041. }
  25042. virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract) override
  25043. {
  25044. Owned<CActivityGraph> realGraph;
  25045. {
  25046. CriticalBlock b(graphCrit);
  25047. if (stack.length())
  25048. realGraph.setown(&stack.popGet());
  25049. }
  25050. if (!realGraph)
  25051. {
  25052. realGraph.setown(new CActivityGraph(ctx, graphName, id, parentActivity, graphDefinition, NULL, logctx));
  25053. realGraph->createGraph(ctx);
  25054. realGraph->onCreate(colocalArg);
  25055. }
  25056. Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
  25057. {
  25058. CriticalBlock b(graphCrit);
  25059. stack.append(*realGraph.getClear());
  25060. }
  25061. return results.getClear();
  25062. }
  25063. protected:
  25064. IRoxieSlaveContext *ctx;
  25065. IRoxieServerActivity *parentActivity;
  25066. StringAttr graphName;
  25067. unsigned id;
  25068. ActivityArray &graphDefinition;
  25069. const IRoxieContextLogger &logctx;
  25070. unsigned numParallel;
  25071. IHThorArg *colocalArg = nullptr;
  25072. mutable CriticalSection graphCrit;
  25073. CIArrayOf<CActivityGraph> stack;
  25074. };
  25075. class CIterationActivityGraph : public CActivityGraph
  25076. {
  25077. IHThorArg * colocalParent;
  25078. unsigned fixedParentExtractSize;
  25079. const byte * fixedParentExtract;
  25080. unsigned graphOutputActivityIndex;
  25081. public:
  25082. CIterationActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager,
  25083. unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
  25084. : CActivityGraph(_ctx, _graphName, _id, _parentActivity, x, _probeManager, _logctx)
  25085. {
  25086. graphOutputActivityIndex = 0;
  25087. loopCounter = _loopCounter;
  25088. colocalParent = _colocalParent;
  25089. graphSlaveContext.setLoopCounter(loopCounter);
  25090. graphCodeContext.set(_ctx->queryCodeContext());
  25091. fixedParentExtractSize = parentExtractSize;
  25092. fixedParentExtract = parentExtract;
  25093. }
  25094. void createIterationGraph(IRoxieSlaveContext *_ctx)
  25095. {
  25096. Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
  25097. ForEachItemIn(idx1, graphDefinition)
  25098. activities.append(*LINK(pseudoActivity));
  25099. graphOutputActivityIndex = queryGraphOutputIndex();
  25100. recursiveCreateGraph(_ctx, graphOutputActivityIndex);
  25101. }
  25102. unsigned queryGraphOutputIndex() const
  25103. {
  25104. ForEachItemIn(i, graphDefinition)
  25105. if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
  25106. return i;
  25107. throwUnexpected();
  25108. }
  25109. void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
  25110. {
  25111. //Check to see if already created
  25112. IRoxieServerActivity & prevActivity = activities.item(whichActivity);
  25113. if (prevActivity.queryId() != 0)
  25114. {
  25115. prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
  25116. return;
  25117. }
  25118. IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
  25119. IRoxieServerActivity * activity = NULL;
  25120. if (donor.isGraphInvariant())
  25121. {
  25122. ThorActivityKind kind = donor.getKind();
  25123. switch (kind)
  25124. {
  25125. case TAKif:
  25126. case TAKchildif:
  25127. case TAKcase:
  25128. case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
  25129. {
  25130. Owned<IHThorArg> helper = &donor.getHelper();
  25131. helper->onCreate(&graphCodeContext, colocalParent, NULL);
  25132. helper->onStart(fixedParentExtract, NULL);
  25133. unsigned branch;
  25134. switch (kind)
  25135. {
  25136. case TAKif: case TAKchildif:
  25137. branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
  25138. break;
  25139. case TAKcase: case TAKchildcase:
  25140. branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
  25141. if (branch >= donor.numInputs())
  25142. branch = donor.numInputs() - 1;
  25143. break;
  25144. default:
  25145. throwUnexpected();
  25146. }
  25147. helper.clear();
  25148. unsigned outputidx;
  25149. unsigned source = donor.getInput(branch, outputidx);
  25150. if (source ==(unsigned) -1)
  25151. activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
  25152. else
  25153. activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
  25154. activities.replace(*activity, whichActivity);
  25155. activity->onCreate(colocalParent);
  25156. if (source ==(unsigned) -1)
  25157. return;
  25158. recursiveCreateGraph(_ctx, source);
  25159. connectInput(whichActivity, 0, source, outputidx, loopCounter);
  25160. break;
  25161. }
  25162. }
  25163. }
  25164. if (!activity)
  25165. {
  25166. activity = donor.createActivity(&graphSlaveContext, probeManager);
  25167. activities.replace(*activity, whichActivity);
  25168. activity->onCreate(colocalParent);
  25169. activity->resetOutputsUsed();
  25170. unsigned inputidx = 0;
  25171. for (;;)
  25172. {
  25173. unsigned outputidx;
  25174. unsigned source = donor.getInput(inputidx, outputidx);
  25175. if (source==(unsigned) -1)
  25176. break;
  25177. recursiveCreateGraph(_ctx, source);
  25178. connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
  25179. inputidx++;
  25180. }
  25181. }
  25182. IntArray &dependencies = donor.queryDependencies();
  25183. IntArray &dependencyIndexes = donor.queryDependencyIndexes();
  25184. IntArray &dependencyControlIds = donor.queryDependencyControlIds();
  25185. ForEachItemIn(idx2, dependencies)
  25186. {
  25187. unsigned input = dependencies.item(idx2);
  25188. recursiveCreateGraph(_ctx, input);
  25189. activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
  25190. }
  25191. }
  25192. virtual CGraphIterationInfo *selectGraphLoopOutput()
  25193. {
  25194. IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
  25195. IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
  25196. return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
  25197. }
  25198. virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
  25199. {
  25200. ForEachItemIn(i, activities)
  25201. activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
  25202. }
  25203. virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
  25204. {
  25205. ForEachItemIn(i, activities)
  25206. activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
  25207. }
  25208. };
  25209. class CDelayedActivityGraph : implements IActivityGraph, public CInterface
  25210. {
  25211. StringAttr graphName;
  25212. ActivityArray & graphDefinition;
  25213. IProbeManager *probeManager;
  25214. unsigned id;
  25215. IRoxieSlaveContext * ctx;
  25216. IHThorArg * colocalParent;
  25217. IRoxieServerActivity *parentActivity;
  25218. public:
  25219. IMPLEMENT_IINTERFACE;
  25220. CDelayedActivityGraph(const char *_graphName, unsigned _id, IRoxieServerActivity *_parentActivity, ActivityArray &x, IProbeManager *_probeManager)
  25221. : graphDefinition(x), probeManager(_probeManager), parentActivity(_parentActivity)
  25222. {
  25223. graphName.set(_graphName);
  25224. id = _id;
  25225. ctx = NULL;
  25226. colocalParent = NULL;
  25227. }
  25228. virtual const char *queryName() const override { return graphName.get(); }
  25229. virtual void abort() override { throwUnexpected(); }
  25230. virtual void reset() override { }
  25231. virtual void execute() override { throwUnexpected(); }
  25232. virtual void getProbeResponse(IPropertyTree *query) override { throwUnexpected(); }
  25233. virtual void noteException(IException *E) override { throwUnexpected(); }
  25234. virtual void checkAbort() override { throwUnexpected(); }
  25235. virtual IThorChildGraph * queryChildGraph() override { throwUnexpected(); }
  25236. virtual IEclGraphResults * queryLocalGraph() override { throwUnexpected(); }
  25237. virtual IRoxieServerChildGraph * queryLoopGraph() override { throwUnexpected(); }
  25238. virtual void gatherStatistics(IStatisticGatherer * statsBuilder) const override { }
  25239. virtual void onCreate(IHThorArg *_colocalParent) override
  25240. {
  25241. colocalParent = _colocalParent;
  25242. }
  25243. virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) override
  25244. {
  25245. Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, parentActivity, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
  25246. ret->createIterationGraph(ctx);
  25247. return ret.getClear();
  25248. }
  25249. };
  25250. IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
  25251. {
  25252. if (childFactories.isDelayed())
  25253. {
  25254. assertex(numParallel==1);
  25255. return new CDelayedActivityGraph(_graphName, id, parentActivity, childFactories, _probeManager);
  25256. }
  25257. else
  25258. {
  25259. if (numParallel==1 || _probeManager != nullptr)
  25260. {
  25261. Owned<IProbeManager> childProbe;
  25262. if (_probeManager)
  25263. childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
  25264. Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, parentActivity, childFactories, childProbe, _logctx);
  25265. ret->createGraph(ctx);
  25266. if (_probeManager)
  25267. _probeManager->endChildGraph(childProbe, parentActivity);
  25268. return ret.getClear();
  25269. }
  25270. else
  25271. return new CProxyActivityGraph(ctx, _graphName, id, parentActivity, childFactories, _logctx, numParallel);
  25272. }
  25273. }
  25274. //================================================================================================================
  25275. #ifdef _USE_CPPUNIT
  25276. #include "unittests.hpp"
  25277. // 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...
  25278. #if _MSC_VER==1200
  25279. #undef protected
  25280. #endif
  25281. static const char *sortAlgorithm;
  25282. class TestMetaData : public CInterface, implements IOutputMetaData
  25283. {
  25284. public:
  25285. IMPLEMENT_IINTERFACE;
  25286. virtual size32_t getRecordSize(const void *) { return 10; }
  25287. virtual size32_t getMinRecordSize() const { return 10; }
  25288. virtual size32_t getFixedSize() const { return 10; }
  25289. virtual void toXML(const byte * self, IXmlWriter & out) {}
  25290. virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
  25291. virtual unsigned getMetaFlags() { return 0; }
  25292. virtual const RtlTypeInfo * queryTypeInfo() const { return nullptr; }
  25293. virtual void destruct(byte * self) {}
  25294. virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25295. virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25296. virtual ISourceRowPrefetcher * createDiskPrefetcher() { return NULL; }
  25297. virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
  25298. virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25299. virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
  25300. virtual void process(const byte * self, IFieldProcessor & target, unsigned from, unsigned to) {}
  25301. virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
  25302. virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
  25303. virtual const RtlRecord &queryRecordAccessor(bool expand) const { throwUnexpected(); }
  25304. } testMeta;
  25305. class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
  25306. {
  25307. char const * const *input;
  25308. IRoxieSlaveContext *ctx;
  25309. unsigned endSeen;
  25310. bool eof;
  25311. unsigned count;
  25312. ActivityTimeAccumulator totalCycles;
  25313. size32_t recordSize;
  25314. unsigned activityId;
  25315. public:
  25316. enum { STATEreset, STATEstarted, STATEstopped } state;
  25317. bool allRead;
  25318. unsigned repeat;
  25319. IMPLEMENT_IINTERFACE;
  25320. TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
  25321. {
  25322. ctx = _ctx;
  25323. input = _input;
  25324. count = 0;
  25325. eof = false;
  25326. allRead = false;
  25327. endSeen = 0;
  25328. recordSize = testMeta.getFixedSize();
  25329. state = STATEreset;
  25330. activityId = 1;
  25331. repeat = 0;
  25332. }
  25333. virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
  25334. virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
  25335. {
  25336. ASSERT(state == STATEreset);
  25337. }
  25338. virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
  25339. {
  25340. ASSERT(state == STATEreset);
  25341. state = STATEstarted;
  25342. }
  25343. virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
  25344. {
  25345. streams.append(this);
  25346. return NULL;
  25347. }
  25348. virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
  25349. virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
  25350. virtual IRoxieServerActivity *queryActivity()
  25351. {
  25352. throwUnexpected();
  25353. }
  25354. virtual IIndexReadActivityInfo *queryIndexReadActivity()
  25355. {
  25356. throwUnexpected();
  25357. }
  25358. virtual void stop()
  25359. {
  25360. state = STATEstopped;
  25361. }
  25362. virtual void reset()
  25363. {
  25364. ASSERT(state == STATEstopped);
  25365. eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
  25366. }
  25367. virtual void resetEOF()
  25368. {
  25369. throwUnexpected();
  25370. }
  25371. virtual void checkAbort() {}
  25372. virtual unsigned queryId() const { return activityId; };
  25373. virtual const void *nextRow()
  25374. {
  25375. ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
  25376. ASSERT(state == STATEstarted);
  25377. ASSERT(allRead || !eof);
  25378. if (eof)
  25379. return NULL;
  25380. again:
  25381. const char *nextSource = input[count++];
  25382. if (nextSource)
  25383. {
  25384. endSeen = 0;
  25385. void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
  25386. memset(ret, 0, recordSize);
  25387. strncpy((char *) ret, nextSource, recordSize);
  25388. return ret;
  25389. }
  25390. else if (repeat)
  25391. {
  25392. repeat--;
  25393. count = 0;
  25394. goto again;
  25395. }
  25396. else
  25397. {
  25398. endSeen++;
  25399. if (endSeen==2)
  25400. eof = true;
  25401. return NULL;
  25402. }
  25403. }
  25404. virtual bool nextGroup(ConstPointerArray & group)
  25405. {
  25406. const void * next;
  25407. while ((next = nextRow()) != NULL)
  25408. group.append(next);
  25409. if (group.ordinality())
  25410. return true;
  25411. return false;
  25412. }
  25413. virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
  25414. virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
  25415. virtual IFinalRoxieInput *queryInput(unsigned idx) const
  25416. {
  25417. return NULL;
  25418. }
  25419. };
  25420. struct SortActivityTest : public CThorSortArg {
  25421. public:
  25422. struct CompareClass : public ICompare {
  25423. virtual int docompare(const void * _left, const void * _right) const {
  25424. return memcmp(_left, _right, 5);
  25425. }
  25426. } compare;
  25427. virtual ICompare * queryCompare() { return &compare; }
  25428. virtual IOutputMetaData * queryOutputMeta()
  25429. {
  25430. return &testMeta;
  25431. }
  25432. virtual unsigned getAlgorithmFlags() { return TAFunstable; }
  25433. virtual const char * getAlgorithm() { return sortAlgorithm; }
  25434. };
  25435. extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
  25436. struct MergeActivityTest : public CThorMergeArg {
  25437. static bool isDedup;
  25438. public:
  25439. struct CompareClass : public ICompare {
  25440. virtual int docompare(const void * _left, const void * _right) const {
  25441. return memcmp(_left, _right, 5);
  25442. }
  25443. } compare;
  25444. virtual ICompare * queryCompare() { return &compare; }
  25445. virtual IOutputMetaData * queryOutputMeta()
  25446. {
  25447. return &testMeta;
  25448. }
  25449. virtual bool dedup() { return isDedup; }
  25450. };
  25451. bool MergeActivityTest::isDedup = false;
  25452. extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
  25453. struct SplitActivityTest : public CThorSplitArg {
  25454. public:
  25455. virtual unsigned numBranches() { return 2; }
  25456. virtual IOutputMetaData * queryOutputMeta()
  25457. {
  25458. return &testMeta;
  25459. }
  25460. };
  25461. extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
  25462. class CcdServerTest : public CppUnit::TestFixture
  25463. {
  25464. CPPUNIT_TEST_SUITE(CcdServerTest);
  25465. CPPUNIT_TEST(testSetup);
  25466. CPPUNIT_TEST(testHeapSort);
  25467. CPPUNIT_TEST(testQuickSort);
  25468. CPPUNIT_TEST(testMerge);
  25469. CPPUNIT_TEST(testMergeDedup);
  25470. CPPUNIT_TEST(testMiscellaneous);
  25471. CPPUNIT_TEST(testSplitter);
  25472. CPPUNIT_TEST(testCleanup);
  25473. CPPUNIT_TEST_SUITE_END();
  25474. protected:
  25475. SlaveContextLogger logctx;
  25476. Owned<const IQueryDll> queryDll;
  25477. Owned<IRoxiePackage> package;
  25478. Owned<IPropertyTree> stateInfo;
  25479. Owned<IQueryFactory> queryFactory;
  25480. Owned<IRoxieSlaveContext> ctx;
  25481. void testSetup()
  25482. {
  25483. selfTestMode = true;
  25484. roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
  25485. }
  25486. void testCleanup()
  25487. {
  25488. roxiemem::releaseRoxieHeap();
  25489. }
  25490. void init()
  25491. {
  25492. package.setown(createRoxiePackage(NULL, NULL));
  25493. queryDll.setown(createExeQueryDll("roxie"));
  25494. stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
  25495. queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
  25496. ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
  25497. queryActiveTimer()->reset();
  25498. }
  25499. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
  25500. {
  25501. testActivity(activity, input, NULL, output);
  25502. }
  25503. void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
  25504. {
  25505. TestInput in(ctx, input);
  25506. TestInput in2(ctx, input2);
  25507. activity->setInput(0, 0, &in);
  25508. if (input2)
  25509. activity->setInput(1, 0, &in2);
  25510. IFinalRoxieInput *out = activity->queryOutput(outputIdx);
  25511. IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
  25512. IOutputMetaData *meta = out->queryOutputMeta();
  25513. void *buf = alloca(meta->getFixedSize());
  25514. for (unsigned iteration = 0; iteration < 8; iteration++)
  25515. {
  25516. // 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)
  25517. // This should be true whether we read all, some, or none of the data.
  25518. // Should not matter if an activity is not started
  25519. if (iteration % 4 == 0)
  25520. activity->onCreate(NULL);
  25521. unsigned count = 0;
  25522. if (iteration % 4 != 3)
  25523. {
  25524. activity->start(0, NULL, false);
  25525. ASSERT(in.state == TestInput::STATEstarted);
  25526. ASSERT(!input2 || in2.state == TestInput::STATEstarted);
  25527. for (;;)
  25528. {
  25529. const void *next = outStream->nextRow();
  25530. if (!next)
  25531. {
  25532. ASSERT(output[count++] == NULL);
  25533. next = outStream->nextRow();
  25534. if (!next)
  25535. {
  25536. ASSERT(output[count++] == NULL);
  25537. break;
  25538. }
  25539. }
  25540. ASSERT(output[count] != NULL);
  25541. unsigned outsize = meta->getRecordSize(next);
  25542. memset(buf, 0, outsize);
  25543. strncpy((char *) buf, output[count++], outsize);
  25544. ASSERT(memcmp(next, buf, outsize) == 0);
  25545. ReleaseRoxieRow(next);
  25546. if (iteration % 4 == 2)
  25547. break;
  25548. }
  25549. if (iteration % 4 != 2)
  25550. {
  25551. // Check that reading after end is harmless
  25552. in.allRead = true;
  25553. const void *next = outStream->nextRow();
  25554. ASSERT(next == NULL);
  25555. }
  25556. }
  25557. activity->stop();
  25558. ASSERT(in.state == TestInput::STATEstopped);
  25559. ASSERT(!input2 || in2.state == TestInput::STATEstopped);
  25560. activity->reset();
  25561. ASSERT(in.state == TestInput::STATEreset);
  25562. ASSERT(!input2 || in2.state == TestInput::STATEreset);
  25563. ctx->queryRowManager().reportLeaks();
  25564. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25565. }
  25566. }
  25567. void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
  25568. {
  25569. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25570. TestInput in(ctx, input);
  25571. in.repeat = repeat;
  25572. activity->setInput(0, 0, &in);
  25573. ArrayOf<IFinalRoxieInput *> out;
  25574. for (unsigned i = 0; i < numOutputs; i++)
  25575. {
  25576. out.append(activity->queryOutput(i));
  25577. }
  25578. activity->onCreate(NULL);
  25579. class casyncfor: public CAsyncFor
  25580. {
  25581. public:
  25582. casyncfor(ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_output, unsigned _repeat)
  25583. : outputs(_outputs), output(_output), repeat(_repeat)
  25584. {}
  25585. void Do(unsigned i)
  25586. {
  25587. IFinalRoxieInput *out = outputs.item(i);
  25588. IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
  25589. out->start(0, NULL, false);
  25590. IOutputMetaData *meta = out->queryOutputMeta();
  25591. void *buf = alloca(meta->getFixedSize());
  25592. unsigned count = 0;
  25593. unsigned repeats = repeat;
  25594. for (;;)
  25595. {
  25596. const void *next = outStream->nextRow();
  25597. if (!next)
  25598. {
  25599. ASSERT(repeats==0);
  25600. ASSERT(output[count] == NULL);
  25601. count++;
  25602. next = outStream->nextRow();
  25603. if (!next)
  25604. {
  25605. ASSERT(output[count] == NULL);
  25606. count++;
  25607. break;
  25608. }
  25609. }
  25610. if (output[count] == NULL && repeats)
  25611. {
  25612. repeats--;
  25613. count = 0;
  25614. }
  25615. ASSERT(output[count] != NULL);
  25616. unsigned outsize = meta->getRecordSize(next);
  25617. memset(buf, 0, outsize);
  25618. strncpy((char *) buf, output[count++], outsize);
  25619. ASSERT(memcmp(next, buf, outsize) == 0);
  25620. ReleaseRoxieRow(next);
  25621. }
  25622. outStream->stop();
  25623. }
  25624. private:
  25625. ArrayOf<IFinalRoxieInput *> &outputs;
  25626. char const * const *output;
  25627. unsigned repeat;
  25628. } afor(out, output, repeat);
  25629. afor.For(numOutputs, numOutputs);
  25630. ASSERT(in.state == TestInput::STATEstopped);
  25631. for (unsigned i2 = 0; i2 < numOutputs; i2++)
  25632. {
  25633. out.item(i2)->reset();
  25634. }
  25635. ASSERT(in.state == TestInput::STATEreset);
  25636. ctx->queryRowManager().reportLeaks();
  25637. ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
  25638. }
  25639. static int compareFunc(const void *l, const void *r)
  25640. {
  25641. return strcmp(*(char **) l, *(char **) r);
  25642. }
  25643. void testSort(unsigned type)
  25644. {
  25645. init();
  25646. sortAlgorithm = NULL;
  25647. if (type==2)
  25648. sortAlgorithm = "heapSort";
  25649. else
  25650. sortAlgorithm = "quickSort";
  25651. DBGLOG("Testing %s activity", sortAlgorithm);
  25652. Owned<IPropertyTree> dummyNode = createPTree("node");
  25653. Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
  25654. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25655. const char * test[] = { NULL, NULL };
  25656. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25657. const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
  25658. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25659. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25660. const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25661. const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
  25662. const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25663. testActivity(activity, test, test);
  25664. testActivity(activity, test12345, test12345);
  25665. testActivity(activity, test54321, test12345);
  25666. testActivity(activity, test11111, test11111);
  25667. testActivity(activity, test11111_12345, test11111_12345);
  25668. testActivity(activity, test11111_54321, test11111_12345);
  25669. testActivity(activity, test54321_54321, test12345_12345);
  25670. // A few larger tests
  25671. char *input[2002];
  25672. char *output[2002];
  25673. input[2000] = input[2001] = output[2000] = output[2001] = NULL;
  25674. unsigned i;
  25675. // identical
  25676. for (i=0; i<2000; i++)
  25677. {
  25678. input[i] = new char[11];
  25679. output[i] = new char[11];
  25680. sprintf(input[i], "1");
  25681. sprintf(output[i], "1");
  25682. }
  25683. testActivity(activity, input, output);
  25684. // Ascending
  25685. for (i=0; i<2000; i++)
  25686. {
  25687. sprintf(input[i], "%04d", i);
  25688. sprintf(output[i], "%04d", i);
  25689. }
  25690. testActivity(activity, input, output);
  25691. // Almost sorted
  25692. for (i=0; i<20; i++)
  25693. {
  25694. unsigned h = i*100;
  25695. sprintf(input[h], "%04d", 1900-h);
  25696. }
  25697. testActivity(activity, input, output);
  25698. // Descending
  25699. for (i=0; i<2000; i++)
  25700. {
  25701. sprintf(input[i], "%04d", 1999-i);
  25702. sprintf(output[i], "%04d", i);
  25703. }
  25704. testActivity(activity, input, output);
  25705. // Random
  25706. for (i=0; i<2000; i++)
  25707. {
  25708. unsigned r = fastRand() % 1500;
  25709. sprintf(input[i], "%04d", r);
  25710. sprintf(output[i], "%04d", r);
  25711. }
  25712. qsort(output, 2000, sizeof(output[0]), compareFunc);
  25713. testActivity(activity, input, output);
  25714. unsigned __int64 us = factory->queryLocalTimeNs();
  25715. DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
  25716. factory->resetNodeProgressInfo();
  25717. if (type)
  25718. {
  25719. // Other than quicksort, it's supposed to be stable. Let's check that it is
  25720. // All sort identical
  25721. for (i=0; i<2000; i++)
  25722. {
  25723. sprintf(input[i], "1 %d", i);
  25724. sprintf(output[i], "1 %d", i);
  25725. }
  25726. testActivity(activity, input, output);
  25727. // Already sorted
  25728. for (i=0; i<2000; i++)
  25729. {
  25730. sprintf(input[i], "%04d %d", i / 10, i);
  25731. sprintf(output[i], "%04d %d", i / 10, i);
  25732. }
  25733. testActivity(activity, input, output);
  25734. // Reverse order
  25735. for (i=0; i<2000; i++)
  25736. {
  25737. sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
  25738. sprintf(output[i], "%04d %d", i / 10, i%10);
  25739. }
  25740. testActivity(activity, input, output);
  25741. }
  25742. for (i=0; i<2000; i++)
  25743. {
  25744. delete [] input[i];
  25745. delete [] output[i];
  25746. }
  25747. DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
  25748. }
  25749. void testQuickSort()
  25750. {
  25751. testSort(0);
  25752. }
  25753. void testHeapSort()
  25754. {
  25755. testSort(2);
  25756. }
  25757. void testMerge()
  25758. {
  25759. DBGLOG("testMerge");
  25760. init();
  25761. Owned<IPropertyTree> splitterNode = createPTree();
  25762. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25763. factory->setInput(0,0,0);
  25764. factory->setInput(1,0,0);
  25765. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25766. const char * test[] = { NULL, NULL };
  25767. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25768. const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
  25769. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25770. const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
  25771. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25772. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25773. 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 };
  25774. testActivity(activity, test, test, test);
  25775. testActivity(activity, test12345, test, test12345);
  25776. testActivity(activity, test, test12345, test12345);
  25777. testActivity(activity, test12345, test12345, test1122334455);
  25778. testActivity(activity, test11111, test, test11111);
  25779. testActivity(activity, test, test11111, test11111);
  25780. testActivity(activity, test11111, test11111, test1111111111);
  25781. testActivity(activity, test11111_12345, test, test1111112345);
  25782. testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
  25783. // Should really test WHICH side gets kept...
  25784. // Should test with more than 2 inputs...
  25785. DBGLOG("testMerge done");
  25786. }
  25787. void testMergeDedup()
  25788. {
  25789. DBGLOG("testMergeDedup");
  25790. init();
  25791. MergeActivityTest::isDedup = true;
  25792. Owned<IPropertyTree> splitterNode = createPTree();
  25793. Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
  25794. factory->setInput(0,0,0);
  25795. factory->setInput(1,0,0);
  25796. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25797. const char * test[] = { NULL, NULL };
  25798. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25799. const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
  25800. const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
  25801. const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
  25802. testActivity(activity, test11111, test, test11111); // No dedup within a stream
  25803. testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
  25804. testActivity(activity, test, test11111, test11111);
  25805. testActivity(activity, test, test, test);
  25806. testActivity(activity, test12345, test, test12345);
  25807. testActivity(activity, test, test12345, test12345);
  25808. testActivity(activity, test12345, test12345, test12345);
  25809. testActivity(activity, test11111_12345, test, test1111112345);
  25810. testActivity(activity, test11111_12345, test11111_12345, test1111112345);
  25811. // Should really test WHICH side gets kept...
  25812. // Should test with more than 2 inputs...
  25813. DBGLOG("testMergeDedup done");
  25814. }
  25815. void doTestSplitter(unsigned numOutputs)
  25816. {
  25817. DBGLOG("testSplit %d", numOutputs);
  25818. init();
  25819. Owned<IPropertyTree> splitterNode = createPTree();
  25820. Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
  25821. factory->setInput(0,0,0);
  25822. Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
  25823. const char * test[] = { NULL, NULL };
  25824. const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
  25825. unsigned start = msTick();
  25826. testSplitActivity(factory, test, test, numOutputs, 0);
  25827. testSplitActivity(factory, test12345, test12345, numOutputs, 0);
  25828. testSplitActivity(factory, test12345, test12345, numOutputs, 100);
  25829. unsigned elapsed = msTick() - start;
  25830. DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
  25831. }
  25832. void testSplitter()
  25833. {
  25834. doTestSplitter(1);
  25835. doTestSplitter(2);
  25836. doTestSplitter(3);
  25837. doTestSplitter(10);
  25838. }
  25839. void testMiscellaneous()
  25840. {
  25841. DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
  25842. DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
  25843. DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
  25844. ASSERT(sizeof(CJoinGroup) <= 120);
  25845. }
  25846. };
  25847. CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
  25848. CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
  25849. #endif