1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142 |
- /*##############################################################################
- HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- ############################################################################## */
- #include "jmisc.hpp"
- #include "jdebug.hpp"
- #include "jptree.hpp"
- #include "rtlkey.hpp"
- #include "jsort.hpp"
- #include "jhtree.hpp"
- #include "jqueue.tpp"
- #include "jisem.hpp"
- #include "thorxmlread.hpp"
- #include "thorrparse.ipp"
- #include "thorxmlwrite.hpp"
- #include "thorsoapcall.hpp"
- #include "thorcommon.ipp"
- #include "thorsort.hpp"
- #include "thorstats.hpp"
- #include "jlzw.hpp"
- #include "javahash.hpp"
- #include "javahash.tpp"
- #include "thorstep.ipp"
- #include "thorpipe.hpp"
- #include "thorfile.hpp"
- #include "eclhelper.hpp"
- #include "eclrtl_imp.hpp"
- #include "rtlfield_imp.hpp"
- #include "rtlds_imp.hpp"
- #include "rtlread_imp.hpp"
- #include <algorithm>
- #include "dafdesc.hpp"
- #include "dautils.hpp"
- #include "ftbase.ipp"
- namespace ccdserver_hqlhelper
- {
- #include "eclhelper_base.hpp"
- }
- #include "ccd.hpp"
- #include "ccdserver.hpp"
- #include "ccdcontext.hpp"
- #include "ccdactivities.hpp"
- #include "ccdquery.hpp"
- #include "ccdstate.hpp"
- #include "ccdqueue.ipp"
- #include "ccdsnmp.hpp"
- #include "ccddali.hpp"
- #include "jsmartsock.hpp"
- #include "dllserver.hpp"
- #include "workflow.hpp"
- #include "roxiemem.hpp"
- #include "roxierowbuff.hpp"
- #include "roxiehelper.hpp"
- #include "roxielmj.hpp"
- #include "roxierow.hpp"
- #include "thorplugin.hpp"
- #include "keybuild.hpp"
- #include "thorstrand.hpp"
- #define MAX_HTTP_HEADERSIZE 8000
- #define MIN_PAYLOAD_SIZE 800
- #pragma warning(disable : 4355)
- #define DEFAULT_PARALLEL_LOOP_THREADS 1
- #define PROBE
- #ifdef _DEBUG
- //#define FAKE_EXCEPTIONS
- //#define TRACE_JOINGROUPS
- //#define TRACE_SPLIT
- //#define _CHECK_HEAPSORT
- //#undef PARALLEL_EXECUTE
- //#define TRACE_SEEK_REQUESTS
- #endif
- using roxiemem::OwnedRoxieRow;
- using roxiemem::OwnedRoxieString;
- using roxiemem::OwnedConstRoxieRow;
- using roxiemem::IRowManager;
- using roxiemem::ReleaseRoxieRows;
- // 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...
- #if _MSC_VER==1200
- #define protected public
- #endif
- #define TRACE_STARTSTOP // This determines if it is available - it is enabled/disabled by a configuration option
- #define TRACE_STRANDS
- #define MAX_SENSIBLE_STRANDS 1024 // Architecture dependent...
- static const SmartStepExtra dummySmartStepExtra(SSEFreadAhead, NULL);
- //=================================================================================
- class RestartableThread : public CInterface
- {
- class MyThread : public Thread
- {
- Linked<RestartableThread> owner;
- public:
- MyThread(RestartableThread *_owner, const char *name) : Thread(name), owner(_owner)
- {
- }
- virtual int run()
- {
- owner->started.signal();
- return owner->run();
- }
- };
- friend class MyThread;
- Semaphore started;
- Owned<MyThread> thread;
- CriticalSection crit;
- StringAttr name;
- public:
- RestartableThread(const char *_name) : name(_name)
- {
- }
- virtual void start(const char *namePrefix)
- {
- StringBuffer s(namePrefix);
- s.append(name);
- {
- CriticalBlock b(crit);
- assertex(!thread);
- thread.setown(new MyThread(this, s));
- thread->start();
- }
- started.wait();
- }
- virtual void join()
- {
- {
- Owned<Thread> tthread;
- {
- CriticalBlock b(crit);
- tthread.setown(thread.getClear());
- }
- if (tthread)
- tthread->join();
- }
- }
- virtual int run() = 0;
- };
- //================================================================================
- //The following don't link their arguments because that creates a circular reference
- //But I wish there was a better way
- class IndirectSlaveContext : implements IRoxieSlaveContext, public CInterface
- {
- public:
- IndirectSlaveContext(IRoxieSlaveContext * _ctx) : ctx(_ctx) {}
- IMPLEMENT_IINTERFACE
- // void set(IRoxieSlaveContext * _ctx) { ctx = _ctx; }
- virtual ICodeContext *queryCodeContext()
- {
- return ctx->queryCodeContext();
- }
- virtual void checkAbort()
- {
- ctx->checkAbort();
- }
- virtual void notifyAbort(IException *E)
- {
- ctx->notifyAbort(E);
- }
- virtual IActivityGraph * queryChildGraph(unsigned id)
- {
- return ctx->queryChildGraph(id);
- }
- virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
- {
- ctx->noteChildGraph(id, childGraph) ;
- }
- virtual IRowManager &queryRowManager()
- {
- return ctx->queryRowManager();
- }
- virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
- {
- ctx->noteStatistic(kind, value);
- }
- virtual void mergeStats(const CRuntimeStatisticCollection &from) const
- {
- ctx->mergeStats(from);
- }
- virtual const CRuntimeStatisticCollection &queryStats() const
- {
- return ctx->queryStats();
- }
- virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0)))
- {
- ctx->CTXLOGva(format, args);
- }
- virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
- {
- ctx->CTXLOGa(category, prefix, text);
- }
- virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0)))
- {
- ctx->logOperatorExceptionVA(E, file, line, format, args);
- }
- 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)))
- {
- ctx->CTXLOGaeva(E, file, line, prefix, format, args);
- }
- virtual void CTXLOGl(LogItem *log) const
- {
- ctx->CTXLOGl(log);
- }
- virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
- {
- return ctx->getLogPrefix(ret);
- }
- virtual unsigned queryTraceLevel() const
- {
- return ctx->queryTraceLevel();
- }
- virtual bool isIntercepted() const
- {
- return ctx->isIntercepted();
- }
- virtual bool isBlind() const
- {
- return ctx->isBlind();
- }
- virtual const QueryOptions &queryOptions() const
- {
- return ctx->queryOptions();
- }
- virtual void addSlavesReplyLen(unsigned len)
- {
- ctx->addSlavesReplyLen(len);
- }
- virtual const char *queryAuthToken()
- {
- return ctx->queryAuthToken();
- }
- virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
- {
- return ctx->resolveLFN(filename, isOpt);
- }
- virtual IRoxieWriteHandler *createLFN(const char *filename, bool overwrite, bool extend, const StringArray &clusters)
- {
- return ctx->createLFN(filename, overwrite, extend, clusters);
- }
- virtual void onFileCallback(const RoxiePacketHeader &header, const char *lfn, bool isOpt, bool isLocal)
- {
- ctx->onFileCallback(header, lfn, isOpt, isLocal);
- }
- virtual IActivityGraph *getLibraryGraph(const LibraryCallFactoryExtra &extra, IRoxieServerActivity *parentActivity)
- {
- return ctx->getLibraryGraph(extra, parentActivity);
- }
- virtual void noteProcessed(unsigned subgraphId, unsigned activityId, unsigned _idx, unsigned _processed, unsigned _strands) const
- {
- ctx->noteProcessed(subgraphId, activityId, _idx, _processed, _strands);
- }
- virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, unsigned subgraphId, unsigned activityId, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
- {
- ctx->mergeActivityStats(fromStats, subgraphId, activityId, _totalCycles, _localCycles);
- }
- virtual IProbeManager *queryProbeManager() const
- {
- return ctx->queryProbeManager();
- }
- virtual IDebuggableContext *queryDebugContext() const
- {
- return ctx->queryDebugContext();
- }
- virtual void printResults(IXmlWriter *output, const char *name, unsigned sequence)
- {
- ctx->printResults(output, name, sequence);
- }
- virtual void setWUState(WUState state)
- {
- ctx->setWUState(state);
- }
- virtual bool checkWuAborted()
- {
- return ctx->checkWuAborted();
- }
- virtual IWorkUnit *updateWorkUnit() const
- {
- return ctx->updateWorkUnit();
- }
- virtual IConstWorkUnit *queryWorkUnit() const
- {
- return ctx->queryWorkUnit();
- }
- virtual IRoxieServerContext *queryServerContext()
- {
- return ctx->queryServerContext();
- }
- virtual IWorkUnitRowReader *getWorkunitRowReader(const char *wuid, const char * name, unsigned sequence, IXmlToRowTransformer * xmlTransformer, IEngineRowAllocator *rowAllocator, bool isGrouped)
- {
- return ctx->getWorkunitRowReader(wuid, name, sequence, xmlTransformer, rowAllocator, isGrouped);
- }
- virtual IEngineRowAllocator *getRowAllocatorEx(IOutputMetaData * meta, unsigned activityId, roxiemem::RoxieHeapFlags flags) const
- {
- return ctx->getRowAllocatorEx(meta, activityId, flags);
- }
- protected:
- IRoxieSlaveContext * ctx;
- };
- //=================================================================================
- #define RESULT_FLUSH_THRESHOLD 10000u
- #ifdef _DEBUG
- #define SOAP_SPLIT_THRESHOLD 100u
- #define SOAP_SPLIT_RESERVE 200u
- #else
- #define SOAP_SPLIT_THRESHOLD 64000u
- #define SOAP_SPLIT_RESERVE 65535u
- #endif
- //=================================================================================
- // General activity statistics
- static const StatisticsMapping actStatistics(StWhenFirstRow, StTimeElapsed, StTimeLocalExecute, StTimeTotalExecute, StSizeMaxRowSize,
- StNumRowsProcessed, StNumSlaves, StNumStarted, StNumStopped, StNumStrands,
- StNumScansPerRow, StNumAllocations, StNumAllocationScans, StKindNone);
- static const StatisticsMapping joinStatistics(&actStatistics, StNumAtmostTriggered, StKindNone);
- static const StatisticsMapping keyedJoinStatistics(&joinStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
- StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
- StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
- StNumIndexRowsRead, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
- StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
- StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
- StNumDiskRejected, StKindNone);
- static const StatisticsMapping indexStatistics(&actStatistics, StNumServerCacheHits, StNumIndexSeeks, StNumIndexScans, StNumIndexWildSeeks,
- StNumIndexSkips, StNumIndexNullSkips, StNumIndexMerges, StNumIndexMergeCompares,
- StNumPreFiltered, StNumPostFiltered, StNumIndexAccepted, StNumIndexRejected,
- StNumBlobCacheHits, StNumLeafCacheHits, StNumNodeCacheHits,
- StNumBlobCacheAdds, StNumLeafCacheAdds, StNumNodeCacheAdds,
- StNumIndexRowsRead, StKindNone);
- static const StatisticsMapping diskStatistics(&actStatistics, StNumServerCacheHits, StNumDiskRowsRead, StNumDiskSeeks, StNumDiskAccepted,
- StNumDiskRejected, StKindNone);
- static const StatisticsMapping soapStatistics(&actStatistics, StTimeSoapcall, StKindNone);
- static const StatisticsMapping groupStatistics(&actStatistics, StNumGroups, StNumGroupMax, StKindNone);
- static const StatisticsMapping sortStatistics(&actStatistics, StTimeSortElapsed, StKindNone);
- //=================================================================================
- const static unsigned minus1U = (0U-1U);
- class CRoxieServerActivityFactoryBase : public CActivityFactory, implements IRoxieServerActivityFactory
- {
- protected:
- IntArray dependencies; // things I am dependent on
- IntArray dependencyIndexes; // things I am dependent on
- IntArray dependencyControlIds; // things I am dependent on
- StringArray dependencyEdgeIds; // How to describe them to the debugger
- unsigned dependentCount; // things dependent on me
- unsigned optParallel = 0; // -1=enable,0=not specified,1=single-threaded,n=<num threads>
- bool optStableInput = true; // is the input forced to ordered?
- bool optUnstableInput = false; // is the input forced to unordered?
- bool optUnordered = false; // is the output specified as unordered?
- unsigned heapFlags;
- mutable CriticalSection statsCrit;
- mutable __int64 processed;
- mutable __int64 started;
- mutable __int64 totalCycles;
- mutable __int64 localCycles;
- public:
- IMPLEMENT_IINTERFACE;
- CRoxieServerActivityFactoryBase(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind)
- {
- processed = 0;
- started = 0;
- totalCycles = 0;
- localCycles = 0;
- dependentCount = 0;
- optParallel = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
- optUnordered = !_graphNode.getPropBool("att[@name='ordered']/@value", true);
- heapFlags = _graphNode.getPropInt("hint[@name='heapflags']/@value", _queryFactory.queryOptions().heapFlags);
- }
-
- ~CRoxieServerActivityFactoryBase()
- {
- }
- StringBuffer &toString(StringBuffer &ret) const
- {
- return ret.appendf("%p", this);
- }
- virtual void addDependency(unsigned _source, ThorActivityKind _kind, unsigned _sourceIdx, int controlId, const char *edgeId)
- {
- dependencies.append(_source);
- dependencyIndexes.append(_sourceIdx);
- dependencyControlIds.append(controlId);
- dependencyEdgeIds.append(edgeId);
- }
- virtual bool isInputOrdered(bool consumerOrdered, unsigned idx) const
- {
- if (optStableInput)
- return true;
- if (optUnstableInput)
- return false;
- if (optUnordered)
- return false;
- return consumerOrdered;
- }
- virtual void noteDependent(unsigned target)
- {
- dependentCount++;
- }
- virtual IntArray &queryDependencies() { return dependencies; }
- virtual IntArray &queryDependencyIndexes() { return dependencyIndexes; }
- virtual IntArray &queryDependencyControlIds() { return dependencyControlIds; }
- virtual StringArray &queryDependencyEdgeIds() { return dependencyEdgeIds; }
- virtual unsigned queryId() const { return id; }
- virtual unsigned querySubgraphId() const { return subgraphId; }
- virtual ThorActivityKind getKind() const { return kind; }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return meta;
- }
- virtual bool isSink() const
- {
- return false;
- }
- virtual bool isFunction() const
- {
- return false;
- }
- virtual bool isGraphInvariant() const
- {
- return false;
- }
- virtual IHThorArg &getHelper() const
- {
- return *helperFactory();
- }
- virtual IRoxieServerActivity *createFunction(IHThorArg &arg, IProbeManager *_probeManager) const
- {
- arg.Release();
- throwUnexpected();
- }
- virtual void mergeStats(const CRuntimeStatisticCollection &from) const
- {
- CActivityFactory::mergeStats(from);
- }
- virtual void noteProcessed(unsigned _idx, unsigned _processed) const
- {
- dbgassertex(!_idx);
- if (_processed)
- {
- CriticalBlock b(statsCrit);
- processed += _processed;
- }
- }
- virtual void mergeActivityStats(const CRuntimeStatisticCollection &fromStats, const ActivityTimeAccumulator &_totalCycles, cycle_t _localCycles) const
- {
- if (_totalCycles.totalCycles || _localCycles)
- {
- CriticalBlock b(statsCrit);
- dbgassertex(_totalCycles.totalCycles >= _localCycles);
- totalCycles += _totalCycles.totalCycles;
- localCycles += _localCycles;
- }
- CActivityFactory::mergeStats(fromStats);
- }
- virtual void noteStarted() const
- {
- CriticalBlock b(statsCrit);
- started ++;
- }
- virtual void noteStarted(unsigned idx) const
- {
- throwUnexpected(); // should be implemented/required by multiOutput cases only
- }
- virtual void getEdgeProgressInfo(unsigned output, IPropertyTree &edge) const
- {
- CriticalBlock b(statsCrit);
- if (output == 0)
- {
- putStatsValue(&edge, "count", "sum", processed);
- if (started)
- putStatsValue(&edge, "started", "sum", started);
- }
- else
- ERRLOG("unexpected call to getEdgeProcessInfo for output %d in activity %d", output, queryId());
- }
- virtual void getNodeProgressInfo(IPropertyTree &node) const
- {
- CActivityFactory::getNodeProgressInfo(node);
- CriticalBlock b(statsCrit);
- if (started)
- putStatsValue(&node, "_roxieStarted", "sum", started);
- if (totalCycles)
- putStatsValue(&node, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
- if (localCycles)
- putStatsValue(&node, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
- }
- virtual void resetNodeProgressInfo()
- {
- CActivityFactory::resetNodeProgressInfo();
- CriticalBlock b(statsCrit);
- processed = 0;
- started = 0;
- totalCycles = 0;
- localCycles = 0;
- }
- virtual void getActivityMetrics(StringBuffer &reply) const
- {
- CActivityFactory::getActivityMetrics(reply);
- CriticalBlock b(statsCrit);
- putStatsValue(reply, "_roxieStarted", "sum", started);
- putStatsValue(reply, "totalTime", "sum", (unsigned) (cycle_to_nanosec(totalCycles)/1000));
- putStatsValue(reply, "localTime", "sum", (unsigned) (cycle_to_nanosec(localCycles)/1000));
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- return localCycles;
- }
- virtual IQueryFactory &queryQueryFactory() const
- {
- return CActivityFactory::queryQueryFactory();
- }
- virtual ActivityArray *queryChildQuery(unsigned idx, unsigned &id)
- {
- return CActivityFactory::queryChildQuery(idx, id);
- }
- virtual void addChildQuery(unsigned id, ActivityArray *childQuery)
- {
- CActivityFactory::addChildQuery(id, childQuery);
- }
- virtual void onCreateChildQueries(IRoxieSlaveContext *ctx, IHThorArg *colocalArg, IArrayOf<IActivityGraph> &childGraphs, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel) const
- {
- ForEachItemIn(idx, childQueries)
- {
- childGraphs.append(*createActivityGraph(ctx, NULL, childQueryIndexes.item(idx), childQueries.item(idx), parentActivity, _probeManager, _logctx, numParallel));
- ctx->noteChildGraph(childQueryIndexes.item(idx), &childGraphs.item(idx));
- childGraphs.item(idx).onCreate(colocalArg);
- }
- }
- IActivityGraph * createChildGraph(IRoxieSlaveContext * ctx, IHThorArg *colocalArg, unsigned childId, IRoxieServerActivity *parentActivity, IProbeManager * _probeManager, const IRoxieContextLogger &_logctx) const
- {
- unsigned match = childQueryIndexes.find(childId);
- assertex(match != NotFound);
- Owned<IActivityGraph> graph = createActivityGraph(ctx, NULL, childQueryIndexes.item(match), childQueries.item(match), parentActivity, _probeManager, _logctx, 1);
- graph->onCreate(colocalArg);
- return graph.getClear();
- }
- virtual IRoxieServerSideCache *queryServerSideCache() const
- {
- return NULL; // Activities that wish to support server-side caching will need to do better....
- }
- virtual bool getEnableFieldTranslation() const
- {
- throwUnexpected(); // only implemented by index-related subclasses
- }
- virtual IDefRecordMeta *queryActivityMeta() const
- {
- throwUnexpected(); // only implemented by index-related subclasses
- }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- // Most activities have nothing to say...
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return actStatistics; // Overridden by anyone that needs more
- }
- virtual roxiemem::RoxieHeapFlags getHeapFlags() const
- {
- return (roxiemem::RoxieHeapFlags)heapFlags;
- }
- };
- class CRoxieServerMultiInputInfo
- {
- private:
- UnsignedArray inputs;
- UnsignedArray inputIndexes;
- public:
- void set(unsigned idx, unsigned source, unsigned sourceidx)
- {
- if (idx==inputs.length())
- {
- inputs.append(source);
- inputIndexes.append(sourceidx);
- }
- else
- {
- while (!inputs.isItem(idx))
- {
- inputs.append(0);
- inputIndexes.append(0);
- }
- inputs.replace(source, idx);
- inputIndexes.replace(sourceidx, idx);
- }
- }
- unsigned get(unsigned idx, unsigned &sourceidx) const
- {
- if (inputs.isItem(idx))
- {
- sourceidx = inputIndexes.item(idx);
- return inputs.item(idx);
- }
- else
- return (unsigned) -1;
- }
- inline unsigned ordinality() const { return inputs.ordinality(); }
- };
- class CRoxieServerMultiInputFactory : public CRoxieServerActivityFactoryBase
- {
- private:
- CRoxieServerMultiInputInfo inputs;
- public:
- CRoxieServerMultiInputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- inputs.set(idx, source, sourceidx);
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- return inputs.get(idx, sourceidx);
- }
- virtual unsigned numInputs() const { return inputs.ordinality(); }
- };
- class DECL_EXCEPTION CWrappedException : implements IException, public CInterface
- {
- Owned<IException> wrapped;
- ThorActivityKind kind;
- unsigned queryId;
- public:
- IMPLEMENT_IINTERFACE;
- CWrappedException(IException *_wrapped, ThorActivityKind _kind, unsigned _queryId)
- : wrapped(_wrapped), kind(_kind), queryId(_queryId)
- {
- }
- virtual int errorCode() const { return wrapped->errorCode(); }
- virtual StringBuffer & errorMessage(StringBuffer &msg) const { return wrapped->errorMessage(msg).appendf(" (in %s %d)", getActivityText(kind), queryId); }
- virtual MessageAudience errorAudience() const { return wrapped->errorAudience(); }
- };
- class CRoxieServerActivityFactory : public CRoxieServerActivityFactoryBase
- {
- protected:
- unsigned input;
- unsigned inputidx;
- public:
- CRoxieServerActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactoryBase(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- input = (unsigned) -1;
- inputidx = 0;
- }
- inline void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- if (idx != 0)
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: id = %d : setInput() parameter out of bounds idx = %d at %s(%d)", id, idx, sanitizeSourceFile(__FILE__), __LINE__);
- if (input != -1)
- 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__);
- input = source;
- inputidx = sourceidx;
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- if (!idx)
- {
- sourceidx = inputidx;
- return input;
- }
- return (unsigned) -1;
- }
- virtual unsigned numInputs() const { return (input == (unsigned)-1) ? 0 : 1; }
- };
- class CRoxieServerMultiOutputFactory : public CRoxieServerActivityFactory
- {
- protected:
- unsigned numOutputs;
- unsigned __int64 *processedArray;
- bool *startedArray;
- CRoxieServerMultiOutputFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- numOutputs = 0;
- processedArray = NULL;
- startedArray = NULL;
- }
- ~CRoxieServerMultiOutputFactory()
- {
- delete [] processedArray;
- delete [] startedArray;
- }
- void setNumOutputs(unsigned num)
- {
- numOutputs = num;
- if (!num)
- num = 1; // Even sink activities like to track how many records they process
- processedArray = new unsigned __int64[num];
- startedArray = new bool[num];
- for (unsigned i = 0; i < num; i++)
- {
- processedArray[i] = 0;
- startedArray[i] = 0;
- }
- }
- virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
- {
- assertex(numOutputs ? idx < numOutputs : idx==0);
- CriticalBlock b(statsCrit);
- putStatsValue(&edge, "count", "sum", processedArray[idx]);
- putStatsValue(&edge, "started", "sum", startedArray[idx]);
- }
- virtual void resetNodeProgressInfo()
- {
- CRoxieServerActivityFactory::resetNodeProgressInfo();
- CriticalBlock b(statsCrit);
- for (unsigned i = 0; i < numOutputs; i++)
- {
- processedArray[i] = 0;
- startedArray[i] = 0;
- }
- }
- virtual void noteProcessed(unsigned idx, unsigned _processed) const
- {
- assertex(numOutputs ? idx < numOutputs : idx==0);
- CriticalBlock b(statsCrit);
- processedArray[idx] += _processed;
- }
- virtual void noteStarted(unsigned idx) const
- {
- assertex(numOutputs ? idx < numOutputs : idx==0);
- CriticalBlock b(statsCrit);
- startedArray[idx] = true;
- }
- };
- class CRoxieServerInternalSinkFactory : public CRoxieServerActivityFactory
- {
- protected:
- bool isInternal;
- bool isRoot;
- unsigned usageCount;
- public:
- CRoxieServerInternalSinkFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- usageCount = _usageCount;
- isRoot = _isRoot;
- isInternal = false; // filled in by derived class constructor
- }
- virtual bool isSink() const
- {
- //only a sink if a root activity
- 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?
- }
- virtual void getEdgeProgressInfo(unsigned idx, IPropertyTree &edge) const
- {
- // 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
- // Just leave it blank is safest.
- }
- };
- typedef enum { STATEreset, STATEstarted, STATEstopped, STATEstarting } activityState;
- const char *queryStateText(activityState state)
- {
- switch (state)
- {
- case STATEreset: return "reset";
- case STATEstarted: return "started";
- case STATEstopped: return "stopped";
- case STATEstarting: return "starting";
- default: return "unknown";
- }
- }
- typedef ICopyArrayOf<IRoxieServerActivity> IRoxieServerActivityCopyArray;
- class CParallelActivityExecutor : public CAsyncFor
- {
- public:
- unsigned parentExtractSize;
- const byte * parentExtract;
- CParallelActivityExecutor(IRoxieServerActivityCopyArray & _activities, unsigned _parentExtractSize, const byte * _parentExtract) :
- activities(_activities), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
- void Do(unsigned i)
- {
- activities.item(i).execute(parentExtractSize, parentExtract);
- }
- private:
- IRoxieServerActivityCopyArray & activities;
- };
- extern IEngineRowStream * ensureSingleStream(IRoxieSlaveContext *ctx, PointerArrayOf<IEngineRowStream> & instreams, Owned<IStrandJunction> &junction)
- {
- if (instreams.length() != 1)
- {
- assertex(instreams.length());
- if (!junction)
- junction.setown(createStrandJunction(ctx->queryRowManager(), instreams.length(), 1, ctx->queryOptions().strandBlockSize, false));
- ForEachItemIn(stream, instreams)
- {
- junction->setInput(stream, instreams.item(stream));
- }
- return junction->queryOutput(0);
- }
- else
- return instreams.item(0);
- }
- extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, Owned<IStrandJunction> &junction, bool consumerOrdered)
- {
- if (input)
- {
- PointerArrayOf<IEngineRowStream> instreams;
- junction.setown(input->getOutputStreams(ctx, idx, instreams, NULL, consumerOrdered, nullptr));
- return ensureSingleStream(ctx, instreams, junction);
- }
- else
- return NULL;
- }
- extern IEngineRowStream *connectSingleStream(IRoxieSlaveContext *ctx, IFinalRoxieInput *input, unsigned idx, bool consumerOrdered)
- {
- Owned<IStrandJunction> junction;
- IEngineRowStream * result = connectSingleStream(ctx, input, idx, junction, consumerOrdered);
- assertex(!junction);
- return result;
- }
- class CRoxieServerActivity : implements CInterfaceOf<IRoxieServerActivity>, implements IFinalRoxieInput, implements IEngineRowStream, implements IRoxieContextLogger
- {
- friend class StrandProcessor;
- protected:
- IFinalRoxieInput *input;
- unsigned sourceIdx;
- IEngineRowStream *inputStream;
- Owned<IStrandJunction> junction;
- IHThorArg &basehelper;
- IRoxieSlaveContext *ctx;
- const IRoxieServerActivityFactory *factory;
- IRoxieServerActivityCopyArray dependencies;
- IntArray dependencyIndexes;
- IntArray dependencyControlIds;
- IArrayOf<IActivityGraph> childGraphs;
- CachedOutputMetaData meta;
- IHThorArg *colocalParent;
- IEngineRowAllocator *rowAllocator;
- CriticalSection statecrit;
- CriticalSection statscrit;
- mutable CRuntimeStatisticCollection stats;
- MapStringToMyClass<ThorSectionTimer> functionTimers;
- unsigned processed;
- ActivityTimeAccumulator totalCycles;
- cycle_t localCycles;
- unsigned activityId;
- activityState state;
- bool createPending;
- bool debugging;
- bool timeActivities;
- bool aborted;
- bool connected = false;
- IProbeManager *probeManager = NULL;
- public:
- IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IRoxieServerActivity>)
- CRoxieServerActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : ctx(_ctx),
- factory(_factory),
- basehelper(_factory->getHelper()),
- activityId(_factory->queryId()),
- stats(_factory->queryStatsMapping()),
- probeManager(_probeManager)
- {
- input = NULL;
- sourceIdx = 0;
- inputStream = NULL;
- meta.set(basehelper.queryOutputMeta());
- processed = 0;
- localCycles = 0;
- state=STATEreset;
- rowAllocator = NULL;
- debugging = _probeManager != NULL; // Don't want to collect timing stats from debug sessions
- colocalParent = NULL;
- createPending = true;
- timeActivities = defaultTimeActivities;
- aborted = false;
- }
-
- CRoxieServerActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : ctx(_ctx), factory(NULL), basehelper(_helper), stats(allStatistics)
- {
- activityId = 0;
- input = NULL;
- sourceIdx = 0;
- inputStream = NULL;
- ctx = NULL;
- meta.set(basehelper.queryOutputMeta());
- processed = 0;
- localCycles = 0;
- state=STATEreset;
- rowAllocator = NULL;
- debugging = false;
- colocalParent = NULL;
- createPending = true;
- timeActivities = defaultTimeActivities;
- aborted = false;
- }
- ~CRoxieServerActivity()
- {
- if (traceStartStop)
- {
- // There was an old comment here stating // Note- CTXLOG may not be safe
- // There were problems in the destruction order of graphs that might mean an IndirectSlaveContext
- // was released while activities still referenced it.
- // However these should now all be fixed
- DBGLOG("%p destroy %d state=%s", this, activityId, queryStateText(state));
- if (watchActivityId && watchActivityId==activityId)
- {
- DBGLOG("WATCH: %p destroy %d state=%s", this, activityId, queryStateText(state));
- }
- }
- if (state!=STATEreset)
- {
- DBGLOG("STATE: Activity %d destroyed but not reset", activityId);
- state = STATEreset; // bit pointless but there you go...
- }
- if (factory && !debugging)
- {
- if (processed)
- factory->noteProcessed(0, processed);
- factory->mergeActivityStats(stats, totalCycles, localCycles);
- }
- if (ctx && factory)
- {
- if (processed)
- ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, 0);
- ctx->mergeActivityStats(stats, factory->querySubgraphId(), activityId, totalCycles, localCycles);
- }
- basehelper.Release();
- ::Release(rowAllocator);
- }
- virtual const IRoxieContextLogger &queryLogCtx()const
- {
- return *this;
- }
- inline const StatisticsMapping & queryStatsMapping() const
- {
- return factory ? factory->queryStatsMapping() : actStatistics;
- }
- virtual void mergeStats(MemoryBuffer &buf)
- {
- stats.deserializeMerge(buf);
- }
- virtual ISectionTimer *registerTimer(unsigned activityId, const char * name)
- {
- CriticalBlock b(statscrit); // reuse statscrit to protect functionTimers - it will not be held concurrently
- ISectionTimer *timer = functionTimers.getValue(name);
- if (!timer)
- {
- timer = ThorSectionTimer::createTimer(stats, name);
- functionTimers.setValue(name, timer);
- timer->Release(); // Value returned is not linked
- }
- return timer;
- }
- virtual IRoxieServerActivity * queryChildActivity(unsigned activityId)
- {
- ForEachItemIn(i, childGraphs)
- {
- IRoxieServerActivity * activity = childGraphs.item(i).queryActivity(activityId);
- if (activity)
- return activity;
- }
- #ifdef _DEBUG
- throwUnexpectedX("Unable to map child activity id to an activity");
- #endif
- return nullptr;
- }
- void mergeStrandStats(unsigned strandProcessed, const ActivityTimeAccumulator & strandCycles, const CRuntimeStatisticCollection & strandStats)
- {
- CriticalBlock cb(statscrit);
- processed += strandProcessed;
- totalCycles.merge(strandCycles);
- stats.merge(strandStats);
- }
- inline void ensureRowAllocator()
- {
- if (!rowAllocator)
- rowAllocator = createRowAllocator(meta.queryOriginal());
- }
- virtual IEngineRowAllocator * createRowAllocator(IOutputMetaData * metadata)
- {
- return ctx->getRowAllocatorEx(metadata, activityId, factory->getHeapFlags());
- }
- virtual IEngineRowAllocator * createRowAllocatorEx(IOutputMetaData * metadata, roxiemem::RoxieHeapFlags extraFlags)
- {
- return ctx->getRowAllocatorEx(metadata, activityId, (roxiemem::RoxieHeapFlags)(factory->getHeapFlags()|extraFlags));
- }
- inline ICodeContext *queryCodeContext()
- {
- return ctx->queryCodeContext();
- }
- // MORE - most of this is copied from ccd.hpp - can't we refactor?
- virtual void CTXLOGa(TracingCategory category, const char *prefix, const char *text) const
- {
- if (ctx)
- ctx->CTXLOGa(category, prefix, text);
- else
- DBGLOG("[%s] %s", prefix, text);
- }
- 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)))
- {
- if (ctx)
- ctx->CTXLOGaeva(E, file, line, prefix, format, args);
- else
- {
- StringBuffer ss;
- ss.appendf("[%s] ERROR", prefix);
- if (E)
- ss.append(": ").append(E->errorCode());
- if (file)
- ss.appendf(": %s(%d) ", file, line);
- if (E)
- E->errorMessage(ss.append(": "));
- if (format)
- {
- ss.append(": ").valist_appendf(format, args);
- }
- LOG(MCoperatorProgress, unknownJob, "%s", ss.str());
- }
- }
- virtual void CTXLOGl(LogItem *log) const
- {
- if (ctx)
- ctx->CTXLOGl(log);
- else
- {
- assert(ctx);
- log->Release(); // Should never happen
- }
- }
- virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const
- {
- stats.addStatistic(kind, value);
- }
- virtual void mergeStats(const CRuntimeStatisticCollection &from) const
- {
- stats.merge(from);
- }
- virtual const CRuntimeStatisticCollection &queryStats() const
- {
- return stats;
- }
- virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
- {
- if (ctx)
- ctx->getLogPrefix(ret);
- return ret.append('@').append(activityId);
- }
- virtual bool isIntercepted() const
- {
- return ctx ? ctx->isIntercepted() : false;
- }
- virtual bool isBlind() const
- {
- return ctx ? ctx->isBlind() : blindLogging;
- }
- virtual unsigned queryTraceLevel() const
- {
- if (ctx)
- return ctx->queryTraceLevel();
- else
- return traceLevel;
- }
- virtual bool isPassThrough()
- {
- return false;
- }
- virtual const IResolvedFile *resolveLFN(const char *filename, bool isOpt)
- {
- return ctx->resolveLFN(filename, isOpt);
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- throwUnexpected(); // should be implemented in more derived class by anyone that has a remote adaptor
- return NULL;
- }
- virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
- {
- throwUnexpected(); // should be implemented in more derived class wherever needed
- }
- virtual IRoxieSlaveContext *queryContext()
- {
- return ctx;
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return junction; }
- virtual IRoxieServerActivity *queryActivity() { return this; }
- virtual IIndexReadActivityInfo *queryIndexReadActivity() { return NULL; }
- virtual bool needsAllocator() const { return false; }
- void _onCreate(IHThorArg *_colocalParent, unsigned _numParallel)
- {
- colocalParent = _colocalParent;
- createPending = true;
- if (needsAllocator())
- ensureRowAllocator();
- processed = 0;
- if (factory)
- factory->onCreateChildQueries(ctx, &basehelper, childGraphs, this, probeManager, *this, _numParallel);
- if (ctx)
- timeActivities = ctx->queryOptions().timeActivities;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- _onCreate(_colocalParent, 1);
- }
- virtual void serializeCreateStartContext(MemoryBuffer &out)
- {
- //This should only be called after onStart has been called on the helper
- assertex(!createPending);
- assertex(state==STATEstarted);
- unsigned startlen = out.length();
- basehelper.serializeCreateContext(out);
- basehelper.serializeStartContext(out);
- if (queryTraceLevel() > 10)
- CTXLOG("serializeCreateStartContext for %d added %d bytes", activityId, out.length()-startlen);
- }
- virtual void serializeExtra(MemoryBuffer &out) {}
- inline void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CriticalBlock cb(statecrit);
- if (state != STATEreset && state != STATEstarting)
- {
- CTXLOG("STATE: Expected state to be reset, but was %s, in activity %d", queryStateText(state), activityId);
- }
- state=STATEstarted;
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- {
- CTXLOG("start %p %d", this, activityId);
- if (watchActivityId && watchActivityId==activityId)
- {
- CTXLOG("WATCH: start %p %d", this, activityId);
- }
- }
- #endif
- executeDependencies(parentExtractSize, parentExtract, 0);
- if (input)
- input->start(parentExtractSize, parentExtract, paused);
- ensureCreated();
- basehelper.onStart(parentExtract, NULL);
- if (factory)
- factory->noteStarted();
- startJunction(junction);
- }
- void executeDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
- {
- //MORE: Create a filtered list and then use asyncfor
- ForEachItemIn(idx, dependencies)
- {
- if (dependencyControlIds.item(idx) == controlId)
- dependencies.item(idx).execute(parentExtractSize, parentExtract);
- }
- }
- void stopDependencies(unsigned parentExtractSize, const byte *parentExtract, unsigned controlId)
- {
- ForEachItemIn(idx, dependencies)
- {
- if (dependencyControlIds.item(idx) == controlId)
- dependencies.item(idx).stop();
- }
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return totalCycles.totalCycles;
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 ret = totalCycles.totalCycles;
- if (input) ret -= input->queryTotalCycles();
- if (ret < 0)
- ret = 0;
- return ret;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return input;
- else
- return NULL;
- }
- inline void ensureCreated()
- {
- if (createPending)
- {
- createPending = false;
- basehelper.onCreate(ctx->queryCodeContext(), colocalParent, NULL);
- }
- }
- virtual void stop()
- {
- // NOTE - don't be tempted to skip the stop for activities that are reset - splitters need to see the stops
- if (state != STATEstopped)
- {
- CriticalBlock cb(statecrit);
- if (state != STATEstopped)
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- {
- CTXLOG("stop %p %d (state currently %s)", this, activityId, queryStateText(state));
- if (watchActivityId && watchActivityId==activityId)
- {
- CTXLOG("WATCH: stop %p %d", this, activityId);
- }
- }
- #endif
- state=STATEstopped;
- // NOTE - this is needed to ensure that dependencies which were not used are properly stopped
- ForEachItemIn(idx, dependencies)
- {
- if (dependencyControlIds.item(idx) == 0)
- dependencies.item(idx).stopSink(dependencyIndexes.item(idx));
- }
- if (inputStream)
- inputStream->stop();
- if (rowAllocator)
- {
- stats.reset(heapStatistics);
- rowAllocator->gatherStats(stats);
- }
- }
- }
- }
- virtual void abort()
- {
- aborted = true;
- // MORE - should abort dependencies here?
- stop();
- }
- inline void reset()
- {
- if (state != STATEreset)
- {
- CriticalBlock cb(statecrit);
- if (state != STATEreset)
- {
- if (state==STATEstarted || state==STATEstarting)
- {
- if (traceStartStop || traceLevel > 2)
- CTXLOG("STATE: activity %d reset without stop", activityId);
- stop();
- }
- state = STATEreset;
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- {
- CTXLOG("reset %p %d", this, activityId);
- if (watchActivityId && watchActivityId==activityId)
- {
- CTXLOG("WATCH: reset %p %d", this, activityId);
- }
- }
- #endif
- resetJunction(junction);
- ForEachItemIn(idx, dependencies)
- dependencies.item(idx).reset();
- localCycles = queryLocalCycles(); // We can't call queryLocalCycles() in the destructor, so save the information here when we can.
- if (input)
- input->reset();
- }
- }
- aborted = false;
- }
- virtual void addDependency(IRoxieServerActivity &source, unsigned sourceIdx, int controlId)
- {
- dependencies.append(source);
- dependencyIndexes.append(sourceIdx);
- dependencyControlIds.append(controlId);
- }
- virtual void resetEOF()
- {
- //would make more sense if the default implementation (and eof member) were in the base class
- }
- // Sink activities should override this....
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- throw MakeStringException(ROXIE_SINK, "Internal error: execute() requires a sink");
- }
- virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
- {
- throw MakeStringException(ROXIE_SINK, "Internal error: executeChild() requires a suitable sink");
- }
- virtual void stopSink(unsigned idx)
- {
- throw MakeStringException(ROXIE_SINK, "Internal error: stopSink() requires a suitable sink");
- }
- virtual void connectInputStreams(bool consumerOrdered)
- {
- if (input && !inputStream)
- inputStream = connectSingleStream(ctx, input, sourceIdx, junction, isInputOrdered(consumerOrdered, 0));
- if (!connected)
- {
- connectDependencies();
- connected = true;
- }
- }
- void connectDependencies()
- {
- ForEachItemIn(i, dependencies)
- dependencies.item(i).connectInputStreams(true);
- }
- virtual __int64 evaluate()
- {
- throw MakeStringException(ROXIE_SINK, "Internal error: evaluate() requires a function");
- }
- virtual IFinalRoxieInput * querySelectOutput(unsigned id)
- {
- return NULL;
- }
- virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
- {
- return false;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- assertex(!idx);
- input = _in;
- sourceIdx = _sourceIdx;
- inputStream = NULL;
- }
- bool isInputOrdered(bool consumerOrdered, unsigned idx) const
- {
- if (!factory)
- return true;
- //Grouping implies the stream processing must be ordered - I think this always applies
- IFinalRoxieInput * curInput = queryInput(idx);
- if (curInput && curInput->queryOutputMeta()->isGrouped())
- return true;
- return factory->isInputOrdered(consumerOrdered, idx);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- assertex(!idx);
- // By default, activities are assumed NOT to support streams
- bool inputOrdered = isInputOrdered(consumerOrdered, 0);
- connectInputStreams(inputOrdered);
- // Return a single stream
- streams.append(this);
- return NULL;
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx == (unsigned) -1)
- idx = 0;
- return idx ? NULL : this;
- }
- virtual IOutputMetaData *queryOutputMeta() const
- {
- return meta.queryOriginal();
- }
- virtual unsigned queryId() const
- {
- return activityId;
- }
- virtual unsigned querySubgraphId() const
- {
- return factory->querySubgraphId();
- }
- virtual void checkAbort()
- {
- ctx->checkAbort();
- }
- IException *makeWrappedException(IException *e)
- {
- StringBuffer msg;
- ThorActivityKind activityKind = factory ? factory->getKind() : TAKnone;
- CTXLOG("makeWrappedException - %s (in %s %d)", e->errorMessage(msg).str(), getActivityText(activityKind), activityId);
- if (QUERYINTERFACE(e, CWrappedException) || QUERYINTERFACE(e, IUserException))
- return e;
- else
- return new CWrappedException(e, activityKind, activityId);
- }
- virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
- {
- }
- virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
- {
- }
- virtual void resetOutputsUsed()
- {
- }
- virtual void noteOutputUsed()
- {
- }
- virtual IRoxieServerSideCache *queryServerSideCache() const
- {
- return factory->queryServerSideCache();
- }
- virtual const IRoxieServerActivityFactory *queryFactory() const
- {
- return factory;
- }
- inline ThorActivityKind getKind() const
- {
- return factory->getKind();
- }
- inline bool isSink() const
- {
- return (factory != NULL) && factory->isSink();
- }
- };
- //=====================================================================================================
- class CRoxieServerLateStartActivity : public CRoxieServerActivity
- {
- protected:
- bool prefiltered;
- bool eof;
- void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
- {
- prefiltered = !any;
- eof = prefiltered;
- if (!prefiltered)
- {
- input->start(parentExtractSize, parentExtract, false);
- startJunction(junction);
- }
- else
- {
- if (traceStartStop)
- CTXLOG("lateStart activity stopping input early as prefiltered");
- inputStream->stop();
- }
- }
- public:
- CRoxieServerLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- prefiltered = false;
- eof = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- IFinalRoxieInput *saveInput = input;
- Owned<IStrandJunction> saveJunction = junction.getClear();
- input = NULL; // Make sure parent does not start the chain yet
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- input = saveInput;
- junction.setown(saveJunction.getClear());
- }
- virtual void stop()
- {
- if (!prefiltered)
- {
- inputStream->stop();
- }
- else if (traceStartStop)
- CTXLOG("lateStart activity NOT stopping input late as prefiltered");
- IEngineRowStream *save = inputStream;
- inputStream = NULL; // We already stopped inputStream - prevent parent from doing so again
- CRoxieServerActivity::stop();
- inputStream = save;
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- prefiltered = false;
- }
- };
- //=================================================================================
- class StrandOptions
- {
- // Typically set from hints, common to many stranded activities
- public:
- explicit StrandOptions(IPropertyTree &_graphNode)
- {
- //PARALLEL(1) can be used to explicitly disable parallel processing.
- numStrands = _graphNode.getPropInt("att[@name='parallel']/@value", 0);
- if ((numStrands == minus1U) || (numStrands > MAX_SENSIBLE_STRANDS))
- numStrands = getAffinityCpus();
- blockSize = _graphNode.getPropInt("hint[@name='strandblocksize']/@value", 0);
- }
- StrandOptions(const StrandOptions &from, IRoxieSlaveContext *ctx)
- {
- numStrands = from.numStrands;
- blockSize = from.blockSize;
- if (!blockSize)
- blockSize = ctx->queryOptions().strandBlockSize;
- if (numStrands == 0)
- numStrands = ctx->queryOptions().forceNumStrands;
- }
- public:
- unsigned numStrands = 0; // if 1 it forces single-stranded operations. (Useful for testing.)
- unsigned blockSize = 0;
- };
- class StrandProcessor : public CInterfaceOf<IEngineRowStream>
- {
- protected:
- CRoxieServerActivity &parent;
- IEngineRowAllocator *rowAllocator;
- IEngineRowStream *inputStream;
- ActivityTimeAccumulator totalCycles;
- mutable CRuntimeStatisticCollection stats;
- unsigned processed = 0;
- unsigned numProcessedLastGroup = 0;
- const bool timeActivities;
- bool stopped = false;
- std::atomic<bool> abortRequested;
- public:
- explicit StrandProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, bool needsAllocator)
- : parent(_parent), inputStream(_inputStream), stats(parent.queryStatsMapping()), timeActivities(_parent.timeActivities), abortRequested(false)
- {
- if (needsAllocator)
- {
- rowAllocator = parent.createRowAllocatorEx(parent.queryOutputMeta(), roxiemem::RHFunique);
- }
- else
- rowAllocator = NULL;
- }
- ~StrandProcessor()
- {
- ::Release(rowAllocator);
- }
- virtual void start()
- {
- processed = 0;
- numProcessedLastGroup = 0;
- totalCycles.reset();
- stats.reset();
- }
- virtual void stop()
- {
- if (!stopped)
- {
- if (inputStream)
- inputStream->stop();
- stats.reset(heapStatistics); // Heap stats are always gathered from scratch each time
- if (rowAllocator)
- rowAllocator->gatherStats(stats);
- parent.stop();
- parent.mergeStrandStats(processed, totalCycles, stats);
- }
- stopped = true;
- }
- virtual void reset()
- {
- stopped = false;
- abortRequested.store(false, std::memory_order_relaxed);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- inline void requestAbort() { abortRequested.store(true, std::memory_order_relaxed); }
- inline bool isAborting() { return abortRequested.load(std::memory_order_relaxed); }
- };
- class CRoxieServerStrandedActivity : public CRoxieServerActivity
- {
- protected:
- StrandOptions strandOptions;
- IArrayOf<StrandProcessor> strands;
- Owned<IStrandBranch> branch;
- Owned<IStrandJunction> splitter;
- Owned<IStrandJunction> sourceJunction; // A junction applied to the output of a source activity
- std::atomic<unsigned> active;
- public:
- CRoxieServerStrandedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- strandOptions(_strandOptions, ctx)
- {
- active = 0;
- }
- ~CRoxieServerStrandedActivity()
- {
- if (strands.ordinality() > 1)
- {
- if (factory && !debugging)
- factory->noteProcessed(0, processed);
- if (ctx && factory)
- ctx->noteProcessed(factory->querySubgraphId(), activityId, 0, processed, strands.ordinality());
- processed = 0; // To avoid reprocessing in base destructor
- }
- }
- virtual void onCreate(IHThorArg *_colocalArg)
- {
- CRoxieServerActivity::_onCreate(_colocalArg, strands.ordinality());
- }
- //This function is pure (But also implemented out of line) to force the derived classes to implement it.
- //After calling the base class start method, and initialising any values from the helper they must call onStartStrands(),
- //this must also happen before any rows are read from the strands (e.g., by a source junction)
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) = 0;
- virtual void reset()
- {
- assertex(active==0);
- ForEachItemIn(idx, strands)
- strands.item(idx).reset();
- resetJunction(splitter);
- CRoxieServerActivity::reset();
- resetJunction(sourceJunction);
- }
- virtual void stop()
- {
- // Called from the strands... which should ensure that stop is not called more than once per strand
- //The first strand to call
- if (active)
- --active;
- if (!active)
- CRoxieServerActivity::stop();
- }
- void requestAbort()
- {
- ForEachItemIn(idx, strands)
- strands.item(idx).requestAbort();
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- assertex(idx == 0);
- assertex(strands.empty());
- CRoxieServerActivity::connectDependencies();
- bool inputOrdered = isInputOrdered(consumerOrdered, idx);
- //Note, numStrands == 1 is an explicit request to disable threading
- if (consumerOptions && (consumerOptions->numStrands != 1) && (strandOptions.numStrands != 1))
- {
- //Check to see if the consumer's settings should override
- if (strandOptions.numStrands == 0)
- {
- strandOptions.numStrands = consumerOptions->numStrands;
- strandOptions.blockSize = consumerOptions->blockSize;
- }
- else if (consumerOptions->numStrands > strandOptions.numStrands)
- {
- strandOptions.numStrands = consumerOptions->numStrands;
- }
- }
- Owned <IStrandJunction> recombiner;
- if (input)
- {
- if (strandOptions.numStrands == 1)
- {
- // 1 means explicitly requested single-strand.
- IEngineRowStream *instream = connectSingleStream(ctx, input, sourceIdx, junction, inputOrdered);
- strands.append(*createStrandProcessor(instream));
- }
- else
- {
- PointerArrayOf<IEngineRowStream> instreams;
- recombiner.setown(input->getOutputStreams(ctx, sourceIdx, instreams, &strandOptions, inputOrdered, orderedCallbacks));
- if ((instreams.length() == 1) && (strandOptions.numStrands != 0)) // 0 means did not specify - we should use the strands that our upstream provides
- {
- assertex(recombiner == NULL);
- // Create a splitter to split the input into n... and a recombiner if need to preserve sorting
- if (inputOrdered)
- {
- branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, input->queryOutputMeta()->isGrouped(), false, orderedCallbacks));
- splitter.set(branch->queryInputJunction());
- recombiner.set(branch->queryOutputJunction());
- }
- else
- {
- splitter.setown(createStrandJunction(ctx->queryRowManager(), 1, strandOptions.numStrands, strandOptions.blockSize, false));
- }
- splitter->setInput(0, instreams.item(0));
- for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
- strands.append(*createStrandProcessor(splitter->queryOutput(strandNo)));
- }
- else
- {
- // Ignore my hint and just use the width already split into...
- ForEachItemIn(strandNo, instreams)
- strands.append(*createStrandProcessor(instreams.item(strandNo)));
- }
- }
- }
- else
- {
- unsigned numStrands = strandOptions.numStrands ? strandOptions.numStrands : 1;
- for (unsigned i=0; i < numStrands; i++)
- strands.append(*createStrandSourceProcessor(inputOrdered));
- if (inputOrdered && (numStrands > 1))
- {
- if (consumerOptions)
- {
- //If the output activities are also stranded then need to create a version of the branch
- bool isGrouped = queryOutputMeta()->isGrouped();
- branch.setown(createStrandBranch(ctx->queryRowManager(), strandOptions.numStrands, strandOptions.blockSize, true, isGrouped, true, orderedCallbacks));
- sourceJunction.set(branch->queryInputJunction());
- recombiner.set(branch->queryOutputJunction());
- assertex((orderedCallbacks && !recombiner) || (!orderedCallbacks && recombiner));
- //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
- for (unsigned strandNo = 0; strandNo < strandOptions.numStrands; strandNo++)
- {
- sourceJunction->setInput(strandNo, &strands.item(strandNo));
- streams.append(sourceJunction->queryOutput(strandNo));
- }
- #ifdef TRACE_STRANDS
- if (traceLevel > 2)
- DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
- #endif
- return recombiner.getClear();
- }
- else
- {
- //Feeding into a non threaded activity, so create a M:1 junction to combine the source strands
- recombiner.setown(createStrandJunction(ctx->queryRowManager(), numStrands, 1, strandOptions.blockSize, inputOrdered));
- }
- }
- }
- ForEachItemIn(i, strands)
- streams.append(&strands.item(i));
- #ifdef TRACE_STRANDS
- if (traceLevel > 2)
- DBGLOG("Executing activity %u with %u strands", activityId, strands.ordinality());
- #endif
- return recombiner.getClear();
- }
- virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) = 0;
- //MORE: Possibly this class should be split into two for sinks and non sinks...
- virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) = 0;
- virtual const void * nextRow()
- {
- throwUnexpected();
- }
- inline unsigned numStrands() const { return strands.ordinality(); }
- protected:
- void onStartStrands()
- {
- ForEachItemIn(idx, strands)
- {
- strands.item(idx).start();
- active++;
- }
- }
- };
- //For some reason gcc doesn't let you specify a function as pure virtual and define it at the same time.
- void CRoxieServerStrandedActivity::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- startJunction(splitter);
- }
- class CRoxieServerStrandedLateStartActivity : public CRoxieServerStrandedActivity
- {
- protected:
- bool prefiltered;
- bool eof;
- void lateStart(unsigned parentExtractSize, const byte *parentExtract, bool any)
- {
- prefiltered = !any;
- eof = prefiltered;
- if (!prefiltered)
- {
- //At this point
- input->start(parentExtractSize, parentExtract, false);
- startJunction(splitter);
- onStartStrands(); // Initialise the strands - the helper will have been correctly initialized by this point.
- startJunction(sourceJunction);
- }
- else
- {
- if (traceStartStop)
- CTXLOG("strandedLateStart activity stopping input early as prefiltered");
- ForEachItemIn(idx, strands)
- strands.item(idx).stop();
- }
- }
- public:
- CRoxieServerStrandedLateStartActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
- : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
- {
- prefiltered = false;
- eof = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- IFinalRoxieInput *save = input;
- 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)
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- input = save;
- }
- virtual void reset()
- {
- CRoxieServerStrandedActivity::reset();
- prefiltered = false;
- }
- };
- //=====================================================================================================
- atomic_t nextInstanceId;
- extern unsigned getNextInstanceId()
- {
- return atomic_add_exchange(&nextInstanceId, 1)+1;
- }
- atomic_t nextRuid;
- ruid_t getNextRuid()
- {
- ruid_t ret = atomic_add_exchange(&nextRuid, 1)+1;
- while (ret < RUID_FIRST)
- ret = atomic_add_exchange(&nextRuid, 1)+1; // ruids 0 and 1 are reserved for pings/unwanted discarder.
- return ret;
- }
- void setStartRuid(unsigned restarts)
- {
- atomic_set(&nextRuid, restarts * 0x10000);
- atomic_set(&nextInstanceId, restarts * 10000);
- }
- enum { LimitSkipErrorCode = 0, KeyedLimitSkipErrorCode = 1 };
- class DECL_EXCEPTION LimitSkipException : public IException, public CInterface
- {
- int code;
- public:
- LimitSkipException(int _code) { code = _code; }
- IMPLEMENT_IINTERFACE;
- virtual int errorCode() const { return code; }
- virtual StringBuffer & errorMessage(StringBuffer &msg) const { return msg.append("LimitSkipException"); }
- virtual MessageAudience errorAudience() const { return MSGAUD_internal; }
- };
- IException *makeLimitSkipException(bool isKeyed)
- {
- // We need to make sure what we throw is IException not something derived from it....
- return new LimitSkipException(isKeyed ? KeyedLimitSkipErrorCode : LimitSkipErrorCode);
- }
- //=================================================================================
- interface IRecordPullerCallback : extends IExceptionHandler
- {
- virtual void processRow(const void *row) = 0;
- virtual void processEOG() = 0;
- virtual void processGroup(const ConstPointerArray &rows) = 0;
- virtual void processDone() = 0;
- };
- class RecordPullerThread : public RestartableThread
- {
- protected:
- IFinalRoxieInput *input;
- Owned<IStrandJunction> junction;
- unsigned sourceIdx = 0;
- IEngineRowStream *inputStream;
- IRecordPullerCallback *helper;
- Semaphore started; // MORE: GH->RKC I'm pretty sure this can be deleted, since handled by RestartableThread
- bool groupAtOnce, eof, eog;
- CriticalSection crit;
- public:
- RecordPullerThread(bool _groupAtOnce)
- : RestartableThread("RecordPullerThread"), groupAtOnce(_groupAtOnce)
- {
- input = NULL;
- inputStream = NULL;
- helper = NULL;
- eof = eog = FALSE;
- }
- inline unsigned __int64 queryTotalCycles() const
- {
- return input->queryTotalCycles();
- }
- void setInput(IRecordPullerCallback *_helper, unsigned _sourceIdx, IFinalRoxieInput *_input)
- {
- helper = _helper;
- input = _input;
- sourceIdx = _sourceIdx;
- }
- IFinalRoxieInput *queryInput() const
- {
- return input;
- }
- virtual void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
- {
- inputStream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
- }
- IEngineRowStream *queryStream() const
- {
- return inputStream;
- }
- void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, unsigned preload, bool noThread, IRoxieSlaveContext *ctx)
- {
- eof = false;
- eog = false;
- input->start(parentExtractSize, parentExtract, paused);
- startJunction(junction);
- try
- {
- if (preload && !paused)
- {
- if (traceLevel > 4)
- DBGLOG("Preload fetching first %d records", preload);
- if (groupAtOnce)
- pullGroups(preload);
- else
- pullRecords(preload);
- }
- if (eof)
- {
- if (traceLevel > 4)
- DBGLOG("No need to start puller after preload");
- helper->processDone();
- }
- else
- {
- if (!noThread)
- {
- StringBuffer logPrefix("[");
- if (ctx) ctx->getLogPrefix(logPrefix);
- logPrefix.append("] ");
- RestartableThread::start(logPrefix);
- started.wait();
- }
- }
- }
- catch (IException *e)
- {
- helper->fireException(e);
- }
- catch (...)
- {
- helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::start"));
- }
- }
- void stop()
- {
- if (traceStartStop)
- DBGLOG("RecordPullerThread::stop");
- {
- 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.
- if (inputStream)
- inputStream->stop();
- }
- RestartableThread::join();
- }
- void reset()
- {
- input->reset();
- resetJunction(junction);
- }
- virtual int run()
- {
- started.signal();
- try
- {
- if (groupAtOnce)
- pullGroups((unsigned) -1);
- else
- pullRecords((unsigned) -1);
- helper->processDone();
- }
- catch (IException *e)
- {
- helper->fireException(e);
- }
- catch (...)
- {
- helper->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in RecordPullerThread::run"));
- }
- return 0;
- }
- void done()
- {
- helper->processDone();
- }
- bool pullRecords(unsigned preload)
- {
- if (eof)
- return false;
- while (preload)
- {
- const void * row;
- {
- CriticalBlock c(crit); // See comments in stop for why this is needed
- row = inputStream->nextRow();
- }
- if (row)
- {
- eog = false;
- helper->processRow(row);
- }
- else if (!eog)
- {
- helper->processEOG();
- eog = true;
- }
- else
- {
- eof = true;
- return false;
- }
- if (preload != (unsigned) -1)
- preload--;
- }
- return true;
- }
- void pullGroups(unsigned preload)
- {
- ConstPointerArray thisGroup;
- unsigned rowsDone = 0;
- while (preload && !eof)
- {
- const void *row;
- {
- CriticalBlock c(crit);
- row = inputStream->nextRow();
- }
- if (row)
- {
- thisGroup.append(row);
- rowsDone++;
- }
- else if (thisGroup.length())
- {
- helper->processGroup(thisGroup);
- thisGroup.kill();
- if (preload != (unsigned) -1)
- {
- if (preload > rowsDone)
- preload -= rowsDone;
- else
- break;
- }
- rowsDone = 0;
- }
- else
- {
- eof = true;
- break;
- }
- }
- }
- };
- //=================================================================================
- #define READAHEAD_SIZE 1000
- // MORE - this code copied from ThreadedConcat code - may be able to common up some.
- class CRoxieServerReadAheadInput : implements IEngineRowStream, implements IFinalRoxieInput, implements IRecordPullerCallback, public CInterface
- {
- QueueOf<const void, true> buffer;
- InterruptableSemaphore ready;
- InterruptableSemaphore space;
- CriticalSection crit;
- bool eof;
- bool disabled;
- IRoxieSlaveContext *ctx;
- RecordPullerThread puller;
- unsigned preload;
- cycle_t totalCycles;
- bool timeActivities;
- public:
- IMPLEMENT_IINTERFACE;
- CRoxieServerReadAheadInput(IRoxieSlaveContext *_ctx, unsigned _preload) : ctx(_ctx), puller(true), preload(_preload)
- {
- eof = false;
- disabled = (ctx->queryDebugContext() != NULL);
- totalCycles = 0;
- timeActivities = ctx->queryOptions().timeActivities;
- }
- virtual IRoxieServerActivity *queryActivity()
- {
- return puller.queryInput()->queryActivity();
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- assertex(!idx);
- puller.connectInputStreams(ctx, consumerOrdered);
- streams.append(this);
- return NULL;
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- return puller.queryInput()->queryIndexReadActivity();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- if (disabled)
- puller.queryInput()->start(parentExtractSize, parentExtract, paused);
- else
- {
- space.reinit(READAHEAD_SIZE);
- ready.reinit();
- puller.start(parentExtractSize, parentExtract, paused, preload, false, ctx);
- }
- }
- virtual void stop()
- {
- if (disabled)
- puller.queryStream()->stop();
- else
- {
- space.interrupt();
- ready.interrupt();
- puller.stop();
- }
- }
- virtual void reset()
- {
- if (disabled)
- puller.queryInput()->reset();
- else
- {
- puller.reset();
- ForEachItemIn(idx1, buffer)
- ReleaseRoxieRow(buffer.item(idx1));
- buffer.clear();
- }
- }
- virtual void resetEOF()
- {
- throwUnexpected();
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return puller.queryInput()->queryOutputMeta();
- }
- void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- assertex(!idx);
- puller.setInput(this, _sourceIdx, _in);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return puller.queryInput();
- else
- return NULL;
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return totalCycles;
- }
- virtual const void * nextRow()
- {
- SimpleActivityTimer t(totalCycles, timeActivities);
- if (disabled)
- return puller.queryStream()->nextRow();
- else
- {
- loop
- {
- {
- CriticalBlock b(crit);
- if (eof && !buffer.ordinality())
- return NULL; // eof
- }
- ready.wait();
- const void *ret;
- {
- CriticalBlock b(crit);
- ret = buffer.dequeue();
- }
- space.signal();
- return ret;
- }
- }
- }
- virtual bool fireException(IException *e)
- {
- // called from puller thread on failure
- ready.interrupt(LINK(e));
- space.interrupt(e);
- return true;
- }
- virtual void processRow(const void *row)
- {
- {
- CriticalBlock b(crit);
- buffer.enqueue(row);
- }
- ready.signal();
- space.wait();
- }
- virtual void processGroup(const ConstPointerArray &rows)
- {
- // NOTE - a bit bizarre in that it waits for the space AFTER using it.
- // But the space semaphore is only there to stop infinite readahead. And otherwise it would deadlock
- // if group was larger than max(space)
- {
- CriticalBlock b(crit);
- ForEachItemIn(idx, rows)
- buffer.enqueue(rows.item(idx));
- buffer.enqueue(NULL);
- }
- for (unsigned i2 = 0; i2 <= rows.length(); i2++) // note - does 1 extra for the null
- {
- ready.signal();
- space.wait();
- }
- }
- virtual void processEOG()
- {
- // Used when output is not grouped - just ignore
- }
- virtual void processDone()
- {
- CriticalBlock b(crit);
- eof = true;
- ready.signal();
- }
- };
- //=================================================================================
- class CRoxieServerTwoInputActivity : public CRoxieServerActivity
- {
- protected:
- IFinalRoxieInput *input1;
- IEngineRowStream *inputStream1;
- Owned<IStrandJunction> junction1;
- unsigned sourceIdx1 = 0;
- Owned<CRoxieServerReadAheadInput> puller;
- public:
- CRoxieServerTwoInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- input1 = NULL;
- inputStream1 = NULL;
- }
- ~CRoxieServerTwoInputActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- input1->start(parentExtractSize, parentExtract, paused);
- startJunction(junction1);
- }
- virtual void stop()
- {
- inputStream1->stop();
- CRoxieServerActivity::stop();
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 ret;
- __int64 inputCycles = input->queryTotalCycles();
- __int64 input1Cycles = input1->queryTotalCycles();
- if (puller)
- ret = totalCycles.totalCycles - (inputCycles > input1Cycles ? inputCycles : input1Cycles);
- else
- ret = totalCycles.totalCycles - (inputCycles + input1Cycles);
- if (ret < 0)
- ret = 0;
- return ret;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- switch (idx)
- {
- case 0:
- return input;
- case 1:
- return input1;
- default:
- return NULL;
- }
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- if (input1)
- input1->reset();
- resetJunction(junction1);
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- switch(idx)
- {
- case 0:
- CRoxieServerActivity::setInput(idx, _sourceIdx, _in);
- break;
- case 1:
- input1 = _in;
- sourceIdx1 = _sourceIdx;
- break;
- default:
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- }
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- inputStream1 = connectSingleStream(ctx, input1, sourceIdx1, junction1, isInputOrdered(consumerOrdered, 1));
- //Assumes input1 will be stranded if any.
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- };
- //=================================================================================
- class CRoxieServerMultiInputBaseActivity : public CRoxieServerActivity
- {
- protected:
- unsigned numInputs;
- unsigned numStreams;
- IFinalRoxieInput **inputArray;
- unsigned *sourceIdxArray;
- IEngineRowStream **streamArray;
- Owned<IStrandJunction> *junctionArray;
- public:
- CRoxieServerMultiInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), numInputs(_numInputs)
- {
- numStreams = numInputs;
- inputArray = new IFinalRoxieInput*[numInputs];
- sourceIdxArray = new unsigned[numInputs];
- streamArray = new IEngineRowStream*[numStreams];
- junctionArray = new Owned<IStrandJunction>[numStreams];
- for (unsigned i1 = 0; i1 < numInputs; i1++)
- {
- inputArray[i1] = NULL;
- sourceIdxArray[i1] = 0;
- }
- for (unsigned i2 = 0; i2 < numStreams; i2++)
- streamArray[i2] = NULL;
- }
- ~CRoxieServerMultiInputBaseActivity()
- {
- delete [] inputArray;
- delete [] sourceIdxArray;
- delete [] streamArray;
- delete [] junctionArray;
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 localCycles = totalCycles.totalCycles;
- for (unsigned i = 0; i < numInputs; i++)
- localCycles -= inputArray[i]->queryTotalCycles();
- if (localCycles < 0)
- localCycles = 0;
- return localCycles;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx < numInputs)
- return inputArray[idx];
- else
- return NULL;
- }
- virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
- {
- return queryInput(idx);
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
- {
- if (whichInput < numInputs)
- return streamArray[whichInput];
- else
- return NULL;
- }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
- {
- if (idx < numInputs)
- return junctionArray[idx];
- else
- return NULL;
- }
- virtual void reset()
- {
- for (unsigned i = 0; i < numInputs; i++)
- inputArray[i]->reset();
- for (unsigned iS = 0; iS < numStreams; iS++)
- {
- resetJunction(junctionArray[iS]);
- }
- CRoxieServerActivity::reset();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- assertex(idx < numInputs && idx < numStreams);
- inputArray[idx] = _in;
- sourceIdxArray[idx] = _sourceIdx;
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- //There could be situations (e.g., NONEMPTY), where you might want to strand the activity.
- for (unsigned i = 0; i < numInputs; i++)
- streamArray[i] = connectSingleStream(ctx, inputArray[i], sourceIdxArray[i], junctionArray[i], consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, NULL, consumerOrdered, nullptr); // The input basesclass does not have an input
- }
- };
- //=================================================================================
- class CRoxieServerMultiInputActivity : public CRoxieServerMultiInputBaseActivity
- {
- public:
- CRoxieServerMultiInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
- for (unsigned i = 0; i < numInputs; i++)
- {
- inputArray[i]->start(parentExtractSize, parentExtract, paused);
- }
- for (unsigned iS = 0; iS < numStreams; iS++)
- {
- startJunction(junctionArray[iS]);
- }
- }
- virtual void stop()
- {
- for (unsigned i = 0; i < numStreams; i++)
- {
- streamArray[i]->stop();
- }
- CRoxieServerMultiInputBaseActivity::stop();
- }
- };
- //=====================================================================================================
- class CRoxieServerInternalSinkActivity : public CRoxieServerActivity
- {
- protected:
- unsigned numOutputs;
- bool executed;
- bool *stopped;
- CriticalSection ecrit;
- Owned<IException> exception;
- public:
- CRoxieServerInternalSinkActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), numOutputs(_numOutputs)
- {
- executed = false;
- stopped = new bool[numOutputs];
- for (unsigned s = 0; s < numOutputs; s++)
- stopped[s] = false;
- }
- ~CRoxieServerInternalSinkActivity()
- {
- delete [] stopped;
- }
- virtual void reset()
- {
- for (unsigned s = 0; s < numOutputs; s++)
- stopped[s] = false;
- executed = false;
- exception.clear();
- CRoxieServerActivity::reset();
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- return NULL;
- }
- virtual void stopSink(unsigned outputIdx)
- {
- if (!stopped[outputIdx])
- {
- stopped[outputIdx] = true;
- for (unsigned s = 0; s < numOutputs; s++)
- if (!stopped[s])
- return;
- stop(); // all outputs stopped - stop parent.
- }
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- virtual void onExecute() = 0;
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- CriticalBlock b(ecrit);
- if (exception)
- throw exception.getLink();
- if (!executed)
- {
- try
- {
- start(parentExtractSize, parentExtract, false);
- {
- ActivityTimer t(totalCycles, timeActivities); // unfortunately this is not really best place for seeing in debugger.
- onExecute();
- }
- stop();
- executed = true;
- }
- catch (IException *E)
- {
- exception.set(E); // (or maybe makeWrappedException?)
- abort();
- throw;
- }
- catch (...)
- {
- exception.set(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__));
- abort();
- throw;
- }
- }
- }
- };
- //=================================================================================
- class CRoxieServerQueryPacket : implements IRoxieServerQueryPacket, public CInterface
- {
- protected:
- Owned<IMessageResult> result;
- Owned<IRoxieQueryPacket> packet;
- Linked<IRoxieServerQueryPacket> continuation;
- unsigned hash;
- unsigned seq;
- unsigned lastDebugSequence;
- Owned<IRoxieQueryPacket> lastDebugResponse;
- ILRUChain *prev;
- ILRUChain *next;
- bool delayed;
- public:
- IMPLEMENT_IINTERFACE;
- CRoxieServerQueryPacket(IRoxieQueryPacket *p) : packet(p)
- {
- hash = 0;
- seq = 0;
- prev = NULL;
- next = NULL;
- delayed = false;
- lastDebugSequence = 0;
- }
- virtual IRoxieQueryPacket *queryPacket() const
- {
- return packet;
- }
- virtual bool isContinuation() const
- {
- return packet && (packet->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO) != 0;
- }
- virtual bool isDelayed() const
- {
- return delayed;
- }
- virtual bool isEnd() const
- {
- return false;
- }
- virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
- {
- return false;
- }
- virtual bool hasResult() const
- {
- return result != NULL;
- }
- virtual bool hasContinuation() const
- {
- return continuation != NULL;
- }
- virtual void setDelayed(bool _delayed)
- {
- delayed = _delayed;
- }
- virtual void setPacket(IRoxieQueryPacket *_packet)
- {
- packet.setown(_packet);
- }
- virtual void setSequence(unsigned _seq)
- {
- assertex(!IsShared());
- seq = _seq;
- }
- virtual unsigned getSequence() const
- {
- return seq;
- }
- IMessageResult *getResult()
- {
- return result.getLink();
- }
- IMessageResult *queryResult()
- {
- return result;
- }
- void setResult(IMessageResult *r)
- {
- result.setown(r);
- }
- IRoxieServerQueryPacket *queryContinuation()
- {
- return continuation;
- }
- void setContinuation(IRoxieServerQueryPacket *c)
- {
- continuation.setown(c);
- }
- virtual unsigned queryHash() const
- {
- return hash;
- }
- virtual void setHash(unsigned _hash)
- {
- hash = _hash;
- }
- virtual ILRUChain *queryPrev() const { return prev; }
- virtual ILRUChain *queryNext() const { return next; }
- virtual void setPrev(ILRUChain *p) { prev = p; }
- virtual void setNext(ILRUChain *n) { next = n; }
- virtual void unchain()
- {
- if (prev && next)
- {
- prev->setNext(next);
- next->setPrev(prev);
- }
- next = NULL;
- prev = NULL;
- }
- virtual IRoxieQueryPacket *getDebugResponse(unsigned sequence)
- {
- if (sequence == lastDebugSequence)
- return lastDebugResponse.getLink();
- else if (sequence > lastDebugSequence)
- {
- lastDebugResponse.clear();
- return NULL;
- }
- else
- throwUnexpected();
- }
- virtual void setDebugResponse(unsigned sequence, IRoxieQueryPacket *response)
- {
- lastDebugSequence = sequence;
- lastDebugResponse.set(response);
- }
- };
- class CRoxieServerQueryPacketEndMarker : public CRoxieServerQueryPacket
- {
- public:
- CRoxieServerQueryPacketEndMarker() : CRoxieServerQueryPacket(NULL)
- {
- }
- virtual bool isEnd() const
- {
- return true;
- }
- };
- class CRoxieServerQueryPacketLimitMarker : public CRoxieServerQueryPacket
- {
- unsigned __int64 rowLimit;
- unsigned __int64 keyedLimit;
- unsigned __int64 stopAfter;
- public:
- CRoxieServerQueryPacketLimitMarker(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter) : CRoxieServerQueryPacket(NULL)
- {
- rowLimit = _rowLimit;
- keyedLimit = _keyedLimit;
- stopAfter = _stopAfter;
- }
- virtual bool isLimit(unsigned __int64 &_rowLimit, unsigned __int64 &_keyedLimit, unsigned __int64 &_stopAfter) const
- {
- _rowLimit = rowLimit;
- _keyedLimit = keyedLimit;
- _stopAfter = stopAfter;
- return true;
- }
- };
- class CRoxieServerSideCache : implements IRoxieServerSideCache, implements ILRUChain
- {
- protected:
- unsigned cacheTableSize;
- unsigned cacheTableSpace;
- IRoxieServerQueryPacket **cacheTable;
- mutable ILRUChain *prev;
- mutable ILRUChain *next;
- mutable CriticalSection crit;
- virtual ILRUChain *queryPrev() const { return prev; }
- virtual ILRUChain *queryNext() const { return next; }
- virtual void setPrev(ILRUChain *p) { prev = p; }
- virtual void setNext(ILRUChain *n) { next = n; }
- virtual void unchain()
- {
- prev->setNext(next);
- next->setPrev(prev);
- next = NULL;
- prev = NULL;
- }
- void moveToHead(IRoxieServerQueryPacket *mru)
- {
- mru->unchain();
- mru->setNext(next);
- next->setPrev(mru);
- mru->setPrev(this);
- next = mru;
- }
- IRoxieServerQueryPacket *removeLRU()
- {
- if (next==this)
- assertex(next != this);
- IRoxieServerQueryPacket *goer = (IRoxieServerQueryPacket *) next;
- goer->unchain(); // NOTE - this will modify the value of next
- return goer;
- }
- void removeEntry(IRoxieServerQueryPacket *goer)
- {
- unsigned v = goer->queryHash() % cacheTableSize;
- loop
- {
- IRoxieServerQueryPacket *found = cacheTable[v];
- assertex(found);
- if (found == goer)
- {
- cacheTable[v] = NULL;
- unsigned vn = v;
- loop
- {
- vn++;
- if (vn==cacheTableSize) vn = 0;
- IRoxieServerQueryPacket *found2 = cacheTable[vn];
- if (!found2)
- break;
- unsigned vm = found2->queryHash() % cacheTableSize;
- if (((vn+cacheTableSize-vm) % cacheTableSize)>=((vn+cacheTableSize-v) % cacheTableSize)) // diff(vn,vm)>=diff(vn,v)
- {
- cacheTable[v] = found2;
- v = vn;
- cacheTable[v] = NULL;
- }
- }
- cacheTableSpace++;
- break;
- }
- v++;
- if (v==cacheTableSize)
- v = 0;
- }
- goer->Release();
- }
- public:
- CRoxieServerSideCache(unsigned _cacheSize)
- {
- cacheTableSize = (_cacheSize*4)/3;
- cacheTable = new IRoxieServerQueryPacket *[cacheTableSize];
- memset(cacheTable, 0, cacheTableSize * sizeof(IRoxieServerQueryPacket *));
- cacheTableSpace = _cacheSize;
- prev = this;
- next = this;
- }
- ~CRoxieServerSideCache()
- {
- for (unsigned i = 0; i < cacheTableSize; i++)
- {
- ::Release(cacheTable[i]);
- }
- delete [] cacheTable;
- }
- virtual IRoxieServerQueryPacket *findCachedResult(const IRoxieContextLogger &logctx, IRoxieQueryPacket *p) const
- {
- unsigned hash = p->hash();
- unsigned et = hash % cacheTableSize;
- if (traceServerSideCache)
- {
- StringBuffer s;
- logctx.CTXLOG("CRoxieServerSideCache::findCachedResult hash %x slot %d %s", hash, et, p->queryHeader().toString(s).str());
- }
- CriticalBlock b(crit);
- loop
- {
- IRoxieServerQueryPacket *found = cacheTable[et];
- if (!found)
- return NULL;
- if (found->queryHash() == hash && found->queryPacket()->cacheMatch(p))
- {
- const_cast<CRoxieServerSideCache *>(this)->moveToHead(found);
- if (traceServerSideCache)
- logctx.CTXLOG("CRoxieServerSideCache::findCachedResult cache hit");
- logctx.noteStatistic(StNumServerCacheHits, 1);
- return NULL;
- // 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....
- //IRoxieServerQueryPacket *ret = new CRoxieServerQueryPacket(p);
- //ret->setResult(found->getResult());
- //return ret;
- }
- et++;
- if (et == cacheTableSize)
- et = 0;
- }
- }
- virtual void noteCachedResult(IRoxieServerQueryPacket *out, IMessageResult *in)
- {
- if (true) //!in->getLength()) // MORE - separate caches for hits and nohits
- {
- unsigned hash = out->queryPacket()->hash();
- out->setHash(hash);
- unsigned et = hash % cacheTableSize;
- if (traceServerSideCache)
- {
- StringBuffer s;
- DBGLOG("CRoxieServerSideCache::noteCachedResult hash %x slot %d %s", hash, et, out->queryPacket()->queryHeader().toString(s).str());
- }
- CriticalBlock b(crit);
- loop
- {
- IRoxieServerQueryPacket *found = cacheTable[et];
- if (!found)
- {
- if (cacheTableSpace)
- {
- out->setResult(LINK(in));
- cacheTable[et] = LINK(out);
- cacheTableSpace--;
- moveToHead(out);
- break;
- }
- else
- {
- IRoxieServerQueryPacket *goer = removeLRU();
- removeEntry(goer);
- et = hash % cacheTableSize;
- continue;
- }
- }
- else if (found->queryHash()==hash && found->queryPacket()->cacheMatch(out->queryPacket()))
- {
- moveToHead(found);
- return; // already in the cache. Because we don't cache until we have result, this can happen where
- // multiple copies of a slave query are in-flight at once.
- }
- et++;
- if (et == cacheTableSize)
- et = 0;
- }
- }
- // MORE - do we need to worry about the attachment between the MessageUnpacker and the current row manager. May all fall out ok...
- // Can I easily spot a null result? Do I want to cache null results separately? only?
- }
- // Note that this caching mechanism (unlike the old keyed-join specific one) does not common up cases where multiple
- // identical queries are in-flight at the same time. But if we can make it persistent between queries that will
- // more than make up for it
- };
- class CRowArrayMessageUnpackCursor : implements IMessageUnpackCursor, public CInterface
- {
- ConstPointerArray &data;
- Linked<IMessageResult> result;
- public:
- IMPLEMENT_IINTERFACE;
- CRowArrayMessageUnpackCursor(ConstPointerArray &_data, IMessageResult *_result)
- : data(_data), result(_result)
- {
- }
- virtual bool atEOF() const
- {
- return data.length()==0;
- }
- virtual bool isSerialized() const
- {
- return false;
- }
- virtual const void * getNext(int length)
- {
- if (!data.length())
- return NULL;
- const void *ret = data.item(0);
- data.remove(0);
- return ret;
- }
- };
- // MORE - should possibly move more over to the lazy version used in indexread?
- class CRowArrayMessageResult : implements IMessageResult, public CInterface
- {
- ConstPointerArray data;
- IRowManager &rowManager;
- bool variableSize;
- public:
- IMPLEMENT_IINTERFACE;
- CRowArrayMessageResult(IRowManager &_rowManager, bool _variableSize) : rowManager(_rowManager), variableSize(_variableSize)
- {
- }
- ~CRowArrayMessageResult()
- {
- ReleaseRoxieRows(data);
- }
- virtual IMessageUnpackCursor *getCursor(IRowManager *rowMgr) const
- {
- CRowArrayMessageResult *_this = (CRowArrayMessageResult *) this;
- return new CRowArrayMessageUnpackCursor(_this->data, _this);
- }
- virtual const void *getMessageHeader(unsigned &length) const
- {
- throwUnexpected(); // should never get called - I don't have a header available
- }
- virtual const void *getMessageMetadata(unsigned &length) const
- {
- length = 0;
- return NULL;
- }
- virtual void discard() const
- {
- throwUnexpected();
- }
- void append(const void *row)
- {
- data.append(row);
- }
- };
- void throwRemoteException(IMessageUnpackCursor *extra)
- {
- RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
- if (rowlen)
- {
- char *xml = (char *) extra->getNext(*rowlen);
- ReleaseRoxieRow(rowlen);
- Owned<IPropertyTree> p = createPTreeFromXMLString(xml);
- ReleaseRoxieRow(xml);
- unsigned code = p->getPropInt("Code", 0);
- const char *msg = p->queryProp("Message");
- if (!msg)
- msg = xml;
- throw MakeStringException(code, "%s", msg);
- }
- throwUnexpected();
- }
- class CRemoteResultAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, implements IExceptionHandler, public CInterface
- {
- friend class CRemoteResultMerger;
- class CRemoteResultMerger
- {
- class HeapEntry : public CInterface
- {
- private:
- CRemoteResultAdaptor &adaptor;
- IMessageUnpackCursor *cursor;
- public:
- const void *current;
- bool isLast;
- bool lastIsComplete;
- IRoxieServerQueryPacket *packet;
- unsigned seq;
- public:
- inline const void *noteResult(IMessageUnpackCursor *_cursor, bool _lastIsComplete)
- {
- cursor = _cursor;
- lastIsComplete = _lastIsComplete;
- return next();
- }
- public:
- HeapEntry(CRemoteResultAdaptor &_adaptor, IRoxieServerQueryPacket *_packet, unsigned _seq) : adaptor(_adaptor), packet(_packet), seq(_seq)
- {
- cursor = NULL;
- current = NULL;
- isLast = false;
- lastIsComplete = true;
- }
- ~HeapEntry()
- {
- ::Release(packet);
- ::Release(cursor);
- ReleaseRoxieRow(current);
- }
- bool isCompleteMatch() const
- {
- if (!isLast || lastIsComplete)
- return true;
- else
- return false;
- }
- const void *next()
- {
- if (cursor)
- {
- ReleaseClearRoxieRow(current);
- current = adaptor.getRow(cursor);
- isLast = cursor->atEOF();
- if (!current)
- {
- cursor->Release();
- cursor = NULL;
- }
- }
- return current;
- }
- unsigned skipTo(IRangeCompare *compare, const void *seek, unsigned numFields, bool requireExactMatch)
- {
- // MORE - This loop should possibly be a binchop... though it's not absolutely clear that is true (depends on term frequencies)
- unsigned skipped = 0;
- loop
- {
- int c = compare->docompare(current, seek, numFields);
- //If larger than the seek values, then we may be allowed to return an inexact match,
- //if equal then it is required to be an exact match,
- if (c > 0)
- {
- if (!requireExactMatch || isCompleteMatch())
- break;
- }
- else if ((c == 0) && isCompleteMatch())
- break;
- skipped++;
- if (!next())
- break;
- }
- return skipped;
- }
- };
- CRemoteResultAdaptor &adaptor;
- CIArrayOf<HeapEntry> heapEntries;
- UnsignedArray heap;
- IRowManager *rowManager;
- unsigned numPending;
- unsigned numFields;
- bool endSeen;
- bool remakePending;
- IRangeCompare *compare;
- bool deferredContinuation;
- inline int doCompare(unsigned l, unsigned r)
- {
- int ret = compare->docompare(heapEntries.item(l).current, heapEntries.item(r).current, numFields);
- if (!ret) ret = heapEntries.item(l).seq - heapEntries.item(r).seq;
- return ret;
- }
- void makeHeap()
- {
- /* Permute blocks to establish the heap property
- For each element p, the children are p*2+1 and p*2+2 (provided these are in range)
- The children of p must both be greater than or equal to p
- The parent of a child c is given by p = (c-1)/2
- */
- unsigned i;
- unsigned n = heap.length();
- unsigned *s = heap.getArray();
- for (i=1; i<n; i++)
- {
- unsigned r = s[i];
- int c = i; /* child */
- while (c > 0)
- {
- int p = (c-1)/2; /* parent */
- if ( doCompare( s[c], s[p] ) >= 0 )
- break;
- s[c] = s[p];
- s[p] = r;
- c = p;
- }
- }
- remakePending = false;
- }
- void remakeHeap()
- {
- /* The row associated with block[0] will have changed
- This code restores the heap property
- */
- unsigned p = 0; /* parent */
- unsigned n = heap.length();
- unsigned *s = heap.getArray();
- while (1)
- {
- unsigned c = p*2 + 1; /* child */
- if ( c >= n )
- break;
- /* Select smaller child */
- if ( c+1 < n && doCompare( s[c+1], s[c] ) < 0 ) c += 1;
- /* If child is greater or equal than parent then we are done */
- if ( doCompare( s[c], s[p] ) >= 0 )
- break;
- /* Swap parent and child */
- unsigned r = s[c];
- s[c] = s[p];
- s[p] = r;
- /* child becomes parent */
- p = c;
- }
- remakePending = false;
- }
- void append(IRoxieServerQueryPacket *p, unsigned seq)
- {
- HeapEntry &h = *new HeapEntry(adaptor, LINK(p), seq);
- IMessageResult *result = p->queryResult();
- assertex(result);
- if (h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
- {
- heapEntries.append(h);
- heap.append(heap.ordinality());
- }
- else
- h.Release();
- }
- void removeHeap(unsigned idx)
- {
- heapEntries.remove(idx);
- ForEachItemIn(i, heap)
- {
- unsigned v = heap.item(i);
- assertex(v != idx);
- if (v > idx)
- heap.replace(v-1, i);
- }
- }
- bool isCompleteMatchFlag(IMessageResult *result)
- {
- unsigned metaLen;
- const byte *metaInfo = (const byte *) result->getMessageMetadata(metaLen);
- if (metaLen)
- {
- unsigned short continuationLen = *(unsigned short *) metaInfo;
- if (continuationLen >= sizeof(bool))
- {
- metaInfo += sizeof(unsigned short);
- return *(bool *) metaInfo;
- }
- }
- return true; // if no continuation info, last row was complete.
- }
- public:
- CRemoteResultMerger(CRemoteResultAdaptor &_adaptor) : adaptor(_adaptor)
- {
- init(NULL, NULL);
- }
- void init(ISteppingMeta *meta, IRowManager *_rowManager)
- {
- if (meta)
- {
- numFields = meta->getNumFields();
- compare = meta->queryCompare();
- }
- else
- {
- numFields = 0;
- compare = NULL;
- }
- rowManager = _rowManager;
- numPending = 0;
- endSeen = false;
- remakePending = false;
- deferredContinuation = false;
- }
- void reset()
- {
- heapEntries.kill();
- heap.kill();
- numPending = 0;
- endSeen = false;
- remakePending = false;
- deferredContinuation = false;
- }
- inline bool noteEndSeen()
- {
- bool hadSeen = endSeen;
- if (!endSeen)
- makeHeap();
- endSeen = true;
- return !hadSeen;
- }
- void noteResult(IRoxieServerQueryPacket *p, unsigned seq)
- {
- if (!p->isContinuation())
- append(p, seq);
- else
- {
- ForEachItemIn(idx, heapEntries)
- {
- HeapEntry &h = heapEntries.item(idx);
- if (h.packet == p)
- {
- IMessageResult *result = p->queryResult();
- if (!h.noteResult(result->getCursor(rowManager), isCompleteMatchFlag(result)))
- {
- heap.zap(idx);
- removeHeap(idx);
- }
- numPending--;
- if (!numPending)
- makeHeap();
- return;
- }
- }
- }
- // If we get here it must be a continuation for one that I have not yet consumed... we don't need to do anything.
- return;
- }
- unsigned skipRows(unsigned &idx, const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, const SmartStepExtra & stepExtra)
- {
- HeapEntry &entry = heapEntries.item(idx);
- unsigned skipped = entry.current ? entry.skipTo(compare, seek, numFields, !stepExtra.returnMismatches()) : 0;
- if (!entry.current)
- {
- IRoxieServerQueryPacket *continuation = entry.packet->queryContinuation();
- if (continuation)
- {
- continuation->Link();
- entry.packet->Release();
- entry.packet = continuation;
- if (continuation->hasResult())
- {
- IMessageResult *result = continuation->queryResult();
- bool lastIsCompleteMatch = isCompleteMatchFlag(result);
- entry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
- }
- else
- {
- if (continuation->isDelayed())
- {
- continuation->setDelayed(false);
- MemoryBuffer serializedSkip;
- adaptor.activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
- continuation->setPacket(continuation->queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
- ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
- adaptor.sentsome.signal();
- }
- numPending++;
- }
- }
- else
- {
- heap.zap(idx);
- removeHeap(idx);
- idx--;
- }
- }
- return skipped;
- }
- const void * nextRowGE(const void * seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- // We discard all rows < seekval from all entries in heap
- // If this results in additional slave requests, we return NULL so that we can wait for them
- // If not, we rebuild the heap (if any were skipped) and return the first row
- deferredContinuation = false;
- if (heap.length())
- {
- unsigned skipped = 0;
- unsigned idx = 0;
- while(heapEntries.isItem(idx))
- {
- skipped += skipRows(idx, seek, rawSeek, numFields, seeklen, stepExtra);
- idx++;
- }
- if (numPending)
- return NULL; // can't answer yet, need more results from slaves
- else
- {
- if (skipped)
- makeHeap();
- return next(wasCompleteMatch, stepExtra);
- }
- }
- else
- return NULL;
- }
- bool doContinuation(HeapEntry &topEntry, bool canDefer)
- {
- IRoxieServerQueryPacket *continuation = topEntry.packet->queryContinuation();
- if (continuation)
- {
- if (continuation->isDelayed() && canDefer)
- {
- if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
- adaptor.activity.queryLogCtx().CTXLOG("Deferring continuation");
- deferredContinuation = true;
- }
- else
- {
- deferredContinuation = false;
- continuation->Link();
- topEntry.packet->Release();
- topEntry.packet = continuation;
- if (continuation->hasResult())
- {
- IMessageResult *result = continuation->queryResult();
- bool lastIsCompleteMatch = isCompleteMatchFlag(result);
- topEntry.noteResult(result->getCursor(rowManager), lastIsCompleteMatch);
- }
- else
- {
- if (continuation->isDelayed()) // has the continuation been requested yet?
- {
- continuation->Link();
- topEntry.packet->Release();
- topEntry.packet = continuation;
- continuation->setDelayed(false);
- if (adaptor.activity.queryLogCtx().queryTraceLevel() > 10)
- adaptor.activity.queryLogCtx().CTXLOG("About to send continuation, from doContinuation");
- ROQ->sendPacket(continuation->queryPacket(), adaptor.activity.queryLogCtx());
- adaptor.sentsome.signal();
- }
- numPending++; // we are waiting for one that is already in flight
- }
- }
- return true; // next not known yet
- }
- else
- return false;
- }
- const void *next(bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- OwnedConstRoxieRow ret;
- if (heap.length())
- {
- if (deferredContinuation)
- {
- unsigned top = heap.item(0);
- HeapEntry &topEntry = heapEntries.item(top);
- doContinuation(topEntry, false);
- return NULL;
- }
- if (remakePending)
- remakeHeap();
- unsigned top = heap.item(0);
- HeapEntry &topEntry = heapEntries.item(top);
- ret.set(topEntry.current);
- wasCompleteMatch = topEntry.isCompleteMatch();
- const void *next = topEntry.next();
- if (!next)
- {
- if (!doContinuation(topEntry, stepExtra.returnMismatches()))
- {
- unsigned last = heap.popGet();
- if (heap.length())
- heap.replace(last, 0);
- removeHeap(top);
- }
- }
- remakePending = true;
- }
- return ret.getClear();
- }
- bool ready()
- {
- return endSeen && numPending == 0;
- }
- };
- IRoxieServerQueryPacket *createRoxieServerQueryPacket(IRoxieQueryPacket *p, bool &cached)
- {
- if (serverSideCache && !debugContext)
- {
- IRoxieServerQueryPacket *ret = serverSideCache->findCachedResult(activity.queryLogCtx(), p);
- if (ret)
- {
- p->Release();
- cached = true;
- return ret;
- }
- }
- cached = false;
- return new CRoxieServerQueryPacket(p);
- }
- #ifdef _DEBUG
- void dumpPending()
- {
- CriticalBlock b(pendingCrit);
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- StringBuffer s;
- unsigned __int64 dummy;
- if (p.isEnd())
- s.append("END");
- else if (p.isLimit(dummy, dummy, dummy))
- s.append("LIMIT");
- else
- {
- IRoxieQueryPacket *i = p.queryPacket();
- s.appendf("%s", p.hasResult() ? "COMPLETE " : "PENDING ");
- if (i)
- {
- RoxiePacketHeader &header = i->queryHeader();
- header.toString(s);
- }
- }
- DBGLOG("Pending %d %s", idx, s.str());
- }
- }
- #endif
- void abortPending()
- {
- CriticalBlock b(pendingCrit);
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- if (!p.hasResult())
- {
- IRoxieQueryPacket *i = p.queryPacket();
- if (i)
- {
- RoxiePacketHeader &header = i->queryHeader();
- ROQ->sendAbort(header, activity.queryLogCtx());
- }
- }
- }
- pending.kill();
- }
- void checkDelayed()
- {
- if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
- {
- bool allDelayed = true;
- CriticalBlock b(pendingCrit);
- unsigned sendIdx = (unsigned) -1;
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- if (p.queryPacket())
- {
- if (p.isDelayed())
- {
- if (sendIdx == (unsigned) -1)
- sendIdx = idx;
- }
- else if (!p.hasResult())
- {
- allDelayed = false;
- break;
- }
- }
- }
- if (allDelayed && sendIdx != (unsigned) -1)
- {
- if (activity.queryLogCtx().queryTraceLevel() > 10)
- activity.queryLogCtx().CTXLOG("About to send debug-deferred from next");
- pending.item(sendIdx).setDelayed(false);
- ROQ->sendPacket(pending.item(sendIdx).queryPacket(), activity.queryLogCtx());
- sentsome.signal();
- }
- }
- else if (deferredStart)
- {
- CriticalBlock b(pendingCrit);
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- if (p.isDelayed())
- {
- if (activity.queryLogCtx().queryTraceLevel() > 10)
- activity.queryLogCtx().CTXLOG("About to send deferred start from next");
- p.setDelayed(false);
- ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
- sentsome.signal();
- }
- }
- deferredStart = false;
- }
- }
- void retryPending()
- {
- CriticalBlock b(pendingCrit);
- checkDelayed();
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- if (!p.hasResult() && !p.isDelayed())
- {
- IRoxieQueryPacket *i = p.queryPacket();
- if (i)
- {
- if (!i->queryHeader().retry())
- {
- StringBuffer s;
- 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());
- activity.queryLogCtx().logOperatorException(E, __FILE__, __LINE__, "CRemoteResultAdaptor::retry");
- throw E;
- }
- if (!localSlave)
- {
- ROQ->sendPacket(i, activity.queryLogCtx());
- atomic_inc(&retriesSent);
- }
- }
- }
- }
- }
- class ChannelBuffer
- {
- protected:
- unsigned bufferLeft;
- MemoryBuffer buffer;
- char *nextBuf;
- unsigned overflowSequence;
- unsigned channel; // == bonded channel
- bool needsFlush;
- InterruptableSemaphore flowController;
- const CRemoteResultAdaptor &owner;
- CriticalSection crit;
- public:
- ChannelBuffer(const CRemoteResultAdaptor &_owner, unsigned _channel) : owner(_owner), channel(_channel), flowController(perChannelFlowLimit)
- {
- overflowSequence = 0;
- needsFlush = false;
- bufferLeft = 0;
- nextBuf = NULL;
- }
- void init(unsigned minSize)
- {
- assertex(!buffer.length());
- if (minSize < MIN_PAYLOAD_SIZE)
- minSize = MIN_PAYLOAD_SIZE;
- unsigned headerSize = sizeof(RoxiePacketHeader)+owner.headerLength();
- unsigned bufferSize = headerSize+minSize;
- if (bufferSize < mtu_size)
- bufferSize = mtu_size;
- buffer.reserveTruncate(bufferSize);
- bufferLeft = bufferSize - headerSize;
- assertex(buffer.toByteArray());
- nextBuf = (char *) buffer.toByteArray() + headerSize;
- needsFlush = false;
- }
- inline IRoxieQueryPacket *flush()
- {
- CriticalBlock cb(crit);
- Owned<IRoxieQueryPacket> ret;
- if (needsFlush)
- {
- buffer.setLength(nextBuf - buffer.toByteArray());
- RoxiePacketHeader *h = (RoxiePacketHeader *) buffer.toByteArray();
- h->init(owner.remoteId, owner.ruid, channel, overflowSequence);
- //patch logPrefix, cachedContext and parent extract into the place reserved in the message buffer
- byte * tgt = (byte*)(h+1);
- owner.copyHeader(tgt, channel);
- ret.setown(createRoxiePacket(buffer));
- if (overflowSequence == OVERFLOWSEQUENCE_MAX)
- overflowSequence = 1; // don't wrap to 0 - that is a bit special
- else
- overflowSequence++;
- needsFlush = false;
- bufferLeft = 0;
- if (owner.flowControlled)
- {
- CriticalUnblock cub(crit);
- while (!flowController.wait(1000))
- {
- StringBuffer s;
- owner.activity.queryLogCtx().CTXLOG("Channel %d blocked by flow control: %s", channel, h->toString(s).str());
- }
- }
- }
- return ret.getClear();
- }
- inline void signal()
- {
- if (owner.flowControlled)
- flowController.signal();
- }
- inline void interrupt(IException *e)
- {
- flowController.interrupt(e);
- }
- inline void *getBuffer(unsigned size)
- {
- CriticalBlock cb(crit);
- if (bufferLeft >= size)
- {
- needsFlush = true;
- void * ret = nextBuf;
- nextBuf += size;
- bufferLeft -= size;
- return ret;
- }
- else if (!needsFlush)
- {
- init(size);
- return getBuffer(size);
- }
- else if (owner.mergeOrder)
- {
- return buffer.reserve(size); // whole query needs to go as single packet if we are to merge
- }
- else
- return NULL; // will force it to flush and start a new packet
- }
- };
- private:
- friend class CRemoteResultMerger;
- bool allread;
- bool contextCached;
- bool preserveOrder;
- InterruptableSemaphore sentsome;
- Owned <IMessageCollator> mc;
- Owned<IMessageUnpackCursor> mu;
- Owned<IMessageResult> mr;
- ChannelBuffer **buffers;
- IHThorArg &helper;
- unsigned __int64 stopAfter;
- unsigned resendSequence;
- IHThorArg *colocalArg;
- IArrayOf<IRoxieServerQueryPacket> pending;
- CriticalSection pendingCrit;
- IRoxieServerSideCache *serverSideCache;
- unsigned sentSequence;
- Owned<IOutputRowDeserializer> deserializer;
- Owned<IEngineRowAllocator> rowAllocator;
- CRemoteResultMerger merger;
- // this is only used to avoid recreating a bufferStream for each row. A better solution may be needed
- MemoryBuffer tempRowBuffer;
- Owned<ISerialStream> bufferStream;
- CThorStreamDeserializerSource rowSource;
- protected:
- IRowManager *rowManager;
- unsigned __int64 rowLimit;
- unsigned __int64 keyedLimit;
- IRoxieServerErrorHandler *errorHandler;
- CachedOutputMetaData meta;
- public:
- ISteppingMeta *mergeOrder;
- IRoxieSlaveContext *ctx;
- IDebuggableContext *debugContext;
- IRoxieServerActivity &activity;
- unsigned parentExtractSize;
- const byte * parentExtract;
- bool flowControlled;
- bool deferredStart;
- MemoryBuffer logInfo;
- MemoryBuffer cachedContext;
- const RemoteActivityId &remoteId;
- ruid_t ruid;
- mutable CriticalSection buffersCrit;
- unsigned processed;
- cycle_t totalCycles;
- bool timeActivities;
- //private: //vc6 doesn't like this being private yet accessed by nested class...
- const void *getRow(IMessageUnpackCursor *mu)
- {
- if (!mu->isSerialized() || (meta.isFixedSize() && !deserializer))
- return mu->getNext(meta.getFixedSize());
- else
- {
- RecordLengthType *rowlen = (RecordLengthType *) mu->getNext(sizeof(RecordLengthType));
- if (rowlen)
- {
- RecordLengthType len = *rowlen;
- ReleaseRoxieRow(rowlen);
- const void *slaveRec = mu->getNext(len);
- if (deserializer && mu->isSerialized())
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- tempRowBuffer.setBuffer(len, const_cast<void *>(slaveRec), false);
- size_t outsize = deserializer->deserialize(rowBuilder, rowSource);
- ReleaseRoxieRow(slaveRec);
- return rowBuilder.finalizeRowClear(outsize);
- }
- else
- return slaveRec;
- }
- else
- return NULL;
- }
- }
- private:
- ChannelBuffer *queryChannelBuffer(unsigned channel, bool force=false)
- {
- CriticalBlock cb(buffersCrit);
- ChannelBuffer *b = buffers[channel];
- if (!b && force)
- {
- if (!contextCached)
- {
- logInfo.clear();
- unsigned char loggingFlags = LOGGING_FLAGSPRESENT | LOGGING_TRACELEVELSET;
- unsigned char ctxTraceLevel = activity.queryLogCtx().queryTraceLevel() + 1; // Avoid passing a 0
- const QueryOptions &options = ctx->queryOptions();
- if (activity.queryLogCtx().isIntercepted())
- loggingFlags |= LOGGING_INTERCEPTED;
- if (options.timeActivities)
- loggingFlags |= LOGGING_TIMEACTIVITIES;
- if (activity.queryLogCtx().isBlind())
- loggingFlags |= LOGGING_BLIND;
- if (options.checkingHeap)
- loggingFlags |= LOGGING_CHECKINGHEAP;
- if (ctx->queryWorkUnit())
- loggingFlags |= LOGGING_WUID;
- if (debugContext)
- {
- loggingFlags |= LOGGING_DEBUGGERACTIVE;
- logInfo.append(loggingFlags).append(ctxTraceLevel);
- MemoryBuffer bpInfo;
- debugContext->serialize(bpInfo);
- bpInfo.append((__uint64)(memsize_t) &activity);
- logInfo.append((unsigned short) bpInfo.length());
- logInfo.append(bpInfo.length(), bpInfo.toByteArray());
- }
- else
- logInfo.append(loggingFlags).append(ctxTraceLevel);
- StringBuffer logPrefix;
- activity.queryLogCtx().getLogPrefix(logPrefix);
- logInfo.append(logPrefix);
- activity.serializeCreateStartContext(cachedContext.clear());
- activity.serializeExtra(cachedContext);
- if (activity.queryVarFileInfo())
- {
- activity.queryVarFileInfo()->queryTimeStamp().serialize(cachedContext);
- cachedContext.append(activity.queryVarFileInfo()->queryCheckSum());
- }
- contextCached = true;
- }
- b = buffers[channel] = new ChannelBuffer(*this, channel);
- }
- return b;
- }
- void processRow(const void *got)
- {
- processed++;
- if (processed > rowLimit)
- {
- ReleaseRoxieRow(got);
- errorHandler->onLimitExceeded(false); // NOTE - should throw exception
- throwUnexpected();
- }
- else if (processed > keyedLimit)
- {
- ReleaseRoxieRow(got);
- errorHandler->onLimitExceeded(true); // NOTE - should throw exception
- throwUnexpected();
- }
- }
- public:
- IMPLEMENT_IINTERFACE;
- CRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled)
- : remoteId(_remoteId), meta(_meta), activity(_activity), helper(_helper), preserveOrder(_preserveOrder), flowControlled(_flowControlled), merger(*this)
- {
- ctx = _ctx;
- errorHandler = _errorHandler;
- colocalArg = NULL;
- allread = false;
- ruid = 0;
- rowLimit = (unsigned __int64) -1;
- keyedLimit = (unsigned __int64) -1;
- contextCached = false;
- stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
- buffers = new ChannelBuffer*[numChannels+1];
- memset(buffers, 0, (numChannels+1)*sizeof(ChannelBuffer *));
- parentExtractSize = 0;
- rowManager = NULL;
- parentExtract = NULL;
- debugContext = NULL;
- mergeOrder = NULL;
- deferredStart = false;
- processed = 0;
- sentSequence = 0;
- resendSequence = 0;
- totalCycles = 0;
- serverSideCache = activity.queryServerSideCache();
- bufferStream.setown(createMemoryBufferSerialStream(tempRowBuffer));
- rowSource.setStream(bufferStream);
- timeActivities = defaultTimeActivities;
- }
- ~CRemoteResultAdaptor()
- {
- if (mc)
- {
- ROQ->queryReceiveManager()->detachCollator(mc);
- mc.clear();
- }
- for (unsigned channel = 0; channel <= numChannels; channel++)
- {
- delete(buffers[channel]);
- }
- delete [] buffers;
- }
- void setMeta(IOutputMetaData *newmeta)
- {
- meta.set(newmeta);
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
- virtual IRoxieServerActivity *queryActivity()
- {
- return &activity;
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- return NULL;
- }
- void setMergeInfo(ISteppingMeta *_mergeOrder)
- {
- mergeOrder = _mergeOrder;
- deferredStart = true;
- }
- void send(IRoxieQueryPacket *p)
- {
- if (p)
- {
- Linked<IRoxieQueryPacket> saver(p); // avoids a race with abortPending, without keeping pendingCrit locked over the send which we might prefer not to
- assertex(p->queryHeader().uid==ruid);
- // MORE: Maybe we should base the fastlane flag on some other
- // criteria !! (i.e A Roxie server prediction based on the
- // activity type/activity behaviour/expected reply size .. etc).
- //
- // Currently (code below) based on high priority, seq=0, and none-child activity.
- // But this could still cause too many reply packets on the fatlane
- // (higher priority output Q), which may cause the activities on the
- // low priority output Q to not get service on time.
- if ((colocalArg == 0) && // not a child query activity??
- (p->queryHeader().activityId & (ROXIE_SLA_PRIORITY | ROXIE_HIGH_PRIORITY)) &&
- (p->queryHeader().overflowSequence == 0) &&
- (p->queryHeader().continueSequence & ~CONTINUE_SEQUENCE_SKIPTO)==0)
- p->queryHeader().retries |= ROXIE_FASTLANE;
- if (p->queryHeader().channel)
- {
- bool cached = false;
- IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(p, cached);
- if (deferredStart)
- rsqp->setDelayed(true);
- rsqp->setSequence(sentSequence++);
- {
- CriticalBlock b(pendingCrit);
- pending.append(*rsqp);
- }
- if (!deferredStart)
- {
- if (!cached)
- ROQ->sendPacket(p, activity.queryLogCtx());
- sentsome.signal();
- }
- }
- else
- {
- // 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
- // Need to add first, then send
- unsigned i;
- bool allCached = true;
- for (i = 1; i <= numChannels; i++)
- {
- IRoxieQueryPacket *q = p->clonePacket(i);
- bool thisChannelCached;
- IRoxieServerQueryPacket *rsqp = createRoxieServerQueryPacket(q, thisChannelCached);
- if (!thisChannelCached)
- allCached = false;
- rsqp->setSequence(sentSequence++);
- if (deferredStart)
- {
- rsqp->setDelayed(true);
- }
- {
- CriticalBlock b(pendingCrit);
- pending.append(*rsqp);
- }
- if (!deferredStart)
- sentsome.signal();
- }
- if (!allCached && !deferredStart)
- ROQ->sendPacket(p, activity.queryLogCtx());
- buffers[0]->signal(); // since replies won't come back on that channel...
- p->Release();
- }
- }
- }
- void *getMem(unsigned partNo, unsigned fileNo, unsigned size)
- {
- unsigned channel = partNo ? getBondedChannel(partNo) : 0;
- size += sizeof(PartNoType);
- ChannelBuffer *b = queryChannelBuffer(channel, true);
- char *buffer = (char *) b->getBuffer(size);
- if (!buffer)
- {
- send(b->flush());
- buffer = (char *) b->getBuffer(size);
- }
- PartNoType sp;
- sp.partNo = partNo;
- sp.fileNo = fileNo;
- memcpy(buffer, &sp, sizeof(sp));
- buffer += sizeof(sp);
- return buffer;
- }
- void injectResult(IMessageResult *result)
- {
- IRoxieServerQueryPacket *f = new CRoxieServerQueryPacket(NULL);
- f->setSequence(sentSequence++);
- f->setResult(result);
- CriticalBlock b(pendingCrit);
- pending.append(*f);
- sentsome.signal(); // MORE - arguably should only send if there is any point waking up the listener thread, to save context swicth
- }
- void flush()
- {
- for (unsigned channel = 0; channel <= numChannels; channel++)
- {
- ChannelBuffer *b = queryChannelBuffer(channel, false);
- if (b)
- send(b->flush());
- }
- }
- void interruptBuffers(IException *e)
- {
- for (unsigned channel = 0; channel <= numChannels; channel++)
- {
- ChannelBuffer *b = queryChannelBuffer(channel, false);
- if (b)
- b->interrupt(LINK(e));
- }
- }
- void senddone()
- {
- CriticalBlock b(pendingCrit);
- pending.append(*new CRoxieServerQueryPacketEndMarker);
- sentsome.signal();
- }
- bool fireException(IException *e)
- {
- {
- CriticalBlock b(pendingCrit);
- pending.append(*new CRoxieServerQueryPacketEndMarker);
- }
- interruptBuffers(e);
- if (mc)
- mc->interrupt(LINK(e));
- sentsome.interrupt(e);
- return true;
- }
- virtual void onCreate(IHThorArg *_colocalArg)
- {
- debugContext = ctx->queryDebugContext();
- colocalArg = _colocalArg;
- if (meta.needsSerializeDisk())
- {
- deserializer.setown(meta.createDiskDeserializer(ctx->queryCodeContext(), activity.queryId()));
- rowAllocator.setown(activity.createRowAllocator(meta.queryOriginal()));
- }
- if (ctx->queryDebugContext() && ctx->queryDebugContext()->getExecuteSequentially())
- deferredStart = true;
- timeActivities = ctx->queryOptions().timeActivities;
- }
- virtual void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAonstart");
- #endif
- sentsome.reinit();
- ruid = getNextRuid();
- rowManager = &ctx->queryRowManager();
- if (mergeOrder)
- merger.init(mergeOrder, rowManager);
- if (mc)
- {
- ROQ->queryReceiveManager()->detachCollator(mc); // Should never happen - implies someone forgot to call onReset!
- }
- mc.setown(ROQ->queryReceiveManager()->createMessageCollator(rowManager, ruid));
- allread = false;
- mu.clear();
- contextCached = false;
- processed = 0;
- resendSequence = 0;
- sentSequence = 0;
- for (unsigned channel = 0; channel <= numChannels; channel++)
- {
- delete(buffers[channel]);
- buffers[channel] = NULL;
- }
- flush();
- parentExtractSize = _parentExtractSize;
- parentExtract = _parentExtract;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAstart");
- #endif
- activity.start(parentExtractSize, parentExtract, paused);
- }
- void setLimits(unsigned __int64 _rowLimit, unsigned __int64 _keyedLimit, unsigned __int64 _stopAfter)
- {
- if (ctx->queryProbeManager())
- {
- if (_rowLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "rowLimit", _rowLimit);
- if (_keyedLimit != (unsigned __int64) -1) ctx->queryProbeManager()->setNodePropertyInt(&activity, "keyedLimit", _keyedLimit);
- if (_stopAfter != I64C(0x7FFFFFFFFFFFFFFF)) ctx->queryProbeManager()->setNodePropertyInt(&activity, "choosenLimit", _stopAfter);
- }
- {
- CriticalBlock b(pendingCrit);
- if (pending.length())
- {
- #ifdef _DEBUG
- dumpPending(); // MORE - only defined in debug build - could have put the ifdef inside the dumpPending method
- #endif
- assertex(pending.length()==0);
- }
- pending.append(*new CRoxieServerQueryPacketLimitMarker(_rowLimit, _keyedLimit, _stopAfter));
- }
- sentsome.signal();
- rowLimit = _rowLimit;
- keyedLimit = _keyedLimit;
- stopAfter = _stopAfter;
- }
- virtual void stop()
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAstop");
- #endif
- onStop();
- activity.stop();
- }
- void onStop()
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAonstop");
- #endif
- abortPending();
- interruptBuffers(NULL);
- sentsome.interrupt();
- if (mc) // May not be set if start() chain threw exception
- mc->interrupt();
- }
- virtual void reset()
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAreset");
- #endif
- activity.reset();
- onReset();
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- // Make sure parent activity calls up the tree
- PointerArrayOf<IEngineRowStream> instreams;
- IStrandJunction *junction = activity.getOutputStreams(ctx, idx, instreams, consumerOptions, consumerOrdered, orderedCallbacks);
- assertex (junction == NULL);
- // I return a single strand (we could change that sometime I guess...)
- streams.append(this);
- return NULL;
- }
- virtual void resetEOF()
- {
- throwUnexpected();
- }
- virtual void onReset()
- {
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- activity.queryLogCtx().CTXLOG("RRAonreset");
- #endif
- if (mc)
- ROQ->queryReceiveManager()->detachCollator(mc);
- merger.reset();
- pending.kill();
- if (mc && ctx)
- ctx->addSlavesReplyLen(mc->queryBytesReceived());
- mc.clear(); // Or we won't free memory for graphs that get recreated
- mu.clear(); //ditto
- deferredStart = false;
- // NOTE: do NOT clear mergeOrder - this is set at create time not per child query
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return helper.queryOutputMeta();
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return totalCycles;
- }
- const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seekLen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- if (activity.queryLogCtx().queryTraceLevel() > 20)
- {
- StringBuffer recstr;
- unsigned i;
- for (i = 0; i < seekLen; i++)
- {
- recstr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
- }
- activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRowGE(rawSeek=%s numFields=%d, seeklen=%d, returnMismatches=%d)", recstr.str(), numFields, seekLen, stepExtra.returnMismatches());
- }
- assertex(mergeOrder);
- if (deferredStart)
- {
- CriticalBlock b(pendingCrit);
- ForEachItemIn(idx, pending)
- {
- IRoxieServerQueryPacket &p = pending.item(idx);
- if (p.isDelayed())
- {
- p.setDelayed(false);
- if (activity.queryLogCtx().queryTraceLevel() > 10)
- activity.queryLogCtx().CTXLOG("About to send deferred start from nextRowGE, setting requireExact to %d", !stepExtra.returnMismatches());
- MemoryBuffer serializedSkip;
- activity.serializeSkipInfo(serializedSkip, seekLen, rawSeek, numFields, seek, stepExtra);
- p.setPacket(p.queryPacket()->insertSkipData(serializedSkip.length(), serializedSkip.toByteArray()));
- ROQ->sendPacket(p.queryPacket(), activity.queryLogCtx());
- sentsome.signal();
- }
- }
- deferredStart = false;
- }
- SimpleActivityTimer t(totalCycles, timeActivities);
- if (processed==stopAfter)
- return NULL;
- if (allread)
- return NULL;
- loop
- {
- if (merger.ready())
- {
- const void *got = merger.nextRowGE(seek, rawSeek, numFields, seekLen, wasCompleteMatch, stepExtra);
- if (got)
- {
- processRow(got);
- return got;
- }
- }
- if (!reload()) // MORE - should pass the seek info here...
- return NULL;
- }
- }
- virtual const void *nextRow()
- {
- // If we are merging then we need to do a heapsort on all
- SimpleActivityTimer t(totalCycles, timeActivities);
- if (activity.queryLogCtx().queryTraceLevel() > 10)
- {
- activity.queryLogCtx().CTXLOG("CRemoteResultAdaptor::nextRow()");
- }
- loop
- {
- checkDelayed();
- if (processed==stopAfter)
- return NULL;
- if (allread)
- return NULL;
- // If we can still consume from the merger or the most recently retrieved mu, do so.
- const void *got = NULL;
- if (mergeOrder && merger.ready())
- {
- bool matched = true;
- got = merger.next(matched, dummySmartStepExtra);
- }
- else if (mu)
- got = getRow(mu);
- if (got)
- {
- processRow(got);
- return got;
- }
- if (!reload())
- return NULL;
- }
- }
- bool reload()
- {
- // Wait for something to be returned from a slave....
- mu.clear();
- sentsome.wait();
- // must be at least an endMarker on the queue since sentsome was signalled
- {
- CriticalBlock b(pendingCrit);
- IRoxieServerQueryPacket &top = pending.item(0);
- if (top.isLimit(rowLimit, keyedLimit, stopAfter)) // This is really a start marker...
- {
- pending.remove(0);
- return true;
- }
- else if (top.isEnd())
- {
- pending.remove(0);
- allread = true;
- if (activity.queryLogCtx().queryTraceLevel() > 5)
- activity.queryLogCtx().CTXLOG("All read on ruid %x", ruid);
- return false;
- }
- else if (mergeOrder)
- {
- unsigned idx = 0;
- bool added = false;
- while (pending.isItem(idx))
- {
- IRoxieServerQueryPacket &item = pending.item(idx);
- if (item.isEnd())
- {
- if (merger.noteEndSeen())
- {
- sentsome.signal(); // Because we waited, yet didn't actually consume anything
- added = true;
- }
- break;
- }
- else if (item.hasResult())
- {
- merger.noteResult(&item, item.getSequence());
- pending.remove(idx);
- added = true;
- }
- else if (item.isContinuation())
- idx++;
- else
- break;
- }
- if (added)
- return true;
- }
- else if (top.hasResult())
- {
- mr.setown(pending.item(0).getResult());
- mu.setown(mr->getCursor(rowManager));
- pending.remove(0);
- return true;
- }
- }
- getNextUnpacker();
- return true;
- }
- void getNextUnpacker()
- {
- mu.clear();
- unsigned ctxTraceLevel = activity.queryLogCtx().queryTraceLevel();
- loop
- {
- checkDelayed();
- unsigned timeout = remoteId.isSLAPriority() ? slaTimeout : (remoteId.isHighPriority() ? highTimeout : lowTimeout);
- activity.queryContext()->checkAbort();
- bool anyActivity;
- if (ctxTraceLevel > 5)
- activity.queryLogCtx().CTXLOG("Calling getNextUnpacker(%d)", timeout);
- mr.setown(mc->getNextResult(timeout, anyActivity));
- if (ctxTraceLevel > 6)
- activity.queryLogCtx().CTXLOG("Called getNextUnpacker(%d), activity=%d", timeout, anyActivity);
- activity.queryContext()->checkAbort();
- if (mr)
- {
- unsigned roxieHeaderLen;
- const RoxiePacketHeader &header = *(const RoxiePacketHeader *) mr->getMessageHeader(roxieHeaderLen);
- #ifdef _DEBUG
- assertex(roxieHeaderLen == sizeof(RoxiePacketHeader));
- #endif
- if (ctxTraceLevel > 5)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("getNextUnpacker got packet %s", header.toString(s).str());
- }
- CriticalBlock b(pendingCrit);
- unsigned idx = 0;
- IRoxieServerQueryPacket *original = NULL;
- IRoxieQueryPacket *op;
- while (pending.isItem(idx))
- {
- original = &pending.item(idx);
- op = original->queryPacket();
- if (op && header.matchPacket(op->queryHeader()))
- break;
- original = NULL;
- idx++;
- }
- if (!original || original->hasResult())
- {
- switch (header.activityId)
- {
- case ROXIE_FILECALLBACK:
- {
- // tell slave to abort
- //if (ctxTraceLevel > 5)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Redundant callback on query %s", header.toString(s).str());
- }
- Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
- OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
- if (len)
- {
- RecordLengthType *rowlen = (RecordLengthType *) len.get();
- OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
- const char *rowdata = (const char *) row.get();
- // bool isOpt = * (bool *) rowdata;
- // bool isLocal = * (bool *) (rowdata+1);
- ROQ->sendAbortCallback(header, rowdata+2, activity.queryLogCtx());
- }
- else
- throwUnexpected();
- break;
- }
- // MORE - ROXIE_ALIVE perhaps should go here too
- default:
- if (ctxTraceLevel > 3)
- activity.queryLogCtx().CTXLOG("Discarding packet %p - original %p is NULL or has result already", mr.get(), original);
- mr->discard();
- break;
- }
- mr.clear();
- }
- else
- {
- atomic_inc(&resultsReceived);
- switch (header.activityId)
- {
- case ROXIE_DEBUGCALLBACK:
- {
- Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
- OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
- if (len)
- {
- RecordLengthType *rowlen = (RecordLengthType *) len.get();
- OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
- char *rowdata = (char *) row.get();
- if (ctxTraceLevel > 5)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Callback on query %s for debug", header.toString(s).str());
- }
- MemoryBuffer slaveInfo;
- slaveInfo.setBuffer(*rowlen, rowdata, false);
- unsigned debugSequence;
- slaveInfo.read(debugSequence);
- Owned<IRoxieQueryPacket> reply = original->getDebugResponse(debugSequence);
- if (!reply)
- reply.setown(activity.queryContext()->queryDebugContext()->onDebugCallback(header, *rowlen, rowdata));
- if (reply)
- {
- original->setDebugResponse(debugSequence, reply);
- ROQ->sendPacket(reply, activity.queryLogCtx());
- }
- }
- else
- throwUnexpected();
- // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
- // Leave original message on pending queue in original location - this is not a reply to it.
- break;
- }
- case ROXIE_FILECALLBACK:
- {
- // we need to send back to the slave a message containing the file info requested.
- Owned<IMessageUnpackCursor> callbackData = mr->getCursor(rowManager);
- OwnedConstRoxieRow len = callbackData->getNext(sizeof(RecordLengthType));
- if (len)
- {
- RecordLengthType *rowlen = (RecordLengthType *) len.get();
- OwnedConstRoxieRow row = callbackData->getNext(*rowlen);
- const char *rowdata = (const char *) row.get();
- bool isOpt = * (bool *) rowdata;
- bool isLocal = * (bool *) (rowdata+1);
- const char *lfn = rowdata+2;
- if (ctxTraceLevel > 5)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Callback on query %s file %s", header.toString(s).str(),(const char *) lfn);
- }
- activity.queryContext()->onFileCallback(header, lfn, isOpt, isLocal);
- }
- else
- throwUnexpected();
- // MORE - somehow we need to make sure slave gets a reply even if I'm not waiting (in udp layer)
- // Leave original message on pending queue in original location - this is not a reply to it.
- break;
- }
- case ROXIE_KEYEDLIMIT_EXCEEDED:
- activity.queryLogCtx().CTXLOG("ROXIE_KEYEDLIMIT_EXCEEDED");
- errorHandler->onLimitExceeded(true); // NOTE - should throw exception!
- throwUnexpected();
- case ROXIE_LIMIT_EXCEEDED:
- activity.queryLogCtx().CTXLOG("ROXIE_LIMIT_EXCEEDED");
- errorHandler->onLimitExceeded(false); // NOTE - should throw exception!
- throwUnexpected();
- case ROXIE_TRACEINFO:
- {
- Owned<IMessageUnpackCursor> extra = mr->getCursor(rowManager);
- loop
- {
- RecordLengthType *rowlen = (RecordLengthType *) extra->getNext(sizeof(RecordLengthType));
- if (rowlen)
- {
- char *logInfo = (char *) extra->getNext(*rowlen);
- MemoryBuffer buf;
- buf.setBuffer(*rowlen, logInfo, false);
- switch ((TracingCategory) *logInfo)
- {
- case LOG_TRACING:
- case LOG_ERROR:
- activity.queryLogCtx().CTXLOGl(new LogItem(buf));
- break;
- case LOG_STATVALUES:
- buf.skip(1);
- activity.mergeStats(buf);
- break;
- case LOG_CHILDCOUNT:
- case LOG_CHILDSTATS:
- unsigned graphId, childId;
- buf.skip(1);
- buf.read(graphId);
- buf.read(childId);
- if (*logInfo == LOG_CHILDCOUNT)
- {
- unsigned idx;
- unsigned childProcessed;
- unsigned childStrands;
- buf.read(idx);
- buf.read(childProcessed);
- buf.read(childStrands);
- if (traceLevel > 5)
- activity.queryLogCtx().CTXLOG("Processing ChildCount %d idx %d strands %d for child %d subgraph %d", childProcessed, idx, childStrands, childId, graphId);
- activity.queryContext()->noteProcessed(graphId, childId, idx, childProcessed, childStrands);
- }
- else
- {
- ActivityTimeAccumulator dummy; // We could serialize from slave? Would get confusing though
- CRuntimeStatisticCollection childStats(allStatistics);
- childStats.deserialize(buf);
- if (traceLevel > 5)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Processing ChildStats for child %d subgraph %d: %s", childId, graphId, childStats.toStr(s).str());
- }
- activity.queryContext()->mergeActivityStats(childStats, graphId, childId, dummy, 0);
- }
- }
- ReleaseRoxieRow(rowlen);
- ReleaseRoxieRow(logInfo);
- }
- else
- break;
- }
- break;
- }
- case ROXIE_EXCEPTION:
- if (ctxTraceLevel > 1)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Exception on query %s", header.toString(s).str());
- }
- op->queryHeader().noteException(header.retries);
- if (op->queryHeader().allChannelsFailed())
- {
- activity.queryLogCtx().CTXLOG("Multiple exceptions on query - aborting");
- Owned<IMessageUnpackCursor> exceptionData = mr->getCursor(rowManager);
- throwRemoteException(exceptionData);
- }
- // Leave it on pending queue in original location
- break;
- case ROXIE_ALIVE:
- if (ctxTraceLevel > 4)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("ROXIE_ALIVE: %s", header.toString(s).str());
- }
- op->queryHeader().noteAlive(header.retries & ROXIE_RETRIES_MASK);
- // Leave it on pending queue in original location
- break;
- default:
- if (header.retries & ROXIE_RETRIES_MASK)
- atomic_inc(&retriesNeeded);
- unsigned metaLen;
- const void *metaData = mr->getMessageMetadata(metaLen);
- if (metaLen)
- {
- // We got back first chunk but there is more.
- // resend the packet, with the cursor info provided.
- // MORE - if smart-stepping, we don't want to send the continuation immediately. Other cases it's not clear that we do.
- if (ctxTraceLevel > 1)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
- }
- if (*((unsigned short *) metaData) + sizeof(unsigned short) != metaLen)
- {
- StringBuffer s;
- activity.queryLogCtx().CTXLOG("Additional data size %d on query %s mergeOrder %p", metaLen, header.toString(s).str(), mergeOrder);
- activity.queryLogCtx().CTXLOG("Additional data is corrupt");
- throwUnexpected();
- }
- MemoryBuffer nextQuery;
- nextQuery.append(sizeof(RoxiePacketHeader), &header);
- nextQuery.append(metaLen, metaData);
- nextQuery.append(op->getTraceLength(), op->queryTraceInfo());
- nextQuery.append(op->getContextLength(), op->queryContextData());
- if (resendSequence == CONTINUESEQUENCE_MAX)
- {
- activity.queryLogCtx().CTXLOG("ERROR: Continuation sequence wrapped"); // shouldn't actually matter.... but suggests a very iffy query!
- resendSequence = 1;
- }
- else
- resendSequence++;
- RoxiePacketHeader *newHeader = (RoxiePacketHeader *) nextQuery.toByteArray();
- newHeader->continueSequence = resendSequence; // NOTE - we clear the skipTo flag since continuation of a skip is NOT a skip...
- newHeader->retries &= ~ROXIE_RETRIES_MASK;
- IRoxieQueryPacket *resend = createRoxiePacket(nextQuery);
- CRoxieServerQueryPacket *fqp = new CRoxieServerQueryPacket(resend);
- fqp->setSequence(original->getSequence());
- pending.add(*fqp, idx+1); // note that pending takes ownership. sendPacket does not release.
- original->setContinuation(LINK(fqp));
- if (mergeOrder)
- fqp->setDelayed(true);
- else
- {
- ROQ->sendPacket(resend, activity.queryLogCtx());
- sentsome.signal();
- }
- // Note that we don't attempt to cache results that have continuation records - too tricky !
- }
- else
- {
- if (serverSideCache)
- serverSideCache->noteCachedResult(original, mr);
- }
- unsigned channel = header.channel;
- {
- ChannelBuffer *b = queryChannelBuffer(channel); // If not something is wrong, or we sent out on channel 0?
- if (b)
- b->signal();
- }
- original->setResult(mr.getClear());
- sentsome.signal();
- return;
- }
- }
- }
- else
- {
- if (!anyActivity && !localSlave)
- {
- activity.queryLogCtx().CTXLOG("Input has stalled - retry required?");
- retryPending();
- }
- }
- }
- }
- inline unsigned headerLength() const
- {
- return logInfo.length() + cachedContext.length() + sizeof(unsigned) + parentExtractSize;
- }
- void copyHeader(byte *tgt, unsigned channel) const
- {
- unsigned len = logInfo.length();
- memcpy(tgt, logInfo.toByteArray(), len);
- tgt += len;
- *(unsigned *) tgt = parentExtractSize;
- tgt += sizeof(unsigned);
- memcpy(tgt, parentExtract, parentExtractSize);
- tgt += parentExtractSize;
- memcpy(tgt, cachedContext.toByteArray(), cachedContext.length());
- tgt += cachedContext.length();
- }
- };
- class CSkippableRemoteResultAdaptor : public CRemoteResultAdaptor
- {
- Owned <IException> exception;
- bool skipping;
- ConstPointerArray buff;
- unsigned index;
- bool pulled;
- void pullInput()
- {
- try
- {
- if (exception)
- throw exception.getClear();
- unsigned __int64 count = 0;
- loop
- {
- const void * next = CRemoteResultAdaptor::nextRow();
- if (next == NULL)
- {
- next = CRemoteResultAdaptor::nextRow();
- if(next == NULL)
- break;
- buff.append(NULL);
- }
- count++;
- if (count > rowLimit)
- {
- ReleaseRoxieRow(next);
- ReleaseRoxieRows(buff);
- errorHandler->onLimitExceeded(false); // throws an exception - user or LimitSkipException
- throwUnexpected();
- }
- else if (count > keyedLimit)
- {
- ReleaseRoxieRow(next);
- ReleaseRoxieRows(buff);
- errorHandler->onLimitExceeded(true); // throws an exception - user or LimitSkipException
- throwUnexpected();
- }
- buff.append(next);
- }
- }
- catch (IException *E)
- {
- if (QUERYINTERFACE(E, LimitSkipException))
- {
- Owned<IException> cleanup = E;
- ReleaseRoxieRows(buff);
- const void *onfail = errorHandler->createLimitFailRow(E->errorCode() == KeyedLimitSkipErrorCode);
- if (onfail)
- buff.append(onfail);
- }
- else
- throw;
- }
- pulled = true;
- }
- public:
- CSkippableRemoteResultAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IOutputMetaData *_meta, IHThorArg &_helper, IRoxieServerActivity &_activity, bool _preserveOrder, bool _flowControlled, bool _skipping) :
- CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, _meta, _helper, _activity, _preserveOrder, _flowControlled)
- {
- skipping = _skipping;
- index = 0;
- pulled = false;
- }
- void setException(IException *E)
- {
- exception.setown(E);
- }
- virtual void onReset()
- {
- roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
- buff.kill();
- index = 0;
- pulled = false;
- exception.clear();
- CRemoteResultAdaptor::onReset();
- }
- void onStart(unsigned _parentExtractSize, const byte * _parentExtract)
- {
- index = 0;
- pulled = false;
- CRemoteResultAdaptor::onStart(_parentExtractSize, _parentExtract);
- }
- virtual const void * nextRowGE(const void *seek, const void *rawSeek, unsigned numFields, unsigned seeklen, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- // 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
- if (exception)
- throw exception.getClear();
- return CRemoteResultAdaptor::nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
- }
- virtual const void *nextRow()
- {
- if (skipping)
- {
- if(!pulled)
- pullInput();
- if(buff.isItem(index))
- {
- const void * next = buff.item(index++);
- if(next)
- processed++;
- return next;
- }
- return NULL;
- }
- else
- {
- if (exception)
- throw exception.getClear();
- return CRemoteResultAdaptor::nextRow();
- }
- }
- };
- //=================================================================================
- class CRoxieServerApplyActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorApplyArg &helper;
- public:
- CRoxieServerApplyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorApplyArg &) basehelper)
- {
- }
- virtual void onExecute()
- {
- helper.start();
- loop
- {
- const void * next = inputStream->ungroupedNextRow();
- if (!next)
- break;
- helper.apply(next);
- ReleaseRoxieRow(next);
- }
- helper.end();
- }
- };
- class CRoxieServerApplyActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerApplyActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerApplyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerApplyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerNullActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- }
- virtual const void *nextRow()
- {
- return NULL;
- }
- };
- IRoxieServerActivity * createRoxieServerNullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- {
- return new CRoxieServerNullActivity(_ctx, _factory, _probeManager);
- }
- class CRoxieServerNullActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNullActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for null activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerPassThroughActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- virtual const void *nextRow()
- {
- const void * next = inputStream->nextRow();
- if (next)
- processed++;
- return next;
- }
- virtual bool isPassThrough()
- {
- return true;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (next)
- processed++;
- return next;
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- IRoxieServerActivity * createRoxieServerPassThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- {
- return new CRoxieServerPassThroughActivity(_ctx, _factory, _probeManager);
- }
- //=================================================================================
- class CRoxieServerChildBaseActivity : public CRoxieServerActivity
- {
- protected:
- bool eof;
- bool first;
- public:
- CRoxieServerChildBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- eof = false;
- first = true;
- }
- ~CRoxieServerChildBaseActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- first = true;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- };
- class CRoxieServerChildBaseActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerChildBaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
- }
- };
- //=================================================================================
- class CRoxieServerChildIteratorActivity : public CRoxieServerChildBaseActivity
- {
- IHThorChildIteratorArg &helper;
- public:
- CRoxieServerChildIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildIteratorArg &) basehelper)
- {
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- bool ok;
- if (first)
- {
- ok = helper.first();
- first = false;
- }
- else
- ok = helper.next();
- try
- {
- while (ok)
- {
- processed++;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.transform(rowBuilder);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- ok = helper.next();
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerChildIteratorActivityFactory : public CRoxieServerChildBaseActivityFactory
- {
- public:
- CRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChildIteratorActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerChildIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChildIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChildNormalizeActivity : public CRoxieServerChildBaseActivity
- {
- IHThorChildNormalizeArg &helper;
- public:
- CRoxieServerChildNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildNormalizeArg &) basehelper)
- {
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- bool ok;
- if (first)
- {
- ok = helper.first();
- first = false;
- }
- else
- ok = helper.next();
- if (ok)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- do {
- unsigned outSize = helper.transform(rowBuilder);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- ok = helper.next();
- }
- while (ok);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerChildNormalizeActivityFactory : public CRoxieServerChildBaseActivityFactory
- {
- public:
- CRoxieServerChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChildNormalizeActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNewChildNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChildNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChildAggregateActivity : public CRoxieServerChildBaseActivity
- {
- IHThorChildAggregateArg &helper;
- public:
- CRoxieServerChildAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildAggregateArg &) basehelper)
- {
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- eof = true;
- processed++;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- helper.clearAggregate(rowBuilder);
- helper.processRows(rowBuilder);
- size32_t finalSize = meta.getRecordSize(rowBuilder.getSelf());
- return rowBuilder.finalizeRowClear(finalSize);
- }
- };
- class CRoxieServerChildAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
- {
- public:
- CRoxieServerChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChildAggregateActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNewChildAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChildAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChildGroupAggregateActivity : public CRoxieServerChildBaseActivity, public IHThorGroupAggregateCallback
- {
- IHThorChildGroupAggregateArg &helper;
- RowAggregator aggregated;
- public:
- IMPLEMENT_IINTERFACE_USING(CRoxieServerChildBaseActivity)
- CRoxieServerChildGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildGroupAggregateArg &) basehelper),
- aggregated(helper, helper)
- {
- }
- void processRow(const void * next)
- {
- aggregated.addRow(next);
- }
-
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
- aggregated.start(rowAllocator);
- }
- virtual void reset()
- {
- aggregated.reset();
- CRoxieServerChildBaseActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (first)
- {
- helper.processRows(this);
- first = false;
- }
- Owned<AggregateRowBuilder> next = aggregated.nextResult();
- if (next)
- {
- processed++;
- return next->finalizeRowClear();
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerChildGroupAggregateActivityFactory : public CRoxieServerChildBaseActivityFactory
- {
- public:
- CRoxieServerChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerChildBaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChildGroupAggregateActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNewChildGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChildGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChildThroughNormalizeActivity : public CRoxieServerChildBaseActivity
- {
- IHThorChildThroughNormalizeArg &helper;
- const void * lastInput;
- unsigned numProcessedLastGroup;
- bool ok;
- public:
- CRoxieServerChildThroughNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerChildBaseActivity(_ctx, _factory, _probeManager), helper((IHThorChildThroughNormalizeArg &) basehelper)
- {
- lastInput = NULL;
- numProcessedLastGroup = 0;
- ok = false;
- }
- virtual void stop()
- {
- CRoxieServerChildBaseActivity::stop();
- ReleaseRoxieRow(lastInput);
- lastInput = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerChildBaseActivity::start(parentExtractSize, parentExtract, paused);
- numProcessedLastGroup = processed;
- ok = false;
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- loop
- {
- if (ok)
- ok = helper.next();
- while (!ok)
- {
- ReleaseRoxieRow(lastInput);
- lastInput = inputStream->nextRow();
- if (!lastInput)
- {
- if (numProcessedLastGroup != processed)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- lastInput = inputStream->nextRow();
- if (!lastInput)
- return NULL;
- }
- ok = helper.first(lastInput);
- }
- try
- {
- do
- {
- unsigned outSize = helper.transform(rowBuilder);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- ok = helper.next();
- } while (ok);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerChildThroughNormalizeActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChildThroughNormalizeActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNewChildThroughNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChildThroughNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerDistributionActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorDistributionArg &helper;
- public:
- CRoxieServerDistributionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDistributionArg &)basehelper)
- {
- }
- virtual void onExecute()
- {
- MemoryAttr ma;
- IDistributionTable * * accumulator = (IDistributionTable * *)ma.allocate(helper.queryInternalRecordSize()->getMinRecordSize());
- helper.clearAggregate(accumulator);
- OwnedConstRoxieRow nextrec(inputStream->nextRow());
- loop
- {
- if (!nextrec)
- {
- nextrec.setown(inputStream->nextRow());
- if (!nextrec)
- break;
- }
- helper.process(accumulator, nextrec);
- nextrec.setown(inputStream->nextRow());
- }
- StringBuffer result;
- result.append("<XML>");
- helper.gatherResult(accumulator, result);
- result.append("</XML>");
- helper.sendResult(result.length(), result.str());
- helper.destruct(accumulator);
- }
- };
- class CRoxieServerDistributionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerDistributionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDistributionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerDistributionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerLinkedRawIteratorActivity : public CRoxieServerActivity
- {
- IHThorLinkedRawIteratorArg &helper;
- public:
- CRoxieServerLinkedRawIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLinkedRawIteratorArg &) basehelper)
- {
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void *ret =helper.next();
- if (ret)
- {
- LinkRoxieRow(ret);
- processed++;
- }
- return ret;
- }
- };
- class CRoxieServerLinkedRawIteratorActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLinkedRawIteratorActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLinkedRawIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerLinkedRawIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerDatasetResultActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerDatasetResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- }
- virtual const void *nextRow()
- {
- throwUnexpected();
- }
- virtual void executeChild(size32_t & retSize, void * & ret, unsigned parentExtractSize, const byte * parentExtract)
- {
- try
- {
- start(parentExtractSize, parentExtract, false);
- {
- ActivityTimer t(totalCycles, timeActivities);
- MemoryBuffer result;
- IRecordSize * inputMeta = input->queryOutputMeta();
- loop
- {
- const void *nextrec = inputStream->ungroupedNextRow();
- if (!nextrec)
- break;
- result.append(inputMeta->getRecordSize(nextrec), nextrec);
- ReleaseRoxieRow(nextrec);
- }
- retSize = result.length();
- ret = result.detach();
- }
- stop();
- reset();
- }
- catch(IException *E)
- {
- ctx->notifyAbort(E);
- abort();
- reset();
- throw;
- }
- catch(...)
- {
- Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
- ctx->notifyAbort(E);
- abort();
- reset();
- throw;
- }
- }
- };
- class CRoxieServerDatasetResultActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerDatasetResultActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDatasetResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerDatasetResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerInlineTableActivity : public CRoxieServerActivity
- {
- IHThorInlineTableArg &helper;
- __uint64 curRow;
- __uint64 numRows;
- public:
- CRoxieServerInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorInlineTableArg &) basehelper)
- {
- curRow = 0;
- numRows = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- curRow = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numRows = helper.numRows();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- // Filtering empty rows, returns the next valid row
- while (curRow < numRows)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.getRow(rowBuilder, curRow++);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- return NULL;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerStrandedInlineTableActivity : public CRoxieServerStrandedActivity
- {
- IHThorInlineTableArg &helper;
- __uint64 numRows;
- //An inline table that isn't stranded
- class InlineTableSimpleProcessor : public StrandProcessor
- {
- protected:
- IHThorInlineTableArg &helper;
- __uint64 curRow;
- __uint64 maxRows;
- public:
- InlineTableSimpleProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper)
- : StrandProcessor(_parent, NULL, true), helper(_helper), curRow(0), maxRows(0)
- {
- }
- virtual void start() override
- {
- StrandProcessor::start();
- curRow = 0;
- maxRows = queryParent().numRows;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- //Return rows while the current section is active
- while (curRow < maxRows)
- {
- RtlDynamicRowBuilder rowBuilder(*rowAllocator);
- unsigned outSize = helper.getRow(rowBuilder, curRow++);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- return NULL;
- }
- CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
- };
- class InlineTableStrandProcessor : public StrandProcessor
- {
- protected:
- IHThorInlineTableArg &helper;
- unsigned whichStrand;
- unsigned numStrands = 0;
- __uint64 sectionSize;
- __uint64 curRow = 0;
- __uint64 sectionMaxRows = 0;
- __uint64 maxRows = 0;
- bool isOrdered;
- bool eosPending;
- public:
- InlineTableStrandProcessor(CRoxieServerActivity &_parent, IHThorInlineTableArg &_helper, unsigned _whichStrand, bool _isOrdered)
- : StrandProcessor(_parent, NULL, true), helper(_helper), whichStrand(_whichStrand), isOrdered(_isOrdered)
- {
- sectionSize = queryParent().strandOptions.blockSize;
- eosPending = false;
- }
- virtual void start() override
- {
- StrandProcessor::start();
- numStrands = queryParent().numStrands();
- maxRows = queryParent().numRows;
- curRow = std::min(whichStrand * sectionSize, maxRows);
- sectionMaxRows = std::min(curRow + sectionSize, maxRows);
- eosPending = isOrdered && (curRow != maxRows);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- //Return rows while the current section is active
- while (curRow < sectionMaxRows)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.getRow(rowBuilder, curRow++);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- if (curRow == maxRows)
- return NULL;
- //Update current position to the next section
- curRow += (numStrands - 1) * sectionSize;
- if (curRow > maxRows)
- curRow = maxRows;
- sectionMaxRows = std::min(curRow + sectionSize, maxRows);
- //If we have output a block of rows, then send the block as a unit - results now come from the next strand
- if (eosPending)
- {
- //If there is another block, then second an end of section marker after it, otherwise make sure NULL is returned next.
- eosPending = isOrdered && (curRow != maxRows);
- return queryEndOfSectionMarker();
- }
- }
- }
- CRoxieServerStrandedInlineTableActivity & queryParent() { return static_cast<CRoxieServerStrandedInlineTableActivity&>(parent); }
- };
- public:
- CRoxieServerStrandedInlineTableActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
- : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorInlineTableArg &) basehelper)
- {
- numRows = 0;
- }
- virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream) { throwUnexpected(); }
- virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered)
- {
- if (strandOptions.numStrands <= 1)
- return new InlineTableSimpleProcessor(*this, helper);
- return new InlineTableStrandProcessor(*this, helper, strands.ordinality(), inputOrdered);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
- numRows = helper.numRows();
- onStartStrands();
- startJunction(sourceJunction); // This must be started *after* all the strands have been initialised
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerInlineTableActivityFactory : public CRoxieServerActivityFactory
- {
- StrandOptions strandOptions;
- public:
- CRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
- {
- optStableInput = false; // do not force the output to be ordered
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerStrandedInlineTableActivity(_ctx, this, _probeManager, strandOptions);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for InlineTable activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerInlineTableActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerInlineTableActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerWorkUnitReadActivity : public CRoxieServerActivity
- {
- IHThorWorkunitReadArg &helper;
- CriticalSection readerCrit;
- Owned<IWorkUnitRowReader> wuReader;
- public:
- CRoxieServerWorkUnitReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorWorkunitReadArg &)basehelper)
- {
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- if (!ctx->queryServerContext())
- {
- throw MakeStringException(ROXIE_INTERNAL_ERROR, "Workunit read activity cannot be executed in slave context");
- }
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- IXmlToRowTransformer * xmlTransformer = helper.queryXmlTransformer();
- OwnedRoxieString fromWuid(helper.getWUID());
- wuReader.setown(ctx->getWorkunitRowReader(fromWuid, helper.queryName(), helper.querySequence(), xmlTransformer, rowAllocator, meta.isGrouped()));
- // MORE _ should that be in onCreate?
- }
- virtual void reset()
- {
- {
- CriticalBlock b(readerCrit);
- wuReader.clear();
- }
- CRoxieServerActivity::reset();
- };
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- Linked<IWorkUnitRowReader> useReader;
- {
- CriticalBlock b(readerCrit);
- if (!wuReader)
- return NULL;
- useReader.set(wuReader);
- }
- const void *ret = useReader->nextRow();
- if (ret)
- processed++;
- return ret;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerWorkUnitReadActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerWorkUnitReadActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for WorkUnitRead activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerWorkUnitReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerWorkUnitReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- interface ILocalGraphEx : public IEclGraphResults
- {
- public:
- virtual void setResult(unsigned id, IGraphResult * result) = 0;
- virtual IEngineRowStream * createResultIterator(unsigned id) = 0;
- virtual void setGraphLoopResult(IGraphResult * result) = 0;
- virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id) = 0;
- };
- class CSafeRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
- {
- public:
- CSafeRoxieInput(unsigned _sourceIdx, IFinalRoxieInput * _input) : input(_input), inputStream(NULL), sourceIdx(_sourceIdx) {}
- IMPLEMENT_IINTERFACE
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- connectInputStreams(ctx, consumerOrdered);
- streams.append(this);
- return NULL;
- }
- void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
- {
- inputStream.set(connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered));
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return input->queryOutputMeta();
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return input->queryTotalCycles();
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
- virtual IRoxieServerActivity *queryActivity()
- {
- return input->queryActivity();
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- return input->queryIndexReadActivity();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CriticalBlock procedure(cs);
- input->start(parentExtractSize, parentExtract, paused);
- startJunction(junction);
- }
- virtual void stop()
- {
- CriticalBlock procedure(cs);
- inputStream->stop();
- }
- virtual void reset()
- {
- CriticalBlock procedure(cs);
- input->reset();
- resetJunction(junction);
- }
- virtual void resetEOF()
- {
- CriticalBlock procedure(cs);
- inputStream->resetEOF();
- }
- virtual const void *nextRow()
- {
- CriticalBlock procedure(cs);
- return inputStream->nextRow();
- }
- virtual bool nextGroup(ConstPointerArray & group)
- {
- CriticalBlock procedure(cs);
- return inputStream->nextGroup(group);
- }
- private:
- CriticalSection cs;
- Linked<IFinalRoxieInput> input;
- Linked<IEngineRowStream> inputStream;
- Owned<IStrandJunction> junction;
- unsigned sourceIdx;
- };
- //=================================================================================
- class CPseudoRoxieInput : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
-
- CPseudoRoxieInput()
- {
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return 0;
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
- virtual IRoxieServerActivity *queryActivity()
- {
- throwUnexpected();
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- throwUnexpected();
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- assertex(!idx);
- streams.append(this);
- return NULL;
- }
- virtual IOutputMetaData * queryOutputMeta() const { throwUnexpected(); }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) { }
- virtual void stop() { }
- virtual void reset() { }
- virtual void checkAbort() { }
- virtual void resetEOF() { }
- };
- class CIndirectRoxieInput : public CPseudoRoxieInput
- {
- public:
- CIndirectRoxieInput() : input(NULL)
- {
- stream = NULL;
- sourceIdx = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- input->start(parentExtractSize, parentExtract, paused);
- startJunction(junction);
- }
- virtual void stop()
- {
- stream->stop();
- }
- virtual void reset()
- {
- input->reset();
- resetJunction(junction);
- }
- virtual const void * nextRow()
- {
- return stream->nextRow();
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- return stream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return input->queryTotalCycles();
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- stream->resetEOF();
- }
- virtual unsigned numConcreteOutputs() const
- {
- return input->numConcreteOutputs();
- }
-
- virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
- {
- return input->queryConcreteInput(idx);
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
- {
- return input->queryConcreteOutputStream(whichInput);
- }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
- {
- return input->queryConcreteOutputJunction(idx);
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return input->queryOutputMeta();
- }
- virtual IRoxieServerActivity *queryActivity()
- {
- return input->queryActivity();
- }
- inline void setInput(unsigned _sourceIdx, IFinalRoxieInput * _input)
- {
- input = _input;
- sourceIdx = _sourceIdx;
- }
- inline void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
- {
- stream = connectSingleStream(ctx, input, sourceIdx, junction, consumerOrdered);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- assertex(idx == 0);
- connectInputStreams(ctx, consumerOrdered);
- streams.append(this);
- return NULL;
- }
- inline IFinalRoxieInput *queryInput() const
- {
- return input;
- }
- protected:
- unsigned sourceIdx;
- IFinalRoxieInput *input;
- IEngineRowStream *stream;
- Owned<IStrandJunction> junction;
- };
- class CExtractMapperInput : public CIndirectRoxieInput
- {
- unsigned savedParentExtractSize;
- const byte * savedParentExtract;
- public:
- CExtractMapperInput()
- {
- savedParentExtractSize = 0;
- savedParentExtract = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CIndirectRoxieInput::start(savedParentExtractSize, savedParentExtract, paused);
- }
- void setParentExtract(unsigned _savedParentExtractSize, const byte * _savedParentExtract)
- {
- savedParentExtractSize = _savedParentExtractSize;
- savedParentExtract = _savedParentExtract;
- }
- };
- class CGraphResult : implements IGraphResult, public CInterface
- {
- CriticalSection cs;
- byte **rowset;
- size32_t count;
- bool complete;
- void clear()
- {
- CriticalBlock func(cs);
- rtlReleaseRowset(count, rowset);
- rowset = NULL;
- count = 0;
- complete = false;
- }
- public:
- IMPLEMENT_IINTERFACE
- CGraphResult()
- {
- complete = false; // dummy result is not supposed to be used...
- rowset = NULL;
- count = 0;
- }
- CGraphResult(size32_t _count, byte **_rowset)
- : count(_count), rowset(_rowset)
- {
- complete = true;
- }
- ~CGraphResult()
- {
- clear();
- }
- // interface IGraphResult
- virtual IEngineRowStream * createIterator()
- {
- if (!complete)
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
- return new CGraphResultIterator(this);
- }
- virtual void getLinkedResult(unsigned & countResult, byte * * & result)
- {
- if (!complete)
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
- result = rtlLinkRowset(rowset);
- countResult = count;
- }
- virtual const void * getLinkedRowResult()
- {
- if (!complete)
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Reading uninitialised graph result");
- if (count != 1)
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Internal Error: Expected a single row result");
- const void * ret = rowset[0];
- LinkRoxieRow(ret);
- return ret;
- }
- //other
- const void * getRow(unsigned i)
- {
- CriticalBlock func(cs);
- if (i >= count)
- return NULL;
- const void * ret = rowset[i];
- if (ret) LinkRoxieRow(ret);
- return ret;
- }
- protected:
- class CGraphResultIterator : public CInterfaceOf<IEngineRowStream>
- {
- unsigned i;
- Linked<CGraphResult> result;
- public:
- CGraphResultIterator(CGraphResult * _result) : result(_result) { i = 0; }
- public:
- virtual const void * nextRow()
- {
- return result->getRow(i++);
- }
- virtual void stop()
- {
- }
- virtual void resetEOF()
- {
- throwUnexpected();
- }
- };
- };
- //=================================================================================
- class CRoxieServerLocalResultReadActivity : public CRoxieServerActivity
- {
- IHThorLocalResultReadArg &helper;
- CriticalSection iterCrit;
- Owned<IEngineRowStream> iter;
- ILocalGraphEx * graph;
- unsigned graphId;
- unsigned sequence;
- public:
- CRoxieServerLocalResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper), graphId(_graphId)
- {
- graph = NULL;
- sequence = 0;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
- sequence = helper.querySequence();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- iter.setown(graph->createResultIterator(sequence));
- }
- virtual void reset()
- {
- {
- CriticalBlock b(iterCrit);
- iter.clear();
- }
- CRoxieServerActivity::reset();
- };
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- Linked<IEngineRowStream> useIter;
- {
- CriticalBlock b(iterCrit);
- if (!iter)
- return NULL;
- useIter.set(iter);
- }
- const void * next = useIter->nextRow();
- if (next)
- {
- processed++;
- atomic_inc(&rowsIn);
- }
- return next;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerLocalResultReadActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned graphId;
- public:
- CRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLocalResultReadActivity(_ctx, this, _probeManager, graphId);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLocalResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
- {
- return new CRoxieServerLocalResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
- }
- //=================================================================================
- class CRoxieServerLocalResultStreamReadActivity : public CRoxieServerActivity
- {
- IHThorLocalResultReadArg &helper;
- unsigned sequence;
- public:
- CRoxieServerLocalResultStreamReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLocalResultReadArg &)basehelper)
- {
- sequence = 0;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- sequence = helper.querySequence();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = inputStream->nextRow();
- if (next)
- {
- processed++;
- atomic_inc(&rowsIn);
- }
- return next;
- }
- virtual bool querySetStreamInput(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * _input)
- {
- if (id == sequence)
- {
- CRoxieServerActivity::setInput(0, _sourceIdx, _input);
- connectInputStreams(true);
- return true;
- }
- return false;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerLocalResultStreamReadActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLocalResultStreamReadActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for LocalResultRead activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLocalResultStreamReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerLocalResultStreamReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerLocalResultWriteActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorLocalResultWriteArg &helper;
- ILocalGraphEx * graph;
- unsigned graphId;
- public:
- CRoxieServerLocalResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorLocalResultWriteArg &)basehelper), graphId(_graphId)
- {
- graph = NULL;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
- graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
- }
- virtual void onExecute()
- {
- RtlLinkedDatasetBuilder builder(rowAllocator);
- inputStream->readAll(builder);
- Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
- graph->setResult(helper.querySequence(), result);
- }
- virtual const void *nextRow()
- {
- return inputStream->nextRow(); // I can act as a passthrough input
- }
- IFinalRoxieInput * querySelectOutput(unsigned id)
- {
- if (id == helper.querySequence())
- {
- executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
- return LINK(this);
- }
- return NULL;
- }
- };
- class CRoxieServerLocalResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
- {
- unsigned graphId;
- public:
- CRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
- {
- isInternal = true;
- Owned<IHThorLocalResultWriteArg> helper = (IHThorLocalResultWriteArg *) helperFactory();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLocalResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLocalResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
- {
- return new CRoxieServerLocalResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
- }
- //=====================================================================================================
- class CRoxieServerDictionaryResultWriteActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorDictionaryResultWriteArg &helper;
- ILocalGraphEx * graph;
- unsigned graphId;
- public:
- CRoxieServerDictionaryResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount, unsigned _graphId)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryResultWriteArg &)basehelper), graphId(_graphId)
- {
- graph = NULL;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
- graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
- }
- virtual void onExecute()
- {
- unsigned sequence = helper.querySequence();
- RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
- loop
- {
- const void *row = inputStream->ungroupedNextRow();
- if (!row)
- break;
- builder.appendOwn(row);
- processed++;
- }
- Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
- graph->setResult(helper.querySequence(), result);
- }
- virtual const void *nextRow()
- {
- return inputStream->nextRow(); // I can act as a passthrough input
- }
- IFinalRoxieInput * querySelectOutput(unsigned id)
- {
- if (id == helper.querySequence())
- {
- executed = true; // Ensure that we don't try to pull as a sink as well as via the passthrough
- return LINK(this);
- }
- return NULL;
- }
- };
- class CRoxieServerDictionaryResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
- {
- unsigned graphId;
- public:
- CRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot), graphId(_graphId)
- {
- isInternal = true;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerDictionaryResultWriteActivity(_ctx, this, _probeManager, usageCount, graphId);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDictionaryResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId, bool _isRoot)
- {
- return new CRoxieServerDictionaryResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId, _isRoot);
- }
- //=================================================================================
- class CRoxieServerGraphLoopResultReadActivity : public CRoxieServerActivity
- {
- protected:
- IHThorGraphLoopResultReadArg &helper;
- CriticalSection iterCrit;
- Owned<IFinalRoxieInput> iterInput;
- Owned<IEngineRowStream> iterStream;
- Owned<IStrandJunction> iterJunction;
- ILocalGraphEx * graph;
- unsigned graphId;
- unsigned sequence;
- public:
- CRoxieServerGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGraphLoopResultReadArg &)basehelper), graphId(_graphId)
- {
- graph = NULL;
- sequence = 0;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (iterInput)
- iterInput->start(parentExtractSize, parentExtract, paused);
- else
- {
- sequence = helper.querySequence();
- if ((int)sequence >= 0)
- {
- try
- {
- iterStream.setown(graph->createGraphLoopResultIterator(sequence));
- iterInput.clear();
- }
- catch (IException * E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- startJunction(iterJunction);
- }
- virtual void stop()
- {
- if (iterStream)
- iterStream->stop();
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- {
- CriticalBlock b(iterCrit);
- if (iterInput)
- iterInput->reset();
- resetJunction(iterJunction);
- iterInput.clear();
- iterStream.clear();
- iterJunction.clear();
- }
- CRoxieServerActivity::reset();
- };
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- Linked<IEngineRowStream> useStream;
- {
- CriticalBlock b(iterCrit);
- if (!iterStream)
- return NULL;
- useStream.set(iterStream);
- }
- const void * next = useStream->nextRow();
- if (next)
- {
- processed++;
- atomic_inc(&rowsIn);
- }
- return next;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
- {
- ensureCreated();
- basehelper.onStart(parentExtract, NULL);
- processor.noteUseIteration(helper.querySequence());
- }
- virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
- {
- //helper already initialised from the gatherIterationUsage() call.
- CRoxieServerActivity::connectInputStreams(true);
- iterInput.set(processor.connectIterationOutput(helper.querySequence(), probeManager, probes, this, 0));
- iterStream.set(connectSingleStream(ctx, iterInput, 0, iterJunction, true));
- }
- virtual IInputSteppingMeta * querySteppingMeta()
- {
- assertex(iterInput);
- return iterInput->querySteppingMeta();
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- assertex(iterStream);
- return iterStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- }
- };
- //variety of CRoxieServerGraphLoopResultReadActivity created internally with a predefined sequence number
- class CRoxieServerInternalGraphLoopResultReadActivity : public CRoxieServerGraphLoopResultReadActivity
- {
- public:
- CRoxieServerInternalGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _sequence)
- : CRoxieServerGraphLoopResultReadActivity(_ctx, _factory, _probeManager, _graphId)
- {
- sequence = _sequence;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if ((int)sequence >= 0)
- {
- try
- {
- iterStream.setown(graph->createGraphLoopResultIterator(sequence));
- iterInput.clear();
- }
- catch (IException * E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned graphId;
- public:
- CRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for GraphLoopResultRead activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
- {
- return new CRoxieServerGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
- }
- //=====================================================================================================
- class CRoxieServerGraphLoopResultWriteActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorGraphLoopResultWriteArg &helper;
- ILocalGraphEx * graph;
- unsigned graphId;
- public:
- CRoxieServerGraphLoopResultWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorGraphLoopResultWriteArg &)basehelper), graphId(_graphId)
- {
- graph = NULL;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
- graph = static_cast<ILocalGraphEx *>(ctx->queryCodeContext()->resolveLocalQuery(graphId));
- }
- virtual void onExecute()
- {
- RtlLinkedDatasetBuilder builder(rowAllocator);
- inputStream->readAll(builder);
- Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
- graph->setGraphLoopResult(result);
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==0)
- return this;
- else
- return NULL;
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- virtual const void *nextRow()
- {
- const void * next = inputStream->nextRow();
- if (next)
- processed++;
- return next;
- }
- virtual bool isPassThrough()
- {
- return true;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (next)
- processed++;
- return next;
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return input->queryOutputMeta();
- }
- };
- class CRoxieServerGraphLoopResultWriteActivityFactory : public CRoxieServerInternalSinkFactory
- {
- unsigned graphId;
- public:
- CRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, true), graphId(_graphId)
- {
- isInternal = true;
- Owned<IHThorGraphLoopResultWriteArg> helper = (IHThorGraphLoopResultWriteArg *) helperFactory();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerGraphLoopResultWriteActivity(_ctx, this, _probeManager, graphId, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerGraphLoopResultWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, unsigned _graphId)
- {
- return new CRoxieServerGraphLoopResultWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _graphId);
- }
- //=================================================================================
- class CRoxieServerDedupActivity : public CRoxieServerActivity
- {
- protected:
- IHThorDedupArg &helper;
- unsigned numKept;
- unsigned numToKeep;
- public:
- CRoxieServerDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
- {
- numKept = 0;
- numToKeep = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numKept = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numToKeep = helper.numToKeep();
- }
- };
- class CRoxieServerDedupKeepLeftActivity : public CRoxieServerDedupActivity
- {
- IRangeCompare * stepCompare;
- const void *prev;
- public:
- CRoxieServerDedupKeepLeftActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
- {
- prev = NULL;
- stepCompare = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- prev = NULL;
- CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
- IInputSteppingMeta * stepMeta = input->querySteppingMeta();
- stepCompare = NULL;
- if (stepMeta)
- stepCompare = stepMeta->queryCompare();
- }
- virtual void reset()
- {
- ReleaseClearRoxieRow(prev);
- CRoxieServerDedupActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next;
- loop
- {
- next = inputStream->nextRow();
- if (!prev || !next || !helper.matches(prev,next))
- {
- numKept = 0;
- break;
- }
- if (numKept < numToKeep-1)
- {
- numKept++;
- break;
- }
- ReleaseRoxieRow(next);
- }
- ReleaseRoxieRow(prev);
- prev = next;
- if (next)
- {
- LinkRoxieRow(next);
- processed++;
- }
- return next;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next;
- loop
- {
- next = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- //If the record was an in-exact match from the index then return it immediately
- //and don't cause it to dedup following legal records.
- if (!wasCompleteMatch)
- {
- assertex(stepExtra.returnMismatches());
- return next;
- }
- if (!prev || !next || !helper.matches(prev,next))
- {
- numKept = 0;
- break;
- }
- if (numKept < numToKeep-1)
- {
- numKept++;
- break;
- }
- //Unusual - deduping by x,y stepped on x,y,z - still want any record back as soon as possible.
- if (stepExtra.returnMismatches())
- {
- //If asked to return mismatches we are only interested in mismatches that will force the stepped
- //condition to advance
- if (stepCompare->docompare(next, seek, numFields) != 0)
- {
- wasCompleteMatch = false;
- break;
- }
- }
- ReleaseRoxieRow(next);
- }
- ReleaseRoxieRow(prev);
- prev = next;
- if (next)
- {
- LinkRoxieRow(next);
- processed++;
- }
- return next;
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- //=================================================================================
- class CRoxieServerDedupKeepRightActivity : public CRoxieServerDedupActivity
- {
- const void *kept;
- bool first;
- public:
- CRoxieServerDedupKeepRightActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerDedupActivity(_ctx, _factory, _probeManager)
- {
- kept = NULL;
- first = true;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- first = true;
- kept = NULL;
- CRoxieServerDedupActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- ReleaseClearRoxieRow(kept);
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (first)
- {
- kept = inputStream->nextRow();
- first = false;
- }
- const void * next;
- loop
- {
- next = inputStream->nextRow();
- if (!kept || !next || !helper.matches(kept,next))
- {
- numKept = 0;
- break;
- }
- if (numKept < numToKeep-1)
- {
- numKept++;
- break;
- }
- ReleaseRoxieRow(kept);
- kept = next;
- }
- const void * ret = kept;
- kept = next;
- // CTXLOG("dedup returns %p", ret);
- if (ret) processed++;
- return ret;
- }
- };
- class CRoxieServerDedupAllActivity : public CRoxieServerActivity
- {
- IHThorDedupArg &helper;
- unsigned survivorIndex;
- ConstPointerArray survivors;
- bool keepLeft;
- bool eof;
- bool first;
- ICompare *primaryCompare;
- public:
- CRoxieServerDedupAllActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _keepLeft)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDedupArg &)basehelper)
- {
- keepLeft = _keepLeft;
- primaryCompare = helper.queryComparePrimary();
- eof = false;
- first = true;
- survivorIndex = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- first = true;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- #ifdef _DEBUG
- while (survivors.isItem(survivorIndex))
- {
- ReleaseRoxieRow(survivors.item(survivorIndex++));
- }
- #endif
- survivors.kill();
- eof = false;
- first = true;
- CRoxieServerActivity::reset();
- }
- void dedupRange(unsigned first, unsigned last, ConstPointerArray & group)
- {
- for (unsigned idxL = first; idxL < last; idxL++)
- {
- const void * left = group.item(idxL);
- if (left)
- {
- for (unsigned idxR = first; idxR < last; idxR++)
- {
- const void * right = group.item(idxR);
- if ((idxL != idxR) && right)
- {
- if (helper.matches(left, right))
- {
- if (keepLeft)
- {
- group.replace(NULL, idxR);
- ReleaseRoxieRow(right);
- }
- else
- {
- group.replace(NULL, idxL);
- ReleaseRoxieRow(left);
- break;
- }
- }
- }
- }
- }
- }
- }
- void dedupRange(unsigned first, unsigned last, void ** rows)
- {
- for (unsigned idxL = first; idxL < last; idxL++)
- {
- void * left = rows[idxL];
- if (left)
- {
- for (unsigned idxR = first; idxR < last; idxR++)
- {
- void * right = rows[idxR];
- if ((idxL != idxR) && right)
- {
- if (helper.matches(left, right))
- {
- if (keepLeft)
- {
- rows[idxR] = NULL;
- ReleaseRoxieRow(right);
- }
- else
- {
- rows[idxL] = NULL;
- ReleaseRoxieRow(left);
- break;
- }
- }
- }
- }
- }
- }
- }
- bool calcNextDedupAll()
- {
- survivors.kill();
- survivorIndex = 0;
- ConstPointerArray group;
- if (eof || !inputStream->nextGroup(group))
- {
- eof = true;
- return false;
- }
- unsigned max = group.ordinality();
- if (primaryCompare)
- {
- //hard, if not impossible, to hit this code once optimisations in place
- MemoryAttr indexbuff(max*sizeof(void *));
- void ** temp = (void **)indexbuff.bufferBase();
- void * *rows = const_cast<void * *>(group.getArray());
- msortvecstableinplace(rows, max, *primaryCompare, temp);
- unsigned first = 0;
- for (unsigned idx = 1; idx < max; idx++)
- {
- if (primaryCompare->docompare(rows[first], rows[idx]) != 0)
- {
- dedupRange(first, idx, rows);
- first = idx;
- }
- }
- dedupRange(first, max, rows);
- for(unsigned idx2=0; idx2<max; ++idx2)
- {
- void * cur = rows[idx2];
- if(cur)
- survivors.append(cur);
- }
- }
- else
- {
- dedupRange(0, max, group);
- for(unsigned idx=0; idx<max; ++idx)
- {
- const void * cur = group.item(idx);
- if(cur)
- survivors.append(cur);
- }
- }
- return true;
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (first)
- {
- calcNextDedupAll();
- first = false;
- }
- while (survivors.isItem(survivorIndex))
- {
- const void *ret = survivors.item(survivorIndex++);
- if (ret)
- {
- processed++;
- return ret;
- }
- }
- calcNextDedupAll();
- return NULL;
- }
- };
- class CRoxieServerDedupActivityFactory : public CRoxieServerActivityFactory
- {
- bool compareAll;
- bool keepLeft;
- public:
- CRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorDedupArg> helper = (IHThorDedupArg *) helperFactory();
- compareAll = helper->compareAll();
- keepLeft = helper->keepLeft();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (compareAll)
- return new CRoxieServerDedupAllActivity(_ctx, this, _probeManager, keepLeft);
- else if (keepLeft)
- return new CRoxieServerDedupKeepLeftActivity(_ctx, this, _probeManager);
- else
- return new CRoxieServerDedupKeepRightActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerHashDedupActivity : public CRoxieServerActivity
- {
- bool eof;
- IHThorHashDedupArg &helper;
- class HashDedupElement
- {
- public:
- HashDedupElement(unsigned _hash, const void *_keyRow)
- : hash(_hash), keyRow(_keyRow)
- {
- }
- ~HashDedupElement()
- {
- ReleaseRoxieRow(keyRow);
- }
- inline unsigned queryHash() const
- {
- return hash;
- }
- inline const void *queryRow() const
- {
- return keyRow;
- }
- private:
- unsigned hash;
- const void *keyRow;
- };
- class HashDedupTable : public SuperHashTable
- {
- public:
- HashDedupTable(IHThorHashDedupArg & _helper, CRoxieServerHashDedupActivity & _activity)
- : helper(_helper),
- activity(_activity),
- keySize(helper.queryKeySize())
- {
- }
- virtual ~HashDedupTable() { _releaseAll(); }
- virtual unsigned getHashFromElement(const void *et) const
- {
- const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
- return element->queryHash();
- }
- virtual unsigned getHashFromFindParam(const void *fp) const { throwUnexpected(); }
- virtual const void * getFindParam(const void *et) const { throwUnexpected(); }
- virtual bool matchesElement(const void *et, const void *searchET) const { throwUnexpected(); }
- virtual bool matchesFindParam(const void *et, const void *key, unsigned fphash) const
- {
- const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
- if (fphash != element->queryHash())
- return false;
- return (helper.queryKeyCompare()->docompare(element->queryRow(), key) == 0);
- }
- virtual void onAdd(void *et) {}
- virtual void onRemove(void *et)
- {
- const HashDedupElement *element = reinterpret_cast<const HashDedupElement *>(et);
- delete element;
- }
- void onCreate(IRoxieSlaveContext *ctx)
- {
- keyRowAllocator.setown(activity.createRowAllocator(keySize.queryOriginal()));
- }
- void reset()
- {
- kill();
- }
- bool insert(const void * row)
- {
- unsigned hash = helper.queryHash()->hash(row);
- RtlDynamicRowBuilder keyRowBuilder(keyRowAllocator, true);
- size32_t thisKeySize = helper.recordToKey(keyRowBuilder, row);
- OwnedConstRoxieRow keyRow = keyRowBuilder.finalizeRowClear(thisKeySize);
- if (find(hash, keyRow.get()))
- return false;
- addNew(new HashDedupElement(hash, keyRow.getClear()), hash);
- return true;
- }
- private:
- IHThorHashDedupArg & helper;
- CachedOutputMetaData keySize;
- Owned<IEngineRowAllocator> keyRowAllocator;
- CRoxieServerHashDedupActivity & activity;
- } table;
- public:
- CRoxieServerHashDedupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashDedupArg &)basehelper), table(helper, *this)
- {
- eof = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(colocalParent);
- table.onCreate(ctx);
- }
- virtual void reset()
- {
- table.reset();
- eof = false;
- CRoxieServerActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- while(!eof)
- {
- const void * next = inputStream->nextRow();
- if(!next)
- {
- if (table.count() == 0)
- eof = true;
- table.reset();
- return NULL;
- }
- if(table.insert(next))
- return next;
- else
- ReleaseRoxieRow(next);
- }
- return NULL;
- }
- };
- class CRoxieServerHashDedupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerHashDedupActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerHashDedupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerHashDedupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerRollupActivity : public CRoxieServerActivity
- {
- IHThorRollupArg &helper;
- OwnedConstRoxieRow left;
- OwnedConstRoxieRow prev;
- OwnedConstRoxieRow right;
- bool readFirstRow;
- public:
- CRoxieServerRollupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorRollupArg &)basehelper)
- {
- readFirstRow = false;
- }
- ~CRoxieServerRollupActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- readFirstRow = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- left.clear();
- prev.clear();
- right.clear();
- CRoxieServerActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!readFirstRow)
- {
- left.setown(inputStream->nextRow());
- prev.set(left);
- readFirstRow = true;
- }
- loop
- {
- right.setown(inputStream->nextRow());
- if(!prev || !right || !helper.matches(prev,right))
- {
- const void * ret = left.getClear();
- if(ret)
- processed++;
- left.setown(right.getClear());
- prev.set(left);
- return ret;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.transform(rowBuilder, left, right);
- if (outSize)
- left.setown(rowBuilder.finalizeRowClear(outSize));
- if (helper.getFlags() & RFrolledismatchleft)
- prev.set(left);
- else
- prev.set(right);
- }
- catch(IException * E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerRollupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerRollupActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerRollupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerRollupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNormalizeActivity : public CRoxieServerActivity
- {
- IHThorNormalizeArg &helper;
- unsigned numThisRow;
- unsigned curRow;
- const void *buffer;
- unsigned numProcessedLastGroup;
- public:
- CRoxieServerNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeArg &)basehelper)
- {
- buffer = NULL;
- numThisRow = 0;
- curRow = 0;
- numProcessedLastGroup = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numThisRow = 0;
- curRow = 0;
- numProcessedLastGroup = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- ReleaseClearRoxieRow(buffer);
- CRoxieServerActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- while (curRow == numThisRow)
- {
- if (buffer)
- ReleaseClearRoxieRow(buffer);
- buffer = inputStream->nextRow();
- if (!buffer && (processed == numProcessedLastGroup))
- buffer = inputStream->nextRow();
- if (!buffer)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- curRow = 0;
- numThisRow = helper.numExpandedRows(buffer);
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned actualSize = helper.transform(rowBuilder, buffer, ++curRow);
- if (actualSize != 0)
- {
- processed++;
- return rowBuilder.finalizeRowClear(actualSize);
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerNormalizeActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNormalizeActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNormalizeChildActivity : public CRoxieServerActivity
- {
- IHThorNormalizeChildArg &helper;
- unsigned numThisRow;
- unsigned curRow;
- const void *buffer;
- unsigned numProcessedLastGroup;
- INormalizeChildIterator * cursor;
- const void * curChildRow;
- bool advanceInput()
- {
- loop
- {
- ReleaseClearRoxieRow(buffer);
- buffer = inputStream->nextRow();
- if (!buffer && (processed == numProcessedLastGroup))
- buffer = inputStream->nextRow();
- if (!buffer)
- {
- numProcessedLastGroup = processed;
- return false;
- }
- curChildRow = cursor->first(buffer);
- if (curChildRow)
- {
- curRow = 0;
- return true;
- }
- }
- }
- public:
- CRoxieServerNormalizeChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeChildArg &)basehelper)
- {
- buffer = NULL;
- cursor = NULL;
- numThisRow = 0;
- curRow = 0;
- numProcessedLastGroup = 0;
- curChildRow = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numThisRow = 0;
- curRow = 0;
- numProcessedLastGroup = 0;
- curChildRow = NULL;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- cursor = helper.queryIterator();
- }
- virtual void stop()
- {
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- cursor = NULL;
- ReleaseClearRoxieRow(buffer);
- CRoxieServerActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (!buffer)
- {
- if (!advanceInput())
- return NULL;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, buffer, curChildRow, ++curRow);
- curChildRow = cursor->next();
- if (!curChildRow)
- ReleaseClearRoxieRow(buffer);
- if (outSize != 0)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerNormalizeChildActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNormalizeChildActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNormalizeChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNormalizeChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNormalizeLinkedChildActivity : public CRoxieServerActivity
- {
- IHThorNormalizeLinkedChildArg &helper;
- OwnedConstRoxieRow curParent;
- OwnedConstRoxieRow curChild;
- unsigned numProcessedLastGroup;
- bool advanceInput()
- {
- loop
- {
- curParent.setown(inputStream->nextRow());
- if (!curParent && (processed == numProcessedLastGroup))
- curParent.setown(inputStream->nextRow());
- if (!curParent)
- {
- numProcessedLastGroup = processed;
- return false;
- }
- curChild.set(helper.first(curParent));
- if (curChild)
- return true;
- }
- }
- public:
- CRoxieServerNormalizeLinkedChildActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorNormalizeLinkedChildArg &)basehelper)
- {
- numProcessedLastGroup = 0;
- }
- ~CRoxieServerNormalizeLinkedChildActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- curParent.clear();
- curChild.clear();
- CRoxieServerActivity::reset();
- }
- const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (!curParent)
- {
- if (!advanceInput())
- return NULL;
- }
- try
- {
- const void *ret = curChild.getClear();
- curChild.set(helper.next());
- if (!curChild)
- curParent.clear();
- if (ret)
- {
- processed++;
- return ret;
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerNormalizeLinkedChildActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNormalizeLinkedChildActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNormalizeLinkedChildActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNormalizeLinkedChildActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSortActivity : public CRoxieServerActivity
- {
- protected:
- IHThorSortArg &helper;
- ICompare *compare;
- Owned<ISortAlgorithm> sorter;
- bool readInput;
- RoxieSortAlgorithm sortAlgorithm;
- unsigned sortFlags;
- public:
- CRoxieServerSortActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, RoxieSortAlgorithm _sortAlgorithm, unsigned _sortFlags)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortArg &)basehelper), sortAlgorithm(_sortAlgorithm), sortFlags(_sortFlags)
- {
- compare = helper.queryCompare();
- readInput = false;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- if (sortAlgorithm==unknownSortAlgorithm)
- sorter.clear();
- else
- sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- assertex(!readInput);
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- if (sorter)
- sorter->reset();
- readInput = false;
- CRoxieServerActivity::reset();
- }
- static RoxieSortAlgorithm useAlgorithm(const char *algorithmName, unsigned sortFlags)
- {
- RoxieSortAlgorithm sortAlgorithm = unknownSortAlgorithm;
- if (!algorithmName)
- algorithmName = "";
- if (stricmp(algorithmName, "quicksort")==0)
- {
- switch (sortFlags & (TAFstable|TAFspill))
- {
- case 0: sortAlgorithm = quickSortAlgorithm; break;
- case TAFstable: sortAlgorithm = stableQuickSortAlgorithm; break;
- case TAFspill: sortAlgorithm = spillingQuickSortAlgorithm; break;
- case TAFstable|TAFspill: sortAlgorithm = stableSpillingQuickSortAlgorithm; break;
- }
- }
- else if (stricmp(algorithmName, "parquicksort")==0)
- {
- switch (sortFlags & TAFstable)
- {
- case 0: sortAlgorithm = parallelQuickSortAlgorithm; break;
- case TAFstable: sortAlgorithm = parallelStableQuickSortAlgorithm; break;
- default: throwUnexpected();
- }
- }
- else if (stricmp(algorithmName, "heapsort")==0)
- sortAlgorithm = heapSortAlgorithm; // NOTE - we do allow UNSTABLE('heapsort') in order to facilitate runtime selection. Also explicit selection of heapsort overrides request to spill
- else if (stricmp(algorithmName, "mergesort")==0)
- sortAlgorithm = (sortFlags & TAFspill) ? spillingMergeSortAlgorithm : mergeSortAlgorithm;
- else if (stricmp(algorithmName, "parmergesort")==0)
- sortAlgorithm = (sortFlags & TAFspill) ? spillingParallelMergeSortAlgorithm : parallelMergeSortAlgorithm;
- else if (stricmp(algorithmName, "tbbqsort")==0)
- sortAlgorithm = tbbQuickSortAlgorithm;
- else if (stricmp(algorithmName, "tbbstableqsort")==0)
- sortAlgorithm = tbbStableQuickSortAlgorithm;
- else
- {
- if (*algorithmName)
- WARNLOG(ROXIE_UNKNOWN_ALGORITHM, "Ignoring unsupported sort order algorithm '%s', using default", algorithmName);
- if (sortFlags & TAFspill)
- sortAlgorithm = ((sortFlags & TAFunstable) != 0) ? spillingQuickSortAlgorithm : stableSpillingQuickSortAlgorithm;
- else if (sortFlags & TAFunstable)
- sortAlgorithm = quickSortAlgorithm;
- else
- sortAlgorithm = heapSortAlgorithm;
- }
- return sortAlgorithm;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!readInput)
- {
- if (sortAlgorithm == unknownSortAlgorithm)
- {
- sorter.clear();
- IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(helper.selectInterface(TAIalgorithm_1));
- OwnedRoxieString algorithmName(sortMethod->getAlgorithm());
- sortAlgorithm = useAlgorithm(algorithmName, sortFlags);
- sorter.setown(createSortAlgorithm(sortAlgorithm, compare, ctx->queryRowManager(), meta, ctx->queryCodeContext(), tempDirectory, activityId));
- }
- sorter->prepare(inputStream);
- noteStatistic(StTimeSortElapsed, cycle_to_nanosec(sorter->getElapsedCycles(true)));
- readInput = true;
- }
- const void *ret = sorter->next();
- if (ret)
- processed++;
- else
- {
- sorter->reset();
- readInput = false; // ready for next group
- }
- return ret;
- }
- };
- class CRoxieServerSortActivityFactory : public CRoxieServerActivityFactory
- {
- RoxieSortAlgorithm sortAlgorithm;
- unsigned sortFlags;
- public:
- CRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorSortArg> sortHelper = (IHThorSortArg *) helperFactory();
- const char *algorithmName = NULL;
- IHThorAlgorithm *sortMethod = static_cast<IHThorAlgorithm *>(sortHelper->selectInterface(TAIalgorithm_1));
- if (sortMethod)
- {
- sortFlags = sortMethod->getAlgorithmFlags();
- if (sortFlags & TAFconstant)
- algorithmName = sortMethod->getAlgorithm();
- }
- else
- sortFlags = TAFstable|TAFconstant;
- bool forceSpill = _queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);
- if (forceSpill)
- sortFlags |= TAFspill;
- if (!(sortFlags & TAFunstable))
- sortFlags |= TAFstable; // Assume stable unless specifically requested otherwise
- if (sortFlags & TAFconstant)
- sortAlgorithm = CRoxieServerSortActivity::useAlgorithm(algorithmName, sortFlags);
- else
- sortAlgorithm = unknownSortAlgorithm;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSortActivity(_ctx, this, _probeManager, sortAlgorithm, sortFlags);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return sortStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSortActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSortActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- static int compareUint64(const void * _left, const void * _right)
- {
- const unsigned __int64 left = *static_cast<const unsigned __int64 *>(_left);
- const unsigned __int64 right = *static_cast<const unsigned __int64 *>(_right);
- if (left < right)
- return -1;
- if (left > right)
- return -1;
- return 0;
- }
- class CRoxieServerQuantileActivity : public CRoxieServerActivity
- {
- protected:
- Owned<ISortAlgorithm> sorter;
- IHThorQuantileArg &helper;
- ConstPointerArray sorted;
- ICompare *compare;
- unsigned flags;
- double skew;
- unsigned __int64 numDivisions;
- bool rangeIsAll;
- size32_t rangeSize;
- rtlDataAttr rangeValues;
- bool calculated;
- bool processedAny;
- bool anyThisGroup;
- bool eof;
- unsigned curQuantile;
- unsigned curIndex;
- unsigned curIndexExtra;
- unsigned skipSize;
- unsigned skipExtra;
- unsigned prevIndex;
- public:
- CRoxieServerQuantileActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _flags)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorQuantileArg &)basehelper), flags(_flags)
- {
- compare = helper.queryCompare();
- skew = 0.0;
- numDivisions = 0;
- calculated = false;
- processedAny = false;
- anyThisGroup = false;
- eof = false;
- rangeIsAll = true;
- rangeSize = 0;
- curQuantile = 0;
- prevIndex = 0;
- curIndex = 0;
- curIndexExtra = 0;
- skipSize = 0;
- skipExtra = 0;
- if (flags & TQFunstable)
- sorter.setown(createQuickSortAlgorithm(compare));
- else
- sorter.setown(createMergeSortAlgorithm(compare));
- }
- virtual void reset()
- {
- sorter->reset();
- calculated = false;
- processedAny = false;
- anyThisGroup = false;
- CRoxieServerActivity::reset();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- skew = helper.getSkew();
- numDivisions = helper.getNumDivisions();
- //Check for -ve integer values and treat as out of range
- if ((__int64)numDivisions < 1)
- numDivisions = 1;
- if (flags & TQFhasrange)
- helper.getRange(rangeIsAll, rangeSize, rangeValues.refdata());
- else
- {
- rangeIsAll = true;
- rangeSize = 0;
- }
- if (rangeSize)
- {
- //Sort the range items into order to allow quick comparison
- qsort(rangeValues.getdata(), rangeSize / sizeof(unsigned __int64), sizeof(unsigned __int64), compareUint64);
- }
- calculated = false;
- processedAny = false;
- anyThisGroup = false;
- eof = false;
- curQuantile = 0;
- prevIndex = 0;
- curIndex = 0;
- curIndexExtra = 0;
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * ret = NULL;
- for(;;)
- {
- if (!calculated)
- {
- if (flags & TQFlocalsorted)
- {
- for (;;)
- {
- const void * next = inputStream->nextRow();
- if (!next)
- break;
- sorted.append(next);
- }
- }
- else
- {
- sorter->prepare(inputStream);
- sorter->getSortedGroup(sorted);
- }
- if (sorted.ordinality() == 0)
- {
- if (processedAny)
- {
- eof = true;
- return NULL;
- }
- //Unusual case 0 rows - add a default row instead
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = helper.createDefault(rowBuilder);
- sorted.append(rowBuilder.finalizeRowClear(thisSize));
- }
- calculated = true;
- processedAny = true;
- anyThisGroup = false;
- curQuantile = 0;
- curIndex = 0;
- curIndexExtra = (numDivisions-1) / 2; // to ensure correctly rounded up
- prevIndex = curIndex-1; // Ensure it doesn't match
- skipSize = (sorted.ordinality() / numDivisions);
- skipExtra = (sorted.ordinality() % numDivisions);
- }
- if (isQuantileIncluded(curQuantile))
- {
- if (!(flags & TQFdedup) || (prevIndex != curIndex))
- {
- const void * lhs = sorted.item(curIndex);
- if (flags & TQFneedtransform)
- {
- unsigned outSize;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- try
- {
- outSize = helper.transform(rowBuilder, lhs, curQuantile);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- if (outSize)
- ret = rowBuilder.finalizeRowClear(outSize);
- }
- else
- {
- LinkRoxieRow(lhs);
- ret = lhs;
- }
- prevIndex = curIndex; // even if output was skipped?
- }
- }
- curIndex += skipSize;
- curIndexExtra += skipExtra;
- if (curIndexExtra >= numDivisions)
- {
- curIndex++;
- curIndexExtra -= numDivisions;
- }
- //Ensure the current index always stays valid.
- if (curIndex >= sorted.ordinality())
- curIndex = sorted.ordinality()-1;
- curQuantile++;
- if (curQuantile > numDivisions)
- {
- sorted.kill();
- sorter->reset();
- calculated = false; // ready for next group
- }
- if (ret)
- {
- anyThisGroup = true;
- processed++;
- return ret;
- }
- if (curQuantile > numDivisions)
- {
- if (anyThisGroup)
- return NULL;
- }
- }
- }
- bool isQuantileIncluded(unsigned quantile) const
- {
- if (quantile == 0)
- return (flags & TQFfirst) != 0;
- if (quantile == numDivisions)
- return (flags & TQFlast) != 0;
- if (rangeIsAll)
- return true;
- //Compare against the list of ranges provided
- //MORE: Since the list is sorted should only need to compare the next (and allow for dups)
- unsigned rangeNum = rangeSize / sizeof(unsigned __int64);
- const unsigned __int64 * ranges = static_cast<const unsigned __int64 *>(rangeValues.getdata());
- for (unsigned i = 0; i < rangeNum; i++)
- {
- if (ranges[i] == quantile)
- return true;
- }
- return false;
- }
- };
- class CRoxieServerQuantileActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned flags;
- public:
- CRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorQuantileArg> quantileHelper = (IHThorQuantileArg *) helperFactory();
- flags = quantileHelper->getFlags();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerQuantileActivity(_ctx, this, _probeManager, flags);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerQuantileActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerQuantileActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerSortedActivity : public CRoxieServerActivity
- {
- IHThorSortedArg &helper;
- ICompare * compare;
- const void *prev;
- IRangeCompare * stepCompare;
- public:
- CRoxieServerSortedActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSortedArg &)basehelper)
- {
- prev = NULL;
- compare = helper.queryCompare();
- stepCompare = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- IInputSteppingMeta * stepMeta = input->querySteppingMeta();
- if (stepMeta)
- stepCompare = stepMeta->queryCompare();
- prev = NULL;
- }
- virtual void reset()
- {
- ReleaseClearRoxieRow(prev);
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void *ret = inputStream->nextRow();
- if (ret && prev && compare->docompare(prev, ret) > 0)
- {
- // MORE - better to give mismatching rows that indexes?
- throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
- }
- ReleaseRoxieRow(prev);
- prev = ret;
- if (ret)
- {
- LinkRoxieRow(prev);
- processed++;
- }
- return ret;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void *ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (ret && prev && compare->docompare(prev, ret) > 0)
- {
- // MORE - better to give mismatching rows that indexes?
- throw MakeStringException(ROXIE_NOT_SORTED, "SORTED(%u) detected incorrectly sorted rows (row %d, %d))", activityId, processed, processed+1);
- }
- ReleaseRoxieRow(prev);
- prev = ret;
- if (ret)
- {
- LinkRoxieRow(prev);
- processed++;
- }
- return ret;
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- };
- class CRoxieServerSortedActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSortedActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSortedActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSortedActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerThroughSpillActivity : public CRoxieServerActivity
- {
- /*
- BE VERY CAREFUL - this code is tricky.
- Note that starts and stops (and resets) can occur in strange orders
- The FIRST start OR stop must initialize the activity but only the first START should call the upstream start.
- The last stop should call the upstream stop.
- The first reset should call the upstream reset.
- 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
- not yet had start or stop called - for this to happen init() is called on all outputs on the first start or stop.
- Some outputs may be completely pruned away when used in a GRAPH - these outputs should not receive any start/stop/reset and should be
- ignored in the minIndex calculation
- */
- public:
- IHThorArg &helper;
- unsigned activeOutputs;
- unsigned numOutputs;
- unsigned numOriginalOutputs;
- QueueOf<const void, true> buffer;
- CriticalSection crit;
- CriticalSection crit2;
- unsigned tailIdx;
- unsigned headIdx;
- Owned<IException> error;
- class OutputAdaptor : implements IEngineRowStream, implements IFinalRoxieInput, public CInterface
- {
- bool eof, eofpending, stopped;
- public:
- CRoxieServerThroughSpillActivity *parent;
- unsigned idx;
- unsigned oid;
- unsigned processed;
- cycle_t totalCycles; // We track this per output so that the pullers get a meaningful value to use when calculating their localtime
- public:
- IMPLEMENT_IINTERFACE;
- OutputAdaptor()
- {
- parent = NULL;
- oid = 0;
- idx = 0;
- processed = 0;
- totalCycles = 0;
- eofpending = false;
- eof = false;
- stopped = false;
- }
- ~OutputAdaptor()
- {
- if (traceStartStop)
- DBGLOG("%p ~OutputAdaptor %d", this, oid);
- if (processed && parent && parent->factory)
- {
- parent->factory->noteProcessed(oid, processed);
- if (parent->ctx)
- parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
- }
- }
- void init()
- {
- if (traceStartStop)
- DBGLOG("%p init Input adaptor %d", this, oid);
- idx = 0;
- processed = 0;
- eofpending = false;
- eof = false;
- stopped = false;
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(idx==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
- virtual IRoxieServerActivity *queryActivity()
- {
- return parent;
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- return parent->queryIndexReadActivity();
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return totalCycles;
- }
- virtual const void * nextRow()
- {
- SimpleActivityTimer t(totalCycles, parent->timeActivities);
- if (eof)
- return NULL;
- const void *ret = parent->readBuffered(idx, oid);
- #ifdef TRACE_SPLIT
- parent->CTXLOG("Adaptor %d got back %p for record %d", oid, ret, idx);
- #endif
- if (ret)
- {
- processed++;
- eofpending = false;
- }
- else if (eofpending)
- eof = true;
- else
- eofpending = true;
- return ret;
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return parent->queryOutputMeta();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- // NOTE: it is tempting to move the init() of all output adaptors here. However that is not a good idea,
- // since adaptors that have not yet started or stopped (but are going to) still need to have been init()'ed
- // for minIndex to give the correct answers
- // therefore, we call init() on all adaptors on receipt of the first start() or stop()
- if (traceStartStop)
- parent->CTXLOG("%p start Input adaptor %d stopped = %d", this, oid, stopped);
- parent->start(oid, parentExtractSize, parentExtract, paused);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- parent->connectInputStreams(consumerOrdered);
- streams.append(this);
- return NULL;
- }
- virtual void stop()
- {
- if (traceStartStop)
- parent->CTXLOG("%p stop Input adaptor %d stopped = %d", this, oid, stopped);
- if (!stopped)
- {
- parent->stop(oid, idx); // NOTE - may call init()
- stopped = true; // parent code relies on stop being called exactly once per adaptor, so make sure it is!
- }
- };
- virtual void reset()
- {
- if (traceStartStop)
- parent->CTXLOG("%p reset Input adaptor %d stopped = %d", this, oid, stopped);
- parent->reset(oid);
- idx = 0; // value should not be relevant really but this is the safest...
- stopped = false;
- };
- virtual void resetEOF()
- {
- parent->resetEOF();
- }
- virtual void checkAbort()
- {
- parent->checkAbort();
- }
- } *adaptors;
- bool *used;
- unsigned nextFreeOutput()
- {
- unsigned i = numOutputs;
- while (i)
- {
- i--;
- if (!used[i])
- return i;
- }
- throwUnexpected();
- }
- unsigned minIndex(unsigned exceptOid)
- {
- // MORE - yukky code (and slow). Could keep them heapsorted by idx or something
- // this is trying to determine whether any of the adaptors will in the future read a given record
- unsigned minIdx = (unsigned) -1;
- for (unsigned i = 0; i < numOutputs; i++)
- {
- if (i != exceptOid && used[i] && adaptors[i].idx < minIdx)
- minIdx = adaptors[i].idx;
- }
- return minIdx;
- }
- inline bool isLastTailReader(unsigned exceptOid)
- {
- for (unsigned i = 0; i < numOutputs; i++)
- {
- if (i != exceptOid && adaptors[i].idx == tailIdx && used[i])
- return false;
- }
- return true;
- }
- void initOutputs()
- {
- activeOutputs = numOutputs;
- for (unsigned i = 0; i < numOriginalOutputs; i++)
- if (used[i])
- adaptors[i].init();
- state = STATEstarting;
- }
- public:
- CRoxieServerThroughSpillActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper(basehelper), numOutputs(_numOutputs)
- {
- numOriginalOutputs = numOutputs;
- adaptors = new OutputAdaptor[numOutputs];
- used = new bool[numOutputs];
- for (unsigned i = 0; i < numOutputs; i++)
- {
- adaptors[i].parent = this;
- adaptors[i].oid = i;
- used[i] = false;
- }
- tailIdx = 0;
- headIdx = 0;
- activeOutputs = numOutputs;
- }
- ~CRoxieServerThroughSpillActivity()
- {
- delete [] adaptors;
- delete [] used;
- }
- const void *readBuffered(unsigned &idx, unsigned oid)
- {
- //False positives are fine, false negatives are not.. so headIdx must only be updated when a row will be available.
- const unsigned curIdx = idx;
- if (curIdx == headIdx) // test once without getting the crit2 sec
- {
- CriticalBlock b2(crit2); // but only one puller gets to read the head
- if (curIdx == headIdx) // test again now that we have it
- {
- 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
- if (error)
- throw error.getLink();
- try
- {
- const void *row = inputStream->nextRow();
- if (activeOutputs==1)
- {
- #ifdef TRACE_SPLIT
- CTXLOG("spill %d optimised return of %p", activityId, row);
- #endif
- headIdx++;
- idx++;
- return row; // optimization for the case where only one output still active.
- }
- CriticalBlock b(crit);
- headIdx++;
- idx++;
- if (activeOutputs==1)
- return row; // optimization for the case where only one output still active.
- buffer.enqueue(row);
- if (row) LinkRoxieRow(row);
- return row;
- }
- catch (IException *E)
- {
- #ifdef TRACE_SPLIT
- CTXLOG("spill %d caught exception", activityId);
- #endif
- error.set(E);
- throw;
- }
- catch (...)
- {
- IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::readBuffered");
- error.set(E);
- throw E;
- }
- }
- }
- CriticalBlock b(crit);
- 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
- unsigned lidx = curIdx - tailIdx;
- idx++;
- if (!lidx)
- {
- // The numOutputs <= 2 check optimizes slightly the common case of 2-way splitters.
- // 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
- if (numOutputs <= 2 || isLastTailReader(oid)) // NOTE - this includes the case where minIndex returns (unsigned) -1, meaning no other active pullers
- {
- tailIdx++;
- const void *ret = buffer.dequeue(); // no need to link - last puller
- #ifdef TRACE_SPLIT
- CTXLOG("last puller return of %p", ret);
- #endif
- return ret;
- }
- }
- const void *ret = buffer.item(lidx);
- if (ret) LinkRoxieRow(ret);
- #ifdef TRACE_SPLIT
- CTXLOG("standard return of %p", ret);
- #endif
- return ret;
- }
- virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CriticalBlock b(crit);
- if (error)
- throw error.getLink();
- if (factory)
- factory->noteStarted(oid);
- if (traceStartStop)
- CTXLOG("SPLIT %p: start %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
- if (state != STATEstarted)
- {
- if (state != STATEstarting)
- initOutputs();
- tailIdx = 0;
- headIdx = 0;
- error.clear();
- try
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- catch (IException *E)
- {
- #ifdef TRACE_SPLIT
- CTXLOG("spill %d caught exception in start", activityId);
- #endif
- error.set(E);
- throw;
- }
- catch (...)
- {
- IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerThroughSpillActivity::start");
- error.set(E);
- throw E;
- }
- }
- }
- void stop(unsigned oid, unsigned & idx)
- {
- // Note that OutputAdaptor code ensures that stop is not called more than once per adaptor
- CriticalBlock b(crit);
- #ifdef TRACE_STARTSTOP
- if (traceStartStop)
- {
- CTXLOG("SPLIT %p: stop %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
- if (watchActivityId && watchActivityId==activityId)
- {
- CTXLOG("WATCH: stop %d", activityId);
- }
- }
- #endif
- if (state != STATEstarting && state != STATEstarted)
- initOutputs();
- if (activeOutputs > 1)
- {
- if (tailIdx==idx)
- {
- // Discard all buffered rows that are there purely for this adaptor to read them
- unsigned min = minIndex(oid);
- if (min != (unsigned) -1)
- // what does -1 signify?? No-one wants anything? In which case can't we kill all rows??
- // Should never happen though if there are still some active.
- // there may be a small window where adaptors are blocked on the semaphore...
- {
- #ifdef TRACE_SPLIT
- CTXLOG("%p: Discarding buffered rows from %d to %d for oid %x (%d outputs active)", this, idx, min, oid, activeOutputs);
- #endif
- while (tailIdx < min)
- {
- ReleaseRoxieRow(buffer.dequeue());
- tailIdx++;
- }
- }
- }
- activeOutputs--;
- idx = (unsigned) -1; // causes minIndex not to save rows for me...
- return;
- }
- #ifdef TRACE_SPLIT
- CTXLOG("%p: All outputs done", this);
- #endif
- activeOutputs = numOutputs;
- CRoxieServerActivity::stop();
- };
- void reset(unsigned oid)
- {
- if (traceStartStop)
- CTXLOG("SPLIT %p: reset %d child %d activeOutputs %d numOutputs %d numOriginalOutputs %d state %s", this, activityId, oid, activeOutputs, numOutputs, numOriginalOutputs, queryStateText(state));
- activeOutputs = numOutputs;
- while (buffer.ordinality())
- ReleaseRoxieRow(buffer.dequeue());
- error.clear();
- if (state != STATEreset) // make sure input is only reset once
- CRoxieServerActivity::reset();
- };
- void connectInputStreams(bool consumerOrdered)
- {
- if (!inputStream)
- CRoxieServerActivity::connectInputStreams(consumerOrdered);
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // Internal logic error - we are not anybody's input
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- // if (outputMeta)
- // return outputMeta;
- // else
- return input->queryOutputMeta(); // not always known (e.g. disk write - though Gavin _could_ fill it in)
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = nextFreeOutput(); // MORE - what is this used for?
- assertex(idx < numOriginalOutputs);
- assertex(!used[idx]);
- used[idx] = true;
- return &adaptors[idx];
- }
- virtual void resetOutputsUsed()
- {
- numOutputs = 1;
- activeOutputs = 1;
- // MORE RKC->GH should we be clearing the used array here? anywhere?
- }
- virtual void noteOutputUsed()
- {
- assertex(numOutputs < numOriginalOutputs);
- numOutputs++;
- activeOutputs = numOutputs;
- }
- virtual bool isPassThrough()
- {
- return numOutputs==1;
- }
- };
- class CRoxieServerThroughSpillActivityFactory : public CRoxieServerMultiOutputFactory
- {
- public:
- CRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorSpillArg> helper = (IHThorSpillArg *) helperFactory();
- setNumOutputs(helper->getTempUsageCount() + 1);
- }
- CRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_helperFactory, unsigned _numOutputs, IPropertyTree &_graphNode)
- : CRoxieServerMultiOutputFactory(0, 0, _queryFactory, _helperFactory, TAKsplit, _graphNode)
- {
- setNumOutputs(_numOutputs);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerThroughSpillActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- IRoxieServerActivityFactory *createRoxieServerThroughSpillActivityFactory(IQueryFactory &_queryFactory, HelperFactory *_factory, unsigned _numOutputs, IPropertyTree &_graphNode)
- {
- return new CRoxieServerThroughSpillActivityFactory(_queryFactory, _factory, _numOutputs, _graphNode);
- }
- //----------------------------------------------------------------------------------------------
- class CRoxieServerSplitActivityFactory : public CRoxieServerMultiOutputFactory
- {
- public:
- CRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorSplitArg> helper = (IHThorSplitArg *) helperFactory();
- setNumOutputs(helper->numBranches());
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSplitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSplitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- #define PIPE_BUFSIZE 0x8000
- static IException *createPipeFailureException(const char *cmd, unsigned retcode, IPipeProcess *pipe)
- {
- StringBuffer msg;
- if(pipe->hasError())
- {
- try
- {
- char error[512];
- size32_t sz = pipe->readError(sizeof(error), error);
- if(sz && sz!=(size32_t)-1)
- msg.append(", stderr: '").append(sz, error).append("'");
- }
- catch (IException *e)
- {
- EXCLOG(e, "Error reading pipe stderr");
- e->Release();
- }
- }
- return MakeStringException(ROXIE_PIPE_ERROR, "Pipe process %s returned error %u%s", cmd, retcode, msg.str());
- }
- class CRoxieServerPipeReadActivity : public CRoxieServerActivity
- {
- IHThorPipeReadArg &helper;
- Owned<IPipeProcess> pipe;
- StringAttr pipeCommand;
- Owned<IOutputRowDeserializer> rowDeserializer;
- Owned<IReadRowStream> readTransformer;
- bool groupSignalled;
- public:
- CRoxieServerPipeReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeReadArg &)basehelper)
- {
- groupSignalled = true;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- groupSignalled = true; // i.e. don't start with a NULL row
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (!readTransformer)
- {
- OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
- readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIteratorPath, helper.getPipeFlags()));
- }
- OwnedRoxieString pipeProgram(helper.getPipeProgram());
- openPipe(pipeProgram);
- }
- virtual void stop()
- {
- CRoxieServerActivity::stop();
- pipe.clear();
- readTransformer->setStream(NULL);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- while (!waitForPipe())
- {
- if (!pipe)
- return NULL;
- if (helper.getPipeFlags() & TPFgroupeachrow)
- {
- if (!groupSignalled)
- {
- groupSignalled = true;
- return NULL;
- }
- }
- }
- const void *ret = readTransformer->next();
- assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
- processed++;
- groupSignalled = false;
- return ret;
- }
- protected:
- bool waitForPipe()
- {
- if (!pipe)
- return false; // done
- if (!readTransformer->eos())
- return true;
- verifyPipe();
- return false;
- }
- void openPipe(char const * cmd)
- {
- pipeCommand.setown(cmd);
- pipe.setown(createPipeProcess());
- if(!pipe->run(NULL, cmd, ".", false, true, true, 0x10000))
- throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
- Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
- readTransformer->setStream(pipeReader.get());
- }
- void verifyPipe()
- {
- if (pipe)
- {
- unsigned err = pipe->wait();
- if(err && !(helper.getPipeFlags() & TPFnofail))
- {
- throw createPipeFailureException(pipeCommand.get(), err, pipe);
- }
- pipe.clear();
- }
- }
- };
- class CRoxieServerPipeThroughActivity : public CRoxieServerActivity, implements IRecordPullerCallback
- {
- IHThorPipeThroughArg &helper;
- RecordPullerThread puller;
- Owned<IPipeProcess> pipe;
- StringAttr pipeCommand;
- InterruptableSemaphore pipeVerified;
- InterruptableSemaphore pipeOpened;
- CachedOutputMetaData inputMeta;
- Owned<IOutputRowSerializer> rowSerializer;
- Owned<IOutputRowDeserializer> rowDeserializer;
- Owned<IPipeWriteXformHelper> writeTransformer;
- Owned<IReadRowStream> readTransformer;
- bool firstRead;
- bool recreate;
- bool inputExhausted;
- bool groupSignalled;
- public:
- CRoxieServerPipeThroughActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorPipeThroughArg &)basehelper), puller(false)
- {
- recreate = helper.recreateEachRow();
- groupSignalled = true;
- firstRead = false;
- inputExhausted = false;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
- rowDeserializer.setown(rowAllocator->createDiskDeserializer(ctx->queryCodeContext()));
- writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- firstRead = true;
- inputExhausted = false;
- groupSignalled = true; // i.e. don't start with a NULL row
- pipeVerified.reinit();
- pipeOpened.reinit();
- writeTransformer->ready();
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (!readTransformer)
- {
- OwnedRoxieString xmlIterator(helper.getXmlIteratorPath());
- readTransformer.setown(createReadRowStream(rowAllocator, rowDeserializer, helper.queryXmlTransformer(), helper.queryCsvTransformer(), xmlIterator, helper.getPipeFlags()));
- }
- if(!recreate)
- {
- OwnedRoxieString pipeProgram(helper.getPipeProgram());
- openPipe(pipeProgram);
- }
- puller.start(parentExtractSize, parentExtract, paused, 0, false, ctx); // Pipe does not support preload presently - locks up
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (idx)
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- puller.setInput(this, _sourceIdx, _in);
- inputMeta.set(_in->queryOutputMeta());
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- puller.connectInputStreams(ctx, consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return puller.queryInput();
- else
- return NULL;
- }
- virtual void stop()
- {
- pipeVerified.interrupt(NULL);
- pipeOpened.interrupt(NULL);
- puller.stop();
- CRoxieServerActivity::stop();
- pipe.clear();
- if (readTransformer)
- readTransformer->setStream(NULL);
- }
- virtual void reset()
- {
- puller.reset();
- CRoxieServerActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- while (!waitForPipe())
- {
- if (!pipe)
- return NULL;
- if (helper.getPipeFlags() & TPFgroupeachrow)
- {
- if (!groupSignalled)
- {
- groupSignalled = true;
- return NULL;
- }
- }
- }
- const void *ret = readTransformer->next();
- assertex(ret != NULL); // if ret can ever be NULL then we need to recode this logic
- processed++;
- groupSignalled = false;
- return ret;
- }
- virtual void processRow(const void *row)
- {
- // called from puller thread
- if(recreate)
- openPipe(helper.getNameFromRow(row));
- writeTransformer->writeTranslatedText(row, pipe);
- ReleaseRoxieRow(row);
- if(recreate)
- {
- closePipe();
- pipeVerified.wait();
- }
- }
- virtual void processDone()
- {
- // called from puller thread
- if(recreate)
- {
- inputExhausted = true;
- pipeOpened.signal();
- }
- else
- {
- closePipe();
- pipeVerified.wait();
- }
- }
- virtual void processEOG()
- {
- }
- void processGroup(const ConstPointerArray &)
- {
- throwUnexpected();
- }
- virtual bool fireException(IException *e)
- {
- pipeOpened.interrupt(LINK(e));
- pipeVerified.interrupt(e);
- return true;
- }
- private:
- bool waitForPipe()
- {
- if (firstRead)
- {
- pipeOpened.wait();
- firstRead = false;
- }
- if (!pipe)
- return false; // done
- if (!readTransformer->eos())
- return true;
- verifyPipe();
- if (recreate && !inputExhausted)
- pipeOpened.wait();
- return false;
- }
- void openPipe(char const * cmd)
- {
- pipeCommand.setown(cmd);
- pipe.setown(createPipeProcess());
- if(!pipe->run(NULL, cmd, ".", true, true, true, 0x10000))
- throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
- writeTransformer->writeHeader(pipe);
- Owned<ISimpleReadStream> pipeReader = pipe->getOutputStream();
- readTransformer->setStream(pipeReader.get());
- pipeOpened.signal();
- }
- void closePipe()
- {
- writeTransformer->writeFooter(pipe);
- pipe->closeInput();
- }
- void verifyPipe()
- {
- if (pipe)
- {
- unsigned err = pipe->wait();
- if(err && !(helper.getPipeFlags() & TPFnofail))
- {
- throw createPipeFailureException(pipeCommand.get(), err, pipe);
- }
- pipe.clear();
- pipeVerified.signal();
- }
- }
- };
- class CRoxieServerPipeWriteActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorPipeWriteArg &helper;
- Owned<IPipeProcess> pipe;
- StringAttr pipeCommand;
- CachedOutputMetaData inputMeta;
- Owned<IOutputRowSerializer> rowSerializer;
- Owned<IPipeWriteXformHelper> writeTransformer;
- bool firstRead;
- bool recreate;
- bool inputExhausted;
- public:
- CRoxieServerPipeWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorPipeWriteArg &)basehelper)
- {
- recreate = helper.recreateEachRow();
- firstRead = false;
- inputExhausted = false;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- inputMeta.set(input->queryOutputMeta());
- rowSerializer.setown(inputMeta.createDiskSerializer(ctx->queryCodeContext(), activityId));
- writeTransformer.setown(createPipeWriteXformHelper(helper.getPipeFlags(), helper.queryXmlOutput(), helper.queryCsvOutput(), rowSerializer));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- firstRead = true;
- inputExhausted = false;
- writeTransformer->ready();
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if(!recreate)
- {
- OwnedRoxieString pipeProgram(helper.getPipeProgram());
- openPipe(pipeProgram);
- }
- }
- virtual void stop()
- {
- if (!aborted && helper.getSequence() >= 0)
- {
- WorkunitUpdate wu = ctx->updateWorkUnit();
- if (wu)
- {
- Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
- if (result)
- {
- result->setResultTotalRowCount(processed);
- result->setResultStatus(ResultStatusCalculated);
- }
- }
- }
- CRoxieServerActivity::stop();
- pipe.clear();
- }
- virtual void onExecute()
- {
- loop
- {
- const void *row = inputStream->ungroupedNextRow();
- if (!row)
- break;
- processed++;
- if(recreate)
- openPipe(helper.getNameFromRow(row));
- writeTransformer->writeTranslatedText(row, pipe);
- ReleaseRoxieRow(row);
- if(recreate)
- closePipe();
- }
- closePipe();
- }
- private:
- void openPipe(char const * cmd)
- {
- pipeCommand.setown(cmd);
- pipe.setown(createPipeProcess());
- if(!pipe->run(NULL, cmd, ".", true, false, true, 0x10000))
- throw MakeStringException(ROXIE_PIPE_ERROR, "Could not run pipe process %s", cmd);
- writeTransformer->writeHeader(pipe);
- }
- void closePipe()
- {
- writeTransformer->writeFooter(pipe);
- pipe->closeInput();
- unsigned err = pipe->wait();
- if(err && !(helper.getPipeFlags() & TPFnofail))
- {
- throw createPipeFailureException(pipeCommand.get(), err, pipe);
- }
- pipe.clear();
- }
- };
- class CRoxieServerPipeReadActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerPipeReadActivity(_ctx, this, _probeManager);
- }
- };
- class CRoxieServerPipeThroughActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerPipeThroughActivity(_ctx, this, _probeManager);
- }
- };
- class CRoxieServerPipeWriteActivityFactory : public CRoxieServerInternalSinkFactory
- {
- public:
- CRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerPipeWriteActivity(_ctx, this, _probeManager, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerPipeReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerPipeReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- IRoxieServerActivityFactory *createRoxieServerPipeThroughActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerPipeThroughActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- IRoxieServerActivityFactory *createRoxieServerPipeWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- {
- return new CRoxieServerPipeWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
- }
- //=====================================================================================================
- class CRoxieServerStreamedIteratorActivity : public CRoxieServerActivity
- {
- IHThorStreamedIteratorArg &helper;
- Owned<IRowStream> rows;
- public:
- CRoxieServerStreamedIteratorActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorStreamedIteratorArg &)basehelper)
- {
- }
- ~CRoxieServerStreamedIteratorActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- rows.setown(helper.createInput());
- }
- virtual void stop()
- {
- if (rows)
- {
- rows->stop();
- rows.clear();
- }
- CRoxieServerActivity::stop();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- assertex(rows != NULL);
- const void * next = rows->nextRow();
- if (next)
- processed++;
- return next;
- }
- };
- class CRoxieServerStreamedIteratorActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerStreamedIteratorActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerStreamedIteratorActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerStreamedIteratorActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerFilterActivity : public CRoxieServerLateStartActivity
- {
- IHThorFilterArg &helper;
- bool anyThisGroup;
- IRangeCompare * stepCompare;
- public:
- CRoxieServerFilterActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterArg &)basehelper)
- {
- anyThisGroup = false;
- stepCompare = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- anyThisGroup = false;
- CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
- lateStart(parentExtractSize, parentExtract, helper.canMatchAny());
- stepCompare = NULL;
- if (!eof)
- {
- IInputSteppingMeta * stepMeta = input->querySteppingMeta();
- if (stepMeta)
- stepCompare = stepMeta->queryCompare();
- }
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- const void * ret = inputStream->nextRow();
- if (!ret)
- {
- //stop returning two NULLs in a row.
- if (anyThisGroup)
- {
- anyThisGroup = false;
- return NULL;
- }
- ret = inputStream->nextRow();
- if (!ret)
- {
- eof = true;
- return NULL; // eof...
- }
- }
- if (helper.isValid(ret))
- {
- anyThisGroup = true;
- processed++;
- return ret;
- }
- ReleaseRoxieRow(ret);
- }
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- //Could assert that this isn't grouped
- // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (!ret)
- {
- eof = true;
- return NULL;
- }
- if (!wasCompleteMatch)
- {
- anyThisGroup = false; // RKC->GH - is this right??
- return ret;
- }
- if (helper.isValid(ret))
- {
- anyThisGroup = true;
- processed++;
- return ret;
- }
- if (!stepExtra.returnMismatches())
- {
- ReleaseRoxieRow(ret);
- return nextRow();
- }
- //If asked to return mismatches we are only interested in mismatches that will force the stepped
- //condition to advance
- if (stepCompare->docompare(ret, seek, numFields) != 0)
- {
- wasCompleteMatch = false;
- anyThisGroup = false; // WHY?
- return ret;
- }
- ReleaseRoxieRow(ret);
- }
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- eof = prefiltered;
- anyThisGroup = false;
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- class CRoxieServerFilterActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- optStableInput = false;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerFilterActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerFilterActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerFilterActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerFilterGroupActivity : public CRoxieServerLateStartActivity
- {
- IHThorFilterGroupArg &helper;
- unsigned curIndex;
- ConstPointerArray gathered;
- IRangeCompare * stepCompare;
- public:
- CRoxieServerFilterGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterGroupArg &)basehelper)
- {
- curIndex = 0;
- stepCompare = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
- lateStart(parentExtractSize, parentExtract, helper.canMatchAny());//sets eof
- assertex(eof == !helper.canMatchAny());
- curIndex = 0;
- stepCompare = NULL;
- if (!eof)
- {
- IInputSteppingMeta * inputStepping = input->querySteppingMeta();
- if (inputStepping)
- stepCompare = inputStepping->queryCompare();
- }
- }
- virtual void reset()
- {
- releaseGathered();
- CRoxieServerLateStartActivity::reset();
- }
- inline void releaseGathered()
- {
- roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
- gathered.kill();
- curIndex = 0;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (eof)
- return NULL;
- if (gathered.ordinality())
- {
- if (gathered.isItem(curIndex))
- {
- const void * ret = gathered.item(curIndex++);
- processed++;
- return ret;
- }
- curIndex = 0;
- gathered.kill();
- return NULL;
- }
- const void * ret = inputStream->nextRow();
- while (ret)
- {
- gathered.append(ret);
- ret = inputStream->nextRow();
- }
- unsigned num = gathered.ordinality();
- if (num != 0)
- {
- if (!helper.isValid(num, (const void * *)gathered.getArray()))
- ReleaseRoxieRows(gathered); // read next group
- }
- else
- eof = true;
- }
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (gathered.ordinality())
- {
- while (gathered.isItem(curIndex))
- {
- const void * ret = gathered.item(curIndex++);
- if (stepCompare->docompare(ret, seek, numFields) >= 0)
- {
- processed++;
- return ret;
- }
- ReleaseRoxieRow(ret);
- }
- curIndex = 0;
- gathered.kill();
- //nextRowGE never returns an end of group marker.
- }
- //Not completely sure about this - it could lead the the start of a group being skipped,
- //so the group filter could potentially work on a different group. If so, we'd need to check the
- //next fields were a subset of the grouping fields - more an issue for the group activity.
-
- //MORE: What do we do with wasCompleteMatch? something like the following????
- #if 0
- loop
- {
- const void * ret;
- if (stepExtra.returnMismatches())
- {
- bool matchedCompletely = true;
- ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (!wasCompleteMatch)
- return ret;
- }
- else
- ret = input->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- #endif
- const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- while (ret)
- {
- gathered.append(ret);
- ret = inputStream->nextRow();
- }
- unsigned num = gathered.ordinality();
- if (num != 0)
- {
- if (!helper.isValid(num, (const void * *)gathered.getArray()))
- ReleaseRoxieRows(gathered); // read next group
- }
- else
- eof = true;
- return IEngineRowStream::ungroupedNextRow();
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- eof = false;
- releaseGathered();
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- class CRoxieServerFilterGroupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerFilterGroupActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerFilterGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerFilterGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSideEffectActivity : public CRoxieServerActivity
- {
- IHThorSideEffectArg &helper;
- CriticalSection ecrit;
- Owned<IException> exception;
- bool executed;
- public:
- CRoxieServerSideEffectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSideEffectArg &)basehelper)
- {
- executed = false;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- CriticalBlock b(ecrit);
- if (exception)
- throw(exception.getLink());
- if (!executed)
- {
- try
- {
- executed = true;
- helper.action();
- }
- catch(IException *E)
- {
- exception.set(E);
- throw;
- }
- }
- return NULL;
- }
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- CriticalBlock b(ecrit);
- if (exception)
- throw(exception.getLink());
- if (!executed)
- {
- try
- {
- ActivityTimer t(totalCycles, timeActivities);
- executed = true;
- start(parentExtractSize, parentExtract, false);
- helper.action();
- stop();
- }
- catch(IException *E)
- {
- ctx->notifyAbort(E);
- abort();
- exception.set(E);
- throw;
- }
- }
- }
- virtual void reset()
- {
- executed = false;
- exception.clear();
- CRoxieServerActivity::reset();
- }
- };
- class CRoxieServerSideEffectActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSideEffectActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot && !meta.queryOriginal();
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSideEffectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerSideEffectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerActionActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorActionArg &helper;
- public:
- CRoxieServerActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorActionArg &)basehelper)
- {
- }
- virtual void onExecute()
- {
- helper.action();
- }
- };
- class CRoxieServerActionActivityFactory : public CRoxieServerInternalSinkFactory
- {
- public:
- CRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerActionActivity(_ctx, this, _probeManager, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- {
- return new CRoxieServerActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
- }
- //=================================================================================
- class CRoxieServerSampleActivity : public CRoxieServerActivity
- {
- IHThorSampleArg &helper;
- unsigned numSamples;
- unsigned numToSkip;
- unsigned whichSample;
- bool anyThisGroup;
- bool eof;
- public:
- CRoxieServerSampleActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSampleArg &)basehelper)
- {
- numSamples = 0;
- numToSkip = 0;
- whichSample = 0;
- anyThisGroup = false;
- eof = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- anyThisGroup = false;
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numSamples = helper.getProportion();
- whichSample = helper.getSampleNumber();
- numToSkip = (whichSample ? whichSample-1 : 0);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- const void * ret = inputStream->nextRow();
- if (!ret)
- {
- //this does work with groups - may or may not be useful...
- //reset the sample for each group.... probably best.
- numToSkip = (whichSample ? whichSample-1 : 0);
- if (anyThisGroup)
- {
- anyThisGroup = false;
- return NULL;
- }
- ret = inputStream->nextRow();
- if (!ret)
- {
- eof = true;
- return NULL; // eof...
- }
- }
- if (numToSkip == 0)
- {
- anyThisGroup = true;
- numToSkip = numSamples-1;
- processed++;
- return ret;
- }
- numToSkip--;
- ReleaseRoxieRow(ret);
- }
- }
- };
- class CRoxieServerSampleActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSampleActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSampleActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSampleActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChooseSetsActivity : public CRoxieServerActivity
- {
- IHThorChooseSetsArg &helper;
- unsigned numSets;
- unsigned * setCounts;
- bool done;
- public:
- CRoxieServerChooseSetsActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsArg &)basehelper)
- {
- setCounts = NULL;
- numSets = 0;
- done = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numSets = helper.getNumSets();
- setCounts = new unsigned[numSets];
- memset(setCounts, 0, sizeof(unsigned)*numSets);
- helper.setCounts(setCounts);
- }
- virtual void reset()
- {
- delete [] setCounts;
- setCounts = NULL;
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done)
- return NULL;
- loop
- {
- const void * ret = inputStream->ungroupedNextRow();
- if (!ret)
- {
- done = true;
- return NULL;
- }
- processed++;
- switch (helper.getRecordAction(ret))
- {
- case 2:
- done = true;
- return ret;
- case 1:
- return ret;
- }
- ReleaseRoxieRow(ret);
- }
- }
- };
- class CRoxieServerChooseSetsActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChooseSetsActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerChooseSetsActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChooseSetsActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerChooseSetsExActivity : public CRoxieServerActivity
- {
- protected:
- IHThorChooseSetsExArg &helper;
- unsigned numSets;
- unsigned curIndex;
- unsigned * setCounts;
- count_t * limits;
- bool done;
- ConstPointerArray gathered;
- virtual bool includeRow(const void * row) = 0;
- virtual void calculateSelection() = 0;
- public:
- CRoxieServerChooseSetsExActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorChooseSetsExArg &)basehelper)
- {
- setCounts = NULL;
- limits = NULL;
- done = false;
- curIndex = 0;
- numSets = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- curIndex = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numSets = helper.getNumSets();
- setCounts = new unsigned[numSets];
- memset(setCounts, 0, sizeof(unsigned)*numSets);
- limits = (count_t *)calloc(sizeof(count_t), numSets);
- helper.getLimits(limits);
- }
- virtual void reset()
- {
- delete [] setCounts;
- setCounts = NULL;
- free(limits);
- limits = NULL;
- roxiemem::ReleaseRoxieRowRange(gathered.getArray(), curIndex, gathered.ordinality());
- gathered.kill();
- curIndex = 0;
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (gathered.ordinality() == 0)
- {
- curIndex = 0;
- if (!inputStream->nextGroup(gathered))
- {
- done = true;
- return NULL;
- }
- ForEachItemIn(idx1, gathered)
- {
- unsigned category = helper.getCategory(gathered.item(idx1));
- if (category)
- setCounts[category-1]++;
- }
- calculateSelection();
- }
- while (gathered.isItem(curIndex))
- {
- const void * row = gathered.item(curIndex);
- gathered.replace(NULL, curIndex);
- curIndex++;
- if (includeRow(row))
- {
- processed++;
- return row;
- }
- ReleaseRoxieRow(row);
- }
- gathered.kill();
- return NULL;
- }
- };
- class CRoxieServerChooseSetsLastActivity : public CRoxieServerChooseSetsExActivity
- {
- unsigned * numToSkip;
- public:
- CRoxieServerChooseSetsLastActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
- {
- numToSkip = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
- numToSkip = (unsigned *)calloc(sizeof(unsigned), numSets);
- }
- virtual void reset()
- {
- free(numToSkip);
- numToSkip = NULL;
- CRoxieServerChooseSetsExActivity::reset();
- }
- protected:
- virtual void calculateSelection()
- {
- for (unsigned idx=0; idx < numSets; idx++)
- {
- if (setCounts[idx] < limits[idx])
- numToSkip[idx] = 0;
- else
- numToSkip[idx] = (unsigned)(setCounts[idx] - limits[idx]);
- }
- }
- virtual bool includeRow(const void * row)
- {
- unsigned category = helper.getCategory(row);
- if (category)
- {
- if (numToSkip[category-1] == 0)
- return true;
- numToSkip[category-1]--;
- }
- return false;
- }
- };
- class CRoxieServerChooseSetsEnthActivity : public CRoxieServerChooseSetsExActivity
- {
- count_t * counter;
- public:
- CRoxieServerChooseSetsEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager) : CRoxieServerChooseSetsExActivity(_ctx, _factory, _probeManager)
- {
- counter = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerChooseSetsExActivity::start(parentExtractSize, parentExtract, paused);
- counter = (count_t *)calloc(sizeof(count_t), numSets);
- }
- virtual void reset()
- {
- free(counter);
- counter = NULL;
- CRoxieServerChooseSetsExActivity::reset();
- }
- protected:
- virtual void calculateSelection()
- {
- }
- virtual bool includeRow(const void * row)
- {
- unsigned category = helper.getCategory(row);
- if (category)
- {
- assertex(category <= numSets);
- counter[category-1] += limits[category-1];
- if(counter[category-1] >= setCounts[category-1])
- {
- counter[category-1] -= setCounts[category-1];
- return true;
- }
- }
- return false;
- }
- };
- class CRoxieServerChooseSetsEnthActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChooseSetsEnthActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerChooseSetsEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChooseSetsEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- class CRoxieServerChooseSetsLastActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerChooseSetsLastActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerChooseSetsLastActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerChooseSetsLastActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerEnthActivity : public CRoxieServerActivity
- {
- IHThorEnthArg &helper;
- unsigned __int64 numerator;
- unsigned __int64 denominator;
- unsigned __int64 counter;
- bool eof;
- public:
- CRoxieServerEnthActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorEnthArg &)basehelper)
- {
- eof = false;
- numerator = denominator = counter = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- numerator = helper.getProportionNumerator();
- denominator = helper.getProportionDenominator();
- if(denominator == 0) denominator = 1; //MORE: simplest way to avoid disaster in this case
- counter = (helper.getSampleNumber()-1) * greatestCommonDivisor(numerator, denominator);
- if (counter >= denominator)
- counter %= denominator;
- }
- inline bool wanted()
- {
- counter += numerator;
- if(counter >= denominator)
- {
- counter -= denominator;
- return true;
- }
- return false;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * ret;
- loop
- {
- ret = inputStream->ungroupedNextRow();
- if (!ret) //eof
- {
- eof = true;
- return ret;
- }
- if (wanted())
- return ret;
- ReleaseRoxieRow(ret);
- }
- }
- };
- class CRoxieServerEnthActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerEnthActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerEnthActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerEnthActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerAggregateActivity : public CRoxieServerActivity
- {
- IHThorAggregateArg &helper;
- bool eof;
- bool isInputGrouped;
- bool abortEarly;
- public:
- CRoxieServerAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorAggregateArg &)basehelper)
- {
- eof = false;
- isInputGrouped = false;
- abortEarly = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
- abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * next = inputStream->nextRow();
- if (!next && isInputGrouped)
- {
- eof = true;
- return NULL;
- }
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t finalSize = helper.clearAggregate(rowBuilder);
- if (next)
- {
- finalSize = helper.processFirst(rowBuilder, next);
- ReleaseRoxieRow(next);
- if (!abortEarly)
- {
- loop
- {
- next = inputStream->nextRow();
- if (!next)
- break;
- finalSize = helper.processNext(rowBuilder, next);
- ReleaseRoxieRow(next);
- }
- }
- }
- if (!isInputGrouped) // either read all, or aborted early
- eof = true;
- processed++;
- return rowBuilder.finalizeRowClear(finalSize);
- }
- };
- class CRoxieServerStrandedAggregateActivity : public CRoxieServerStrandedActivity, implements IOrderedCallbackCollection
- {
- class AggregateProcessor : public StrandProcessor, implements IStrandThreaded, implements IOrderedOutputCallback
- {
- protected:
- IHThorAggregateArg &helper;
- OwnedConstRoxieRow result;
- bool eof = false;
- bool isInputGrouped = false;
- bool abortEarly = false;
- public:
- AggregateProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorAggregateArg &_helper, bool _isInputGrouped, bool _abortEarly)
- : StrandProcessor(_parent, _inputStream, true), helper(_helper), isInputGrouped(_isInputGrouped), abortEarly(_abortEarly)
- {
- }
- virtual const void * nextRow() override
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof || isAborting())
- return NULL;
- const void * next = inputStream->nextRow();
- if (!next && isInputGrouped)
- {
- eof = true;
- return NULL;
- }
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t finalSize = helper.clearAggregate(rowBuilder);
- if (next)
- {
- finalSize = helper.processFirst(rowBuilder, next);
- ReleaseRoxieRow(next);
- if (!abortEarly)
- {
- loop
- {
- next = inputStream->nextRow();
- if (!next)
- break;
- finalSize = helper.processNext(rowBuilder, next);
- ReleaseRoxieRow(next);
- if (isAborting())
- break;
- }
- }
- }
- if (!isInputGrouped) // either read all, or aborted early
- eof = true;
- processed++;
- return rowBuilder.finalizeRowClear(finalSize);
- }
- virtual void main() override
- {
- isInputGrouped = true; // gather no row if there are no input rows.
- result.setown(nextRow());
- queryActivity().noteStrandFinished(inputStream);
- }
- virtual void reset() override
- {
- StrandProcessor::reset();
- result.clear();
- eof = false;
- }
- //interface IOutputOutputCallback
- virtual bool noteEndOfInputChunk() { return true; }
- virtual void noteEndOfInput() {}
- virtual void stopStream()
- {
- inputStream->stop();
- }
- const void * queryResult() const { return result; }
- CRoxieServerStrandedAggregateActivity & queryActivity() { return static_cast<CRoxieServerStrandedAggregateActivity &>(parent); }
- };
- //This class is only used when a single aggregate is being calculated.
- class AggregateCombiner : public CInterfaceOf<IEngineRowStream>
- {
- public:
- explicit AggregateCombiner(CRoxieServerStrandedAggregateActivity & _parent) : parent(_parent)
- {
- }
- virtual const void *nextRow()
- {
- return parent.getCombinedAggregate();
- }
- virtual void stop()
- {
- parent.outputStopped();
- }
- virtual void resetEOF()
- {
- throwUnexpected();
- }
- protected:
- CRoxieServerStrandedAggregateActivity & parent;
- } combiner;
- class NullCallback : implements IOrderedOutputCallback
- {
- public:
- virtual bool noteEndOfInputChunk() { return true; }
- virtual void noteEndOfInput() {}
- } nullCallback;
- public:
- CRoxieServerStrandedAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
- : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), helper((IHThorAggregateArg &)basehelper), combiner(*this)
- {
- isInputGrouped = false;
- abortEarly = false;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- CRoxieServerStrandedActivity::setInput(idx, _sourceIdx, _in);
- isInputGrouped = input->queryOutputMeta()->isGrouped(); // could be done earlier, in setInput?
- abortEarly = !isInputGrouped && (factory->getKind() == TAKexistsaggregate); // ditto
- //For EXISTS(), and aggregates that rely on the input order, force to execute single threaded
- //MORE: Ordered should be able to process a block at a time and then merge them, similar to disk write processing.
- if (abortEarly || (!isInputGrouped && queryFactory()->isInputOrdered(false, 0)))
- strandOptions.numStrands = 1;
- else if (!isInputGrouped)
- combineStreams = true;
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks) override
- {
- PointerArrayOf<IEngineRowStream> localStreams;
- //If streams are being combined, this class should be notified of end of sections, otherwise grouped aggregates can inform a downstream activity.
- IOrderedCallbackCollection * callbacks = combineStreams ? static_cast<IOrderedCallbackCollection *>(this) : orderedCallbacks;
- Owned<IStrandJunction> outJunction = CRoxieServerStrandedActivity::getOutputStreams(ctx, idx, localStreams, consumerOptions, consumerOrdered, callbacks);
- if (localStreams.ordinality() == 1)
- combineStreams = false; // Select a more efficient/simpler code path
- if (combineStreams)
- {
- assertex(!outJunction); // this needs more thought!
- streams.append(&combiner);
- }
- else
- {
- streams.swapWith(localStreams);
- }
- return outJunction.getClear();
- }
- virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
- {
- if (traceLevel > 4)
- DBGLOG("Create aggregate strand processor %u", strandOptions.numStrands);
- return new AggregateProcessor(*this, instream, (IHThorAggregateArg &) basehelper, isInputGrouped && !combineStreams, abortEarly);
- }
- virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused) override
- {
- CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
- if (combineStreams)
- {
- barrier.setown(createStrandBarrier());
- ForEachItemIn(i, strands)
- barrier->startStrand(queryAggregate(i));
- active.store(1);
- }
- else
- active.store(0);
- }
- virtual void reset() override
- {
- CRoxieServerStrandedActivity::reset();
- barrier.clear();
- calculated = false;
- }
- //Helper functions for the single aggregate case
- const void * getCombinedAggregate()
- {
- if (calculated)
- return NULL;
- calculated= true;
- barrier->waitForStrands();
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t finalSize = helper.clearAggregate(rowBuilder);
- bool isFirst = true;
- for (unsigned i=0; i < numStrands(); i++)
- {
- const void * next = queryAggregate(i).queryResult();
- if (next)
- {
- if (isFirst)
- {
- finalSize = cloneRow(rowBuilder, next, helper.queryOutputMeta());
- isFirst = false;
- }
- else
- finalSize = helper.mergeAggregate(rowBuilder, next);
- }
- }
- return rowBuilder.finalizeRowClear(finalSize);
- }
- void outputStopped()
- {
- //only called if generating a single result.
- assertex(combineStreams);
- if (barrier)
- {
- requestAbort(); // if strands are still running, abort them
- barrier->waitForStrands();
- }
- else
- {
- ForEachItemIn(i, strands)
- queryAggregate(i).stopStream();
- }
- CRoxieServerStrandedActivity::stop();
- }
- void noteStrandFinished(IRowStream * stream)
- {
- barrier->noteStrandFinished(stream);
- }
- virtual IOrderedOutputCallback * queryCallback(unsigned i)
- {
- //The non-ordered aggregate does not need to process the ordered call back information.
- //If the ordered single aggregate was implemented then it would need to be processed instead of ignored,
- //however it needs some care since the strands are not yet created. So cannot return strand(i).
- return &nullCallback;
- }
- inline AggregateProcessor & queryAggregate(unsigned i)
- {
- return static_cast<AggregateProcessor &>(strands.item(i));
- }
- protected:
- IHThorAggregateArg &helper;
- Owned<IStrandBarrier> barrier;
- IEngineRowStream * combinedStream = nullptr;
- bool isInputGrouped;
- bool abortEarly;
- bool combineStreams = false;
- bool calculated = false;
- };
- class CRoxieServerAggregateActivityFactory : public CRoxieServerActivityFactory
- {
- StrandOptions strandOptions;
- public:
- CRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
- {
- Owned<IHThorAggregateArg> helper = (IHThorAggregateArg *) helperFactory();
- if (!(helper->getAggregateFlags() & TAForderedmerge))
- optStableInput = false;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerStrandedAggregateActivity(_ctx, this, _probeManager, strandOptions);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- typedef unsigned t_hashPrefix;
- class CRoxieServerHashAggregateActivity : public CRoxieServerActivity
- {
- IHThorHashAggregateArg &helper;
- RowAggregator aggregated;
- bool eof;
- bool gathered;
- bool isGroupedAggregate;
- public:
- CRoxieServerHashAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, bool _isGroupedAggregate, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorHashAggregateArg &)basehelper),
- isGroupedAggregate(_isGroupedAggregate),
- aggregated(helper, helper)
- {
- eof = false;
- gathered = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- gathered = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- aggregated.reset();
- CRoxieServerActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (!gathered)
- {
- aggregated.start(rowAllocator);
- bool eog = true;
- loop
- {
- const void * next = inputStream->nextRow();
- if (!next)
- {
- if (isGroupedAggregate)
- {
- if (eog)
- eof = true;
- break;
- }
- next = inputStream->nextRow();
- if (!next)
- break;
- }
- eog = false;
- aggregated.addRow(next);
- ReleaseRoxieRow(next);
- }
- gathered = true;
- }
- Owned<AggregateRowBuilder> next = aggregated.nextResult();
- if (next)
- {
- processed++;
- return next->finalizeRowClear();
- }
- if (!isGroupedAggregate)
- eof = true;
- aggregated.reset();
- gathered = false;
- return NULL;
- }
- };
- class CRoxieServerHashAggregateActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- isGroupedAggregate = _graphNode.getPropBool("att[@name='grouped']/@value");
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerHashAggregateActivity(_ctx, this, isGroupedAggregate, _probeManager);
- }
- protected:
- bool isGroupedAggregate;
- };
- IRoxieServerActivityFactory *createRoxieServerHashAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerHashAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerDegroupActivity : public CRoxieServerActivity
- {
- IHThorDegroupArg &helper;
- bool eof;
- public:
- CRoxieServerDegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDegroupArg &)basehelper)
- {
- eof = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * ret = inputStream->ungroupedNextRow();
- if (ret)
- processed++;
- else
- eof = true;
- return ret;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (ret)
- processed++;
- else
- eof = true;
- return ret;
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- eof = false;
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- class CRoxieServerDegroupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerDegroupActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerDegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSpillReadActivity : public CRoxieServerActivity
- {
- IHThorDiskReadArg &helper;
- bool needTransform;
- bool eof;
- bool anyThisGroup;
- unsigned __int64 rowLimit;
- unsigned __int64 choosenLimit;
- public:
- CRoxieServerSpillReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorDiskReadArg &)basehelper)
- {
- needTransform = helper.needTransform();
- rowLimit = (unsigned __int64) -1;
- choosenLimit = 0;
- eof = false;
- anyThisGroup = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- anyThisGroup = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (helper.canMatchAny())
- eof = false;
- else
- eof = true;
- choosenLimit = helper.getChooseNLimit();
- rowLimit = helper.getRowLimit();
- helper.setCallback(NULL); // members should not be called - change if they are
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (processed==choosenLimit)
- {
- eof = true;
- return NULL;
- }
- if (needTransform)
- {
- loop
- {
- const void *in = inputStream->nextRow();
- if (!in)
- {
- if (anyThisGroup)
- {
- anyThisGroup = false;
- return NULL;
- }
- in = inputStream->nextRow();
- if (!in)
- {
- eof = true;
- return NULL; // eof...
- }
- }
- unsigned outSize;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- try
- {
- outSize = helper.transform(rowBuilder, in);
- ReleaseRoxieRow(in);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- if (outSize)
- {
- anyThisGroup = true;
- processed++;
- if (processed==rowLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- helper.onLimitExceeded();
- }
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- }
- else
- {
- const void *ret = inputStream->nextRow();
- if (ret)
- {
- processed++;
- if (processed==rowLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- ReleaseClearRoxieRow(ret);
- helper.onLimitExceeded(); // should not return
- throwUnexpected();
- }
- }
- return ret;
- }
- }
- };
- class CRoxieServerSpillReadActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSpillReadActivity(_ctx, this, _probeManager);
- }
- virtual void addDependency(unsigned source, ThorActivityKind sourceKind, unsigned sourceIdx, int controlId, const char *edgeId)
- {
- if (sourceKind==TAKspill || sourceKind==TAKdiskwrite) // Bit of a hack - codegen probably should differentiate
- setInput(0, source, sourceIdx);
- else
- CRoxieServerActivityFactory::addDependency(source, kind, sourceIdx, controlId, edgeId);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSpillReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSpillReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSpillWriteActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerSpillWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- }
- ~CRoxieServerSpillWriteActivity()
- {
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- return inputStream->nextRow();
- }
- };
- //==================================================================================
- class CRoxieServerDiskWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
- {
- protected:
- Owned<IExtRowWriter> outSeq;
- Owned<IOutputRowSerializer> rowSerializer;
- Linked<IFileIOStream> diskout;
- bool blockcompressed;
- bool extend;
- bool overwrite;
- bool encrypted;
- bool grouped;
- IHThorDiskWriteArg &helper;
- CachedOutputMetaData diskmeta;
- Owned<IRoxieWriteHandler> writer;
- bool tallycrc;
- unsigned __int64 uncompressedBytesWritten;
- CRC32 crc;
- void updateWorkUnitResult(unsigned __int64 reccount)
- {
- assertex(writer);
- // MORE - a lot of this is common with hthor
- WorkunitUpdate wu = ctx->updateWorkUnit();
- if (wu)
- {
- OwnedRoxieString rawLogicalName = helper.getFileName();
- StringBuffer lfn; // logical filename
- expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
- if (lfn.length())
- {
- unsigned flags = helper.getFlags();
- WUFileKind fileKind;
- if (TDXtemporary & flags)
- fileKind = WUFileTemporary;
- else if(TDXjobtemp & flags)
- fileKind = WUFileJobOwned;
- else if(TDWowned & flags)
- fileKind = WUFileOwned;
- else
- fileKind = WUFileStandard;
- StringArray clusters;
- writer->getClusters(clusters);
- wu->addFile(lfn.str(), &clusters, helper.getTempUsageCount(), fileKind, NULL);
- if (!(flags & TDXtemporary) && helper.getSequence() >= 0)
- {
- Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
- if (result)
- {
- result->setResultTotalRowCount(reccount);
- result->setResultStatus(ResultStatusCalculated);
- if (helper.getFlags() & TDWresult)
- result->setResultFilename(lfn.str());
- else
- result->setResultLogicalName(lfn.str());
- }
- }
- }
- }
- }
- void resolve()
- {
- OwnedRoxieString rawLogicalName = helper.getFileName();
- assertex(rawLogicalName);
- assertex((helper.getFlags() & TDXtemporary) == 0);
- StringArray clusters;
- unsigned clusterIdx = 0;
- while(true)
- {
- OwnedRoxieString cluster(helper.getCluster(clusterIdx));
- if(!cluster)
- break;
- clusters.append(cluster);
- clusterIdx++;
- }
- if (clusters.length())
- {
- if (extend)
- throw MakeStringException(0, "Cannot combine EXTEND and CLUSTER flags on disk write of file %s", rawLogicalName.get());
- }
- else
- {
- if (roxieName.length())
- clusters.append(roxieName.str());
- else
- clusters.append(".");
- }
- writer.setown(ctx->createLFN(rawLogicalName, overwrite, extend, clusters));
- // MORE - need to check somewhere that single part if it's an existing file or an external one...
- }
- public:
- CRoxieServerDiskWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper((IHThorDiskWriteArg &)basehelper)
- {
- extend = ((helper.getFlags() & TDWextend) != 0);
- overwrite = ((helper.getFlags() & TDWoverwrite) != 0);
- grouped = false; // don't think we need to support it...
- diskmeta.set(helper.queryDiskRecordSize());
- blockcompressed = (((helper.getFlags() & TDWnewcompress) != 0) || (((helper.getFlags() & TDXcompress) != 0) && (diskmeta.getFixedSize() >= MIN_ROWCOMPRESS_RECSIZE))); //always use new compression
- encrypted = false; // set later
- tallycrc = true;
- uncompressedBytesWritten = 0;
- }
- ~CRoxieServerDiskWriteActivity()
- {
- }
- virtual bool needsAllocator() const
- {
- return true;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
-
- resolve();
- Owned<IFileIO> io;
- void *ekey;
- size32_t ekeylen;
- helper.getEncryptKey(ekeylen, ekey);
- Owned<ICompressor> ecomp;
- if (ekeylen!=0)
- {
- ecomp.setown(createAESCompressor256(ekeylen,ekey));
- memset(ekey,0,ekeylen);
- rtlFree(ekey);
- encrypted = true;
- blockcompressed = true;
- }
- if (blockcompressed)
- io.setown(createCompressedFileWriter(writer->queryFile(), (diskmeta.isFixedSize() ? diskmeta.getFixedSize() : 0), extend, true, ecomp));
- else
- io.setown(writer->queryFile()->open(extend ? IFOwrite : IFOcreate));
- if (!io)
- throw MakeStringException(errno, "Failed to create%s file %s for writing", (encrypted ? " encrypted" : (blockcompressed ? " compressed" : "")), writer->queryFile()->queryFilename());
- diskout.setown(createBufferedIOStream(io));
- if (extend)
- diskout->seek(0, IFSend);
- tallycrc = !factory->queryQueryFactory().queryOptions().skipFileFormatCrcCheck && !(helper.getFlags() & TDRnocrccheck) && !blockcompressed;
- Owned<IRowInterfaces> rowIf = createRowInterfaces(input->queryOutputMeta(), activityId, factory->getHeapFlags(), ctx->queryCodeContext());
- rowSerializer.set(rowIf->queryRowSerializer());
- unsigned rwFlags = rw_autoflush;
- if(grouped)
- rwFlags |= rw_grouped;
- if(tallycrc)
- rwFlags |= rw_crc;
- outSeq.setown(createRowWriter(diskout, rowIf, rwFlags));
- }
- virtual void stop()
- {
- if (aborted)
- {
- if (writer)
- writer->finish(false, this);
- }
- else
- {
- if (outSeq)
- outSeq->flush(&crc);
- if (outSeq)
- uncompressedBytesWritten = outSeq->getPosition();
- outSeq.clear();
- diskout.clear(); // Make sure file is properly closed or date may not match published info
- if (writer)
- {
- updateWorkUnitResult(processed);
- writer->finish(true, this);
- }
- }
- writer.clear();
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- diskout.clear();
- outSeq.clear();
- writer.clear();
- uncompressedBytesWritten = 0;
- crc.reset();
- }
- virtual void onExecute()
- {
- loop
- {
- const void *nextrec = inputStream->ungroupedNextRow();
- if (!nextrec)
- break;
- processed++;
- outSeq->putRow(nextrec);
- }
- }
- virtual void setFileProperties(IFileDescriptor *desc) const
- {
- IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
- IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
- if (blockcompressed)
- {
- // caller has already set @size from file size...
- fileProps.setPropBool("@blockCompressed", true);
- fileProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
- partProps.setPropInt64("@compressedSize", partProps.getPropInt64("@size", 0));
- fileProps.setPropInt64("@size", uncompressedBytesWritten);
- partProps.setPropInt64("@size", uncompressedBytesWritten);
- }
- else if (tallycrc && crc.get())
- partProps.setPropInt64("@fileCrc", crc.get());
- if (encrypted)
- fileProps.setPropBool("@encrypted", true);
- fileProps.setPropInt64("@recordCount", processed);
- unsigned flags = helper.getFlags();
- if (flags & TDWpersist)
- fileProps.setPropBool("@persistent", true);
- if (grouped)
- fileProps.setPropBool("@grouped", true);
- if (flags & (TDWowned|TDXjobtemp|TDXtemporary))
- fileProps.setPropBool("@owned", true);
- if (flags & TDWresult)
- fileProps.setPropBool("@result", true);
- IConstWorkUnit *workUnit = ctx->queryWorkUnit();
- if (workUnit)
- {
- fileProps.setProp("@owner", workUnit->queryUser());
- fileProps.setProp("@workunit", workUnit->queryWuid());
- fileProps.setProp("@job", workUnit->queryJobName());
- }
- if (flags & TDWexpires)
- setExpiryTime(fileProps, helper.getExpiryDays());
- if (flags & TDWupdate)
- {
- unsigned eclCRC;
- unsigned __int64 totalCRC;
- helper.getUpdateCRCs(eclCRC, totalCRC);
- fileProps.setPropInt("@eclCRC", eclCRC);
- fileProps.setPropInt64("@totalCRC", totalCRC);
- }
- fileProps.setPropInt("@formatCrc", helper.getFormatCrc());
- IRecordSize * inputMeta = input->queryOutputMeta();
- if ((inputMeta->isFixedSize()) && !isOutputTransformed())
- fileProps.setPropInt("@recordSize", inputMeta->getFixedSize() + (grouped ? 1 : 0));
- const char *recordECL = helper.queryRecordECL();
- if (recordECL && *recordECL)
- fileProps.setProp("ECL", recordECL);
- fileProps.setProp("@kind", "flat"); // default, derivitives may override
- }
- virtual IUserDescriptor *queryUserDescriptor() const
- {
- IConstWorkUnit *workUnit = ctx->queryWorkUnit();
- if (workUnit)
- return workUnit->queryUserDescriptor();
- else
- return NULL;
- }
- virtual bool isOutputTransformed() const { return false; }
- };
- //=================================================================================
- class CRoxieServerCsvWriteActivity : public CRoxieServerDiskWriteActivity
- {
- IHThorCsvWriteArg &csvHelper;
- CSVOutputStream csvOutput;
- public:
- CRoxieServerCsvWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), csvHelper(static_cast<IHThorCsvWriteArg &>(helper))
- {
- csvOutput.init(csvHelper.queryCsvParameters(), false);
- }
- virtual void onExecute()
- {
- OwnedRoxieString header(csvHelper.queryCsvParameters()->getHeader());
- if (header)
- {
- csvOutput.beginLine();
- csvOutput.writeHeaderLn(strlen(header), header);
- diskout->write(csvOutput.length(), csvOutput.str());
- }
- loop
- {
- const void *nextrec = inputStream->ungroupedNextRow();
- if (!nextrec)
- break;
- processed++;
- csvOutput.beginLine();
- csvHelper.writeRow((const byte *)nextrec, &csvOutput);
- csvOutput.endLine();
- diskout->write(csvOutput.length(), csvOutput.str());
- ReleaseRoxieRow(nextrec);
- }
- OwnedRoxieString footer(csvHelper.queryCsvParameters()->getFooter());
- if (footer)
- {
- csvOutput.beginLine();
- csvOutput.writeHeaderLn(strlen(footer), footer);
- diskout->write(csvOutput.length(), csvOutput.str());
- }
- }
- virtual void setFileProperties(IFileDescriptor *desc) const
- {
- CRoxieServerDiskWriteActivity::setFileProperties(desc);
- IPropertyTree &props = desc->queryProperties();
- props.setProp("@format","utf8n");
- ICsvParameters *csvParameters = csvHelper.queryCsvParameters();
- StringBuffer separator;
- OwnedRoxieString rs(csvParameters->getSeparator(0));
- const char *s = rs;
- while (s && *s)
- {
- if (',' == *s)
- separator.append("\\,");
- else
- separator.append(*s);
- ++s;
- }
- props.setProp("@csvSeparate", separator.str());
- props.setProp("@csvQuote", rs.setown(csvParameters->getQuote(0)));
- props.setProp("@csvTerminate", rs.setown(csvParameters->getTerminator(0)));
- props.setProp("@csvEscape", rs.setown(csvParameters->getEscape(0)));
- props.setProp("@kind", "csv");
- }
- virtual bool isOutputTransformed() const { return true; }
- };
- class CRoxieServerXmlWriteActivity : public CRoxieServerDiskWriteActivity
- {
- IHThorXmlWriteArg &xmlHelper;
- StringAttr rowTag;
- ThorActivityKind kind;
- unsigned headerLength;
- unsigned footerLength;
- public:
- CRoxieServerXmlWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, ThorActivityKind _kind)
- : CRoxieServerDiskWriteActivity(_ctx, _factory, _probeManager), xmlHelper(static_cast<IHThorXmlWriteArg &>(helper)), kind(_kind), headerLength(0), footerLength(0)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerDiskWriteActivity::start(parentExtractSize, parentExtract, paused);
- OwnedRoxieString xmlpath(xmlHelper.getXmlIteratorPath());
- if (!xmlpath)
- rowTag.set(DEFAULTXMLROWTAG);
- else
- {
- const char *path = xmlpath;
- if (*path == '/') path++;
- if (strchr(path, '/')) UNIMPLEMENTED; // more what do we do with /mydata/row
- rowTag.set(path);
- }
- }
- virtual void onExecute()
- {
- StringBuffer header;
- OwnedRoxieString suppliedHeader(xmlHelper.getHeader());
- if (kind==TAKjsonwrite)
- buildJsonHeader(header, suppliedHeader, rowTag);
- else if (suppliedHeader)
- header.set(suppliedHeader);
- else
- header.append(DEFAULTXMLHEADER).newline();
- headerLength = header.length();
- diskout->write(header.length(), header.str());
- Owned<IXmlWriterExt> writer = createIXmlWriterExt(xmlHelper.getXmlFlags(), 0, NULL, (kind==TAKjsonwrite) ? WTJSON : WTStandard);
- writer->outputBeginArray(rowTag); //need to set this
- writer->clear(); //but not output it
- loop
- {
- OwnedConstRoxieRow nextrec = inputStream->ungroupedNextRow();
- if (!nextrec)
- break;
- processed++;
- writer->clear().outputBeginNested(rowTag, false);
- xmlHelper.toXML((const byte *)nextrec.get(), *writer);
- writer->outputEndNested(rowTag);
- diskout->write(writer->length(), writer->str());
- }
- OwnedRoxieString suppliedFooter(xmlHelper.getFooter());
- StringBuffer footer;
- if (kind==TAKjsonwrite)
- buildJsonFooter(footer.newline(), suppliedFooter, rowTag);
- else if (suppliedFooter)
- footer.append(suppliedFooter);
- else
- footer.append(DEFAULTXMLFOOTER);
- footerLength=footer.length();
- diskout->write(footer.length(), footer);
- }
- virtual void reset()
- {
- CRoxieServerDiskWriteActivity::reset();
- rowTag.clear();
- }
- virtual void setFileProperties(IFileDescriptor *desc) const
- {
- CRoxieServerDiskWriteActivity::setFileProperties(desc);
- desc->queryProperties().setProp("@format","utf8n");
- desc->queryProperties().setProp("@rowTag",rowTag.get());
- desc->queryProperties().setProp("@kind", (kind==TAKjsonwrite) ? "json" : "xml");
- desc->queryProperties().setPropInt(FPheaderLength, headerLength);
- desc->queryProperties().setPropInt(FPfooterLength, footerLength);
- }
- virtual bool isOutputTransformed() const { return true; }
- };
- class CRoxieServerDiskWriteActivityFactory : public CRoxieServerMultiOutputFactory
- {
- bool isRoot;
- bool isTemp;
- public:
- CRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *) helperFactory();
- isTemp = (helper->getFlags() & TDXtemporary) != 0;
- setNumOutputs(helper->getTempUsageCount());
- if (_kind!=TAKdiskwrite)
- assertex(numOutputs == 0);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- switch (numOutputs)
- {
- case 0:
- switch (kind)
- {
- case TAKdiskwrite: return new CRoxieServerDiskWriteActivity(_ctx, this, _probeManager);
- case TAKcsvwrite: return new CRoxieServerCsvWriteActivity(_ctx, this, _probeManager);
- case TAKxmlwrite:
- case TAKjsonwrite:
- return new CRoxieServerXmlWriteActivity(_ctx, this, _probeManager, kind);
- };
- throwUnexpected();
- case 1:
- return new CRoxieServerSpillWriteActivity(_ctx, this, _probeManager);
- default:
- return new CRoxieServerThroughSpillActivity(_ctx, this, _probeManager, numOutputs);
- }
- }
- virtual bool isSink() const
- {
- return numOutputs == 0 && !isTemp; // MORE - check with Gavin if this is right if not a temp but reread in same job...
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDiskWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerDiskWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerIndexWriteActivity : public CRoxieServerInternalSinkActivity, implements IRoxiePublishCallback
- {
- IHThorIndexWriteArg &helper;
- bool overwrite;
- Owned<ClusterWriteHandler> clusterHandler;
- Owned<IRoxieWriteHandler> writer;
- unsigned __int64 reccount;
- unsigned int fileCrc;
- StringBuffer filename;
- void updateWorkUnitResult()
- {
- // MORE - a lot of this is common with hthor
- WorkunitUpdate wu = ctx->updateWorkUnit();
- if (wu)
- {
- OwnedRoxieString rawLogicalName = helper.getFileName();
- StringBuffer lfn; // logical filename
- expandLogicalFilename(lfn, rawLogicalName, wu, false, false);
- if (lfn.length())
- {
- if (helper.getSequence() >= 0)
- {
- Owned<IWUResult> result = wu->updateResultBySequence(helper.getSequence());
- if (result)
- {
- result->setResultTotalRowCount(reccount);
- result->setResultStatus(ResultStatusCalculated);
- result->setResultLogicalName(lfn.str());
- }
- }
- if(clusterHandler)
- clusterHandler->finish(writer->queryFile());
- CTXLOG("Created roxie index file %s", lfn.str());
- }
- }
- }
- virtual void resolve()
- {
- StringArray clusters;
- unsigned clusterIdx = 0;
- while(true)
- {
- OwnedRoxieString cluster(helper.getCluster(clusterIdx));
- if(!cluster)
- break;
- clusters.append(cluster);
- clusterIdx++;
- }
- if (roxieName.length())
- clusters.append(roxieName.str());
- else
- clusters.append(".");
- OwnedRoxieString fname(helper.getFileName());
- writer.setown(ctx->createLFN(fname, overwrite, false, clusters)); // MORE - if there's a workunit, use if for scope.
- filename.set(writer->queryFile()->queryFilename());
- if (writer->queryFile()->exists())
- {
- if (overwrite)
- {
- CTXLOG("Removing existing %s from DFS",filename.str());
- writer->queryFile()->remove();
- }
- else
- throw MakeStringException(99, "Cannot write index file %s, file already exists (missing OVERWRITE attribute?)", filename.str());
- }
- }
- void buildUserMetadata(Owned<IPropertyTree> & metadata)
- {
- size32_t nameLen;
- char * nameBuff;
- size32_t valueLen;
- char * valueBuff;
- unsigned idx = 0;
- while(helper.getIndexMeta(nameLen, nameBuff, valueLen, valueBuff, idx++))
- {
- StringBuffer name(nameLen, nameBuff);
- StringBuffer value(valueLen, valueBuff);
- if(*nameBuff == '_' && strcmp(name, "_nodeSize") != 0)
- {
- OwnedRoxieString fname(helper.getFileName());
- throw MakeStringException(0, "Invalid name %s in user metadata for index %s (names beginning with underscore are reserved)", name.str(), fname.get());
- }
- if(!validateXMLTag(name.str()))
- {
- OwnedRoxieString fname(helper.getFileName());
- throw MakeStringException(0, "Invalid name %s in user metadata for index %s (not legal XML element name)", name.str(), fname.get());
- }
- if(!metadata)
- metadata.setown(createPTree("metadata"));
- metadata->setProp(name.str(), value.str());
- }
- }
- void buildLayoutMetadata(Owned<IPropertyTree> & metadata)
- {
- if(!metadata)
- metadata.setown(createPTree("metadata"));
- metadata->setProp("_record_ECL", helper.queryRecordECL());
- void * layoutMetaBuff;
- size32_t layoutMetaSize;
- if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
- {
- metadata->setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
- rtlFree(layoutMetaBuff);
- }
- }
- public:
- CRoxieServerIndexWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, 0), helper(static_cast<IHThorIndexWriteArg &>(basehelper))
- {
- overwrite = ((helper.getFlags() & TIWoverwrite) != 0);
- reccount = 0;
- fileCrc = 0;
- }
- ~CRoxieServerIndexWriteActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- resolve();
- }
- virtual void onExecute()
- {
- bool isVariable = helper.queryDiskRecordSize()->isVariableSize();
- size32_t maxDiskRecordSize;
- if (isVariable)
- {
- if (helper.getFlags() & TIWmaxlength)
- maxDiskRecordSize = helper.getMaxKeySize();
- else
- maxDiskRecordSize = KEYBUILD_MAXLENGTH; // Current default behaviour, could be improved in the future
- }
- else
- maxDiskRecordSize = helper.queryDiskRecordSize()->getFixedSize();
- if (maxDiskRecordSize > KEYBUILD_MAXLENGTH)
- throw MakeStringException(99, "Index maximum record length (%d) exceeds 32k internal limit", maxDiskRecordSize);
- OwnedMalloc<char> rowBuffer(maxDiskRecordSize, true);
- fileCrc = -1;
- {
- Owned<IFileIO> io;
- try
- {
- io.setown(writer->queryFile()->open(IFOcreate));
- }
- catch(IException * e)
- {
- e->Release();
- clearKeyStoreCache(false);
- io.setown(writer->queryFile()->open(IFOcreate));
- }
- if(!io)
- throw MakeStringException(errno, "Failed to create file %s for writing", filename.str());
- Owned<IFileIOStream> out = createIOStream(io);
- unsigned flags = COL_PREFIX | HTREE_FULLSORT_KEY;
- if (helper.getFlags() & TIWrowcompress)
- flags |= HTREE_COMPRESSED_KEY|HTREE_QUICK_COMPRESSED_KEY;
- else if (!(helper.getFlags() & TIWnolzwcompress))
- flags |= HTREE_COMPRESSED_KEY;
- if (isVariable)
- flags |= HTREE_VARSIZE;
- Owned<IPropertyTree> metadata;
- buildUserMetadata(metadata);
- buildLayoutMetadata(metadata);
- unsigned nodeSize = metadata ? metadata->getPropInt("_nodeSize", NODESIZE) : NODESIZE;
- Owned<IKeyBuilder> builder = createKeyBuilder(out, flags, maxDiskRecordSize, nodeSize, helper.getKeyedSize(), 0);
- class BcWrapper : implements IBlobCreator
- {
- IKeyBuilder *builder;
- public:
- BcWrapper(IKeyBuilder *_builder) : builder(_builder) {}
- virtual unsigned __int64 createBlob(size32_t size, const void * ptr)
- {
- return builder->createBlob(size, (const char *) ptr);
- }
- } bc(builder);
- // Loop thru the results
- loop
- {
- OwnedConstRoxieRow nextrec(inputStream->ungroupedNextRow());
- if (!nextrec)
- break;
- try
- {
- unsigned __int64 fpos=0;
- RtlStaticRowBuilder rowBuilder(rowBuffer, maxDiskRecordSize);
- size32_t thisSize = helper.transform(rowBuilder, nextrec, &bc, fpos);
- builder->processKeyData(rowBuffer, fpos, thisSize);
- }
- catch(IException * e)
- {
- throw makeWrappedException(e);
- }
- reccount++;
- }
- if(metadata)
- builder->finish(metadata,&fileCrc);
- else
- builder->finish(&fileCrc);
- }
- }
- virtual void stop()
- {
- if (writer)
- {
- if (!aborted)
- updateWorkUnitResult();
- writer->finish(!aborted, this);
- writer.clear();
- }
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- writer.clear();
- }
- //interface IRoxiePublishCallback
- virtual void setFileProperties(IFileDescriptor *desc) const
- {
- IPropertyTree &partProps = desc->queryPart(0)->queryProperties(); //properties of the first file part.
- IPropertyTree &fileProps = desc->queryProperties(); // properties of the logical file
- // Now publish to name services
- StringBuffer dir,base;
- offset_t indexFileSize = writer->queryFile()->size();
- if(clusterHandler)
- clusterHandler->splitPhysicalFilename(dir, base);
- else
- splitFilename(filename.str(), &dir, &dir, &base, &base);
- desc->setDefaultDir(dir.str());
- //properties of the first file part.
- Owned<IPropertyTree> attrs;
- if(clusterHandler)
- attrs.setown(createPTree("Part")); // clusterHandler is going to set attributes
- else
- {
- // add cluster
- StringBuffer mygroupname;
- desc->setNumParts(1);
- desc->setPartMask(base.str());
- attrs.set(&desc->queryPart(0)->queryProperties());
- }
- attrs->setPropInt64("@size", indexFileSize);
- CDateTime createTime, modifiedTime, accessedTime;
- writer->queryFile()->getTime(&createTime, &modifiedTime, &accessedTime);
- // round file time down to nearest sec. Nanosec accurancy is not preserved elsewhere and can lead to mismatch later.
- unsigned hour, min, sec, nanosec;
- modifiedTime.getTime(hour, min, sec, nanosec);
- modifiedTime.setTime(hour, min, sec, 0);
- StringBuffer timestr;
- modifiedTime.getString(timestr);
- if(timestr.length())
- attrs->setProp("@modified", timestr.str());
- if(clusterHandler)
- clusterHandler->setDescriptorParts(desc, base.str(), attrs);
- // properties of the logical file
- IPropertyTree & properties = desc->queryProperties();
- properties.setProp("@kind", "key");
- properties.setPropInt64("@size", indexFileSize);
- properties.setPropInt64("@recordCount", reccount);
- WorkunitUpdate workUnit = ctx->updateWorkUnit();
- if (workUnit)
- {
- properties.setProp("@owner", workUnit->queryUser());
- properties.setProp("@workunit", workUnit->queryWuid());
- properties.setProp("@job", workUnit->queryJobName());
- }
- char const * rececl = helper.queryRecordECL();
- if(rececl && *rececl)
- properties.setProp("ECL", rececl);
- if (helper.getFlags() & TIWexpires)
- setExpiryTime(properties, helper.getExpiryDays());
- if (helper.getFlags() & TIWupdate)
- {
- unsigned eclCRC;
- unsigned __int64 totalCRC;
- helper.getUpdateCRCs(eclCRC, totalCRC);
- properties.setPropInt("@eclCRC", eclCRC);
- properties.setPropInt64("@totalCRC", totalCRC);
- }
- properties.setPropInt("@fileCrc", fileCrc);
- properties.setPropInt("@formatCrc", helper.getFormatCrc());
- void * layoutMetaBuff;
- size32_t layoutMetaSize;
- if(helper.getIndexLayout(layoutMetaSize, layoutMetaBuff))
- {
- properties.setPropBin("_record_layout", layoutMetaSize, layoutMetaBuff);
- rtlFree(layoutMetaBuff);
- }
- }
- IUserDescriptor *queryUserDescriptor() const
- {
- IConstWorkUnit *workUnit = ctx->queryWorkUnit();
- if (workUnit)
- return workUnit->queryUserDescriptor();
- else
- return NULL;
- }
- };
- //=================================================================================
- class CRoxieServerIndexWriteActivityFactory : public CRoxieServerMultiOutputFactory
- {
- public:
- CRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- setNumOutputs(0);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerIndexWriteActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return true;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerIndexWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- static inline void getLimitType(unsigned flags, bool & limitFail, bool & limitOnFail)
- {
- if((flags & JFmatchAbortLimitSkips) != 0)
- {
- limitFail = false;
- limitOnFail = false;
- }
- else
- {
- limitOnFail = ((flags & JFonfail) != 0);
- limitFail = !limitOnFail;
- }
- }
- class CRoxieServerJoinActivity : public CRoxieServerTwoInputActivity
- {
- enum { JSfill, JSfillleft, JSfillright, JScollate, JScompare, JSleftonly, JSrightonly } state;
- IHThorJoinArg &helper;
- ICompare * collate;
- ICompare * collateupper;
- ThorActivityKind activityKind;
- bool leftOuterJoin;
- bool rightOuterJoin;
- bool exclude;
- bool limitFail;
- bool limitOnFail;
- bool forceSpill;
- unsigned keepLimit;
- unsigned joinLimit;
- unsigned atmostLimit;
- unsigned abortLimit;
- unsigned atmostsTriggered;
- bool betweenjoin;
- OwnedRowArray right;
- const void * left;
- const void * pendingRight;
- unsigned rightIndex;
- unsigned joinCounter;
- BoolArray matchedRight;
- bool matchedLeft;
- Owned<IException> failingLimit;
- ConstPointerArray filteredRight;
- Owned<IRHLimitedCompareHelper> limitedhelper;
- OwnedConstRoxieRow defaultLeft;
- OwnedConstRoxieRow defaultRight;
- Owned<IEngineRowAllocator> defaultLeftAllocator;
- Owned<IEngineRowAllocator> defaultRightAllocator;
- Owned<IGroupedInput> sortedLeft;
- Owned<IGroupedInput> groupedSortedRight;
- bool cloneLeft;
- void createDefaultLeft()
- {
- if (!defaultLeft)
- {
- if (!defaultLeftAllocator)
- defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
- size32_t thisSize = helper.createDefaultLeft(rowBuilder);
- defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- void createDefaultRight()
- {
- if (!defaultRight)
- {
- if (!defaultRightAllocator)
- defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
- size32_t thisSize = helper.createDefaultRight(rowBuilder);
- defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- public:
- CRoxieServerJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
- : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
- {
- // MORE - some of this should be done in factory
- unsigned joinFlags = helper.getJoinFlags();
- leftOuterJoin = (joinFlags & JFleftouter) != 0;
- rightOuterJoin = (joinFlags & JFrightouter) != 0;
- exclude = (joinFlags & JFexclude) != 0;
- cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
- getLimitType(joinFlags, limitFail, limitOnFail);
- if (joinFlags & JFslidingmatch)
- {
- betweenjoin = true;
- collate = helper.queryCompareLeftRightLower();
- collateupper = helper.queryCompareLeftRightUpper();
- }
- else
- {
- betweenjoin = false;
- collate = collateupper = helper.queryCompareLeftRight();
- }
- rightIndex = 0;
- joinCounter = 0;
- state = JSfill;
- matchedLeft = false;
- joinLimit = 0;
- keepLimit = 0; // wait until ctx available
- atmostLimit = 0; // wait until ctx available
- abortLimit = 0; // wait until ctx available
- atmostsTriggered = 0;
- assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0);
- left = NULL;
- pendingRight = NULL;
- activityKind = _factory->getKind();
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- left = NULL;
- rightIndex = 0;
- joinCounter = 0;
- state = JSfill;
- matchedLeft = false;
- CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
- keepLimit = helper.getKeepLimit();
- if (keepLimit == 0)
- keepLimit = (unsigned)-1;
- atmostsTriggered = 0;
- atmostLimit = helper.getJoinLimit();
- if(atmostLimit == 0)
- atmostLimit = (unsigned)-1;
- else
- assertex(!rightOuterJoin && !betweenjoin);
- abortLimit = helper.getMatchAbortLimit();
- if (abortLimit == 0)
- abortLimit = (unsigned)-1;
- if (rightOuterJoin)
- createDefaultLeft();
- if ((leftOuterJoin && (activityKind==TAKjoin || activityKind==TAKjoinlight || activityKind==TAKdenormalizegroup)) || limitOnFail)
- createDefaultRight();
- bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
- RoxieSortAlgorithm sortAlgorithm;
- if (forceSpill)
- sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
- else
- sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
- if (helper.isLeftAlreadySorted())
- sortedLeft.setown(createDegroupedInputReader(inputStream));
- else
- sortedLeft.setown(createSortedInputReader(inputStream, createSortAlgorithm(sortAlgorithm, helper.queryCompareLeft(), ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
- ICompare *compareRight = helper.queryCompareRight();
- if (helper.isRightAlreadySorted())
- groupedSortedRight.setown(createGroupedInputReader(inputStream1, compareRight));
- else
- groupedSortedRight.setown(createSortedGroupedInputReader(inputStream1, compareRight, createSortAlgorithm(sortAlgorithm, compareRight, ctx->queryRowManager(), input1->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
- if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
- { //limited match join (s[1..n])
- limitedhelper.setown(createRHLimitedCompareHelper());
- limitedhelper->init( helper.getJoinLimit(), groupedSortedRight, collate, helper.queryPrefixCompare() );
- }
- }
- virtual void reset()
- {
- if (atmostsTriggered)
- noteStatistic(StNumAtmostTriggered, atmostsTriggered);
- right.clear();
- ReleaseClearRoxieRow(left);
- ReleaseClearRoxieRow(pendingRight);
- defaultRight.clear();
- defaultLeft.clear();
- sortedLeft.clear();
- groupedSortedRight.clear();
- CRoxieServerTwoInputActivity::reset();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
- {
- puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
- puller->setInput(0, _sourceIdx, _in);
- _in = puller;
- _sourceIdx = 0;
- }
- CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL : this;
- }
- void fillLeft()
- {
- matchedLeft = false;
- left = sortedLeft->nextRow(); // NOTE: already degrouped by the IGroupedInput we attached
- if (betweenjoin && left && pendingRight && (collate->docompare(left, pendingRight) >= 0))
- fillRight();
- if (limitedhelper && 0==rightIndex)
- {
- rightIndex = 0;
- joinCounter = 0;
- right.clear();
- matchedRight.kill();
- if (left)
- {
- limitedhelper->getGroup(right,left);
- ForEachItemIn(idx, right)
- matchedRight.append(false);
- }
- }
- }
- void fillRight()
- {
- if (limitedhelper)
- return;
- failingLimit.clear();
- if(betweenjoin && left)
- {
- aindex_t start = 0;
- while(right.isItem(start) && (collateupper->docompare(left, right.item(start)) > 0))
- start++;
- if(start>0)
- right.clearPart(0, start);
- }
- else
- right.clear();
- rightIndex = 0;
- joinCounter = 0;
- unsigned groupCount = 0;
- const void * next;
- while(true)
- {
- if(pendingRight)
- {
- next = pendingRight;
- pendingRight = NULL;
- }
- else
- {
- next = groupedSortedRight->nextRow();
- }
- if(!rightOuterJoin && next && (!left || (collateupper->docompare(left, next) > 0))) // if right is less than left, and not right outer, can skip group
- {
- while(next)
- {
- ReleaseClearRoxieRow(next);
- next = groupedSortedRight->nextRow();
- }
- continue;
- }
- while(next)
- {
- if(groupCount==abortLimit)
- {
- if(limitFail)
- failLimit();
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if(limitOnFail)
- {
- assertex(!failingLimit);
- try
- {
- failLimit();
- }
- catch(IException * except)
- {
- failingLimit.setown(except);
- }
- assertex(failingLimit != NULL);
- }
- right.append(next);
- do
- {
- next = groupedSortedRight->nextRow();
- ReleaseRoxieRow(next);
- } while(next);
- break;
- }
- else if(groupCount==atmostLimit)
- {
- atmostsTriggered++;
- right.clear();
- groupCount = 0;
- while(next)
- {
- ReleaseRoxieRow(next);
- next = groupedSortedRight->nextRow();
- }
- }
- else
- {
- right.append(next);
- groupCount++;
- }
- next = groupedSortedRight->nextRow();
- }
- // 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
- if(betweenjoin && left)
- {
- pendingRight = groupedSortedRight->nextRow();
- if(!pendingRight || (collate->docompare(left, pendingRight) < 0))
- break;
- }
- else
- break;
- }
- matchedRight.kill();
- ForEachItemIn(idx, right)
- matchedRight.append(false);
- }
- const void * joinRecords(const void * curLeft, const void * curRight, unsigned counter)
- {
- if (cloneLeft)
- {
- LinkRoxieRow(curLeft);
- return curLeft;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = helper.transform(rowBuilder, curLeft, curRight, counter);
- if (thisSize)
- return rowBuilder.finalizeRowClear(thisSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned numRows = rows.ordinality();
- const void * right = numRows ? rows.item(0) : defaultRight.get();
- size32_t thisSize = helper.transform(rowBuilder, curLeft, right, numRows, (const void * *)rows.getArray());
- if (thisSize)
- return rowBuilder.finalizeRowClear(thisSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * joinException(const void * curLeft, IException * except)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = helper.onFailTransform(rowBuilder, curLeft, defaultRight, except);
- return rowBuilder.finalizeRowClear(thisSize);
- }
- void failLimit()
- {
- helper.onMatchAbortLimitExceeded();
- CommonXmlWriter xmlwrite(0);
- if (input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
- {
- input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
- }
- throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in join %d for row %s", abortLimit, queryId(), xmlwrite.str());
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- switch (state)
- {
- case JSfill:
- fillLeft();
- state = JSfillright;
- break;
- case JSfillright:
- fillRight();
- state = JScollate;
- break;
- case JSfillleft:
- fillLeft();
- state = JScollate;
- break;
- case JScollate:
- if (right.ordinality() == 0)
- {
- if (left == NULL)
- return NULL;
- state = JSleftonly;
- }
- else
- {
- if (!left)
- state = JSrightonly;
- else
- {
- int diff;
- if(betweenjoin)
- diff = ((collate->docompare(left, right.item(0)) < 0) ? -1 : ((collateupper->docompare(left, right.item(right.ordinality()-1)) > 0) ? +1 : 0));
- else
- diff = collate->docompare(left, right.item(0));
- bool limitExceeded = right.ordinality()>abortLimit;
- if (diff == 0)
- {
- if (limitExceeded)
- {
- const void * ret = NULL;
- if(failingLimit)
- ret = joinException(left, failingLimit);
- ReleaseRoxieRow(left);
- left = NULL;
- state = JSfillleft;
- ForEachItemIn(idx, right)
- matchedRight.replace(true, idx);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- else
- {
- state = JScompare;
- joinLimit = keepLimit;
- }
- }
- else if (diff < 0)
- state = JSleftonly;
- else if (limitExceeded)
- {
- // MORE - Roxie code seems to think there should be a destroyRowset(right) here....
- state = JSfillright;
- }
- else
- state = JSrightonly;
- }
- }
- break;
- case JSrightonly:
- if (rightOuterJoin)
- {
- switch (activityKind)
- {
- case TAKjoin:
- {
- while (right.isItem(rightIndex))
- {
- if (!matchedRight.item(rightIndex))
- {
- const void * rhs = right.item(rightIndex++);
- const void *ret = joinRecords(defaultLeft, rhs, 0);
- if (ret)
- {
- processed++;
- return ret;
- }
- }
- else
- rightIndex++;
- }
- break;
- }
- //Probably excessive to implement the following, but possibly useful
- case TAKdenormalize:
- {
- OwnedConstRoxieRow newLeft;
- newLeft.set(defaultLeft);
- unsigned rowSize = 0;
- unsigned leftCount = 0;
- while (right.isItem(rightIndex))
- {
- if (!matchedRight.item(rightIndex))
- {
- const void * rhs = right.item(rightIndex);
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
- if (thisSize)
- {
- rowSize = thisSize;
- newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- rightIndex++;
- }
- state = JSfillright;
- if (rowSize)
- {
- processed++;
- return newLeft.getClear();
- }
- break;
- }
- case TAKdenormalizegroup:
- {
- filteredRight.kill();
- while (right.isItem(rightIndex))
- {
- if (!matchedRight.item(rightIndex))
- filteredRight.append(right.item(rightIndex));
- rightIndex++;
- }
- state = JSfillright;
- if (filteredRight.ordinality())
- {
- const void * ret = denormalizeRecords(defaultLeft, filteredRight);
- filteredRight.kill();
- if (ret)
- {
- processed++;
- return ret;
- }
- }
- break;
- }
- }
- }
- state = JSfillright;
- break;
-
- case JSleftonly:
- {
- const void * ret = NULL;
- if (!matchedLeft && leftOuterJoin)
- {
- switch (activityKind)
- {
- case TAKjoin:
- ret = joinRecords(left, defaultRight, 0);
- break;
- case TAKdenormalize:
- ret = left;
- left = NULL;
- break;
- case TAKdenormalizegroup:
- filteredRight.kill();
- ret = denormalizeRecords(left, filteredRight);
- break;
- }
- }
- ReleaseRoxieRow(left);
- left = NULL;
- state = JSfillleft;
- if (ret)
- {
- processed++;
- return ret;
- }
- break;
- }
- case JScompare:
- if (joinLimit != 0)
- {
- switch (activityKind)
- {
- case TAKjoin:
- {
- while (right.isItem(rightIndex))
- {
- const void * rhs = right.item(rightIndex++);
- if (helper.match(left, rhs))
- {
- matchedRight.replace(true, rightIndex-1);
- matchedLeft = true;
- if (!exclude)
- {
- const void *ret = joinRecords(left, rhs, ++joinCounter);
- if (ret)
- {
- processed++;
- joinLimit--;
- return ret;
- }
- }
- }
- }
- break;
- }
- case TAKdenormalize:
- {
- OwnedConstRoxieRow newLeft;
- newLeft.set(left);
- unsigned rowSize = 0;
- unsigned leftCount = 0;
- while (right.isItem(rightIndex) && joinLimit)
- {
- try
- {
- const void * rhs = right.item(rightIndex++);
- if (helper.match(left, rhs))
- {
- matchedRight.replace(true, rightIndex-1);
- matchedLeft = true;
- if (!exclude)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned thisSize = helper.transform(rowBuilder, newLeft, rhs, ++leftCount);
- if (thisSize)
- {
- rowSize = thisSize;
- newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
- joinLimit--;
- }
- }
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- state = JSleftonly;
- rightIndex = 0;
- if (rowSize)
- {
- processed++;
- return newLeft.getClear();
- }
- break;
- }
- case TAKdenormalizegroup:
- {
- filteredRight.kill();
- while (right.isItem(rightIndex))
- {
- const void * rhs = right.item(rightIndex++);
- if (helper.match(left, rhs))
- {
- matchedRight.replace(true, rightIndex-1);
- filteredRight.append(rhs);
- matchedLeft = true;
- if (filteredRight.ordinality()==joinLimit)
- break;
- }
- }
- state = JSleftonly;
- rightIndex = 0;
- if (!exclude && filteredRight.ordinality())
- {
- const void * ret = denormalizeRecords(left, filteredRight);
- filteredRight.kill();
- if (ret)
- {
- processed++;
- return ret;
- }
- }
- break;
- }
- }
- }
- state = JSleftonly;
- rightIndex = 0;
- joinCounter = 0;
- break;
- }
- }
- }
- };
- class CRoxieServerJoinActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned input2;
- unsigned input2idx;
- bool forceSpill;
- public:
- CRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- forceSpill = _graphNode.getPropBool("hint[@name='spill']/@value", _queryFactory.queryOptions().allSortsMaySpill);
- input2 = 0;
- input2idx = 0;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerJoinActivity(_ctx, this, _probeManager, forceSpill);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- if (idx==1)
- {
- input2 = source;
- input2idx = sourceidx;
- }
- else
- CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- switch (idx)
- {
- case 1:
- sourceidx = input2idx;
- return input2;
- case 0:
- return CRoxieServerActivityFactory::getInput(idx, sourceidx);
- default:
- return (unsigned) -1;
- }
- }
- virtual unsigned numInputs() const { return 2; }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return joinStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- #define CONCAT_READAHEAD 1000
- class CRoxieThreadedConcatReader : implements IRecordPullerCallback, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- CRoxieThreadedConcatReader(InterruptableSemaphore &_ready, bool _grouped)
- : puller(false), grouped(_grouped), atEog(true), ready(_ready), eof(false)
- {
- }
- void start(unsigned parentExtractSize, const byte *parentExtract, bool paused, IRoxieSlaveContext *ctx)
- {
- space.reinit(CONCAT_READAHEAD);
- puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().concatPreload, false, ctx);
- }
- void stop()
- {
- space.interrupt();
- puller.stop();
- }
- IFinalRoxieInput *queryInput() const
- {
- return puller.queryInput();
- }
- void reset()
- {
- puller.reset();
- ForEachItemIn(idx, buffer)
- ReleaseRoxieRow(buffer.item(idx));
- buffer.clear();
- eof = false;
- atEog = true;
- }
- void setInput(unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- puller.setInput(this, _sourceIdx, _in);
- }
- void connectInputStreams(IRoxieSlaveContext *ctx, bool consumerOrdered)
- {
- puller.connectInputStreams(ctx, consumerOrdered);
- }
- virtual void processRow(const void *row)
- {
- buffer.enqueue(row);
- ready.signal();
- space.wait();
- }
- virtual void processGroup(const ConstPointerArray &rows)
- {
- // We use record-by-record input mode of the puller thread even in grouped mode.
- throwUnexpected();
- }
- virtual void processEOG()
- {
- if (grouped)
- processRow(NULL);
- }
- virtual void processDone()
- {
- processRow(NULL);
- }
- virtual bool fireException(IException *e)
- {
- // called from puller thread on failure
- ready.interrupt(LINK(e));
- space.interrupt(e);
- return true;
- }
- bool peek(const void * &row, bool &anyActive)
- {
- if (!eof)
- {
- if (buffer.ordinality())
- {
- space.signal();
- row = buffer.dequeue();
- if (row==NULL)
- {
- if (atEog)
- {
- eof = true;
- return false;
- }
- else
- atEog = true;
- }
- else if (grouped)
- atEog = false;
- return true;
- }
- anyActive = true;
- }
- return false;
- }
- protected:
- RecordPullerThread puller;
- InterruptableSemaphore space;
- InterruptableSemaphore &ready;
- SafeQueueOf<const void, true> buffer;
- bool atEog;
- bool eof;
- bool grouped;
- };
- typedef CopyReferenceArrayOf<CRoxieThreadedConcatReader> ReaderArray;
- class CRoxieServerThreadedConcatActivity : public CRoxieServerActivity
- {
- InterruptableSemaphore ready;
- ReaderArray pullers;
- unsigned numInputs;
- unsigned nextPuller; // for round robin
- unsigned readyPending;
- bool eof;
- bool inGroup;
- bool grouped;
- public:
- CRoxieServerThreadedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), grouped(_grouped)
- {
- numInputs = _numInputs;
- eof = (numInputs==0);
- inGroup = false;
- nextPuller = 0;
- readyPending = 0;
- for (unsigned i = 0; i < numInputs; i++)
- pullers.append(*new CRoxieThreadedConcatReader(ready, _grouped));
- }
- ~CRoxieServerThreadedConcatActivity()
- {
- ForEachItemIn(idx, pullers)
- delete &pullers.item(idx);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = (numInputs==0);
- inGroup = false;
- nextPuller = 0;
- readyPending = 0;
- ready.reinit();
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- ForEachItemIn(idx, pullers)
- {
- pullers.item(idx).start(parentExtractSize, parentExtract, paused, ctx);
- // NOTE - it is ok to start the thread running while parts of the subgraph are still being started, since everything
- // in the part of the subgraph that the thread uses has been started.
- // Note that splitters are supposed to cope with being used when only some outputs have been started.
- }
- }
- virtual void stop()
- {
- ready.interrupt();
- ForEachItemIn(idx, pullers)
- pullers.item(idx).stop();
- CRoxieServerActivity::stop();
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- return 0;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (pullers.isItem(idx))
- return pullers.item(idx).queryInput();
- else
- return NULL;
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- ForEachItemIn(idx, pullers)
- pullers.item(idx).reset();
- eof = false;
- inGroup = false;
- nextPuller = 0;
- readyPending = 0;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (pullers.isItem(idx))
- pullers.item(idx).setInput(_sourceIdx, _in);
- else
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- ForEachItemIn(i, pullers)
- pullers.item(i).connectInputStreams(ctx, consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr); // No input actually connected
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- if (readyPending && !inGroup)
- {
- if (readyPending > 1)
- ready.signal(readyPending-1);
- readyPending = 0;
- }
- else
- ready.wait();
- bool anyActive = false;
- ForEachItemIn(unused_index, pullers)
- {
- // NOTE - we round robin not just because it's more efficient, but because it ensures the preservation of grouping information
- const void *ret;
- bool fetched = pullers.item(nextPuller).peek(ret, anyActive);
- if (fetched)
- {
- inGroup = (ret != NULL);
- return ret;
- }
- if (inGroup && grouped)
- {
- // Some other puller has data, but we can't consume it until the group we are reading is complete.
- readyPending++;
- anyActive = true;
- break;
- }
- nextPuller++;
- if (nextPuller==pullers.ordinality())
- nextPuller = 0;
- }
- if (!anyActive)
- break;
- // A ready signal without anything being ready means someone reached end-of-file.
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerOrderedConcatActivity : public CRoxieServerMultiInputActivity
- {
- IEngineRowStream *curStream;
- bool eogSeen;
- bool anyThisGroup;
- bool grouped;
- unsigned streamIdx;
- public:
- CRoxieServerOrderedConcatActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _grouped, unsigned _numInputs)
- : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- eogSeen = false;
- anyThisGroup = false;
- grouped = _grouped;
- streamIdx = 0;
- curStream = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
- streamIdx = 0;
- curStream = streamArray[streamIdx];
- eogSeen = false;
- anyThisGroup = false;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!curStream)
- return NULL; // eof
- const void * next = curStream->nextRow();
- if (next)
- {
- anyThisGroup = true;
- eogSeen = false;
- processed++;
- return next;
- }
- else if (!eogSeen)
- {
- eogSeen = true;
- if (grouped)
- {
- if (anyThisGroup)
- {
- anyThisGroup = false;
- return NULL;
- }
- else
- return nextRow();
- }
- else
- return nextRow();
- }
- else if (streamIdx < numStreams-1)
- {
- streamIdx++;
- curStream = streamArray[streamIdx];
- eogSeen = false;
- return nextRow();
- }
- else
- {
- curStream = NULL;
- return NULL;
- }
- }
- };
- class CRoxieServerConcatActivityFactory : public CRoxieServerMultiInputFactory
- {
- bool ordered;
- bool grouped;
- public:
- CRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned <IHThorFunnelArg> helper = (IHThorFunnelArg *) helperFactory();
- ordered = helper->isOrdered();
- grouped = helper->queryOutputMeta()->isGrouped();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (ordered || (_probeManager && _probeManager->queryDebugManager()))
- return new CRoxieServerOrderedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
- else
- return new CRoxieServerThreadedConcatActivity(_ctx, this, _probeManager, grouped, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerConcatActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerConcatActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNonEmptyActivity : public CRoxieServerMultiInputBaseActivity
- {
- IEngineRowStream* selectedStream;
- unsigned savedParentExtractSize;
- const byte * savedParentExtract;
- bool foundInput;
- public:
- CRoxieServerNonEmptyActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- foundInput = false;
- selectedStream = NULL;
- savedParentExtractSize = 0;;
- savedParentExtract = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- //Don't start the inputs yet so we can short-circuit...
- CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
- savedParentExtractSize = parentExtractSize;
- savedParentExtract = parentExtract;
- }
- virtual void stop()
- {
- if (foundInput)
- {
- if (selectedStream)
- selectedStream->stop();
- }
- else
- {
- for (unsigned i = 0; i < numStreams; i++)
- streamArray[i]->stop();
- }
- CRoxieServerMultiInputBaseActivity::stop();
- }
- virtual void reset()
- {
- CRoxieServerMultiInputBaseActivity::reset();
- foundInput = false;
- selectedStream = NULL;
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- return 0; // Can't easily calculate anything reliable but local processing is negligible
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!foundInput)
- {
- foundInput = true;
- assertex(numInputs == numStreams); // If this ceases to be true we will need to rethink some of this
- //If we get an exception in this loop then stop() will stop any started inputs
- for (unsigned i=0; i < numStreams; i++)
- {
- selectedStream = streamArray[i];
- inputArray[i]->start(savedParentExtractSize, savedParentExtract, false); // Assumes 1:1 mapping streams to inputs
- startJunction(junctionArray[i]);
- const void * next = selectedStream->nextRow();
- if (next)
- {
- //Found a row so stop remaining
- for (unsigned j=i+1; j < numInputs; j++)
- streamArray[j]->stop();
- processed++;
- return next;
- }
- selectedStream->stop();
- }
- selectedStream = NULL;
- return NULL;
- }
- if (!selectedStream)
- return NULL;
- const void * next = selectedStream->nextRow();
- if (next)
- processed++;
- return next;
- }
- };
- class CRoxieServerNonEmptyActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNonEmptyActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNonEmptyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNonEmptyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerMergeActivity : public CRoxieServerMultiInputActivity
- {
- IHThorMergeArg &helper;
- unsigned *mergeheap;
- unsigned activeInputs;
- const void **pending;
- bool first;
- ICompare *compare;
- bool dedup;
- void permute()
- {
- assertex(activeInputs == 0);
- for(unsigned i = 0; i < numStreams; i++)
- if(pullInput(i))
- mergeheap[activeInputs++] = i;
- // the tree structure: element p has children p*2+1 and p*2+2, or element c has parent (unsigned)(c-1)/2
- // the heap property: no element should be smaller than its parent
- // the dedup variant: if(dedup), the top of the heap should also not be equal to either child
- // 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
- if (activeInputs >= 2)
- for(unsigned p = (activeInputs-2)/2; p > 0; --p)
- siftDown(p);
- if(dedup)
- siftDownDedupTop();
- else
- siftDown(0);
- }
- void readNext()
- {
- if(!pullInput(mergeheap[0]))
- if(!promote(0))
- return;
- // we have changed the element at the top of the heap, so need to sift it down to maintain the heap property
- if(dedup)
- siftDownDedupTop();
- else
- siftDown(0);
- }
- bool pullInput(unsigned i)
- {
- const void *next = streamArray[i]->ungroupedNextRow();
- pending[i] = next;
- return (next != NULL);
- }
- bool promote(unsigned p)
- {
- activeInputs--;
- if(activeInputs == p)
- return false;
- mergeheap[p] = mergeheap[activeInputs];
- return true;
- }
- bool siftDown(unsigned p)
- {
- // assuming that all descendants of p form a heap, sift p down to its correct position, and so include it in the heap
- bool nochange = true;
- while(1)
- {
- unsigned c = p*2 + 1;
- if(c >= activeInputs)
- return nochange;
- if(c+1 < activeInputs)
- {
- int childcmp = BuffCompare(c+1, c);
- if((childcmp < 0) || ((childcmp == 0) && (mergeheap[c+1] < mergeheap[c])))
- ++c;
- }
- int cmp = BuffCompare(c, p);
- if((cmp > 0) || ((cmp == 0) && (mergeheap[c] > mergeheap[p])))
- return nochange;
- nochange = false;
- unsigned r = mergeheap[c];
- mergeheap[c] = mergeheap[p];
- mergeheap[p] = r;
- p = c;
- }
- }
- void siftDownDedupTop()
- {
- // same as siftDown(0), except that it also ensures that the top of the heap is not equal to either of its children
- if(activeInputs < 2)
- return;
- unsigned c = 1;
- int childcmp = 1;
- if(activeInputs >= 3)
- {
- childcmp = BuffCompare(2, 1);
- if(childcmp < 0)
- c = 2;
- }
- int cmp = BuffCompare(c, 0);
- if(cmp > 0)
- return;
- // the following loop ensures the correct property holds on the smaller branch, and that childcmp==0 iff the top matches the other branch
- while(cmp <= 0)
- {
- if(cmp == 0)
- {
- if(mergeheap[c] < mergeheap[0])
- {
- unsigned r = mergeheap[c];
- mergeheap[c] = mergeheap[0];
- mergeheap[0] = r;
- }
- ReleaseClearRoxieRow(pending[mergeheap[c]]);
- if(!pullInput(mergeheap[c]))
- if(!promote(c))
- break;
- siftDown(c);
- }
- else
- {
- unsigned r = mergeheap[c];
- mergeheap[c] = mergeheap[0];
- mergeheap[0] = r;
- if(siftDown(c))
- break;
- }
- cmp = BuffCompare(c, 0);
- }
- // the following loop ensures the uniqueness property holds on the other branch too
- c = 3-c;
- if(activeInputs <= c)
- return;
- while(childcmp == 0)
- {
- if(mergeheap[c] < mergeheap[0])
- {
- unsigned r = mergeheap[c];
- mergeheap[c] = mergeheap[0];
- mergeheap[0] = r;
- }
- ReleaseClearRoxieRow(pending[mergeheap[c]]);
- if(!pullInput(mergeheap[c]))
- if(!promote(c))
- break;
- siftDown(c);
- childcmp = BuffCompare(c, 0);
- }
- }
- inline int BuffCompare(unsigned a, unsigned b)
- {
- return compare->docompare(pending[mergeheap[a]], pending[mergeheap[b]]);
- }
- public:
- CRoxieServerMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorMergeArg &)basehelper)
- {
- activeInputs = 0;
- first = true;
- mergeheap = new unsigned[numInputs];
- pending = new const void *[numStreams];
- compare = helper.queryCompare();
- dedup = helper.dedup();
- for (unsigned i = 0; i < numStreams; i++)
- pending[i] = NULL;
- }
- ~CRoxieServerMergeActivity()
- {
- delete [] mergeheap;
- delete [] pending;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- activeInputs = 0;
- first = true;
- CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- for (unsigned i = 0; i < numStreams; i++)
- ReleaseClearRoxieRow(pending[i]);
- CRoxieServerMultiInputActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (first)
- {
- permute();
- first = false;
- }
- if (activeInputs)
- {
- const void *next = pending[mergeheap[0]];
- readNext();
- if (next)
- processed++;
- return next;
- }
- else
- return NULL;
- }
- };
- class CRoxieServerMergeActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerMergeActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerRegroupActivity : public CRoxieServerMultiInputActivity
- {
- IHThorRegroupArg &helper;
- unsigned streamIndex;
- bool eof;
- unsigned __int64 numProcessedLastGroup;
- public:
- CRoxieServerRegroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorRegroupArg &)basehelper)
- {
- streamIndex = 0;
- eof = false;
- numProcessedLastGroup = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- streamIndex = 0;
- eof = false;
- numProcessedLastGroup = processed;
- CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
- }
- const void * nextFromInputs()
- {
- unsigned initialStream = streamIndex;
- while (streamIndex < numStreams)
- {
- const void * next = streamArray[streamIndex]->nextRow();
- if (next)
- {
- if ((streamIndex != initialStream) && (streamIndex != initialStream+1))
- {
- ReleaseRoxieRow(next);
- throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
- }
- return next;
- }
- streamIndex++;
- }
- if ((initialStream != 0) && (initialStream+1 != numStreams))
- throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched groups supplied to Regroup (%d)", factory->queryId());
- streamIndex = 0;
- return NULL;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void * ret = nextFromInputs();
- if (ret)
- {
- processed++;
- return ret;
- }
- if (numProcessedLastGroup != processed)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerRegroupActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerRegroupActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerRegroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerRegroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerCombineActivity : public CRoxieServerMultiInputActivity
- {
- IHThorCombineArg &helper;
- unsigned __int64 numProcessedLastGroup;
- public:
- CRoxieServerCombineActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCombineArg &)basehelper)
- {
- numProcessedLastGroup = 0;
- }
- ~CRoxieServerCombineActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = processed;
- CRoxieServerMultiInputActivity::start(parentExtractSize, parentExtract, paused);
- }
- void nextInputs(ConstPointerArray & out)
- {
- for (unsigned i=0; i < numStreams; i++)
- {
- const void * next = streamArray[i]->nextRow();
- if (next)
- out.append(next);
- }
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- ConstPointerArray group;
- nextInputs(group);
- if ((group.ordinality() == 0) && (numProcessedLastGroup == processed))
- nextInputs(group);
- if (group.ordinality() == 0)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- else if (group.ordinality() != numInputs)
- {
- ReleaseRoxieRows(group);
- throw MakeStringException(ROXIE_MISMATCH_GROUP_ERROR, "Mismatched group input for Combine Activity(%d)", factory->queryId());
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, group.ordinality(), group.getArray());
- ReleaseRoxieRows(group);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- ReleaseRoxieRows(group);
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerCombineActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerCombineActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerCombineActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerCombineActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerCombineGroupActivity : public CRoxieServerTwoInputActivity
- {
- IHThorCombineGroupArg &helper;
- unsigned __int64 numProcessedLastGroup;
- public:
- CRoxieServerCombineGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorCombineGroupArg &)basehelper)
- {
- numProcessedLastGroup = 0;
- }
- ~CRoxieServerCombineGroupActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = processed;
- CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL : this;
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- const void * left = inputStream->nextRow();
- if (!left && (numProcessedLastGroup == processed))
- left = inputStream->nextRow();
- if (!left)
- {
- if (numProcessedLastGroup == processed)
- {
- const void * nextRight = inputStream1->nextRow();
- if (nextRight)
- {
- ReleaseRoxieRow(nextRight);
- throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing LEFT record for Combine Group (%d)", factory->queryId());
- }
- }
- else
- numProcessedLastGroup = processed;
- return NULL;
- }
- ConstPointerArray group;
- loop
- {
- const void * in = inputStream1->nextRow();
- if (!in)
- break;
- group.append(in);
- }
- if (group.ordinality() == 0)
- {
- ReleaseRoxieRow(left);
- ReleaseRoxieRows(group);
- throw MakeStringException(ROXIE_MISSING_GROUP_ERROR, "Missing RIGHT group for Combine Group (%d)", factory->queryId());
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, left, group.ordinality(), (const void * *)group.getArray());
- ReleaseRoxieRow(left);
- ReleaseRoxieRows(group);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- ReleaseRoxieRow(left);
- ReleaseRoxieRows(group);
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerCombineGroupActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned input2;
- unsigned input2idx;
- public:
- CRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- input2 = 0;
- input2idx = 0;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerCombineGroupActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- if (idx==1)
- {
- input2 = source;
- input2idx = sourceidx;
- }
- else
- CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- switch (idx)
- {
- case 1:
- sourceidx = input2idx;
- return input2;
- case 0:
- return CRoxieServerActivityFactory::getInput(idx, sourceidx);
- default:
- return (unsigned) -1;
- }
- }
- virtual unsigned numInputs() const { return 2; }
- };
- IRoxieServerActivityFactory *createRoxieServerCombineGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerCombineGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerRollupGroupActivity : public CRoxieServerActivity
- {
- IHThorRollupGroupArg &helper;
- bool eof;
- public:
- CRoxieServerRollupGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorRollupGroupArg &)basehelper)
- {
- eof = false;
- }
- ~CRoxieServerRollupGroupActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- ConstPointerArray group;
- loop
- {
- const void * in = inputStream->nextRow();
- if (!in)
- break;
- group.append(in);
- }
- if (group.ordinality() == 0)
- {
- eof = true;
- return NULL;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, group.ordinality(), (const void * *)group.getArray());
- ReleaseRoxieRows(group);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException * E)
- {
- ReleaseRoxieRows(group);
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerRollupGroupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerRollupGroupActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerRollupGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerRollupGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerFilterProjectActivity : public CRoxieServerLateStartActivity
- {
- IHThorFilterProjectArg &helper;
- unsigned numProcessedLastGroup;
- unsigned __int64 recordCount;
- public:
- CRoxieServerFilterProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFilterProjectArg &)basehelper)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- }
- ~CRoxieServerFilterProjectActivity()
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
- lateStart(parentExtractSize, parentExtract, helper.canMatchAny()); //sets eof
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- const void * in = inputStream->nextRow();
- if (!in)
- {
- recordCount = 0;
- if (numProcessedLastGroup == processed)
- in = inputStream->nextRow();
- if (!in)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, in, ++recordCount);
- ReleaseRoxieRow(in);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerFilterProjectActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- //MORE: Code generator needs to indicate if the count is used.
- //optStableInput = false;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerFilterProjectActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerFilterProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerFilterProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================
- class CRoxieServerStrandedProjectActivity : public CRoxieServerStrandedActivity
- {
- class ProjectProcessor : public StrandProcessor
- {
- protected:
- IHThorProjectArg &helper;
- public:
- ProjectProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorProjectArg &_helper)
- : StrandProcessor(_parent, _inputStream, true), helper(_helper)
- {
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- OwnedConstRoxieRow in = inputStream->nextRow();
- if (!in)
- {
- if (numProcessedLastGroup == processed)
- in.setown(inputStream->nextRow());
- if (!in)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize;
- outSize = helper.transform(rowBuilder, in);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- throw parent.makeWrappedException(E);
- }
- }
- }
- };
- public:
- CRoxieServerStrandedProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const StrandOptions &_strandOptions)
- : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
- onStartStrands();
- }
- virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
- {
- return new ProjectProcessor(*this, instream, (IHThorProjectArg &) basehelper);
- }
- virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
- };
- class CRoxieServerProjectActivity : public CRoxieServerActivity
- {
- unsigned numProcessedLastGroup;
- unsigned __int64 recordCount;
- bool count;
- public:
- CRoxieServerProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- count(_count)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- OwnedConstRoxieRow in = inputStream->nextRow();
- if (!in)
- {
- recordCount = 0;
- if (numProcessedLastGroup == processed)
- in.setown(inputStream->nextRow());
- if (!in)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize;
- if (count)
- outSize = ((IHThorCountProjectArg &) basehelper).transform(rowBuilder, in, ++recordCount);
- else
- outSize = ((IHThorProjectArg &) basehelper).transform(rowBuilder, in);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerProjectActivityFactory : public CRoxieServerActivityFactory
- {
- protected:
- StrandOptions strandOptions;
- bool count;
- public:
- CRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
- {
- count = (kind==TAKcountproject || kind==TAKprefetchcountproject);
- optStableInput = count;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- // 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.
- if (kind == TAKproject) // Not supported on prefetch or count projects
- return new CRoxieServerStrandedProjectActivity(_ctx, this, _probeManager, strandOptions);
- else
- return new CRoxieServerProjectActivity(_ctx, this, _probeManager, count);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerPrefetchProjectActivity : public CRoxieServerActivity, implements IRecordPullerCallback
- {
- unsigned numProcessedLastGroup;
- bool count;
- bool eof;
- bool allPulled;
- bool isThreaded;
- unsigned preload;
- unsigned __int64 recordCount;
- IHThorPrefetchProjectArg &helper;
- RecordPullerThread puller;
- InterruptableSemaphore ready;
- InterruptableSemaphore space;
- class PrefetchInfo : public CInterface
- {
- public:
- inline PrefetchInfo(IHThorPrefetchProjectArg &helper, const void *_in, unsigned __int64 _recordCount)
- {
- if (helper.preTransform(extract, _in, _recordCount))
- {
- in.setown(_in);
- recordCount = _recordCount;
- }
- else
- {
- ReleaseRoxieRow(_in);
- recordCount = 0;
- }
- }
- OwnedConstRoxieRow in;
- unsigned __int64 recordCount;
- rtlRowBuilder extract;
- };
- QueueOf<PrefetchInfo, true> pulled;
- CriticalSection pulledCrit;
- public:
- CRoxieServerPrefetchProjectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _count)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorPrefetchProjectArg &) basehelper),
- puller(false),
- count(_count)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- eof = false;
- allPulled = false;
- isThreaded = (helper.getFlags() & PPFparallel) != 0;
- preload = 0;
- }
- ~CRoxieServerPrefetchProjectActivity()
- {
- while (pulled.ordinality())
- ::Release(pulled.dequeue());
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (idx)
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- puller.setInput(this, _sourceIdx, _in);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- puller.connectInputStreams(ctx, consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return puller.queryInput();
- else
- return NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = 0;
- recordCount = 0;
- eof = false;
- allPulled = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- preload = helper.getLookahead();
- if (!preload)
- preload = ctx->queryOptions().prefetchProjectPreload;
- space.reinit(preload);
- ready.reinit();
- puller.start(parentExtractSize, parentExtract, paused, preload, !isThreaded, ctx);
- }
- virtual void stop()
- {
- space.interrupt();
- ready.interrupt();
- CRoxieServerActivity::stop();
- puller.stop();
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- puller.reset();
- allPulled = false;
- while (pulled.ordinality())
- ::Release(pulled.dequeue());
- }
- virtual PrefetchInfo *readNextRecord()
- {
- if (!isThreaded)
- {
- if (!allPulled) // This looks like it's thread unsafe but we are inside the if(!isThreaded) so should be ok
- puller.pullRecords(1);
- }
- else
- ready.wait();
- CriticalBlock b(pulledCrit);
- PrefetchInfo *ret = pulled.ordinality() ? pulled.dequeue() : NULL;
- space.signal();
- return ret;
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- loop
- {
- Owned<PrefetchInfo> in = readNextRecord();
- if (!in)
- {
- recordCount = 0;
- if (numProcessedLastGroup == processed)
- in.setown(readNextRecord());
- if (!in)
- {
- numProcessedLastGroup = processed;
- eof = true;
- return NULL;
- }
- }
- try
- {
- if (in->in)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize;
- IThorChildGraph *child = helper.queryChild();
- Owned<IEclGraphResults> results;
- if (child)
- results.setown(child->evaluate(in->extract.size(), in->extract.getbytes()));
- outSize = helper.transform(rowBuilder, in->in, results, in->recordCount);
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- // interface IExceptionHandler
- virtual bool fireException(IException *e)
- {
- // called from puller thread on failure
- ready.interrupt(LINK(e));
- space.interrupt(e);
- return true;
- }
- // interface IRecordPullerCallback
- virtual void processRow(const void *row)
- {
- {
- CriticalBlock b(pulledCrit);
- pulled.enqueue(new PrefetchInfo(helper, row, ++recordCount));
- }
- if (isThreaded)
- {
- ready.signal();
- space.wait();
- }
- }
- virtual void processEOG()
- {
- {
- CriticalBlock b(pulledCrit);
- pulled.enqueue(NULL);
- }
- if (isThreaded)
- {
- ready.signal();
- space.wait();
- }
- }
- virtual void processGroup(const ConstPointerArray &rows)
- {
- throwUnexpected();
- }
- virtual void processDone()
- {
- CriticalBlock b(pulledCrit);
- allPulled = true;
- if (isThreaded)
- ready.signal();
- }
- };
- class CRoxieServerPrefetchProjectActivityFactory : public CRoxieServerProjectActivityFactory
- {
- public:
- CRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerPrefetchProjectActivity(_ctx, this, _probeManager, count);
- }
- };
- extern IRoxieServerActivityFactory *createRoxieServerPrefetchProjectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerPrefetchProjectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CPointerArrayRoxieInput : public CPseudoRoxieInput
- {
- public:
- CPointerArrayRoxieInput()
- {
- rowset = NULL;
- rowcount = 0;
- curRow = 0;
- }
- void init(size32_t _rowcount, byte **_rowset)
- {
- rowset = _rowset;
- rowcount = _rowcount;
- curRow = 0;
- }
- virtual const void * nextRow()
- {
- if (curRow < rowcount)
- {
- const void * ret = rowset[curRow];
- if (ret)
- LinkRoxieRow(ret);
- curRow++;
- return ret;
- }
- return NULL;
- }
- protected:
- byte **rowset;
- size32_t rowcount;
- size32_t curRow;
- };
- class CRoxieServerLoopActivity : public CRoxieServerActivity
- {
- protected:
- IHThorLoopArg &helper;
- ThorActivityKind activityKind;
- unsigned maxIterations;
- bool finishedLooping;
- unsigned flags;
- bool eof;
- rtlRowBuilder loopExtractBuilder;
- unsigned loopGraphId;
- Linked<IOutputMetaData> counterMeta;
- public:
- CRoxieServerLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorLoopArg &)basehelper), loopGraphId(_loopGraphId), counterMeta(_counterMeta)
- {
- eof = false;
- finishedLooping = false;
- activityKind = factory->getKind();
- flags = helper.getFlags();
- maxIterations = 0;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- int iterations = (int) helper.numIterations();
- maxIterations = (iterations >= 0) ? iterations : 0;
- finishedLooping = ((activityKind == TAKloopcount) && (maxIterations == 0));
- if ((flags & IHThorLoopArg::LFnewloopagain) && !helper.loopFirstTime())
- finishedLooping = true;
- loopExtractBuilder.clear();
- helper.createParentExtract(loopExtractBuilder); // could possibly delay this until execution actually happens
- }
- virtual void stop()
- {
- CRoxieServerActivity::stop();
- loopExtractBuilder.clear();
- }
- void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
- {
- if (flags & IHThorLoopArg::LFcounter)
- {
- void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
- *((thor_loop_counter_t *)counterRow) = counter;
- RtlLinkedDatasetBuilder builder(rowAllocator);
- builder.appendOwn(counterRow);
- Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
- graph->setInputResult(2, counterResult);
- }
- }
- };
- //=================================================================================
- class CRoxieServerSequentialLoopActivity : public CRoxieServerLoopActivity
- {
- Owned<IActivityGraph> loopQuery;
- Owned<IRoxieServerChildGraph> loopGraph;
- IEngineRowStream * curStream;
- RtlLinkedDatasetBuilder *loopInputBuilder;
- CPointerArrayRoxieInput arrayInput;
- Linked<IEngineRowStream> resultStream;
- unsigned loopCounter;
- public:
- CRoxieServerSequentialLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta)
- {
- curStream = NULL;
- loopCounter = 0;
- loopInputBuilder = NULL;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerLoopActivity::onCreate(_colocalParent);
- loopQuery.set(ctx->queryChildGraph(loopGraphId));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- curStream = inputStream;
- loopCounter = 1;
- CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
- //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
- loopGraph.set(loopQuery->queryLoopGraph());
- loopInputBuilder = new RtlLinkedDatasetBuilder(rowAllocator);
- }
- virtual void stop()
- {
- delete loopInputBuilder;
- loopInputBuilder = NULL;
- CRoxieServerLoopActivity::stop();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- unsigned emptyIterations = 0;
- loop
- {
- loop
- {
- const void * ret = curStream->nextRow();
- if (!ret)
- {
- ret = curStream->nextRow(); // more cope with groups somehow....
- if (!ret)
- {
- if (finishedLooping)
- {
- eof = true;
- return NULL;
- }
- break;
- }
- }
- if (finishedLooping ||
- ((flags & IHThorLoopArg::LFfiltered) && !helper.sendToLoop(loopCounter, ret)))
- {
- processed++;
- return ret;
- }
- loopInputBuilder->appendOwn(ret);
- }
- switch (activityKind)
- {
- case TAKloopdataset:
- {
- if (!(flags & IHThorLoopArg::LFnewloopagain))
- {
- if (!helper.loopAgain(loopCounter, loopInputBuilder->getcount(), (const void**) loopInputBuilder->queryrows()))
- {
- if (loopInputBuilder->getcount() == 0)
- {
- eof = true;
- return NULL;
- }
- arrayInput.init(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
- // MORE - should builder be cleared here?
- curStream = &arrayInput;
- finishedLooping = true;
- continue; // back to the input loop again
- }
- }
- break;
- }
- case TAKlooprow:
- if (!loopInputBuilder->getcount())
- {
- finishedLooping = true;
- eof = true;
- return NULL;
- }
- break;
- }
- if (loopInputBuilder->getcount())
- emptyIterations = 0;
- else
- {
- //note: any outputs which didn't go around the loop again, would return the record, reinitializing emptyIterations
- emptyIterations++;
- if (emptyIterations > maxEmptyLoopIterations)
- throw MakeStringException(ROXIE_TOO_MANY_EMPTY_LOOP, "Executed LOOP with empty input and output %u times", emptyIterations);
- if (emptyIterations % 32 == 0)
- CTXLOG("Executing LOOP with empty input and output %u times", emptyIterations);
- }
- checkAbort();
- try
- {
- Owned<IRoxieGraphResults> results = executeIteration(loopExtractBuilder.size(), loopExtractBuilder.getbytes(), loopCounter);
- resultStream.setown(results->createIterator(0));
- if (flags & IHThorLoopArg::LFnewloopagain)
- {
- Owned<IEngineRowStream> againResult = results->createIterator(helper.loopAgainResult());
- OwnedConstRoxieRow row = againResult->nextRow();
- assertex(row);
- //Result is a row which contains a single boolean field.
- if (!((const bool *)row.get())[0])
- finishedLooping = true;
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- curStream = resultStream.get();
- loopCounter++;
- if ((activityKind == TAKloopcount) && (loopCounter > maxIterations))
- finishedLooping = true;
- }
- }
- IRoxieGraphResults * executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
- {
- try
- {
- loopGraph->beforeExecute();
- Owned<IGraphResult> inputRowsResult = new CGraphResult(loopInputBuilder->getcount(), loopInputBuilder->linkrows());
- loopInputBuilder->clear();
- loopGraph->setInputResult(1, inputRowsResult);
- createCounterResult(loopGraph, counter);
- Owned<IRoxieGraphResults> ret = loopGraph->execute(parentExtractSize, parentExtract);
- loopGraph->afterExecute();
- return ret.getClear();
- }
- catch (...)
- {
- CTXLOG("Exception thrown in loop body - cleaning up");
- loopGraph->afterExecute();
- throw;
- }
- }
- };
- //=================================================================================
- typedef SafeQueueOf<const void, true> SafeRowQueue;
- class CRowQueuePseudoInput : public CPseudoRoxieInput
- {
- public:
- CRowQueuePseudoInput(SafeRowQueue & _input, IOutputMetaData * _meta)
- : meta(_meta), input(_input)
- {
- eof = false;
- }
- virtual const void * nextRow()
- {
- if (eof)
- return NULL;
- const void * ret = input.dequeue();
- if (!ret)
- eof = true;
- return ret;
- }
- virtual IOutputMetaData * queryOutputMeta() const { return meta; }
- protected:
- SafeRowQueue & input;
- IOutputMetaData * meta;
- bool eof;
- };
- class CRoxieServerParallelLoopActivity;
- class LoopFilterPseudoInput : public CIndirectRoxieInput
- {
- public:
- LoopFilterPseudoInput(CRoxieServerParallelLoopActivity * _activity, unsigned _counter) :
- activity(_activity), counter(_counter)
- {
- }
- virtual const void * nextRow();
- protected:
- CRoxieServerParallelLoopActivity * activity;
- unsigned counter;
- };
- class LoopExecutorThread : public RestartableThread
- {
- protected:
- Owned<CSafeRoxieInput> safeInput;
- CRoxieServerParallelLoopActivity * activity;
- bool eof;
- CriticalSection crit;
- unsigned flags;
- SafeRowQueue tempResults[2];
- unsigned savedParentExtractSize;
- const byte * savedParentExtract;
- IArrayOf<IActivityGraph> cachedGraphs;
- IRoxieSlaveContext *ctx;
- public:
- LoopExecutorThread()
- : RestartableThread("LoopExecutorThread")
- {
- activity = NULL;
- eof = false;
- flags = 0;
- ctx = NULL;
- savedParentExtract = NULL;
- savedParentExtractSize = 0;
- }
- void setInput(CRoxieServerParallelLoopActivity * _activity, unsigned _sourceIdx, IFinalRoxieInput *_input, unsigned _flags)
- {
- activity = _activity;
- flags = _flags;
- // 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.
- safeInput.setown(new CSafeRoxieInput(_sourceIdx, _input));
- }
- void connectInputStreams(bool consumerOrdered)
- {
- safeInput->connectInputStreams(ctx, consumerOrdered);
- }
- IFinalRoxieInput *queryInput() const
- {
- return safeInput;
- }
- void onCreate(IRoxieSlaveContext * _ctx);
- void start(unsigned parentExtractSize, const byte *parentExtract, bool paused);
- void stop();
- void reset();
- virtual int run();
- protected:
- void executeLoop();
- void executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput);
- IFinalRoxieInput * createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter);
- };
- class CRoxieServerParallelLoopActivity : public CRoxieServerLoopActivity
- {
- friend class LoopFilterPseudoInput;
- friend class LoopExecutorThread;
- QueueOf<const void, true> ready;
- CriticalSection helperCS;
- CriticalSection cs;
- unsigned defaultNumParallel;
- LoopExecutorThread executor;
- IProbeManager* probeManager;
- CriticalSection canAccess;
- CriticalSection scrit;
- InterruptableSemaphore readySpace;
- InterruptableSemaphore recordsReady;
- protected:
- bool includeInLoop(unsigned counter, const void * row)
- {
- CriticalBlock b(helperCS);
- return helper.sendToLoop(counter, row);
- }
- public:
- CRoxieServerParallelLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _loopGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerLoopActivity(_ctx, _factory, _probeManager, _loopGraphId, _counterMeta),
- readySpace(parallelLoopFlowLimit)
- {
- probeManager = _probeManager;
- defaultNumParallel = 0;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- executor.onCreate(ctx);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CriticalBlock b(scrit); // can stop while still starting, if unlucky...
- readySpace.reinit(parallelLoopFlowLimit);
- recordsReady.reinit();
- CRoxieServerLoopActivity::start(parentExtractSize, parentExtract, paused);
- defaultNumParallel = helper.defaultParallelIterations();
- if (!defaultNumParallel)
- defaultNumParallel = DEFAULT_PARALLEL_LOOP_THREADS;
- //MORE: If numIterations <= number of parallel iterations[1],
- //then we don't need to create a separate thread to do the processing, and the results will also avoid
- //being transferred via a queue
- executor.start(parentExtractSize, parentExtract, paused);
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (idx)
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- executor.setInput(this, _sourceIdx, _in, flags);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- executor.connectInputStreams(consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return executor.queryInput();
- else
- return NULL;
- }
- virtual void stop()
- {
- CriticalBlock b(scrit); // can stop while still starting, if unlucky...
- readySpace.interrupt();
- recordsReady.interrupt();
- executor.join(); // MORE - may not be needed given stop/reset split
- CRoxieServerLoopActivity::stop();
- }
- virtual void reset()
- {
- while (ready.ordinality())
- ReleaseRoxieRow(ready.dequeue());
- executor.reset();
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (eof)
- return NULL;
- recordsReady.wait();
- CriticalBlock procedure(canAccess);
- if (ready.ordinality())
- {
- const void *result = ready.dequeue();
- readySpace.signal();
- if (result)
- processed++;
- return result;
- }
- else
- eof = true;
- }
- }
- unsigned getNumParallel(unsigned iter)
- {
- return defaultNumParallel;
- }
- inline void enqueueResult(const void * row)
- {
- try
- {
- while(!readySpace.wait(1000))
- {
- CTXLOG("Blocked waiting for space in loop %p activity id: %d output queue: %d records in queue", this, queryId(), ready.ordinality());
- }
- }
- catch (...)
- {
- ReleaseRoxieRow(row);
- throw;
- }
- CriticalBlock b2(canAccess);
- ready.enqueue(row);
- recordsReady.signal();
- }
- inline void finishResults()
- {
- recordsReady.signal();
- }
- virtual bool fireException(IException *e)
- {
- readySpace.interrupt(LINK(e));
- recordsReady.interrupt(e);
- return true;
- }
- IActivityGraph * createChildGraphInstance()
- {
- return factory->createChildGraph(ctx, &helper, loopGraphId, this, probeManager, *this);
- }
- IActivityGraph * queryChildGraph()
- {
- return ctx->queryChildGraph(loopGraphId);
- }
- };
- //=================================================================================
- const void * LoopFilterPseudoInput::nextRow()
- {
- loop
- {
- const void * next = stream->nextRow();
- if (!next || activity->includeInLoop(counter, next))
- return next;
- activity->enqueueResult(next);
- }
- }
- void LoopExecutorThread::onCreate(IRoxieSlaveContext * _ctx)
- {
- //Initialise the cached graph list with the child instance that will always be created. Other iterations will be created on demand.
- ctx = _ctx;
- cachedGraphs.append(*LINK(activity->queryChildGraph()));
- }
- void LoopExecutorThread::start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- savedParentExtractSize = parentExtractSize;
- savedParentExtract = parentExtract;
- eof = false;
- StringBuffer logPrefix("[");
- ctx->getLogPrefix(logPrefix).append("] ");
- RestartableThread::start(logPrefix);
- }
- int LoopExecutorThread::run()
- {
- try
- {
- executeLoop();
- }
- catch (IException *e)
- {
- activity->fireException(e);
- }
- catch (...)
- {
- activity->fireException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unexpected exception caught in LoopExecutorThread::run"));
- }
- return 0;
- }
- void LoopExecutorThread::stop()
- {
- safeInput->stop();
- RestartableThread::join();
- }
- void LoopExecutorThread::reset()
- {
- safeInput->reset();
- }
- void LoopExecutorThread::executeLoop()
- {
- unsigned iterations = 0;
- unsigned counter = 0;
- unsigned outputIndex = 0;
- //Note, activities don't link inputs, so need to be careful that special inputs remain linked while the activity is executing.
- loop
- {
- if (activity->activityKind == TAKloopcount)
- {
- if (counter == activity->maxIterations)
- break;
- }
- else
- {
- //This condition isn't quite right because it needs to be whether the filtered
- //input is empty. May be ok if we include that in the semantics,
- if (tempResults[1-outputIndex].ordinality() == 0)
- break;
- }
- unsigned numParallel = activity->getNumParallel(iterations);
- Linked<IFinalRoxieInput> curInput;
- if (iterations == 0)
- curInput.set(safeInput);
- else
- {
- SafeRowQueue & inputQueue = tempResults[1-outputIndex];
- inputQueue.enqueue(NULL);
- curInput.setown(new CRowQueuePseudoInput(inputQueue, activity->queryOutputMeta()));
- }
- SafeRowQueue * curOutput = NULL;
- if (counter+numParallel > activity->maxIterations)
- numParallel = activity->maxIterations - counter;
- else if (counter+numParallel < activity->maxIterations)
- curOutput = &tempResults[outputIndex];
- executeLoopInstance(counter, numParallel, 0, curInput, curOutput); // CurInput is always SOME sort of proxy so idx always 0
- outputIndex = 1-outputIndex;
- counter += numParallel;
- iterations++;
- }
- //Check for TAKlooprow, where end of loop couldn't be determined ahead of time
- SafeRowQueue & inputQueue = tempResults[1-outputIndex];
- while (inputQueue.ordinality())
- {
- const void * next = inputQueue.dequeue();
- activity->enqueueResult(next);
- }
- activity->finishResults();
- }
- void LoopExecutorThread::executeLoopInstance(unsigned counter, unsigned numIterations, unsigned inputIdx, IFinalRoxieInput * input, SafeRowQueue * spillOutput)
- {
- IArrayOf<IFinalRoxieInput> savedInputs; // activities don't link their inputs, so this list keeps filters alive.
- Linked<IFinalRoxieInput> curInput = input;
- unsigned i;
- for (i= 0; i != numIterations; i++)
- {
- unsigned thisCounter = counter+i+1;
- IFinalRoxieInput * filtered = curInput;
- if (flags & IHThorLoopArg::LFfiltered)
- {
- LoopFilterPseudoInput *newFiltered = new LoopFilterPseudoInput(activity, thisCounter);
- newFiltered->setInput(inputIdx, curInput);
- filtered = newFiltered;
- savedInputs.append(*filtered);
- inputIdx = 0;
- }
- //graph is kept, so new curInput will be guaranteed to exist
- curInput.setown(createLoopIterationGraph(i, inputIdx, filtered, thisCounter));
- inputIdx = 0;
- }
- Owned<IStrandJunction> curJunction;
- IEngineRowStream *curStream = connectSingleStream(ctx, curInput, inputIdx, curJunction, true);
- try
- {
- curInput->start(savedParentExtractSize, savedParentExtract, false);
- if (spillOutput)
- {
- loop
- {
- const void * next = curStream->nextRow();
- if (!next)
- break;
- spillOutput->enqueue(next);
- }
- }
- else
- {
- loop
- {
- const void * next = curStream->nextRow();
- if (!next)
- break;
- activity->enqueueResult(next);
- }
- }
- }
- catch (IException *E)
- {
- ctx->notifyAbort(E);
- for (i= 0; i != numIterations; i++)
- {
- cachedGraphs.item(i).queryLoopGraph()->afterExecute();
- }
- curStream->stop();
- curInput->reset();
- throw;
- }
- for (i= 0; i != numIterations; i++)
- {
- cachedGraphs.item(i).queryLoopGraph()->afterExecute();
- }
- curStream->stop();
- curInput->reset();
- }
- IFinalRoxieInput * LoopExecutorThread::createLoopIterationGraph(unsigned i, unsigned inputIdx, IFinalRoxieInput * input, unsigned counter)
- {
- if (!cachedGraphs.isItem(i))
- cachedGraphs.append(*activity->createChildGraphInstance());
- Linked<IRoxieServerChildGraph> loopGraph = cachedGraphs.item(i).queryLoopGraph();
- loopGraph->beforeExecute();
- if (!loopGraph->querySetInputResult(1, inputIdx, input))
- throwUnexpected(); // a loop which doesn't use the value from the previous iteration. Should probably handle even if daft.
- activity->createCounterResult(loopGraph, counter);
- return loopGraph->selectOutput(0);
- }
- //=================================================================================
- class CCounterRowMetaData : implements IOutputMetaData, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE
- virtual size32_t getRecordSize(const void *) { return sizeof(thor_loop_counter_t); }
- virtual size32_t getMinRecordSize() const { return sizeof(thor_loop_counter_t); }
- virtual size32_t getFixedSize() const { return sizeof(thor_loop_counter_t); }
- virtual void toXML(const byte * self, IXmlWriter & out) { }
- virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
- virtual unsigned getMetaFlags() { return 0; }
- virtual void destruct(byte * self) {}
- virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputMetaData * querySerializedDiskMeta() { return this; }
- virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
- virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
- };
- class CRoxieServerLoopActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned loopGraphId;
- unsigned flags;
- Linked<IOutputMetaData> counterMeta;
- public:
- CRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
- {
- Owned<IHThorLoopArg> helper = (IHThorLoopArg *) helperFactory();
- flags = helper->getFlags();
- counterMeta.setown(new CCounterRowMetaData);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (flags & IHThorLoopArg::LFparallel)
- return new CRoxieServerParallelLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
- else
- return new CRoxieServerSequentialLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
- {
- return new CRoxieServerLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
- }
- //=================================================================================
- class CRoxieServerGraphLoopActivity : public CRoxieServerActivity
- {
- protected:
- IHThorGraphLoopArg &helper;
- unsigned maxIterations;
- unsigned flags;
- rtlRowBuilder GraphExtractBuilder;
- unsigned loopGraphId;
- Linked<IOutputMetaData> counterMeta;
- public:
- CRoxieServerGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorGraphLoopArg &)basehelper), loopGraphId(_GraphGraphId), counterMeta(_counterMeta)
- {
- flags = helper.getFlags();
- maxIterations = 0;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- int iterations = (int) helper.numIterations();
- maxIterations = (iterations >= 0) ? iterations : 0;
- if (maxIterations > maxGraphLoopIterations)
- throw MakeStringException(ROXIE_TOO_MANY_GRAPH_LOOP, "Attempt to execute graph %u times", maxIterations);
- if (maxIterations != 0)
- {
- GraphExtractBuilder.clear();
- helper.createParentExtract(GraphExtractBuilder);
- }
- }
- virtual void stop()
- {
- CRoxieServerActivity::stop();
- GraphExtractBuilder.clear();
- }
- void createCounterResult(IRoxieServerChildGraph * graph, unsigned counter)
- {
- if (flags & IHThorGraphLoopArg::GLFcounter)
- {
- void * counterRow = ctx->queryRowManager().allocate(sizeof(thor_loop_counter_t), activityId);
- *((thor_loop_counter_t *)counterRow) = counter;
- RtlLinkedDatasetBuilder builder(rowAllocator);
- builder.appendOwn(counterRow);
- Owned<CGraphResult> counterResult = new CGraphResult(builder.getcount(), builder.linkrows());
- graph->setInputResult(0, counterResult);
- }
- }
- };
- //=================================================================================
- class CRoxieServerSequentialGraphLoopActivity : public CRoxieServerGraphLoopActivity
- {
- Owned<IActivityGraph> GraphQuery;
- Owned<IRoxieServerChildGraph> loopGraph;
- Linked<IEngineRowStream> resultStream;
- bool evaluated;
- public:
- CRoxieServerSequentialGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta)
- {
- evaluated = false;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
- GraphQuery.set(ctx->queryChildGraph(loopGraphId));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused);
- //MORE: Not sure about this, should IRoxieServerChildGraph be combined with IActivityGraph?
- loopGraph.set(GraphQuery->queryLoopGraph());
- evaluated = false;
- }
- virtual void stop()
- {
- if (loopGraph)
- loopGraph->clearGraphLoopResults();
- CRoxieServerGraphLoopActivity::stop();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!evaluated)
- {
- executeEntireGraph();
- evaluated = true;
- }
- const void * ret = resultStream->nextRow();
- if (ret)
- processed++;
- return ret;
- }
- void executeIteration(unsigned parentExtractSize, const byte *parentExtract, unsigned counter)
- {
- try
- {
- loopGraph->beforeExecute();
- createCounterResult(loopGraph, counter);
- loopGraph->executeGraphLoop(parentExtractSize, parentExtract);
- loopGraph->afterExecute();
- }
- catch (...)
- {
- CTXLOG("Exception thrown in graph body - cleaning up");
- loopGraph->afterExecute();
- throw;
- }
- }
- void createInitialGraphInput()
- {
- loopGraph->clearGraphLoopResults();
- RtlLinkedDatasetBuilder builder(rowAllocator);
- inputStream->readAll(builder);
- Owned<CGraphResult> result = new CGraphResult(builder.getcount(), builder.linkrows());
- loopGraph->setGraphLoopResult(0, result);
- }
- void executeEntireGraph()
- {
- createInitialGraphInput();
- for (unsigned loopCounter=1; loopCounter <= maxIterations; loopCounter++)
- {
- executeIteration(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), loopCounter);
- }
- resultStream.setown(loopGraph->getGraphLoopResult(maxIterations));
- }
- };
- //=================================================================================
- struct GraphOutputSplitterArg : public ccdserver_hqlhelper::CThorSplitArg
- {
- public:
- virtual unsigned numBranches()
- {
- return 0;
- }
- virtual IOutputMetaData * queryOutputMeta()
- {
- return NULL;// get it from the parent..
- }
- };
- extern "C" IHThorArg * createGraphOutputSplitter() { return new GraphOutputSplitterArg; }
- class CGraphIterationInfo : public CInterface
- {
- private:
- Owned<IRoxieServerActivityFactory> factory; // Note - before sourceAct, so destroyed last
- unsigned sourceIdx;
- Linked<IRoxieServerActivity> sourceAct;
- Linked<IFinalRoxieInput> sourceInput;
- unsigned numUses;
- unsigned iteration;
- public:
- CGraphIterationInfo(IRoxieServerActivity * _sourceAct, IFinalRoxieInput *_input, unsigned _sourceIdx, unsigned _iteration)
- : sourceAct(_sourceAct), sourceInput(_input), sourceIdx(_sourceIdx), iteration(_iteration)
- {
- numUses = 0;
- }
- inline void noteUsed()
- {
- numUses++;
- }
- void createSplitter(IRoxieSlaveContext *ctx, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
- {
- if (numUses > 1)
- {
- Owned<IPropertyTree> splitterNode = createPTree();
- factory.setown(createRoxieServerThroughSpillActivityFactory(sourceAct->queryFactory()->queryQueryFactory(), createGraphOutputSplitter, numUses, *splitterNode));
- IRoxieServerActivity *splitter = factory->createActivity(ctx, NULL);
- splitter->onCreate(NULL);
- IFinalRoxieInput *input = sourceAct->queryOutput(sourceIdx);
- if (probeManager)
- {
- IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(input), sourceAct, splitter, sourceIdx, 0, iteration);
- probes.append(*LINK(inputProbe));
- input = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
- sourceIdx = 0;
- }
- sourceAct.setown(splitter);
- sourceAct->setInput(0, sourceIdx, input);
- sourceIdx = 0;
- sourceInput.clear();
- }
- }
- IFinalRoxieInput *connectOutput(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
- {
- // MORE - not really necessary to create splitters in separate pass, is it?
- if (factory) // we created a splitter....
- sourceInput.set(sourceAct->queryOutput(sourceIdx));
- IFinalRoxieInput *ret = sourceInput;
- if (probeManager)
- {
- IRoxieProbe * inputProbe = probeManager->createProbe(sourceInput, sourceAct, targetAct, sourceIdx, targetIdx, iteration);
- probes.append(*LINK(inputProbe));
- ret = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
- // MORE - do we need to connect the stream in the probe?
- }
- if (factory) // we created a splitter....
- sourceIdx++;
- return ret;
- }
- };
- class CRoxieServerParallelGraphLoopActivity : public CRoxieServerGraphLoopActivity, implements IRoxieServerLoopResultProcessor
- {
- Owned<IActivityGraph> childGraph;
- IFinalRoxieInput * resultInput;
- IEngineRowStream * resultStream;
- Owned<IStrandJunction> resultJunction;
- CIArrayOf<CGraphIterationInfo> outputs;
- IArrayOf<IRoxieServerChildGraph> iterationGraphs;
- Owned<CExtractMapperInput> inputExtractMapper;
- IProbeManager *probeManager;
- unsigned createLoopCounter;
- IArrayOf<IRoxieProbe> probes;
- public:
- CRoxieServerParallelGraphLoopActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _GraphGraphId, IOutputMetaData * _counterMeta)
- : CRoxieServerGraphLoopActivity(_ctx, _factory, _probeManager, _GraphGraphId, _counterMeta), probeManager(_probeManager)
- {
- inputExtractMapper.setown(new CExtractMapperInput);
- resultInput = NULL;
- resultStream = NULL;
- createLoopCounter = 0;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerGraphLoopActivity::onCreate(_colocalParent);
- childGraph.set(ctx->queryChildGraph(loopGraphId));
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- //Input needs to be handled very carefully.....
- //We don't want to call onStart on the input unless it is actually used, so don't use the base CRoxieServerActivity implementation.
- //This activity's input needs to be started with (parentExtractSize, parentExtract), but the elements in the graph need to be started with the
- //GraphExtractBuilder parent extract. So we need to wrap the input in a pseudo-input (inputExtractMapper) that passes through a different
- //parentExtract. Something very similar will be needed for query library calls with streaming inputs when they are implemented.
- assertex(idx == 0);
- inputExtractMapper->setInput(_sourceIdx, _in);
- }
- virtual void connectInputStreams(bool consumerOrdered)
- {
- //NB: inputExtractMapper is not connected at this point - only if/when it is used from within the graph
- CRoxieServerActivity::connectInputStreams(consumerOrdered);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return inputExtractMapper->queryInput();
- else
- return NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerGraphLoopActivity::start(parentExtractSize, parentExtract, paused); // initialises GraphExtractBuilder
- inputExtractMapper->setParentExtract(parentExtractSize, parentExtract);
- createExpandedGraph(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), probeManager);
- resultInput->start(GraphExtractBuilder.size(), GraphExtractBuilder.getbytes(), paused);
- startJunction(resultJunction);
- }
- virtual void stop()
- {
- if (resultStream)
- resultStream->stop();
- CRoxieServerGraphLoopActivity::stop();
- }
- virtual void reset()
- {
- if (resultInput)
- resultInput->reset();
- resetJunction(resultJunction);
- resultInput = NULL;
- resultStream = NULL;
- resultJunction.clear();
- outputs.kill();
- iterationGraphs.kill(); // must be done after all activities killed
- if (probeManager)
- {
- probeManager->deleteGraph(NULL, (IArrayOf<IInputBase>*)&probes);
- probes.kill();
- }
- CRoxieServerGraphLoopActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * ret = resultStream->nextRow();
- if (ret)
- processed++;
- return ret;
- }
- void createExpandedGraph(unsigned parentExtractSize, const byte *parentExtract, IProbeManager *probeManager)
- {
- //result(0) is the input to the graph.
- resultInput = inputExtractMapper;
- outputs.append(* new CGraphIterationInfo(resultInput->queryActivity(), resultInput, 0, 1));
- for (createLoopCounter=1; createLoopCounter <= maxIterations; createLoopCounter++)
- {
- IRoxieServerChildGraph * graph = childGraph->createGraphLoopInstance(ctx, createLoopCounter, parentExtractSize, parentExtract, *this);
- graph->beforeExecute();
- iterationGraphs.append(*graph);
- graph->gatherIterationUsage(*this);
- CGraphIterationInfo *iteration = graph->selectGraphLoopOutput();
- outputs.append(*iteration);
- }
- createLoopCounter = 0;
- createSplitters(probeManager, probes);
- ForEachItemIn(i2, iterationGraphs)
- iterationGraphs.item(i2).associateIterationOutputs(*this);
- resultInput = outputs.tos().connectOutput(probeManager, probes, this, 0);
- resultStream = connectSingleStream(ctx, resultInput, 0, resultJunction, true);
- }
- void createSplitters(IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
- {
- ForEachItemIn(i, outputs)
- {
- CGraphIterationInfo & next = outputs.item(i);
- next.createSplitter(ctx, probeManager, probes);
- }
- }
- //IRoxieServerLoopResultProcessor
- virtual void noteUseIteration(unsigned _whichIteration)
- {
- int whichIteration = (int) _whichIteration; // May go negative - API is unsigned for historical reasons
- if (whichIteration >= 0)
- {
- if (!outputs.isItem(whichIteration))
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d from iteration %d", whichIteration, createLoopCounter);
- outputs.item(whichIteration).noteUsed();
- }
- }
- virtual IFinalRoxieInput* connectIterationOutput(unsigned whichIteration, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes, IRoxieServerActivity *targetAct, unsigned targetIdx)
- {
- if (outputs.isItem(whichIteration))
- {
- CGraphIterationInfo & next = outputs.item(whichIteration);
- return next.connectOutput(probeManager, probes, targetAct, targetIdx);
- }
- return NULL;
- }
- };
- //=================================================================================
- class CRoxieServerGraphLoopActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned loopGraphId;
- unsigned flags;
- Linked<IOutputMetaData> counterMeta;
- public:
- CRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), loopGraphId(_loopGraphId)
- {
- Owned<IHThorGraphLoopArg> helper = (IHThorGraphLoopArg *) helperFactory();
- flags = helper->getFlags();
- counterMeta.setown(new CCounterRowMetaData);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (kind == TAKparallelgraphloop)
- return new CRoxieServerParallelGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
- else
- return new CRoxieServerSequentialGraphLoopActivity(_ctx, this, _probeManager, loopGraphId, counterMeta);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerGraphLoopActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _loopGraphId)
- {
- return new CRoxieServerGraphLoopActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _loopGraphId);
- }
- //=====================================================================================================
- class CRoxieServerLibraryCallActivity : public CRoxieServerActivity
- {
- class OutputAdaptor : public CExtractMapperInput
- {
- bool stopped;
- public:
- CRoxieServerLibraryCallActivity *parent;
- IOutputMetaData * meta = nullptr;
- unsigned oid;
- unsigned processed;
- public:
- OutputAdaptor()
- {
- parent = NULL;
- oid = 0;
- init();
- }
- ~OutputAdaptor()
- {
- if (traceStartStop)
- DBGLOG("%p ~OutputAdaptor %d", this, oid);
- if (processed && parent && parent->factory)
- {
- parent->factory->noteProcessed(oid, processed);
- if (parent->ctx)
- parent->ctx->noteProcessed(parent->querySubgraphId(), parent->activityId, oid, processed, 0);
- }
- }
- void setParent(CRoxieServerLibraryCallActivity * _parent, IOutputMetaData * _meta, unsigned _oid)
- {
- parent = _parent;
- meta = _meta;
- oid = _oid;
- }
- void init()
- {
- processed = 0;
- stopped = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- parent->start(oid, parentExtractSize, parentExtract, paused);
- CExtractMapperInput::start(parentExtractSize, parentExtract, paused);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- //MORE value of consumerOrdered depends on whether this activity is marked as ordered.
- if (!oid) // Only need to set up once
- {
- parent->connectInputStreams(true); // To handle dependencies etc
- }
- return CExtractMapperInput::getOutputStreams(ctx, 0, streams, nullptr, true, nullptr);
- }
- //This override should not really be needed, but input is set up too late for the call to connect strands
- virtual IOutputMetaData * queryOutputMeta() const
- {
- return meta;
- }
- virtual void stop()
- {
- if (!stopped)
- {
- stopped = true;
- parent->stop(oid); // parent code relies on stop being called exactly once per adaptor, so make sure it is!
- CExtractMapperInput::stop();
- }
- };
- virtual void reset()
- {
- parent->reset(oid);
- CExtractMapperInput::reset();
- init();
- };
- virtual void checkAbort()
- {
- parent->checkAbort();
- }
- };
-
- IHThorLibraryCallArg &helper;
- unsigned numInputs;
- unsigned numOutputs;
- unsigned numActiveOutputs;
- bool started;
- OutputAdaptor* outputAdaptors;
- CExtractMapperInput * * inputAdaptors;
- bool * inputUsed;
- bool * outputUsed;
- Owned<IException> error;
- CriticalSection crit;
- rtlRowBuilder libraryExtractBuilder;
- Owned<IActivityGraph> libraryGraph;
- const LibraryCallFactoryExtra & extra;
- public:
- CRoxieServerLibraryCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, unsigned _numOutputs, const LibraryCallFactoryExtra & _extra)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorLibraryCallArg &)basehelper), extra(_extra)
- {
- numInputs = _numInputs;
- numOutputs = _numOutputs;
- numActiveOutputs = numOutputs;
- inputAdaptors = new CExtractMapperInput*[numInputs];
- inputUsed = new bool[numInputs];
- for (unsigned i1 = 0; i1 < numInputs; i1++)
- {
- inputAdaptors[i1] = new CExtractMapperInput;
- inputUsed[i1] = false;
- }
- outputAdaptors = new OutputAdaptor[numOutputs];
- outputUsed = new bool[numOutputs];
- for (unsigned i2 = 0; i2 < numOutputs; i2++)
- {
- outputAdaptors[i2].setParent(this, helper.queryOutputMeta(i2), i2);
- outputUsed[i2] = false;
- }
- started = false;
- }
- ~CRoxieServerLibraryCallActivity()
- {
- for (unsigned i1 = 0; i1 < numInputs; i1++)
- ::Release(inputAdaptors[i1]);
- delete [] inputAdaptors;
- delete [] inputUsed;
- delete [] outputAdaptors;
- delete [] outputUsed;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- libraryGraph.setown(ctx->getLibraryGraph(extra, this));
- libraryGraph->onCreate(_colocalParent);
- //Now map the inputs and outputs to the adapters
- IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
- for (unsigned i1=0; i1<numInputs; i1++)
- inputUsed[i1] = graph->querySetInputResult(i1, 0, inputAdaptors[i1]);
- for (unsigned i2=0; i2<numOutputs; i2++)
- {
- unsigned outputIndex = extra.outputs.item(i2);
- Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+outputIndex);
- outputAdaptors[i2].setInput(0, output); // MORE - no idea if this 0 is right??
- outputAdaptors[i2].connectInputStreams(ctx, true);
- }
- }
- virtual void start(unsigned oid, unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CriticalBlock b(crit);
- if (error)
- throw error.getLink();
- if (factory)
- factory->noteStarted(oid);
- if (!started)
- {
- // even though it is not complete, we don't want to run this again if it fails.
- started = true;
- //see notes on splitter above
- try
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- catch (IException *E)
- {
- #ifdef TRACE_SPLIT
- CTXLOG("spill %d caught exception in start", activityId);
- #endif
- error.set(E);
- throw;
- }
- catch (...)
- {
- IException *E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught in CRoxieServerLibraryCallActivity::start");
- error.set(E);
- throw E;
- }
- //recreate the parent extract, and use it to reinitialize the graphs...
- libraryExtractBuilder.clear();
- helper.createParentExtract(libraryExtractBuilder);
- // 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
- // some inputs before we see start on others.
- for (unsigned i1 = 0; i1 < numInputs; i1++)
- {
- if (inputUsed[i1])
- inputAdaptors[i1]->setParentExtract(parentExtractSize, parentExtract);
- else
- inputAdaptors[i1]->queryInput()->stopall();
- }
- for (unsigned i2 = 0; i2 < numOutputs; i2++)
- outputAdaptors[i2].setParentExtract(libraryExtractBuilder.size(), libraryExtractBuilder.getbytes());
- //call stop on all the unused inputs.
- IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
- graph->beforeExecute();
- ForEachItemIn(i3, extra.unusedOutputs)
- {
- Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
- output->stopall();
- }
- }
- }
- virtual void stop(unsigned oid)
- {
- CriticalBlock b(crit);
- if (--numActiveOutputs == 0)
- {
- //call stop on all the unused inputs.
- IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
- graph->beforeExecute();
- ForEachItemIn(i3, extra.unusedOutputs)
- {
- Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
- output->stopall();
- }
- CRoxieServerActivity::stop();
- }
- }
- void reset(unsigned oid)
- {
- started = false;
- error.clear();
- numActiveOutputs = numOutputs;
- if (state != STATEreset) // make sure input is only reset once
- {
- CRoxieServerActivity::reset();
- libraryGraph->reset();
- //Call reset on all unused inputs/outputs from the graph - no one else will.
- for (unsigned i1 = 0; i1 < numInputs; i1++)
- {
- if (!inputUsed[i1])
- inputAdaptors[i1]->reset();
- }
- IRoxieServerChildGraph * graph = libraryGraph->queryLoopGraph();
- ForEachItemIn(i3, extra.unusedOutputs)
- {
- Owned<IFinalRoxieInput> output = graph->selectOutput(numInputs+extra.unusedOutputs.item(i3));
- output->reset();
- }
- }
- };
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- inputAdaptors[idx]->setInput(_sourceIdx, _in);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx < numInputs && inputAdaptors[idx])
- return inputAdaptors[idx]->queryInput();
- else
- return NULL;
- }
- public:
- virtual const void *nextRow()
- {
- throwUnexpected(); // Internal logic error - we are not anybody's input
- }
- virtual IOutputMetaData * queryOutputMeta() const
- {
- throwUnexpected(); // should be called on outputs instead
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- assertex(idx!=(unsigned)-1);
- assertex(!outputUsed[idx]);
- outputUsed[idx] = true;
- return &outputAdaptors[idx];
- }
- };
- void LibraryCallFactoryExtra::set(const LibraryCallFactoryExtra & _other)
- {
- ForEachItemIn(i1, _other.outputs)
- outputs.append(_other.outputs.item(i1));
- ForEachItemIn(i2, _other.unusedOutputs)
- unusedOutputs.append(_other.unusedOutputs.item(i2));
- maxOutputs = _other.maxOutputs;
- graphid = _other.graphid;
- libraryName.set(_other.libraryName);
- embeddedGraphName.set(_other.embeddedGraphName);
- interfaceHash = _other.interfaceHash;
- embedded = _other.embedded;
- }
- void LibraryCallFactoryExtra::calcUnused()
- {
- for (unsigned i=0; i < maxOutputs; i++)
- if (!outputs.contains(i))
- unusedOutputs.append(i);
- }
- class CRoxieServerLibraryCallActivityFactory : public CRoxieServerMultiOutputFactory
- {
- private:
- CRoxieServerMultiInputInfo inputs;
- LibraryCallFactoryExtra extra;
- public:
- CRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
- : CRoxieServerMultiOutputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- extra.set(_extra);
- extra.calcUnused();
- setNumOutputs(extra.outputs.ordinality());
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLibraryCallActivity(_ctx, this, _probeManager, numInputs(), numOutputs, extra);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- inputs.set(idx, source, sourceidx);
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- return inputs.get(idx, sourceidx);
- }
- virtual unsigned numInputs() const { return inputs.ordinality(); }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- addXrefLibraryInfo(reply, extra.libraryName);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLibraryCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, LibraryCallFactoryExtra & _extra)
- {
- return new CRoxieServerLibraryCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _extra);
- }
- //=====================================================================================================
- // CRoxieServerNWayInputActivity is a multi-input, multi-output activity, where the outputs are a subset of the inputs
- // Used to implement RANGE(<rowset-expression>, [set-of-indices])
- class CRoxieServerNWayInputBaseActivity : public CRoxieServerMultiInputBaseActivity
- {
- protected:
- PointerArrayOf<IFinalRoxieInput> selectedInputs;
- PointerArrayOf<IEngineRowStream> selectedStreams;
- PointerArrayOf<IStrandJunction> selectedJunctions;
- public:
- CRoxieServerNWayInputBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- }
- virtual void stop()
- {
- ForEachItemIn(i2, selectedStreams)
- selectedStreams.item(i2)->stop();
- CRoxieServerMultiInputBaseActivity::stop();
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 localCycles = totalCycles.totalCycles;
- ForEachItemIn(i, selectedInputs)
- {
- localCycles -= selectedInputs.item(i)->queryTotalCycles();
- }
- if (localCycles < 0)
- localCycles = 0;
- return localCycles;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (selectedInputs.isItem(idx))
- return selectedInputs.item(idx);
- else
- return NULL;
- }
- virtual void reset()
- {
- ForEachItemIn(i, selectedInputs)
- selectedInputs.item(i)->reset();
- selectedInputs.kill();
- selectedStreams.kill();
- selectedJunctions.kill();
- CRoxieServerMultiInputBaseActivity::reset();
- }
- virtual const void * nextRow()
- {
- throwUnexpected();
- }
- virtual unsigned numConcreteOutputs() const
- {
- return selectedInputs.ordinality();
- }
- virtual IFinalRoxieInput * queryConcreteInput(unsigned idx)
- {
- return queryInput(idx);
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput)
- {
- if (selectedStreams.isItem(whichInput))
- return selectedStreams.item(whichInput);
- return NULL;
- }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const
- {
- if (selectedJunctions.isItem(idx))
- return selectedJunctions.item(idx);
- return NULL;
- }
- };
- class CRoxieServerNWayInputActivity : public CRoxieServerNWayInputBaseActivity
- {
- IHThorNWayInputArg & helper;
- public:
- CRoxieServerNWayInputActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorNWayInputArg &)basehelper)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerNWayInputBaseActivity::start(parentExtractSize, parentExtract, paused);
- bool selectionIsAll;
- size32_t selectionLen;
- rtlDataAttr selection;
- helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
- selectedInputs.kill();
- selectedStreams.kill();
- selectedJunctions.kill();
- assertex(numInputs==numStreams); // Will need refactoring when that ceases to be true
- if (selectionIsAll)
- {
- for (unsigned i=0; i < numInputs; i++)
- {
- selectedInputs.append(inputArray[i]);
- selectedStreams.append(streamArray[i]); // Assumes 1:1 relationship - is that good?
- selectedJunctions.append(junctionArray[i]);
- }
- }
- else
- {
- const size32_t * selections = (const size32_t *)selection.getdata();
- unsigned max = selectionLen/sizeof(size32_t);
- for (unsigned i = 0; i < max; i++)
- {
- unsigned nextIndex = selections[i];
- //Check there are no duplicates..... Assumes there are a fairly small number of inputs, so n^2 search is ok.
- for (unsigned j=i+1; j < max; j++)
- {
- if (nextIndex == selections[j])
- throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Selection list for nway input can not contain duplicates");
- }
- if (nextIndex > numInputs || nextIndex > numStreams)
- throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "Index %d in RANGE selection list is out of range", nextIndex);
- selectedInputs.append(inputArray[nextIndex-1]);
- selectedStreams.append(streamArray[nextIndex-1]); // Assumes 1:1 relationship - is that good?
- selectedJunctions.append(junctionArray[nextIndex-1]);
- }
- }
- // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs and selectedJunctions
- }
- virtual void stop()
- {
- // NB: Whatever pulls this nwayinput activity, starts and stops the selectedInputs
- }
- };
- class CRoxieServerNWayInputActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNWayInputActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNWayInputActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNWayInputActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerNWayGraphLoopResultReadActivity : public CRoxieServerNWayInputBaseActivity
- {
- IHThorNWayGraphLoopResultReadArg & helper;
- IArrayOf<IRoxieServerActivity> resultReaders;
- Owned<IStrandJunction> *resultJunctions;
- unsigned graphId;
- bool grouped;
- bool selectionIsAll;
- size32_t selectionLen;
- rtlDataAttr selection;
- public:
- CRoxieServerNWayGraphLoopResultReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _graphId)
- : CRoxieServerNWayInputBaseActivity(_ctx, _factory, _probeManager, 0), helper((IHThorNWayGraphLoopResultReadArg &)basehelper)
- {
- grouped = helper.isGrouped();
- graphId = _graphId;
- selectionIsAll = false;
- selectionLen = 0;
- resultJunctions = NULL;
- }
- ~CRoxieServerNWayGraphLoopResultReadActivity()
- {
- delete [] resultJunctions;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (selectedInputs.ordinality() == 0)
- {
- initInputSelection();
- unsigned max = selectionLen / sizeof(size32_t);
- const size32_t * selections = (const size32_t *)selection.getdata();
- IProbeManager * probeManager = NULL; // MORE!!
- for (unsigned i = 0; i < max; i++)
- {
- CRoxieServerActivity * resultInput = new CRoxieServerInternalGraphLoopResultReadActivity(ctx, factory, probeManager, graphId, selections[i]);
- resultReaders.append(*resultInput);
- selectedInputs.append(resultInput);
- resultInput->onCreate(colocalParent);
- resultInput->start(parentExtractSize, parentExtract, paused);
- selectedStreams.append(connectSingleStream(ctx, resultInput, 0, resultJunctions[i], true));
- selectedJunctions.append(resultJunctions[i]);
- }
- }
- }
- virtual void reset()
- {
- resultReaders.kill();
- CRoxieServerNWayInputBaseActivity::reset();
- ForEachItemIn(i, selectedStreams)
- resetJunction(resultJunctions[i]);
- }
- virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract)
- {
- ensureCreated();
- basehelper.onStart(parentExtract, NULL);
- initInputSelection();
- unsigned max = selectionLen / sizeof(size32_t);
- const size32_t * selections = (const size32_t *)selection.getdata();
- for (unsigned i = 0; i < max; i++)
- processor.noteUseIteration(selections[i]);
- }
- virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor, unsigned parentExtractSize, const byte * parentExtract, IProbeManager *probeManager, IArrayOf<IRoxieProbe> &probes)
- {
- //selection etc. already initialised from the gatherIterationUsage() call.
- unsigned max = selectionLen / sizeof(size32_t);
- const size32_t * selections = (const size32_t *)selection.getdata();
- resultJunctions = new Owned<IStrandJunction> [max];
- for (unsigned i = 0; i < max; i++)
- {
- IFinalRoxieInput *in = processor.connectIterationOutput(selections[i], probeManager, probes, this, i);
- selectedInputs.append(in);
- selectedStreams.append(connectSingleStream(ctx, in, 0, resultJunctions[i], true));
- selectedJunctions.append(resultJunctions[i]);
- }
- }
- protected:
- void initInputSelection()
- {
- helper.getInputSelection(selectionIsAll, selectionLen, selection.refdata());
- if (selectionIsAll)
- throw MakeStringException(ROXIE_NWAY_INPUT_ERROR, "ALL not yet supported for NWay graph inputs");
- }
- };
- class CRoxieServerNWayGraphLoopResultReadActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned graphId;
- public:
- CRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _graphId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), graphId(_graphId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNWayGraphLoopResultReadActivity(_ctx, this, _probeManager, graphId);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for NWay GraphLoopResultRead activity");
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNWayGraphLoopResultReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned graphId)
- {
- return new CRoxieServerNWayGraphLoopResultReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, graphId);
- }
- //=================================================================================
- class RoxieSteppedInput : implements ISteppedInput, public CInterface
- {
- public:
- RoxieSteppedInput(IFinalRoxieInput * _input, IEngineRowStream *_stream) { input = _input; inputStream = _stream; }
- IMPLEMENT_IINTERFACE
- protected:
- virtual const void * nextInputRow()
- {
- #ifdef TRACE_SEEK_REQUESTS
- IRoxieContextLogger * logger = input->queryActivity();
- const void * ret = doNextInputRow();
- {
- CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
- if (!ret)
- xmlwrite.outputBool(true,"eof");
- else if (input->queryOutputMeta()->hasXML())
- input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
- logger->CTXLOG("next() returns (%s)", xmlwrite.str());
- }
- return ret;
- #else
- return inputStream->ungroupedNextRow();
- #endif
- }
- virtual const void * nextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- #ifdef TRACE_SEEK_REQUESTS
- IRoxieContextLogger * logger = input->queryActivity();
- {
- CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
- if (input->queryOutputMeta()->hasXML())
- input->queryOutputMeta()->toXML((byte *) seek, xmlwrite);
- logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) seek(%s)",
- numFields,
- stepExtra.readAheadManyResults() ? "readahead " : "",
- stepExtra.returnMismatches() ? "mismatch" : "exact",
- stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
- stepExtra.queryExtraSeeks() ? "multi-seek":"",
- xmlwrite.str());
- }
- const void * ret = doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- {
- CommonXmlWriter xmlwrite(XWFtrim|XWFopt|XWFnoindent);
- if (!ret)
- xmlwrite.outputBool(true,"eof");
- else if (input->queryOutputMeta()->hasXML())
- input->queryOutputMeta()->toXML((byte *) ret, xmlwrite);
- logger->CTXLOG("nextInputRowGE(%d, %s%s%s, %s) result(%s)",
- numFields,
- stepExtra.readAheadManyResults() ? "readahead " : "",
- stepExtra.returnMismatches() ? "mismatch" : "exact",
- stepExtra.onlyReturnFirstSeekMatch() ? " single-match" : "",
- stepExtra.queryExtraSeeks() ? "multi-seek":"",
- xmlwrite.str());
- }
- return ret;
- #else
- return doNextInputRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- #endif
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- virtual IInputSteppingMeta * queryInputSteppingMeta()
- {
- return input->querySteppingMeta();
- }
- inline const void * doNextInputRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- assertex(wasCompleteMatch);
- return inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- }
- protected:
- IFinalRoxieInput * input;
- IEngineRowStream * inputStream;
- };
- //=================================================================================
- class CRoxieServerNWayBaseActivity : public CRoxieServerMultiInputBaseActivity
- {
- public:
- CRoxieServerNWayBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- }
- void startExpandedInputs(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- ForEachItemIn(ei, expandedInputs)
- expandedInputs.item(ei)->start(parentExtractSize, parentExtract, paused);
- ForEachItemIn(idx, expandedInputs)
- startJunction(expandedJunctions.item(idx));
- }
- virtual void stop()
- {
- ForEachItemIn(i, expandedStreams)
- expandedStreams.item(i)->stop();
- CRoxieServerMultiInputBaseActivity::stop();
- }
- virtual void reset()
- {
- ForEachItemIn(idx, expandedInputs)
- resetJunction(expandedJunctions.item(idx));
- expandedInputs.kill();
- expandedStreams.kill();
- expandedJunctions.kill();
- CRoxieServerMultiInputBaseActivity::reset();
- }
- protected:
- PointerArrayOf<IFinalRoxieInput> expandedInputs;
- PointerArrayOf<IEngineRowStream> expandedStreams;
- PointerArrayOf<IStrandJunction> expandedJunctions;
- };
- //=================================================================================
- class CRoxieServerNaryActivity : public CRoxieServerNWayBaseActivity
- {
- public:
- CRoxieServerNaryActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
- for (unsigned i=0; i < numInputs; i++)
- {
- IFinalRoxieInput * cur = inputArray[i];
- CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
- if (nWayInput)
- {
- nWayInput->start(parentExtractSize, parentExtract, paused);
- unsigned numRealInputs = cur->numConcreteOutputs();
- for (unsigned j = 0; j < numRealInputs; j++)
- {
- expandedInputs.append(cur->queryConcreteInput(j));
- expandedStreams.append(cur->queryConcreteOutputStream(j));
- expandedJunctions.append(cur->queryConcreteOutputJunction(j));
- }
- }
- else
- {
- expandedInputs.append(cur);
- // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
- expandedStreams.append(queryConcreteOutputStream(i));
- expandedJunctions.append(queryConcreteOutputJunction(i));
- }
- }
- startExpandedInputs(parentExtractSize, parentExtract, paused);
- }
- };
- //=================================================================================
- class CRoxieStreamMerger : public CStreamMerger
- {
- public:
- CRoxieStreamMerger() : CStreamMerger(true)
- {
- streamArray = NULL;
- }
- void initInputs(unsigned _numInputs, IEngineRowStream ** _streamArray)
- {
- CStreamMerger::initInputs(_numInputs);
- streamArray = _streamArray;
- }
- virtual bool pullInput(unsigned i, const void * seek, unsigned numFields, const SmartStepExtra * stepExtra)
- {
- const void * next;
- bool matches = true;
- if (seek)
- next = streamArray[i]->nextRowGE(seek, numFields, matches, *stepExtra);
- else
- next = streamArray[i]->ungroupedNextRow();
- pending[i] = next;
- pendingMatches[i] = matches;
- return (next != NULL);
- }
- virtual void releaseRow(const void * row)
- {
- ReleaseRoxieRow(row);
- }
- protected:
- IEngineRowStream **streamArray;
- };
- class CRoxieServerNWayMergeActivity : public CRoxieServerNaryActivity
- {
- public:
- CRoxieServerNWayMergeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),
- helper((IHThorNWayMergeArg &)basehelper)
- {
- initializedMeta = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
- merger.init(helper.queryCompare(), helper.dedup(), helper.querySteppingMeta()->queryCompare());
- merger.initInputs(expandedStreams.length(), expandedStreams.getArray());
- }
- virtual void stop()
- {
- merger.done();
- CRoxieServerNaryActivity::stop();
- }
- virtual void reset()
- {
- merger.cleanup();
- CRoxieServerNaryActivity::reset();
- initializedMeta = false;
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = merger.nextRow();
- if (next)
- processed++;
- return next;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool & wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = merger.nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (next)
- processed++;
- return next;
- }
- virtual IInputSteppingMeta * querySteppingMeta()
- {
- if (expandedStreams.ordinality() == 0)
- return NULL;
- if (!initializedMeta)
- {
- meta.init(helper.querySteppingMeta(), false);
- ForEachItemIn(i, expandedStreams)
- {
- if (meta.getNumFields() == 0)
- break;
- IInputSteppingMeta * inputMeta = expandedInputs.item(i)->querySteppingMeta();
- meta.intersect(inputMeta);
- }
- initializedMeta = true;
- }
- if (meta.getNumFields() == 0)
- return NULL;
- return &meta;
- }
- protected:
- IHThorNWayMergeArg &helper;
- CRoxieStreamMerger merger;
- CSteppingMeta meta;
- bool initializedMeta;
- };
- class CRoxieServerNWayMergeActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNWayMergeActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNWayMergeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNWayMergeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNWayMergeJoinActivity : public CRoxieServerNaryActivity
- {
- public:
- CRoxieServerNWayMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs, CMergeJoinProcessor & _processor)
- : CRoxieServerNaryActivity(_ctx, _factory, _probeManager, _numInputs),processor(_processor),
- helper((IHThorNWayMergeJoinArg &)basehelper)
- {
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerNaryActivity::onCreate(_colocalParent);
- ICodeContext * codectx = ctx->queryCodeContext();
- inputAllocator.setown(createRowAllocator(helper.queryInputMeta()));
- outputAllocator.setown(createRowAllocator(helper.queryOutputMeta()));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerNaryActivity::start(parentExtractSize, parentExtract, paused);
- ForEachItemIn(i1, expandedInputs)
- {
- Owned<RoxieSteppedInput> stepInput = new RoxieSteppedInput(expandedInputs.item(i1), expandedStreams.item(i1));
- processor.addInput(stepInput);
- }
- processor.beforeProcessing(inputAllocator, outputAllocator);
- }
- virtual void stop()
- {
- processor.afterProcessing();
- CRoxieServerNaryActivity::stop();
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return processor.gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- processor.queryResetEOF();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = processor.nextRow();
- if (next)
- processed++;
- return next;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * next = processor.nextGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (next)
- processed++;
- return next;
- }
- virtual IInputSteppingMeta * querySteppingMeta()
- {
- return processor.queryInputSteppingMeta();
- }
- protected:
- IHThorNWayMergeJoinArg & helper;
- CMergeJoinProcessor & processor;
- Owned<IEngineRowAllocator> inputAllocator;
- Owned<IEngineRowAllocator> outputAllocator;
- };
- class CRoxieServerAndMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
- {
- public:
- CRoxieServerAndMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andProcessor), andProcessor(helper)
- {
- }
- protected:
- CAndMergeJoinProcessor andProcessor;
- };
- class CRoxieServerAndLeftMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
- {
- public:
- CRoxieServerAndLeftMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, andLeftProcessor), andLeftProcessor(helper)
- {
- }
- protected:
- CAndLeftMergeJoinProcessor andLeftProcessor;
- };
- class CRoxieServerMofNMergeJoinActivity : public CRoxieServerNWayMergeJoinActivity
- {
- public:
- CRoxieServerMofNMergeJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, mofnProcessor), mofnProcessor(helper)
- {
- }
- protected:
- CMofNMergeJoinProcessor mofnProcessor;
- };
- class CRoxieServerProximityJoinActivity : public CRoxieServerNWayMergeJoinActivity
- {
- public:
- CRoxieServerProximityJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayMergeJoinActivity(_ctx, _factory, _probeManager, _numInputs, proximityProcessor), proximityProcessor(helper)
- {
- }
- protected:
- CProximityJoinProcessor proximityProcessor;
- };
- class CRoxieServerNWayMergeJoinActivityFactory : public CRoxieServerMultiInputFactory
- {
- unsigned flags;
- public:
- CRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorNWayMergeJoinArg> helper = (IHThorNWayMergeJoinArg *) helperFactory();
- flags = helper->getJoinFlags();
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (flags & IHThorNWayMergeJoinArg::MJFhasrange)
- return new CRoxieServerProximityJoinActivity(_ctx, this, _probeManager, numInputs());
- switch (flags & IHThorNWayMergeJoinArg::MJFkindmask)
- {
- case IHThorNWayMergeJoinArg::MJFinner:
- return new CRoxieServerAndMergeJoinActivity(_ctx, this, _probeManager, numInputs());
- case IHThorNWayMergeJoinArg::MJFleftonly:
- case IHThorNWayMergeJoinArg::MJFleftouter:
- return new CRoxieServerAndLeftMergeJoinActivity(_ctx, this, _probeManager, numInputs());
- case IHThorNWayMergeJoinArg::MJFmofn:
- return new CRoxieServerMofNMergeJoinActivity(_ctx, this, _probeManager, numInputs());
- default:
- throwUnexpected();
- }
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNWayMergeJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNWayMergeJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerNWaySelectActivity : public CRoxieServerNWayBaseActivity
- {
- IHThorNWaySelectArg &helper;
- public:
- CRoxieServerNWaySelectActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerNWayBaseActivity(_ctx, _factory, _probeManager, _numInputs),
- helper((IHThorNWaySelectArg &)basehelper)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerNWayBaseActivity::start(parentExtractSize, parentExtract, paused);
- unsigned whichInput = helper.getInputIndex();
- selectedInput = nullptr;
- selectedStream = nullptr;
- if (whichInput--)
- {
- for (unsigned i=0; i < numInputs; i++)
- {
- IFinalRoxieInput * cur = inputArray[i];
- CRoxieServerNWayInputBaseActivity *nWayInput = dynamic_cast<CRoxieServerNWayInputBaseActivity *>(cur);
- if (nWayInput)
- {
- nWayInput->start(parentExtractSize, parentExtract, paused);
- unsigned numRealInputs = cur->numConcreteOutputs();
- if (whichInput < numRealInputs)
- {
- expandedInputs.append(cur->queryConcreteInput(whichInput));
- expandedStreams.append(cur->queryConcreteOutputStream(whichInput));
- expandedJunctions.append(cur->queryConcreteOutputJunction(whichInput));
- break;
- }
- whichInput -= numRealInputs;
- }
- else
- {
- if (whichInput == 0)
- {
- expandedInputs.append(cur);
- // NB: this activities input streams + junction have been setup and held in CRoxieServerMultiInputActivity base
- expandedStreams.append(queryConcreteOutputStream(i));
- expandedJunctions.append(queryConcreteOutputJunction(i));
- break;
- }
- whichInput -= 1;
- }
- }
- }
- if (expandedInputs.ordinality())
- {
- startExpandedInputs(parentExtractSize, parentExtract, paused);
- selectedInput = expandedInputs.item(0);
- selectedStream = expandedStreams.item(0);
- }
- }
- const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!selectedStream)
- return NULL;
- return selectedStream->nextRow();
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- if (!selectedInput)
- return false;
- return selectedInput->gatherConjunctions(collector);
- }
-
- virtual void resetEOF()
- {
- if (selectedStream)
- selectedStream->resetEOF();
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!selectedStream)
- return NULL;
- return selectedStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- if (selectedInput)
- return selectedInput->querySteppingMeta();
- return NULL;
- }
- protected:
- IFinalRoxieInput * selectedInput = nullptr;
- IEngineRowStream * selectedStream = nullptr;
- Owned<IStrandJunction> selectedJunction;
- };
- class CRoxieServerNWaySelectActivityFactory : public CRoxieServerMultiInputFactory
- {
- public:
- CRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerNWaySelectActivity(_ctx, this, _probeManager, numInputs());
- }
- };
- IRoxieServerActivityFactory *createRoxieServerNWaySelectActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerNWaySelectActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerRemoteActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
- {
- protected:
- IHThorRemoteArg &helper;
- CRemoteResultAdaptor remote;
- public:
- CRoxieServerRemoteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteID)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorRemoteArg &)basehelper),
- remote(_ctx, this, _remoteID, meta.queryOriginal(), helper, *this, false, false) // MORE - if they need it stable we'll have to think!
- {
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return NULL;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- remote.onCreate(_colocalParent);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- remote.onStart(parentExtractSize, parentExtract);
- remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
- unsigned fileNo = 0; // MORE - superfiles require us to do this per file part... maybe (needs thought)
- remote.getMem(0, fileNo, 0); // the cached context is all we need to send
- remote.flush();
- remote.senddone();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL: &remote;
- }
- virtual void reset()
- {
- processed = remote.processed;
- remote.processed = 0;
- CRoxieServerActivity::reset();
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- helper.onLimitExceeded();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- UNIMPLEMENTED; // MORE - is there an ONFAIL for a limit folded into a remote?
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CRoxieServerRemoteActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- RemoteActivityId remoteId;
- bool isRoot;
- CRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerRemoteActivity(_ctx, this, _probeManager, remoteId);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
- }
- virtual bool isSink() const
- {
- //I don't think the action version of this is implemented - but this would be the code
- return isRoot && !meta.queryOriginal();
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return allStatistics; // Child queries...
- }
- };
- IRoxieServerActivityFactory *createRoxieServerRemoteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, bool _isRoot)
- {
- return new CRoxieServerRemoteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _isRoot);
- }
- //=================================================================================
- class CRoxieServerIterateActivity : public CRoxieServerActivity
- {
- IHThorIterateArg &helper;
- OwnedConstRoxieRow defaultRecord;
- OwnedConstRoxieRow left;
- OwnedConstRoxieRow right;
- unsigned counter;
- public:
- CRoxieServerIterateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorIterateArg &)basehelper)
- {
- counter = 0;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- counter = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = helper.createDefault(rowBuilder);
- defaultRecord.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- virtual void reset()
- {
- defaultRecord.clear();
- right.clear();
- left.clear();
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- right.setown(inputStream->nextRow());
- if (!right)
- {
- bool skippedGroup = (left == NULL) && (counter > 0); //we have just skipped entire group, but shouldn't output a double null
- left.clear();
- counter = 0;
- if (skippedGroup) continue;
- return NULL;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.transform(rowBuilder, left ? left : defaultRecord, right, ++counter);
- if (outSize)
- {
- left.setown(rowBuilder.finalizeRowClear(outSize));
- processed++;
- return left.getLink();
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- };
- class CRoxieServerIterateActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerIterateActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIterateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerIterateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerProcessActivity : public CRoxieServerActivity
- {
- IHThorProcessArg &helper;
- OwnedConstRoxieRow curRight;
- OwnedConstRoxieRow initialRight;
- unsigned counter;
- Owned<IEngineRowAllocator> rightRowAllocator;
- public:
- CRoxieServerProcessActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorProcessArg &)basehelper)
- {
- counter = 0;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- rightRowAllocator.setown(createRowAllocator(helper.queryRightRecordSize()));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- counter = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- RtlDynamicRowBuilder rowBuilder(rightRowAllocator);
- size32_t thisSize = helper.createInitialRight(rowBuilder);
- initialRight.setown(rowBuilder.finalizeRowClear(thisSize));
- curRight.set(initialRight);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- try
- {
- loop
- {
- const void * in = inputStream->nextRow();
- if (!in)
- {
- bool eog = (curRight != initialRight); // processed any records?
- counter = 0;
- curRight.set(initialRight);
- if (eog)
- return NULL;
- in = inputStream->nextRow();
- if (!in)
- return NULL;
- }
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- RtlDynamicRowBuilder rightRowBuilder(rightRowAllocator);
- size32_t outSize = helper.transform(rowBuilder, rightRowBuilder, in, curRight, ++counter);
- ReleaseRoxieRow(in);
- if (outSize)
- {
- //MORE: This should be returned...
- size32_t rightSize = rightRowAllocator->queryOutputMeta()->getRecordSize(rightRowBuilder.getSelf());
- curRight.setown(rightRowBuilder.finalizeRowClear(rightSize));
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- };
- class CRoxieServerProcessActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerProcessActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerProcessActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerProcessActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerGroupActivity : public CRoxieServerActivity
- {
- IHThorGroupArg &helper;
- bool endPending;
- bool eof;
- bool first;
- unsigned numGroups;
- unsigned numGroupMax;
- unsigned numProcessedLastGroup;
- const void *next;
- public:
- CRoxieServerGroupActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorGroupArg &)basehelper)
- {
- next = NULL;
- endPending = false;
- eof = false;
- first = true;
- numGroups = 0;
- numGroupMax = 0;
- numProcessedLastGroup = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- endPending = false;
- eof = false;
- first = true;
- numGroups = 0;
- numGroupMax = 0;
- numProcessedLastGroup = processed;
- assertex(next == NULL);
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- noteStatistic(StNumGroups, numGroups);
- noteStatistic(StNumGroupMax, numGroupMax);
- ReleaseClearRoxieRow(next);
- CRoxieServerActivity::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (first)
- {
- next = inputStream->nextRow();
- first = false;
- }
- if (eof || endPending)
- {
- endPending = false;
- return NULL;
- }
- const void * prev = next;
- next = inputStream->ungroupedNextRow();
- if (next)
- {
- assertex(prev);
- if (!helper.isSameGroup(prev, next))
- {
- noteEndOfGroup();
- endPending = true;
- }
- }
- else
- {
- noteEndOfGroup();
- eof = true;
- }
- if (prev)
- processed++;
- return prev;
- }
- inline void noteEndOfGroup()
- {
- unsigned numThisGroup = processed - numProcessedLastGroup;
- if (numThisGroup == 0)
- return;
- numProcessedLastGroup = processed;
- if (numThisGroup > numGroupMax)
- numGroupMax = numThisGroup;
- numGroups++;
- }
- };
- class CRoxieServerGroupActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerGroupActivity(_ctx, this, _probeManager);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return groupStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerGroupActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerGroupActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerFirstNActivity : public CRoxieServerLateStartActivity
- {
- unsigned __int64 limit;
- unsigned __int64 skip;
- unsigned doneThisGroup;
- IHThorFirstNArg &helper;
- public:
- CRoxieServerFirstNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorFirstNArg &)basehelper)
- {
- doneThisGroup = 0;
- limit = 0;
- skip = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- doneThisGroup = 0;
- CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
- limit = helper.getLimit();
- skip = helper.numToSkip();
- lateStart(parentExtractSize, parentExtract, limit > 0);
- if (limit + skip >= limit)
- limit += skip;
- }
- const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- const void *ret;
- loop
- {
- ret = inputStream->nextRow();
- if (!ret)
- {
- if (meta.isGrouped())
- {
- if (doneThisGroup > skip)
- {
- doneThisGroup = 0;
- return NULL;
- }
- doneThisGroup = 0;
- }
- ret = inputStream->nextRow();
- if (!ret)
- {
- eof = true;
- return NULL;
- }
- }
- doneThisGroup++;
- if (doneThisGroup > skip)
- break;
- ReleaseRoxieRow(ret);
- }
- if (doneThisGroup <= limit)
- {
- processed++;
- return ret;
- }
- ReleaseRoxieRow(ret);
- if (meta.isGrouped())
- {
- while ((ret = inputStream->nextRow()) != NULL)
- ReleaseRoxieRow(ret);
- doneThisGroup = 0;
- }
- else
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerFirstNActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerFirstNActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerFirstNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerFirstNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSelectNActivity : public CRoxieServerActivity
- {
- bool done;
- IHThorSelectNArg &helper;
- public:
- CRoxieServerSelectNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSelectNArg &)basehelper)
- {
- done = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- const void *defaultRow()
- {
- if (!rowAllocator)
- ensureRowAllocator(); // We delay as often not needed...
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = helper.createDefault(rowBuilder);
- return rowBuilder.finalizeRowClear(thisSize);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done)
- return NULL;
- done = true;
- processed++; // always going to return a row!
- unsigned __int64 index = helper.getRowToSelect();
- while (--index)
- {
- const void * next = inputStream->ungroupedNextRow();
- if (!next)
- return defaultRow();
- ReleaseRoxieRow(next);
- }
- const void * next = inputStream->ungroupedNextRow();
- if (!next)
- next = defaultRow();
- return next;
- }
- };
- class CRoxieServerSelectNActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSelectNActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSelectNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSelectNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerSelfJoinActivity : public CRoxieServerActivity
- {
- IHThorJoinArg &helper;
- ICompare *collate;
- OwnedRowArray group;
- bool matchedLeft;
- BoolArray matchedRight;
- bool eof;
- bool first;
- unsigned leftIndex;
- unsigned rightIndex;
- unsigned rightOuterIndex;
- unsigned joinLimit;
- unsigned atmostLimit;
- unsigned atmostsTriggered;
- unsigned abortLimit;
- unsigned keepLimit;
- unsigned joinCounter;
- bool leftOuterJoin;
- bool rightOuterJoin;
- bool exclude;
- bool limitFail;
- bool limitOnFail;
- bool cloneLeft;
- bool forceSpill;
- OwnedConstRoxieRow defaultLeft;
- OwnedConstRoxieRow defaultRight;
- OwnedConstRoxieRow lhs;
- Owned<IException> failingLimit;
- bool failingOuterAtmost;
- Owned<IEngineRowAllocator> defaultAllocator;
- Owned<IRHLimitedCompareHelper> limitedhelper;
- Owned<CRHDualCache> dualcache;
- Owned<IGroupedInput> groupedInput;
- IRowStream *dualCacheInput;
- bool fillGroup()
- {
- group.clear();
- matchedLeft = false;
- matchedRight.kill();
- failingOuterAtmost = false;
- const void * next;
- unsigned groupCount = 0;
- while((next = groupedInput->nextRow()) != NULL)
- {
- if(groupCount==abortLimit)
- {
- if(limitFail)
- failLimit(next);
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if(limitOnFail)
- {
- assertex(!failingLimit);
- try
- {
- failLimit(next);
- }
- catch(IException * except)
- {
- failingLimit.setown(except);
- }
- assertex(failingLimit != NULL);
- group.append(next);
- groupCount++;
- break;
- }
- group.clear();
- groupCount = 0;
- while(next)
- {
- ReleaseRoxieRow(next);
- next = groupedInput->nextRow();
- }
- }
- else if(groupCount==atmostLimit)
- {
- atmostsTriggered++;
- if(leftOuterJoin)
- {
- group.append(next);
- groupCount++;
- failingOuterAtmost = true;
- break;
- }
- else
- {
- group.clear();
- groupCount = 0;
- while (next)
- {
- ReleaseRoxieRow(next);
- next = groupedInput->nextRow();
- }
- }
- }
- else
- {
- group.append(next);
- groupCount++;
- }
- }
- if(group.ordinality()==0)
- {
- eof = true;
- return false;
- }
- leftIndex = 0;
- rightIndex = 0;
- rightOuterIndex = 0;
- joinCounter = 0;
- joinLimit = keepLimit;
- ForEachItemIn(idx, group)
- matchedRight.append(false);
- return true;
- }
- void failLimit(const void * next)
- {
- helper.onMatchAbortLimitExceeded();
- CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
- if (!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
- {
- input->queryOutputMeta()->toXML((byte *) next, xmlwrite);
- }
- throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %d match candidates in self-join %d for row %s", abortLimit, queryId(), xmlwrite.str());
- }
- virtual bool needsAllocator() const { return true; }
- const void *joinRecords(const void * curLeft, const void * curRight, unsigned counter, IException * except)
- {
- try
- {
- if (cloneLeft && !except)
- {
- LinkRoxieRow(curLeft);
- return curLeft;
- }
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outsize = except ? helper.onFailTransform(rowBuilder, curLeft, curRight, except) : helper.transform(rowBuilder, curLeft, curRight, counter);
- if (outsize)
- return rowBuilder.finalizeRowClear(outsize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- void createDefaultLeft()
- {
- if (!defaultLeft)
- {
- if (!defaultAllocator)
- defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultAllocator);
- size32_t thisSize = helper.createDefaultLeft(rowBuilder);
- defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- void createDefaultRight()
- {
- if (!defaultRight)
- {
- if (!defaultAllocator)
- defaultAllocator.setown(createRowAllocator(input->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultAllocator);
- size32_t thisSize = helper.createDefaultRight(rowBuilder);
- defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- public:
- CRoxieServerSelfJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _forceSpill)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorJoinArg &)basehelper), forceSpill(_forceSpill)
- {
- collate = helper.queryCompareLeftRight();
- eof = false;
- first = true;
- keepLimit = 0;
- atmostLimit = 0;
- atmostsTriggered = 0;
- unsigned joinFlags = helper.getJoinFlags();
- leftOuterJoin = (joinFlags & JFleftouter) != 0;
- rightOuterJoin = (joinFlags & JFrightouter) != 0;
- cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
- exclude = (joinFlags & JFexclude) != 0;
- abortLimit = 0;
- joinLimit = 0;
- assertex((joinFlags & (JFfirst | JFfirstleft | JFfirstright)) == 0); // no longer supported
- getLimitType(joinFlags, limitFail, limitOnFail);
- if((joinFlags & JFslidingmatch) != 0)
- throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Internal Error: Sliding self join not supported");
- failingOuterAtmost = false;
- matchedLeft = false;
- leftIndex = 0;
- rightIndex = 0;
- rightOuterIndex = 0;
- joinCounter = 0;
- dualCacheInput = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- first = true;
- failingLimit.clear();
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- keepLimit = helper.getKeepLimit();
- if(keepLimit == 0)
- keepLimit = (unsigned)-1;
- atmostsTriggered = 0;
- atmostLimit = helper.getJoinLimit();
- if(atmostLimit == 0)
- atmostLimit = (unsigned)-1;
- else
- assertex(!rightOuterJoin);
- abortLimit = helper.getMatchAbortLimit();
- if (abortLimit == 0)
- abortLimit = (unsigned)-1;
- if (rightOuterJoin)
- createDefaultLeft();
- if (leftOuterJoin || limitOnFail)
- createDefaultRight();
- ICompare *compareLeft = helper.queryCompareLeft();
- if (helper.isLeftAlreadySorted())
- groupedInput.setown(createGroupedInputReader(inputStream, compareLeft));
- else
- {
- bool isStable = (helper.getJoinFlags() & JFunstable) == 0;
- RoxieSortAlgorithm sortAlgorithm;
- if (forceSpill)
- sortAlgorithm = isStable ? stableSpillingQuickSortAlgorithm : spillingQuickSortAlgorithm;
- else
- sortAlgorithm = isStable ? stableQuickSortAlgorithm : quickSortAlgorithm;
- groupedInput.setown(createSortedGroupedInputReader(inputStream, compareLeft, createSortAlgorithm(sortAlgorithm, compareLeft, ctx->queryRowManager(), input->queryOutputMeta(), ctx->queryCodeContext(), tempDirectory, activityId)));
- }
- if ((helper.getJoinFlags() & JFlimitedprefixjoin) && helper.getJoinLimit())
- { //limited match join (s[1..n])
- dualcache.setown(new CRHDualCache());
- dualcache->init(groupedInput);
- dualCacheInput = dualcache->queryOut1();
- failingOuterAtmost = false;
- matchedLeft = false;
- leftIndex = 0;
- rightOuterIndex = 0;
- joinCounter = 0;
- limitedhelper.setown(createRHLimitedCompareHelper());
- limitedhelper->init( helper.getJoinLimit(), dualcache->queryOut2(), collate, helper.queryPrefixCompare() );
- }
- }
- virtual void reset()
- {
- if (atmostsTriggered)
- noteStatistic(StNumAtmostTriggered, atmostsTriggered);
- group.clear();
- groupedInput.clear();
- CRoxieServerActivity::reset();
- defaultLeft.clear();
- defaultRight.clear();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (limitedhelper)
- {
- while(!eof) //limited match join
- {
- if (!group.isItem(rightIndex))
- {
- lhs.setown(dualCacheInput->nextRow());
- if (lhs)
- {
- rightIndex = 0;
- joinCounter = 0;
- group.clear();
- limitedhelper->getGroup(group,lhs);
- }
- else
- {
- eof = true;
- }
- }
- if (group.isItem(rightIndex))
- {
- const void * rhs = group.item(rightIndex++);
- if(helper.match(lhs, rhs))
- {
- const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- }
- }
- return NULL;
- }
- else
- {
- if (first)
- {
- first = false;
- fillGroup();
- }
- while(!eof)
- {
- if(failingOuterAtmost)
- while(group.isItem(leftIndex))
- {
- const void * ret = joinRecords(group.item(leftIndex++), defaultRight, 0, NULL);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- if((joinLimit == 0) || !group.isItem(rightIndex))
- {
- if(leftOuterJoin && !matchedLeft && !failingLimit)
- {
- const void * ret = joinRecords(group.item(leftIndex), defaultRight, 0, NULL);
- if(ret)
- {
- matchedLeft = true;
- processed++;
- return ret;
- }
- }
- leftIndex++;
- matchedLeft = false;
- rightIndex = 0;
- joinCounter = 0;
- joinLimit = keepLimit;
- }
- if(!group.isItem(leftIndex))
- {
- if(failingLimit || failingOuterAtmost)
- {
- const void * lhs;
- while((lhs = groupedInput->nextRow()) != NULL) // dualCache never active here
- {
- const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
- ReleaseRoxieRow(lhs);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- failingLimit.clear();
- }
- if(rightOuterJoin && !failingLimit)
- while(group.isItem(rightOuterIndex))
- if(!matchedRight.item(rightOuterIndex++))
- {
- const void * ret = joinRecords(defaultLeft, group.item(rightOuterIndex-1), 0, NULL);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- if(!fillGroup())
- return NULL;
- continue;
- }
- const void * lhs = group.item(leftIndex);
- if(failingLimit)
- {
- leftIndex++;
- const void * ret = joinRecords(lhs, defaultRight, 0, failingLimit);
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- else
- {
- const void * rhs = group.item(rightIndex++);
- if(helper.match(lhs, rhs))
- {
- matchedLeft = true;
- matchedRight.replace(true, rightIndex-1);
- if(!exclude)
- {
- const void * ret = joinRecords(lhs, rhs, ++joinCounter, NULL);
- if(ret)
- {
- processed++;
- joinLimit--;
- return ret;
- }
- }
- }
- }
- }
- return NULL;
- }
- }
- };
- class CRoxieServerSelfJoinActivityFactory : public CRoxieServerActivityFactory
- {
- bool forceSpill;
- public:
- CRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- forceSpill = queryFactory.queryOptions().allSortsMaySpill || _graphNode.getPropBool("hint[@name='spill']/@value", false);;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSelfJoinActivity(_ctx, this, _probeManager, forceSpill);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return joinStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSelfJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSelfJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerLookupJoinActivity : public CRoxieServerTwoInputActivity
- {
- private:
- class LookupTable : public CInterface
- {
- public:
- LookupTable(IHThorHashJoinArg &helper)
- : leftRightCompare(helper.queryCompareLeftRight()), rightCompare(helper.queryCompareRight()),
- leftHash(helper.queryHashLeft()), rightHash(helper.queryHashRight())
- {
- size = 0;
- }
- virtual const void *find(const void * left) const = 0;
- virtual const void *findNext(const void * left) const = 0;
- protected:
- ICompare * leftRightCompare;
- ICompare * rightCompare;
- IHash * leftHash;
- IHash * rightHash;
- unsigned size;
- };
- class DedupLookupTable : public LookupTable
- {
- public:
- DedupLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
- : LookupTable(helper)
- {
- size = (4*rightRows.length())/3 + 1;
- table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem (and size rounded up to actual available size)
- ForEachItemIn(idx, rightRows)
- add(rightRows.item(idx));
- }
- ~DedupLookupTable()
- {
- roxiemem::ReleaseRoxieRowArray(size, table);
- free(table);
- }
- virtual const void *find(const void * left) const
- {
- unsigned index = leftHash->hash(left) % size;
- unsigned start = index;
- while (table[index])
- {
- if(leftRightCompare->docompare(left, table[index]) == 0)
- return table[index];
- index++;
- if (index==size)
- index = 0;
- if (index==start)
- throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
- }
- return NULL;
- }
- virtual const void *findNext(const void * left) const
- {
- return NULL;
- }
- protected:
- void add(const void * right)
- {
- unsigned index = rightHash->hash(right) % size;
- unsigned start = index;
- while (table[index])
- {
- if (rightCompare->docompare(table[index], right) == 0)
- {
- ReleaseRoxieRow(right);
- return;
- }
- index++;
- if (index==size)
- index = 0;
- if (index==start)
- throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on add)");
- }
- table[index] = right;
- }
- const void * * table;
- };
- class FewLookupTable : public LookupTable
- {
- public:
- FewLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
- : LookupTable(helper)
- {
- size = (4*rightRows.length())/3 + 1;
- table = (const void * *)calloc(size, sizeof(void *)); // This should probably be allocated from roxiemem
- findex = fstart = BadIndex;
- ForEachItemIn(idx, rightRows)
- add(rightRows.item(idx));
- }
- ~FewLookupTable()
- {
- roxiemem::ReleaseRoxieRowArray(size, table);
- free(table);
- }
- virtual const void *find(const void * left) const
- {
- fstart = leftHash->hash(left) % size;
- findex = fstart;
- return doFind(left);
- }
- virtual const void *findNext(const void * left) const
- {
- if (findex == BadIndex)
- return NULL;
- advance();
- return doFind(left);
- }
- protected:
- void add(const void * right)
- {
- unsigned start = rightHash->hash(right) % size;
- unsigned index = start;
- while (table[index])
- {
- index++;
- if (index==size)
- index = 0;
- if (index==start)
- throwUnexpected(); //table is full, should never happen
- }
- table[index] = right;
- }
- void advance() const
- {
- findex++;
- if(findex==size)
- findex = 0;
- if(findex==fstart)
- throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
- }
- const void *doFind(const void * left) const
- {
- while(table[findex])
- {
- if (leftRightCompare->docompare(left, table[findex]) == 0)
- return table[findex];
- advance();
- }
- findex = BadIndex;
- return NULL;
- }
- const void * * table;
- unsigned mutable fstart;
- unsigned mutable findex;
- static unsigned const BadIndex;
- };
- class ManyLookupTable : public LookupTable
- {
- public:
- ManyLookupTable(ConstPointerArray &rightRows, IHThorHashJoinArg &helper)
- : LookupTable(helper)
- {
- rightRows.swapWith(rowtable);
- UInt64Array groups;
- unsigned numRows = rowtable.length();
- if (numRows)
- {
- unsigned groupStart = 0;
- const void *groupStartRow = rowtable.item(0);
- for (unsigned i=1; i < numRows; i++)
- {
- const void *thisRow = rowtable.item(i);
- if (rightCompare->docompare(groupStartRow, thisRow))
- {
- groups.append(makeint64(groupStart, i-groupStart));
- groupStart = i;
- groupStartRow = thisRow;
- }
- }
- groups.append(makeint64(groupStart, numRows-groupStart));
- }
- size = (4*groups.length())/3 + 1;
- table = (__uint64 *) calloc(size, sizeof(__uint64)); // This should probably be allocated from roxiemem
- ForEachItemIn(idx, groups)
- {
- unsigned __int64 group = groups.item(idx);
- unsigned groupstart = high(group);
- const void *row = rowtable.item(groupstart);
- add(row, group);
- }
- }
- ~ManyLookupTable()
- {
- roxiemem::ReleaseRoxieRows(rowtable);
- free(table);
- }
- void add(const void *row, unsigned __int64 group)
- {
- unsigned start = rightHash->hash(row) % size;
- unsigned index = start;
- while (table[index])
- {
- index++;
- if (index==size)
- index = 0;
- if (index==start)
- throwUnexpected(); //table is full, should never happen
- }
- table[index] = group;
- }
- virtual const void *find(const void * left) const
- {
- unsigned index = leftHash->hash(left) % size;
- unsigned start = index;
- while (table[index])
- {
- __uint64 group = table[index];
- currentMatch = high(group);
- const void *right = rowtable.item(currentMatch);
- if (leftRightCompare->docompare(left, right) == 0)
- {
- currentMatch++;
- matchCount = low(group) - 1;
- return right;
- }
- index++;
- if (index==size)
- index = 0;
- if (index==start)
- throw MakeStringException(ROXIE_JOIN_ERROR, "Internal error in lookup join activity (hash table full on lookup)");
- }
- matchCount = 0;
- return NULL;
- }
- virtual const void *findNext(const void * left) const
- {
- if (!matchCount)
- return NULL;
- matchCount--;
- return rowtable.item(currentMatch++);
- }
- protected:
- __uint64 *table;
- ConstPointerArray rowtable;
- mutable unsigned currentMatch = 0;
- mutable unsigned matchCount = 0;
- };
- IHThorHashJoinArg &helper;
- bool leftOuterJoin;
- bool exclude;
- bool eog;
- bool many;
- bool dedupRHS;
- bool useFewTable;
- bool matchedGroup;
- const void *left;
- OwnedConstRoxieRow defaultRight;
- Owned<LookupTable> table;
- unsigned keepLimit;
- unsigned atmostLimit;
- unsigned atmostsTriggered;
- unsigned limitLimit;
- unsigned joinCounter;
- bool limitFail;
- bool limitOnFail;
- bool hasGroupLimit;
- bool isSmartJoin;
- unsigned keepCount;
- bool gotMatch;
- bool cloneLeft;
- ConstPointerArray rightGroup;
- aindex_t rightGroupIndex;
- Owned<IException> failingLimit;
- ConstPointerArray filteredRight;
- ThorActivityKind activityKind;
- Owned<IEngineRowAllocator> defaultRightAllocator;
-
- void createDefaultRight()
- {
- if (!defaultRight)
- {
- if (!defaultRightAllocator)
- defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
- size32_t thisSize = helper.createDefaultRight(rowBuilder);
- defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- public:
- CRoxieServerLookupJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _useFewTable)
- : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorHashJoinArg &)basehelper), useFewTable(_useFewTable)
- {
- unsigned joinFlags = helper.getJoinFlags();
- leftOuterJoin = (joinFlags & JFleftouter) != 0;
- assertex((joinFlags & JFrightouter) == 0);
- exclude = (joinFlags & JFexclude) != 0;
- many = (joinFlags & JFmanylookup) != 0;
- cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
- dedupRHS = (joinFlags & (JFmanylookup | JFmatchrequired | JFtransformMaySkip)) == 0; // optimisation: can implicitly dedup RHS unless is many lookup, or match required, or transform may skip
- left = NULL;
- activityKind = factory->getKind();
- eog = false;
- matchedGroup = false;
- gotMatch = false;
- keepLimit = 0;
- keepCount = 0;
- joinCounter = 0;
- atmostLimit = 0;
- atmostsTriggered = 0;
- limitLimit = 0;
- rightGroupIndex = 0;
- hasGroupLimit = false;
- isSmartJoin = (joinFlags & JFsmart) != 0;
- getLimitType(joinFlags, limitFail, limitOnFail);
- }
- void loadRight()
- {
- ConstPointerArray rightset;
- try
- {
- const void * next;
- while(true)
- {
- next = inputStream1->ungroupedNextRow();
- if(!next)
- break;
- rightset.append(next);
- }
- if (!dedupRHS)
- {
- if (useFewTable)
- {
- table.setown(new FewLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
- }
- else
- {
- if (!helper.isRightAlreadySorted())
- {
- if (helper.getJoinFlags() & JFunstable)
- {
- qsortvec(const_cast<void * *>(rightset.getArray()), rightset.ordinality(), *helper.queryCompareRight());
- }
- else
- {
- unsigned rightord = rightset.ordinality();
- MemoryAttr tempAttr(rightord*sizeof(void **)); // Temp storage for stable sort. This should probably be allocated from roxiemem
- void **temp = (void **) tempAttr.bufferBase();
- void **_rows = const_cast<void * *>(rightset.getArray());
- msortvecstableinplace(_rows, rightord, *helper.queryCompareRight(), temp);
- }
- }
- table.setown(new ManyLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
- }
- }
- else
- {
- table.setown(new DedupLookupTable(rightset, helper)); // NOTE - takes ownership of rightset
- }
- }
- catch (...)
- {
- roxiemem::ReleaseRoxieRows(rightset);
- throw;
- }
- };
- virtual void reset()
- {
- if (atmostsTriggered)
- noteStatistic(StNumAtmostTriggered, atmostsTriggered);
- CRoxieServerTwoInputActivity::reset();
- ReleaseClearRoxieRow(left);
- defaultRight.clear();
- table.clear();
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eog = false;
- matchedGroup = false;
- left = NULL;
- CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
- keepLimit = helper.getKeepLimit();
- if(keepLimit==0) keepLimit = static_cast<unsigned>(-1);
- atmostsTriggered = 0;
- atmostLimit = helper.getJoinLimit();
- limitLimit = helper.getMatchAbortLimit();
- hasGroupLimit = ((atmostLimit > 0) || (limitLimit > 0));
- if(atmostLimit==0) atmostLimit = static_cast<unsigned>(-1);
- if(limitLimit==0) limitLimit = static_cast<unsigned>(-1);
- getLimitType(helper.getJoinFlags(), limitFail, limitOnFail);
- switch (activityKind)
- {
- case TAKlookupjoin:
- case TAKlookupdenormalizegroup:
- case TAKsmartjoin:
- case TAKsmartdenormalizegroup:
- if (leftOuterJoin)
- createDefaultRight();
- break;
- }
- if (limitOnFail)
- createDefaultRight();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
- {
- puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
- puller->setInput(0, _sourceIdx, _in);
- _in = puller;
- _sourceIdx = 0;
- }
- CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if(!table)
- loadRight();
- switch (activityKind)
- {
- case TAKlookupjoin:
- case TAKsmartjoin:
- return nextRowJoin();
- case TAKlookupdenormalize:
- case TAKlookupdenormalizegroup:
- case TAKsmartdenormalize:
- case TAKsmartdenormalizegroup:
- return nextRowDenormalize();
- }
- throwUnexpected();
- }
- private:
- const void * nextRowJoin()
- {
- if(!table)
- loadRight();
- while(true)
- {
- const void * right = NULL;
- if(!left)
- {
- left = inputStream->nextRow();
- keepCount = keepLimit;
- joinCounter = 0;
- if(!left)
- {
- if (isSmartJoin)
- left = inputStream->nextRow();
- if (!left)
- {
- if(matchedGroup || eog)
- {
- matchedGroup = false;
- eog = true;
- return NULL;
- }
- eog = true;
- continue;
- }
- }
- eog = false;
- gotMatch = false;
- right = getRightFirst();
- }
- else
- right = getRightNext();
- const void * ret = NULL;
- if(failingLimit)
- {
- ret = joinException(left, failingLimit);
- }
- else
- {
- while(right)
- {
- if(helper.match(left, right))
- {
- gotMatch = true;
- if(exclude)
- break;
- ret = joinRecords(left, right, ++joinCounter);
- if(ret)
- {
- processed++;
- break;
- }
- }
- right = getRightNext();
- ret = NULL;
- }
- if(leftOuterJoin && !gotMatch)
- {
- ret = joinRecords(left, defaultRight, 0);
- gotMatch = true;
- }
- }
- if(ret)
- {
- matchedGroup = true;
- processed++;
- if(!many || (--keepCount == 0) || failingLimit)
- {
- ReleaseClearRoxieRow(left);
- failingLimit.clear();
- }
- return ret;
- }
- ReleaseClearRoxieRow(left);
- }
- }
- const void * nextRowDenormalize()
- {
- while(true)
- {
- left = inputStream->nextRow();
- if(!left)
- {
- if (!matchedGroup || isSmartJoin)
- left = inputStream->nextRow();
- if (!left)
- {
- matchedGroup = false;
- return NULL;
- }
- }
- gotMatch = false;
- const void * right = getRightFirst();
- const void * ret = NULL;
- if (failingLimit)
- ret = joinException(left, failingLimit);
- else if (activityKind == TAKlookupdenormalize || activityKind == TAKsmartdenormalize)
- {
- OwnedConstRoxieRow newLeft;
- newLeft.set(left);
- unsigned rowSize = 0;
- unsigned leftCount = 0;
- keepCount = keepLimit;
- while (right)
- {
- try
- {
- if (helper.match(left, right))
- {
- gotMatch = true;
- if (exclude)
- break;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
- if (thisSize)
- {
- rowSize = thisSize;
- newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
- }
- if(!many || (--keepCount == 0))
- break;
- }
- right = getRightNext();
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- if (rowSize)
- ret = newLeft.getClear();
- else if (leftOuterJoin && !gotMatch)
- {
- ret = left;
- left = NULL;
- }
- }
- else
- {
- filteredRight.kill();
- keepCount = keepLimit;
- while (right)
- {
- if (helper.match(left, right))
- {
- gotMatch = true;
- if(exclude)
- break;
- filteredRight.append(right);
- if(!many || (--keepCount == 0))
- break;
- }
- right = getRightNext();
- }
- if((filteredRight.ordinality() > 0) || (leftOuterJoin && !gotMatch))
- ret = denormalizeRecords(left, filteredRight);
- filteredRight.kill();
- }
- ReleaseRoxieRow(left);
- left = NULL;
- failingLimit.clear();
- if(ret)
- {
- matchedGroup = true;
- processed++;
- return ret;
- }
- }
- }
- const void * joinRecords(const void * left, const void * right, unsigned counter)
- {
- if (cloneLeft)
- {
- LinkRoxieRow(left);
- return left;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.transform(rowBuilder, left, right, counter);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * joinException(const void * left, IException * except)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.onFailTransform(rowBuilder, left, defaultRight, except);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * denormalizeRecords(const void * left, ConstPointerArray & rows)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned numRows = rows.ordinality();
- const void * right = numRows ? rows.item(0) : defaultRight.get();
- unsigned outSize = helper.transform(rowBuilder, left, right, numRows, (const void * *)rows.getArray());
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * getRightFirst() { if(hasGroupLimit) return fillRightGroup(); else return table->find(left); }
- const void * getRightNext() { if(hasGroupLimit) return readRightGroup(); else return table->findNext(left); }
- const void * readRightGroup() { if(rightGroup.isItem(rightGroupIndex)) return rightGroup.item(rightGroupIndex++); else return NULL; }
- const void *fillRightGroup()
- {
- rightGroup.kill();
- for(const void * right = table->find(left); right; right = table->findNext(left))
- {
- rightGroup.append(right);
- if(rightGroup.ordinality() > limitLimit)
- {
- if(limitFail)
- failLimit();
- gotMatch = true;
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if(limitOnFail)
- {
- assertex(!failingLimit);
- try
- {
- failLimit();
- }
- catch(IException * e)
- {
- failingLimit.setown(e);
- }
- assertex(failingLimit != NULL);
- }
- else
- {
- rightGroup.kill();
- }
- break;
- }
- if(rightGroup.ordinality() > atmostLimit)
- {
- atmostsTriggered++;
- rightGroup.kill();
- break;
- }
- }
- rightGroupIndex = 0;
- return readRightGroup();
- }
- void failLimit()
- {
- helper.onMatchAbortLimitExceeded();
- CommonXmlWriter xmlwrite(XWFtrim|XWFopt );
- if(!ctx->isBlind() && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
- {
- input->queryOutputMeta()->toXML(static_cast<const unsigned char *>(left), xmlwrite);
- }
- throw MakeStringException(ROXIE_TOO_MANY_RESULTS, "More than %u match candidates in join %d for row %s", limitLimit, queryId(), xmlwrite.str());
- }
-
- };
- unsigned const CRoxieServerLookupJoinActivity::FewLookupTable::BadIndex(static_cast<unsigned>(-1));
- class CRoxieServerLookupJoinActivityFactory : public CRoxieServerJoinActivityFactory
- {
- public:
- CRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorHashJoinArg> helper = (IHThorHashJoinArg *) helperFactory();
- useFewTable = _graphNode.getPropBool("hint[@name='usefewtable']/@value", false);
- if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright | JFslidingmatch)) != 0)
- throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for lookup join activity"); // code generator should never create such an activity
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLookupJoinActivity(_ctx, this, _probeManager, useFewTable);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return joinStatistics;
- }
- protected:
- bool useFewTable;
- };
- IRoxieServerActivityFactory *createRoxieServerLookupJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerLookupJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerAllJoinActivity : public CRoxieServerTwoInputActivity
- {
- private:
- IHThorAllJoinArg &helper;
- bool leftOuterJoin;
- bool rightOuterJoin;
- bool exclude;
- OwnedConstRoxieRow defaultRight;
- OwnedConstRoxieRow defaultLeft;
- Owned<IEngineRowAllocator> defaultRightAllocator;
- Owned<IEngineRowAllocator> defaultLeftAllocator;
- const void *left;
- unsigned countForLeft;
- ConstPointerArray rightset;
- BoolArray matchedRight; // MORE - could use a bitset...
- unsigned keepLimit;
- bool started;
- bool eog;
- bool eos;
- bool matchedLeft;
- bool matchedGroup;
- bool leftIsGrouped;
- bool cloneLeft;
- unsigned rightIndex;
- unsigned joinCounter;
- unsigned rightOrdinality;
- ThorActivityKind activityKind;
- ConstPointerArray filteredRight;
- void createDefaultLeft()
- {
- if (!defaultLeft)
- {
- if (!defaultLeftAllocator)
- defaultLeftAllocator.setown(createRowAllocator(input->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultLeftAllocator);
- size32_t thisSize = helper.createDefaultLeft(rowBuilder);
- defaultLeft.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- void createDefaultRight()
- {
- if (!defaultRight)
- {
- if (!defaultRightAllocator)
- defaultRightAllocator.setown(createRowAllocator(input1->queryOutputMeta()));
- RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
- size32_t thisSize = helper.createDefaultRight(rowBuilder);
- defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- public:
- CRoxieServerAllJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerTwoInputActivity(_ctx, _factory, _probeManager), helper((IHThorAllJoinArg &)basehelper)
- {
- unsigned joinFlags = helper.getJoinFlags();
- leftOuterJoin = (joinFlags & JFleftouter) != 0;
- rightOuterJoin = (joinFlags & JFrightouter) != 0;
- cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
- keepLimit = (unsigned) -1;
- exclude = (joinFlags & JFexclude) != 0;
- left = NULL;
- started = true;
- eog = false;
- eos = false;
- matchedLeft = false;
- matchedGroup = false;
- activityKind = factory->getKind();
- rightIndex = 0;
- rightOrdinality = 0;
- leftIsGrouped = false;
- countForLeft = 0;
- joinCounter = 0;
- }
- virtual void reset()
- {
- defaultRight.clear();
- defaultLeft.clear();
- ReleaseRoxieRows(rightset);
- matchedRight.kill();
- CRoxieServerTwoInputActivity::reset();
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eog = false;
- eos = false;
- matchedLeft = false;
- matchedGroup = false;
- started = false;
- left = NULL;
- CRoxieServerTwoInputActivity::start(parentExtractSize, parentExtract, paused);
- keepLimit = helper.getKeepLimit();
- if(keepLimit==0)
- keepLimit = (unsigned) -1;
- countForLeft = keepLimit;
- joinCounter = 0;
- leftIsGrouped = input->queryOutputMeta()->isGrouped();
- if((activityKind==TAKalljoin || activityKind==TAKalldenormalizegroup) && leftOuterJoin)
- createDefaultRight();
- if(rightOuterJoin)
- createDefaultLeft();
- }
- void loadRight()
- {
- const void * next;
- while(true)
- {
- next = inputStream1->ungroupedNextRow();
- if(!next)
- break;
- rightset.append(next);
- matchedRight.append(false);
- }
- rightIndex = 0;
- joinCounter = 0;
- rightOrdinality = rightset.ordinality();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (!idx && (helper.getJoinFlags() & JFparallel) != 0)
- {
- puller.setown(new CRoxieServerReadAheadInput(ctx, ctx->queryOptions().parallelJoinPreload));
- puller->setInput(0, _sourceIdx, _in);
- _in = puller;
- _sourceIdx = 0;
- }
- CRoxieServerTwoInputActivity::setInput(idx, _sourceIdx, _in);
- }
- const void * joinRecords(const void * left, const void * right, unsigned counter)
- {
- // MORE - could share some code with lookup join
- if (cloneLeft)
- {
- LinkRoxieRow(left);
- return left;
- }
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize = helper.transform(rowBuilder, left, right, counter);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- const void * denormalizeRecords(const void * curLeft, ConstPointerArray & rows)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned numRows = rows.ordinality();
- const void * right = numRows ? rows.item(0) : defaultRight.get();
- unsigned outSize = helper.transform(rowBuilder, curLeft, right, numRows, rows.getArray());
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- else
- return NULL;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if(!started)
- {
- started = true;
- left = inputStream->nextRow();
- matchedLeft = false;
- countForLeft = keepLimit;
- joinCounter = 0;
- if(left == NULL)
- {
- eos = true;
- return NULL;
- }
- loadRight();
- }
- const void * ret;
- const void * right;
- if(eos)
- return NULL;
- while(true)
- {
- ret = NULL;
- if((rightIndex == rightOrdinality) || (countForLeft==0))
- {
- if(leftOuterJoin && left && !matchedLeft)
- {
- switch(activityKind)
- {
- case TAKalljoin:
- ret = joinRecords(left, defaultRight, 0);
- break;
- case TAKalldenormalize:
- ret = left;
- left = NULL;
- break;
- case TAKalldenormalizegroup:
- filteredRight.kill();
- ret = denormalizeRecords(left, filteredRight);
- break;
- default:
- throwUnexpected();
- }
- }
- rightIndex = 0;
- joinCounter = 0;
- ReleaseRoxieRow(left);
- left = NULL;
- if(ret)
- {
- matchedGroup = true;
- processed++;
- return ret;
- }
- }
- if(!left)
- {
- left = inputStream->nextRow();
- matchedLeft = false;
- countForLeft = keepLimit;
- joinCounter = 0;
- }
- if(!left)
- {
- if(eog)
- {
- eos = true;
- matchedGroup = false;
- return NULL;
- }
- eog = true;
- if (matchedGroup && leftIsGrouped)
- {
- matchedGroup = false;
- return NULL;
- }
- matchedGroup = false;
- continue;
- }
- eog = false;
- switch(activityKind)
- {
- case TAKalljoin:
- while(rightIndex < rightOrdinality)
- {
- right = rightset.item(rightIndex);
- if(helper.match(left, right))
- {
- matchedLeft = true;
- matchedRight.replace(true, rightIndex);
- if(!exclude)
- ret = joinRecords(left, right, ++joinCounter);
- }
- rightIndex++;
- if(ret)
- {
- countForLeft--;
- matchedGroup = true;
- processed++;
- return ret;
- }
- }
- break;
- case TAKalldenormalize:
- {
- OwnedConstRoxieRow newLeft;
- newLeft.set(left);
- unsigned rowSize = 0;
- unsigned leftCount = 0;
- while((rightIndex < rightOrdinality) && countForLeft)
- {
- right = rightset.item(rightIndex);
- if(helper.match(left, right))
- {
- matchedLeft = true;
- matchedRight.replace(true, rightIndex);
- if(!exclude)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned thisSize = helper.transform(rowBuilder, newLeft, right, ++leftCount);
- if(thisSize)
- {
- rowSize = thisSize;
- newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
- --countForLeft;
- }
- }
- catch (IException *e)
- {
- throw makeWrappedException(e);
- }
- }
- }
- rightIndex++;
- }
- if(rowSize)
- {
- processed++;
- return newLeft.getClear();
- }
- }
- break;
- case TAKalldenormalizegroup:
- filteredRight.kill();
- while((rightIndex < rightOrdinality) && countForLeft)
- {
- right = rightset.item(rightIndex);
- if(helper.match(left, right))
- {
- matchedLeft = true;
- matchedRight.replace(true, rightIndex);
- filteredRight.append(right);
- --countForLeft;
- }
- ++rightIndex;
- }
- if(!exclude && filteredRight.ordinality())
- {
- ret = denormalizeRecords(left, filteredRight);
- filteredRight.kill();
- if(ret)
- {
- processed++;
- return ret;
- }
- }
- break;
- default:
- throwUnexpected();
- }
- }
- }
- };
- class CRoxieServerAllJoinActivityFactory : public CRoxieServerJoinActivityFactory
- {
- public:
- CRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- Owned<IHThorAllJoinArg> helper = (IHThorAllJoinArg *) helperFactory();
- if((helper->getJoinFlags() & (JFfirst | JFfirstleft | JFfirstright)) != 0)
- throw MakeStringException(ROXIE_INVALID_FLAGS, "Invalid flags for join all activity"); // code generator should never create such an activity
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerAllJoinActivity(_ctx, this, _probeManager);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return joinStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerAllJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerAllJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerTopNActivity : public CRoxieServerLateStartActivity
- {
- unsigned limit;
- bool hasBest;
- bool eoi;
- const void **sorted;
- unsigned sortedCount;
- unsigned curIndex;
- IHThorTopNArg &helper;
- ICompare &compare;
- public:
- CRoxieServerTopNActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerLateStartActivity(_ctx, _factory, _probeManager), helper((IHThorTopNArg &)basehelper), compare(*helper.queryCompare())
- {
- sorted = NULL;
- sortedCount = 0;
- curIndex = 0;
- limit = 0;
- eoi = false;
- hasBest = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- assertex(sorted == NULL);
- sortedCount = 0;
- curIndex = 0;
- eoi = false;
-
- CRoxieServerLateStartActivity::start(parentExtractSize, parentExtract, paused);
- limit = (unsigned) helper.getLimit();
- hasBest = helper.hasBest();
- lateStart(parentExtractSize, parentExtract, limit > 0);
- // MORE - should we use an expanding array instead?
- if (limit > 0)
- sorted = (const void **) ctx->queryRowManager().allocate((limit+1) * sizeof(const void *), activityId);
- }
- virtual void reset()
- {
- if (sorted)
- {
- roxiemem::ReleaseRoxieRowRange(sorted, curIndex, sortedCount);
- curIndex = 0;
- sortedCount = 0;
- ReleaseRoxieRow(sorted);
- sorted = NULL;
- }
- CRoxieServerLateStartActivity::reset();
- }
- bool abortEarly()
- {
- if (hasBest && (sortedCount == limit))
- {
- int compare = helper.compareBest(sorted[sortedCount-1]);
- if (compare == 0)
- {
- if (meta.isGrouped())
- {
- //MORE: This would be more efficient if we had a away of skipping to the end of the incoming group.
- const void * next;
- while ((next = inputStream->nextRow()) != NULL)
- ReleaseRoxieRow(next);
- }
- else
- eoi = true;
- return true;
- }
- //This only checks the lowest element - we could check all elements inserted, but it would increase the number of compares
- if (compare < 0)
- throw MakeStringException(ROXIE_TOPN_ROW_ERROR, "TOPN: row found that exceeds the best value");
- }
- return false;
- }
- void getSorted()
- {
- curIndex = 0;
- sortedCount = 0;
- if(eoi)
- return;
- const void * next;
- while ((next = inputStream->nextRow()) != NULL)
- {
- if (sortedCount < limit)
- {
- binary_vec_insert_stable(next, sorted, sortedCount, compare);
- sortedCount++;
- if(abortEarly())
- return;
- }
- else
- {
- if(limit && compare.docompare(sorted[sortedCount-1], next) > 0) // MORE - if stability is an issue, need to consider whether this should be > or >=
- {
- binary_vec_insert_stable(next, sorted, sortedCount, compare); // MORE - not sure this is stable!
- ReleaseRoxieRow(sorted[sortedCount]);
- if(abortEarly())
- return;
- }
- else
- {
- ReleaseRoxieRow(next); // do not bother with insertion sort if we know next will fall off the end
- }
- }
- }
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (curIndex >= sortedCount)
- {
- bool eog = sortedCount != 0;
- getSorted();
- if(sortedCount == 0)
- {
- eof = true;
- return NULL;
- }
- if (eog)
- return NULL;
- }
- processed++;
- return sorted[curIndex++];
- }
- };
- class CRoxieServerTopNActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerTopNActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerTopNActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerTopNActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerLimitActivity : public CRoxieServerActivity
- {
- protected:
- unsigned __int64 rowLimit;
- IHThorLimitArg &helper;
- public:
- CRoxieServerLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorLimitArg &)basehelper)
- {
- rowLimit = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- rowLimit = helper.getRowLimit(); // could conceivably depend on context so should not compute any earlier than this
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * ret = inputStream->nextRow();
- if (ret)
- {
- processed++;
- if (processed > rowLimit)
- {
- ReleaseRoxieRow(ret);
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- helper.onLimitExceeded();
- }
- }
- return ret;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (ret)
- {
- if (wasCompleteMatch)
- processed++;
- if (processed > rowLimit)
- {
- ReleaseRoxieRow(ret);
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- helper.onLimitExceeded();
- }
- }
- return ret;
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- //Do not reset the rowLimit
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- class CRoxieServerLimitActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerLimitActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerSkipLimitActivity : public CRoxieServerLimitActivity
- {
- ConstPointerArray buff;
- bool started;
- unsigned index;
- IHThorLimitTransformExtra * transformExtra;
- public:
- CRoxieServerSkipLimitActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _onFail)
- : CRoxieServerLimitActivity(_ctx, _factory, _probeManager)
- {
- transformExtra = NULL;
- started = false;
- index = 0;
- if (_onFail)
- transformExtra = static_cast<IHThorLimitTransformExtra *>(helper.selectInterface(TAIlimittransformextra_1));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- started = false;
- index = 0;
- CRoxieServerLimitActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
- buff.kill();
- index = 0;
- started = false;
- CRoxieServerLimitActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!started)
- pullInput();
- if (buff.isItem(index))
- {
- const void * next = buff.item(index++);
- if(next)
- processed++;
- return next;
- }
- return NULL;
- }
- protected:
- void pullInput()
- {
- unsigned count = 0;
- loop
- {
- const void * next = inputStream->nextRow();
- if (next == NULL)
- {
- next = inputStream->nextRow();
- if(next == NULL)
- break;
- buff.append(NULL);
- }
- count++;
- if (count > rowLimit)
- {
- ReleaseRoxieRow(next);
- ReleaseRoxieRows(buff);
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if (transformExtra)
- {
- ensureRowAllocator();
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = transformExtra->transformOnLimitExceeded(rowBuilder);
- if (outSize)
- buff.append(rowBuilder.finalizeRowClear(outSize));
- }
- break;
- }
- buff.append(next);
- }
- started = true;
- }
- };
- class CRoxieServerSkipLimitActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSkipLimitActivity(_ctx, this, _probeManager, kind==TAKcreaterowlimit);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSkipLimitActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSkipLimitActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerCatchActivity : public CRoxieServerActivity
- {
- IHThorCatchArg &helper;
- public:
- CRoxieServerCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper)
- {
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- try
- {
- const void *ret = inputStream->nextRow();
- if (ret)
- processed++;
- return ret;
- }
- catch (IException *E)
- {
- E->Release();
- helper.onExceptionCaught();
- }
- catch (...)
- {
- helper.onExceptionCaught();
- }
- throwUnexpected(); // onExceptionCaught should have thrown something
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- try
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void * ret = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (ret && wasCompleteMatch)
- processed++;
- return ret;
- }
- catch (IException *E)
- {
- E->Release();
- helper.onExceptionCaught();
- }
- catch (...)
- {
- helper.onExceptionCaught();
- }
- throwUnexpected(); // onExceptionCaught should have thrown something
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF(); // MORE - why not in base class?
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- };
- class CRoxieServerSkipCatchActivity : public CRoxieServerActivity
- {
- ConstPointerArray buff;
- bool started;
- unsigned index;
- IHThorCatchArg &helper;
- bool createRow;
- public:
- CRoxieServerSkipCatchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _createRow)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorCatchArg &)basehelper), createRow(_createRow)
- {
- started = false;
- index = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- started = false;
- index = 0;
- try
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- catch (IException *E)
- {
- onException(E);
- started = true;
- }
- catch (...)
- {
- onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
- started = true;
- }
- }
- virtual void reset()
- {
- roxiemem::ReleaseRoxieRowRange(buff.getArray(), index, buff.ordinality());
- buff.kill();
- index = 0;
- started = false;
- CRoxieServerActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!started)
- pullInput();
- if (buff.isItem(index))
- {
- const void * next = buff.item(index++);
- if(next)
- processed++;
- return next;
- }
- return NULL;
- }
- protected:
- void onException(IException *E)
- {
- inputStream->stop();
- ReleaseRoxieRows(buff);
- if (createRow)
- {
- ensureRowAllocator();
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transformOnExceptionCaught(rowBuilder, E);
- if (outSize)
- buff.append(rowBuilder.finalizeRowClear(outSize));
- }
- E->Release();
- }
- void pullInput()
- {
- try
- {
- bool EOGseen = false;
- loop
- {
- const void * next = inputStream->nextRow();
- buff.append(next);
- if (next == NULL)
- {
- if (EOGseen)
- break;
- EOGseen = true;
- }
- else
- EOGseen = false;
- }
- }
- catch (IException *E)
- {
- onException(E);
- }
- catch (...)
- {
- onException(MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught"));
- }
- started = true;
- }
- };
- class CRoxieServerCatchActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- switch (kind)
- {
- case TAKcatch:
- return new CRoxieServerCatchActivity(_ctx, this, _probeManager);
- case TAKskipcatch:
- return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, false);
- case TAKcreaterowcatch:
- return new CRoxieServerSkipCatchActivity(_ctx, this, _probeManager, true);
- default:
- throwUnexpected();
- }
- }
- };
- IRoxieServerActivityFactory *createRoxieServerCatchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerCatchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerPullActivity : public CRoxieServerActivity
- {
- ConstPointerArray buff;
- bool started;
- unsigned index;
- public:
- CRoxieServerPullActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- started = false;
- index = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- started = false;
- index = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- while (buff.isItem(index))
- ReleaseRoxieRow(buff.item(index++));
- buff.kill();
- started = false;
- index = 0;
- CRoxieServerActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (!started)
- pullInput();
- if (buff.isItem(index))
- {
- const void * next = buff.item(index++);
- if (next)
- processed++;
- return next;
- }
- return NULL;
- }
- protected:
- void pullInput()
- {
- bool EOGseen = false;
- loop
- {
- const void * next = inputStream->nextRow();
- buff.append(next);
- if (next == NULL)
- {
- if (EOGseen)
- break;
- EOGseen = true;
- }
- else
- EOGseen = false;
- }
- started = true;
- }
- };
- class CRoxieServerPullActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerPullActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerPullActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerPullActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerTraceActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerTraceActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorTraceArg &) basehelper),
- keepLimit(0), skip(0), sample(0)
- {
- assertex(meta.hasXML());
- traceEnabled = defaultTraceEnabled && !isBlind();
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- if (ctx)
- traceEnabled = ctx->queryOptions().traceEnabled && !isBlind();
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (traceEnabled && helper.canMatchAny())
- {
- keepLimit = helper.getKeepLimit();
- if (keepLimit==(unsigned) -1)
- keepLimit = ctx->queryOptions().traceLimit;
- skip = helper.getSkip();
- sample = helper.getSample();
- if (sample)
- sample--;
- name.setown(helper.getName());
- if (!name)
- name.set("Row");
- }
- else
- keepLimit = 0;
- }
- virtual void stop()
- {
- name.clear();
- CRoxieServerActivity::stop();
- }
- virtual bool isPassThrough()
- {
- return true;
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- const void *row = inputStream->nextRow();
- if (row)
- {
- onTrace(row);
- processed++;
- }
- return row;
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- // MORE - will need rethinking once we rethink the nextRowGE interface for global smart-stepping.
- ActivityTimer t(totalCycles, timeActivities);
- const void * row = inputStream->nextRowGE(seek, numFields, wasCompleteMatch, stepExtra);
- if (row)
- {
- onTrace(row);
- processed++;
- }
- return row;
- }
- virtual bool gatherConjunctions(ISteppedConjunctionCollector & collector)
- {
- return input->gatherConjunctions(collector);
- }
- virtual void resetEOF()
- {
- inputStream->resetEOF();
- }
- IInputSteppingMeta * querySteppingMeta()
- {
- return input->querySteppingMeta();
- }
- protected:
- void onTrace(const void *row)
- {
- if (keepLimit && helper.isValid(row))
- {
- if (skip)
- skip--;
- else if (sample)
- sample--;
- else
- {
- CommonXmlWriter xmlwrite(XWFnoindent);
- meta.toXML((const byte *) row, xmlwrite);
- CTXLOG("TRACE: <%s>%s<%s>", name.get(), xmlwrite.str(), name.get());
- keepLimit--;
- sample = helper.getSample();
- if (sample)
- sample--;
- }
- }
- }
- OwnedRoxieString name;
- IHThorTraceArg &helper;
- unsigned keepLimit;
- unsigned skip;
- unsigned sample;
- bool traceEnabled;
- };
- class CRoxieServerTraceActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerTraceActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerTraceActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerTraceActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerCaseActivity : public CRoxieServerMultiInputBaseActivity
- {
- IHThorCaseArg &helper;
- unsigned cond;
- bool unusedStopped;
- IEngineRowStream *active;
- public:
- CRoxieServerCaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numInputs)
- : CRoxieServerMultiInputBaseActivity(_ctx, _factory, _probeManager, _numInputs), helper((IHThorCaseArg &)basehelper)
- {
- unusedStopped = false;
- cond = 0;
- active = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerMultiInputBaseActivity::start(parentExtractSize, parentExtract, paused);
- cond = helper.getBranch();
- //CHOOSE defaults to the last argument if out of range.
- if (cond >= numInputs)
- cond = numInputs - 1;
- inputArray[cond]->start(parentExtractSize, parentExtract, paused);
- startJunction(junctionArray[cond]);
- assertex(numInputs==numStreams);
- for (unsigned idx = 0; idx < numStreams; idx++)
- {
- if (idx!=cond)
- streamArray[idx]->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
- }
- active = streamArray[cond];
- unusedStopped = true;
- }
- virtual void stop()
- {
- for (unsigned idx = 0; idx < numStreams; idx++)
- {
- if (idx==cond || !unusedStopped)
- streamArray[idx]->stop();
- }
- CRoxieServerMultiInputBaseActivity::stop();
- }
- virtual void reset()
- {
- unusedStopped = false;
- active = NULL;
- CRoxieServerMultiInputBaseActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (active)
- {
- const void *ret = active->nextRow();
- if (ret)
- processed++;
- return ret;
- }
- return NULL;
- }
- };
- class CRoxieServerCaseActivityFactory : public CRoxieServerMultiInputFactory
- {
- bool graphInvariant;
- public:
- CRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- graphInvariant = _graphInvariant;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerCaseActivity(_ctx, this, _probeManager, numInputs());
- }
- virtual bool isGraphInvariant() const
- {
- return graphInvariant;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerCaseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
- {
- return new CRoxieServerCaseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
- }
- //=================================================================================
- class CRoxieServerIfActivity : public CRoxieServerActivity
- {
- IHThorIfArg &helper;
- IFinalRoxieInput *inputTrue;
- IFinalRoxieInput *inputFalse;
- IEngineRowStream *streamTrue;
- IEngineRowStream *streamFalse;
- unsigned sourceIdxFalse = 0;
- unsigned sourceIdxTrue = 0;
- Owned<IStrandJunction> junctionTrue;
- Owned<IStrandJunction> junctionFalse;
- bool cond;
- bool unusedStopped;
- public:
- CRoxieServerIfActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
- {
- inputFalse = NULL;
- inputTrue = NULL;
- streamTrue = NULL;
- streamFalse = NULL;
- unusedStopped = false;
- cond = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- cond = helper.getCondition();
- if (cond)
- {
- inputTrue->start(parentExtractSize, parentExtract, paused);
- startJunction(junctionTrue);
- if (streamFalse)
- streamFalse->stop(); // Note: stopping unused branches early helps us avoid buffering splits too long.
- }
- else
- {
- if (inputFalse)
- {
- inputFalse->start(parentExtractSize, parentExtract, paused);
- startJunction(junctionFalse);
- }
- streamTrue->stop();
- }
- unusedStopped = true;
- }
- virtual void stop()
- {
- if (!unusedStopped || cond)
- streamTrue->stop();
- if (streamFalse && (!unusedStopped || !cond))
- streamFalse->stop();
- CRoxieServerActivity::stop();
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 localCycles = totalCycles.totalCycles;
- localCycles -= inputTrue->queryTotalCycles();
- if (inputFalse)
- localCycles -= inputFalse->queryTotalCycles();
- if (localCycles < 0)
- localCycles = 0;
- return localCycles;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- switch (idx)
- {
- case 0:
- return inputTrue;
- case 1:
- return inputFalse;
- default:
- return NULL;
- }
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { return nullptr; }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- IFinalRoxieInput *in = cond ? inputTrue : inputFalse;
- if (in)
- return in->queryIndexReadActivity();
- return NULL;
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- inputTrue->reset();
- if (inputFalse)
- inputFalse->reset();
- resetJunction(junctionTrue);
- resetJunction(junctionFalse);
- unusedStopped = false;
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (idx==1)
- {
- inputFalse = _in;
- sourceIdxFalse = _sourceIdx;
- }
- else
- {
- assertex(!idx);
- inputTrue = _in;
- sourceIdxTrue = _sourceIdx;
- }
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- //It should be possible to stream IF(), but the number of strands would need to match on the two branches.
- streamTrue = connectSingleStream(ctx, inputTrue, sourceIdxTrue, junctionTrue, consumerOrdered);
- streamFalse = connectSingleStream(ctx, inputFalse, sourceIdxFalse, junctionFalse, consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, nullptr, consumerOrdered, nullptr);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- IEngineRowStream *in = cond ? streamTrue : streamFalse;
- if (in)
- {
- const void * ret;
- if ((ret = in->nextRow()) != NULL)
- processed++;
- return ret;
- }
- return NULL;
- }
- };
- class CRoxieServerIfActivityFactory : public CRoxieServerActivityFactory
- {
- unsigned input2;
- unsigned input2idx;
- bool graphInvariant;
- public:
- CRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- graphInvariant = _graphInvariant;
- input2 = (unsigned)-1;
- input2idx = (unsigned)-1;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerIfActivity(_ctx, this, _probeManager);
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- if (idx==1)
- {
- input2 = source;
- input2idx = sourceidx;
- }
- else
- CRoxieServerActivityFactory::setInput(idx, source, sourceidx);
- }
- virtual unsigned getInput(unsigned idx, unsigned &sourceidx) const
- {
- switch (idx)
- {
- case 1:
- sourceidx = input2idx;
- return input2;
- case 0:
- return CRoxieServerActivityFactory::getInput(idx, sourceidx);
- default:
- return (unsigned) -1;
- }
- }
- virtual unsigned numInputs() const { return (input2 == (unsigned)-1) ? 1 : 2; }
- virtual bool isGraphInvariant() const
- {
- return graphInvariant;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIfActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _graphInvariant)
- {
- return new CRoxieServerIfActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _graphInvariant);
- }
- //=================================================================================
- class CRoxieServerActionBaseActivity : public CRoxieServerActivity
- {
- CriticalSection ecrit;
- Owned<IException> exception;
- bool executed;
- public:
- CRoxieServerActionBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- executed = false;
- }
- virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract) = 0;
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- CriticalBlock b(ecrit);
- if (exception)
- throw(exception.getLink());
- if (!executed)
- {
- try
- {
- executed = true;
- start(parentExtractSize, parentExtract, false);
- doExecuteAction(parentExtractSize, parentExtract);
- stop();
- }
- catch (IException * E)
- {
- ctx->notifyAbort(E);
- abort();
- exception.set(E);
- throw;
- }
- }
- }
- virtual void reset()
- {
- executed = false;
- exception.clear();
- CRoxieServerActivity::reset();
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- return NULL;
- }
- };
- class CRoxieServerIfActionActivity : public CRoxieServerActionBaseActivity
- {
- IHThorIfArg &helper;
- public:
- CRoxieServerIfActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorIfArg &)basehelper)
- {
- }
- virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
- {
- bool cond;
- {
- ActivityTimer t(totalCycles, timeActivities);
- cond = helper.getCondition();
- }
- stopDependencies(parentExtractSize, parentExtract, cond ? 2 : 1);
- executeDependencies(parentExtractSize, parentExtract, cond ? 1 : 2);
- }
- };
- class CRoxieServerIfActionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerIfActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIfActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerIfActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerParallelActionActivity : public CRoxieServerActionBaseActivity
- {
- public:
- CRoxieServerParallelActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
- {
- }
- virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
- {
- #ifdef PARALLEL_EXECUTE
- CParallelActivityExecutor afor(dependencies, parentExtractSize, parentExtract);
- afor.For(dependencies.ordinality(), dependencies.ordinality(), true);
- #else
- ForEachItemIn(idx, dependencies)
- {
- dependencies.item(idx).execute(parentExtractSize, parentExtract);
- }
- #endif
- }
- };
- class CRoxieServerParallelActionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- assertex(!isRoot); // non-internal should be expanded out..
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerParallelActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerParallelActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerParallelActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerSequentialActionActivity : public CRoxieServerActionBaseActivity
- {
- IHThorSequentialArg &helper;
- public:
- CRoxieServerSequentialActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager), helper((IHThorSequentialArg &)basehelper)
- {
- }
- virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
- {
- unsigned numBranches = helper.numBranches();
- for (unsigned branch=1; branch <= numBranches; branch++)
- executeDependencies(parentExtractSize, parentExtract, branch);
- }
- };
- class CRoxieServerSequentialActionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSequentialActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSequentialActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerSequentialActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerWhenActivity : public CRoxieServerActivity
- {
- public:
- CRoxieServerWhenActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- savedExtractSize = 0;
- savedExtract = NULL;
- eofseen = false;
- eogseen = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- savedExtractSize = parentExtractSize;
- savedExtract = parentExtract;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
- executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
- eofseen = false;
- eogseen = false;
- }
- virtual void stop()
- {
- if (state == STATEreset || (!aborted && !eofseen)) // If someone else aborted, then WHEN clauses don't trigger, whatever
- {
- stopDependencies(savedExtractSize, savedExtract, WhenSuccessId);
- stopDependencies(savedExtractSize, savedExtract, WhenFailureId);
- }
- else if (state != STATEstopped)
- {
- stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // These ones don't get executed
- executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId); // These ones do
- }
- CRoxieServerActivity::stop();
- }
- virtual const void *nextRow()
- {
- try
- {
- ActivityTimer t(totalCycles, timeActivities); // bit of a waste of time....
- const void *ret = inputStream->nextRow();
- if (!ret)
- {
- if (eogseen)
- eofseen = true;
- else
- eogseen = true;
- }
- else
- eogseen = false;
- return ret;
- }
- catch (...)
- {
- aborted = true;
- throw;
- }
- }
- protected:
- const byte *savedExtract;
- unsigned savedExtractSize;
- bool eofseen;
- bool eogseen;
- };
- class CRoxieServerWhenActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerWhenActivity(_ctx, this, _probeManager);
- }
- };
- extern IRoxieServerActivityFactory *createRoxieServerWhenActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerWhenActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=================================================================================
- class CRoxieServerWhenActionActivity : public CRoxieServerActionBaseActivity
- {
- public:
- CRoxieServerWhenActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActionBaseActivity(_ctx, _factory, _probeManager)
- {
- savedExtractSize = 0;
- savedExtract = NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- savedExtractSize = parentExtractSize;
- savedExtract = parentExtract;
- CRoxieServerActionBaseActivity::start(parentExtractSize, parentExtract, paused);
- executeDependencies(parentExtractSize, parentExtract, WhenBeforeId);
- executeDependencies(parentExtractSize, parentExtract, WhenParallelId); // MORE: This should probably be done in parallel!
- }
- virtual void stop()
- {
- if (state != STATEstopped)
- {
- stopDependencies(savedExtractSize, savedExtract, aborted ? WhenSuccessId : WhenFailureId); // these are NOT going to execute
- executeDependencies(savedExtractSize, savedExtract, aborted ? WhenFailureId : WhenSuccessId);
- }
- CRoxieServerActionBaseActivity::stop();
- }
- virtual void doExecuteAction(unsigned parentExtractSize, const byte * parentExtract)
- {
- executeDependencies(parentExtractSize, parentExtract, 1);
- }
- protected:
- unsigned savedExtractSize;
- const byte *savedExtract;
- };
- class CRoxieServerWhenActionActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerWhenActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- private:
- bool isRoot;
- };
- extern IRoxieServerActivityFactory *createRoxieServerWhenActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerWhenActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=================================================================================
- class CRoxieServerStrandedParseActivity : public CRoxieServerStrandedActivity
- {
- INlpParseAlgorithm * algorithm;
- class ParseProcessor : public StrandProcessor, implements IMatchedAction
- {
- protected:
- IHThorParseArg &helper;
- INlpParser * parser;
- INlpResultIterator * rowIter;
- const void * in;
- char * curSearchText;
- size32_t curSearchTextLen;
- bool processRecord(const void * inRec)
- {
- if (helper.searchTextNeedsFree())
- rtlFree(curSearchText);
- curSearchTextLen = 0;
- curSearchText = NULL;
- helper.getSearchText(curSearchTextLen, curSearchText, inRec);
- return parser->performMatch(*this, in, curSearchTextLen, curSearchText);
- }
- public:
- ParseProcessor(CRoxieServerActivity &_parent, IEngineRowStream *_inputStream, IHThorParseArg &_helper, INlpParseAlgorithm * _algorithm)
- : StrandProcessor(_parent, _inputStream, false), helper(_helper)
- {
- parser = _algorithm->createParser(parent.queryCodeContext(), parent.queryId(), helper.queryHelper(), &helper);
- rowIter = parser->queryResultIter();
- in = NULL;
- curSearchText = NULL;
- curSearchTextLen = 0;
- }
- ~ParseProcessor()
- {
- ::Release(parser);
- }
- virtual void start()
- {
- StrandProcessor::start();
- numProcessedLastGroup = 0;
- curSearchTextLen = 0;
- curSearchText = NULL;
- in = NULL;
- parser->reset();
- }
- virtual void reset()
- {
- if (helper.searchTextNeedsFree())
- rtlFree(curSearchText);
- curSearchText = NULL;
- ReleaseClearRoxieRow(in);
- StrandProcessor::reset();
- }
- virtual const void * nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (rowIter->isValid())
- {
- OwnedConstRoxieRow out = rowIter->getRow();
- rowIter->next();
- processed++;
- return out.getClear();
- }
- ReleaseClearRoxieRow(in);
- in = inputStream->nextRow();
- if (!in)
- {
- if (processed == numProcessedLastGroup)
- in = inputStream->nextRow();
- if (!in)
- {
- processed = numProcessedLastGroup;
- return NULL;
- }
- in = inputStream->nextRow();
- if (!in)
- return NULL;
- }
- processRecord(in);
- rowIter->first();
- }
- }
- virtual unsigned onMatch(ARowBuilder & self, const void * curRecord, IMatchedResults * results, IMatchWalker * walker)
- {
- try
- {
- return helper.transform(self, curRecord, results, walker);
- }
- catch (IException *E)
- {
- throw parent.makeWrappedException(E);
- }
- }
- };
- public:
- CRoxieServerStrandedParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, INlpParseAlgorithm * _algorithm, const StrandOptions &_strandOptions)
- : CRoxieServerStrandedActivity(_ctx, _factory, _probeManager, _strandOptions), algorithm(_algorithm)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerStrandedActivity::start(parentExtractSize, parentExtract, paused);
- onStartStrands();
- }
- virtual StrandProcessor *createStrandProcessor(IEngineRowStream *instream)
- {
- return new ParseProcessor(*this, instream, (IHThorParseArg &) basehelper, algorithm);
- }
- virtual StrandProcessor *createStrandSourceProcessor(bool inputOrdered) { throwUnexpected(); }
- };
- class CRoxieServerParseActivityFactory : public CRoxieServerActivityFactory
- {
- Owned<INlpParseAlgorithm> algorithm;
- Owned<IHThorParseArg> helper;
- StrandOptions strandOptions;
- public:
- CRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), strandOptions(_graphNode)
- {
- helper.setown((IHThorParseArg *) helperFactory());
- algorithm.setown(createThorParser(rc, *helper));
- optStableInput = false;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerStrandedParseActivity(_ctx, this, _probeManager, algorithm, strandOptions);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, IResourceContext *rc)
- {
- return new CRoxieServerParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, rc);
- }
- //=====================================================================================================
- class CRoxieServerWorkUnitWriteActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorWorkUnitWriteArg &helper;
- bool isReread;
- bool grouped;
- IRoxieServerContext *serverContext;
- public:
- CRoxieServerWorkUnitWriteActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, bool _isReread, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorWorkUnitWriteArg &)basehelper), isReread(_isReread)
- {
- grouped = (helper.getFlags() & POFgrouped) != 0;
- serverContext = NULL;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
- serverContext = ctx->queryServerContext();
- if (!serverContext)
- {
- throw MakeStringException(ROXIE_PIPE_ERROR, "Pipe output activity cannot be executed in slave context");
- }
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onExecute()
- {
- int sequence = helper.getSequence();
- const char *storedName = helper.queryName();
- if (!storedName)
- storedName = "Dataset";
- MemoryBuffer result;
- bool saveInContext = (int) sequence < 0 || isReread;
- if (!meta.queryOriginal()) // this is a bit of a hack - don't know why no meta on an output....
- meta.set(input->queryOutputMeta());
- Owned<IOutputRowSerializer> rowSerializer;
- Owned<IXmlWriter> xmlwriter;
- bool appendRaw = false;
- IHpccProtocolResultsWriter *results = NULL;
- IHpccNativeProtocolResultsWriter *nativeResults = NULL;
- IHpccProtocolResponse *protocol = serverContext->queryProtocol();
- unsigned protocolFlags = (protocol) ? protocol->getFlags() : 0;
- if ((int) sequence >= 0)
- {
- results = (protocol) ? protocol->queryHpccResultsSection() : NULL;
- if (results)
- {
- nativeResults = dynamic_cast<IHpccNativeProtocolResultsWriter*>(results);
- xmlwriter.setown(results->addDataset(helper.queryName(), sequence, "Dataset", appendRaw, serverContext->getXmlFlags(), (helper.getFlags() & POFextend) != 0, serverContext->queryXmlns(sequence))); //xmlwriter only returned if needed
- }
- }
- size32_t outputLimitBytes = 0;
- IConstWorkUnit *workunit = serverContext->queryWorkUnit();
- if (workunit)
- {
- size32_t outputLimit;
- if (helper.getFlags() & POFmaxsize)
- outputLimit = helper.getMaxSize();
- else
- {
- // In absense of OPT_OUTPUTLIMIT check pre 5.2 legacy name OPT_OUTPUTLIMIT_LEGACY
- outputLimit = workunit->getDebugValueInt(OPT_OUTPUTLIMIT, workunit->getDebugValueInt(OPT_OUTPUTLIMIT_LEGACY, defaultDaliResultLimit));
- }
- if (outputLimit>defaultDaliResultOutputMax)
- 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);
- assertex(outputLimit<=0x1000); // 32bit limit because MemoryBuffer/CMessageBuffers involved etc.
- outputLimitBytes = outputLimit * 0x100000;
- }
- if (workunit != NULL || (results && protocol->getFlags() & HPCC_PROTOCOL_NATIVE_RAW))
- {
- ensureRowAllocator();
- rowSerializer.setown(rowAllocator->createDiskSerializer(ctx->queryCodeContext()));
- }
- __int64 initialProcessed = processed;
- RtlLinkedDatasetBuilder builder(rowAllocator);
- loop
- {
- const void *row = inputStream->nextRow();
- if (saveInContext)
- {
- if (row || grouped)
- builder.append(row);
- }
- if (grouped && (processed != initialProcessed))
- {
- if (workunit)
- result.append(row == NULL);
- if (results)
- {
- if (protocolFlags & HPCC_PROTOCOL_NATIVE_RAW && nativeResults)
- {
- char val = (char)(row == NULL);
- nativeResults->appendRaw(sequence, 1, &val);
- }
- else if (xmlwriter)
- {
- xmlwriter->outputBeginNested("Row", false);
- xmlwriter->outputCString("1", "@__GroupBreak__");
- xmlwriter->outputEndNested("Row");
- }
- }
- }
- if (!row)
- {
- row = inputStream->nextRow();
- if (!row)
- break;
- if (saveInContext)
- builder.append(row);
- }
- processed++;
- if (workunit)
- {
- CThorDemoRowSerializer serializerTarget(result);
- rowSerializer->serialize(serializerTarget, (const byte *) row);
- }
- if ((int) sequence >= 0)
- {
- if (appendRaw && nativeResults)
- {
- // MORE - should be able to serialize straight to the response...
- MemoryBuffer rowbuff;
- CThorDemoRowSerializer serializerTarget(rowbuff);
- rowSerializer->serialize(serializerTarget, (const byte *) row);
- nativeResults->appendRawRow(sequence, rowbuff.length(), rowbuff.toByteArray());
- }
- else if (xmlwriter)
- {
- xmlwriter->outputBeginNested(DEFAULTXMLROWTAG, false);
- helper.serializeXml((byte *) row, *xmlwriter);
- xmlwriter->outputEndNested(DEFAULTXMLROWTAG);
- results->finalizeXmlRow(sequence);
- }
- else if (nativeResults)
- {
- SimpleOutputWriter x;
- helper.serializeXml((byte *) row, x);
- x.newline();
- nativeResults->appendSimpleRow(sequence, x.str());
- }
- }
- ReleaseRoxieRow(row);
- if (outputLimitBytes && result.length() > outputLimitBytes)
- {
- StringBuffer errMsg("Dataset too large to output to workunit (limit ");
- errMsg.append(outputLimitBytes/0x100000).append(" megabytes), in result (");
- const char *name = helper.queryName();
- if (name)
- errMsg.append("name=").append(name);
- else
- errMsg.append("sequence=").append(helper.getSequence());
- errMsg.append(")");
- throw MakeStringExceptionDirect(0, errMsg.str());
- }
- }
- if (xmlwriter)
- xmlwriter->outputEndArray(DEFAULTXMLROWTAG);
- if (saveInContext)
- serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
- if (workunit)
- serverContext->appendResultRawContext(storedName, sequence, result.length(), result.toByteArray(), processed, (helper.getFlags() & POFextend) != 0, false); // MORE - shame to do extra copy...
- }
- };
- class CRoxieServerWorkUnitWriteActivityFactory : public CRoxieServerInternalSinkFactory
- {
- bool isReread;
- public:
- CRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
- {
- isReread = usageCount > 0;
- Owned<IHThorWorkUnitWriteArg> helper = (IHThorWorkUnitWriteArg *) helperFactory();
- isInternal = (helper->getSequence()==ResultSequenceInternal);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerWorkUnitWriteActivity(_ctx, this, _probeManager, isReread, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- {
- return new CRoxieServerWorkUnitWriteActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
- }
- //=====================================================================================================
- class CRoxieServerWorkUnitWriteDictActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorDictionaryWorkUnitWriteArg &helper;
- IRoxieServerContext *serverContext;
- public:
- CRoxieServerWorkUnitWriteDictActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _usageCount)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _usageCount), helper((IHThorDictionaryWorkUnitWriteArg &)basehelper)
- {
- serverContext = NULL;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerInternalSinkActivity::onCreate(_colocalParent);
- serverContext = ctx->queryServerContext();
- if (!serverContext)
- {
- throw MakeStringException(ROXIE_PIPE_ERROR, "Write Dictionary activity cannot be executed in slave context");
- }
- }
- virtual bool needsAllocator() const { return true; }
- virtual void onExecute()
- {
- int sequence = helper.getSequence();
- const char *storedName = helper.queryName();
- assertex(storedName && *storedName);
- assertex(sequence < 0);
- RtlLinkedDictionaryBuilder builder(rowAllocator, helper.queryHashLookupInfo());
- loop
- {
- const void *row = inputStream->ungroupedNextRow();
- if (!row)
- break;
- builder.appendOwn(row);
- processed++;
- }
- serverContext->appendResultDeserialized(storedName, sequence, builder.getcount(), builder.linkrows(), (helper.getFlags() & POFextend) != 0, LINK(meta.queryOriginal()));
- }
- };
- class CRoxieServerWorkUnitWriteDictActivityFactory : public CRoxieServerInternalSinkFactory
- {
- public:
- CRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
- {
- Owned<IHThorDictionaryWorkUnitWriteArg> helper = (IHThorDictionaryWorkUnitWriteArg *) helperFactory();
- isInternal = (helper->getSequence()==ResultSequenceInternal);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerWorkUnitWriteDictActivity(_ctx, this, _probeManager, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerWorkUnitWriteDictActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- {
- return new CRoxieServerWorkUnitWriteDictActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
- }
- //=================================================================================
- class CRoxieServerRemoteResultActivity : public CRoxieServerInternalSinkActivity
- {
- IHThorRemoteResultArg &helper;
- public:
- CRoxieServerRemoteResultActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, unsigned _numOutputs)
- : CRoxieServerInternalSinkActivity(_ctx, _factory, _probeManager, _numOutputs), helper((IHThorRemoteResultArg &)basehelper)
- {
- }
- virtual void onExecute()
- {
- OwnedConstRoxieRow row = inputStream->nextRow();
- helper.sendResult(row); // should be only one row or something has gone wrong!
- }
- };
- class CRoxieServerRemoteResultActivityFactory : public CRoxieServerInternalSinkFactory
- {
- public:
- CRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- : CRoxieServerInternalSinkFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot)
- {
- Owned<IHThorRemoteResultArg> helper = (IHThorRemoteResultArg *) helperFactory();
- isInternal = (helper->getSequence()==ResultSequenceInternal);
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerRemoteResultActivity(_ctx, this, _probeManager, usageCount);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerRemoteResultActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, unsigned _usageCount, bool _isRoot)
- {
- return new CRoxieServerRemoteResultActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _usageCount, _isRoot);
- }
- //=================================================================================
- class CRoxieServerXmlParseActivity : public CRoxieServerActivity, implements IXMLSelect
- {
- IHThorXmlParseArg &helper;
- Owned<IXMLParse> xmlParser;
- const void * in;
- char * srchStr;
- unsigned numProcessedLastGroup;
- bool srchStrNeedsFree;
- Owned<IColumnProvider> lastMatch;
- public:
- IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
- CRoxieServerXmlParseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorXmlParseArg &)basehelper)
- {
- srchStrNeedsFree = helper.searchTextNeedsFree();
- numProcessedLastGroup = 0;
- srchStr = NULL;
- in = NULL;
- }
- ~CRoxieServerXmlParseActivity()
- {
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- numProcessedLastGroup = 0;
- srchStr = NULL;
- in = NULL;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- if (helper.searchTextNeedsFree())
- rtlFree(srchStr);
- srchStr = NULL;
- ReleaseClearRoxieRow(in);
- xmlParser.clear();
- CRoxieServerActivity::reset();
- }
- virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
- {
- lastMatch.set(&entry);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if(xmlParser)
- {
- loop
- {
- if(!xmlParser->next())
- {
- if (srchStrNeedsFree)
- {
- rtlFree(srchStr);
- srchStr = NULL;
- }
- xmlParser.clear();
- break;
- }
- if(lastMatch)
- {
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = helper.transform(rowBuilder, in, lastMatch);
- lastMatch.clear();
- if (outSize)
- {
- processed++;
- return rowBuilder.finalizeRowClear(outSize);
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- }
- }
- ReleaseClearRoxieRow(in);
- in = inputStream->nextRow();
- if(!in)
- {
- if(numProcessedLastGroup == processed)
- in = inputStream->nextRow();
- if(!in)
- {
- numProcessedLastGroup = processed;
- return NULL;
- }
- }
- size32_t srchLen;
- helper.getSearchText(srchLen, srchStr, in);
- OwnedRoxieString xmlIteratorPath(helper.getXmlIteratorPath());
- xmlParser.setown(createXMLParse(srchStr, srchLen, xmlIteratorPath, *this));
- }
- }
- };
- class CRoxieServerXmlParseActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerXmlParseActivity(_ctx, this, _probeManager);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerXmlParseActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerXmlParseActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //=====================================================================================================
- class CRoxieServerDiskReadBaseActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler, implements IIndexReadContext
- {
- protected:
- IHThorDiskReadBaseArg &helper;
- IHThorCompoundExtra * compoundHelper;
- RemoteActivityId remoteId; // Note we copy it rather than reference
- Owned<CSkippableRemoteResultAdaptor> remote;
- unsigned numParts;
- unsigned __int64 rowLimit;
- unsigned __int64 stopAfter;
- Linked<IInMemoryIndexManager> manager;
- Owned<IInMemoryIndexCursor> cursor;
- Owned<IDirectReader> reader;
- CThorContiguousRowBuffer deserializeSource;
- Owned<ISourceRowPrefetcher> prefetcher;
- bool eof;
- bool isKeyed;
- bool variableFileName;
- bool isOpt;
- bool sorted;
- bool maySkip;
- bool isLocal;
- bool forceRemote;
- CachedOutputMetaData diskSize;
- Owned<const IResolvedFile> varFileInfo;
- Owned<IFileIOArray> varFiles;
- inline bool useRemote()
- {
- return remote != NULL && (forceRemote || numParts > 1);
- }
- public:
- IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
- CRoxieServerDiskReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorDiskReadBaseArg &)basehelper),
- numParts(_numParts),
- remoteId(_remoteId),
- manager(_manager),
- isLocal(_isLocal),
- sorted(_sorted),
- maySkip(_maySkip),
- deserializeSource(NULL)
- {
- forceRemote = factory->queryQueryFactory().queryOptions().disableLocalOptimizations;
- if ((forceRemote || numParts != 1) && !isLocal) // NOTE : when numParts == 0 (variable case) we create, even though we may not use
- remote.setown(new CSkippableRemoteResultAdaptor(_ctx, this, remoteId, meta.queryOriginal(), helper, *this, sorted, false, _maySkip));
- compoundHelper = NULL;
- eof = false;
- rowLimit = (unsigned __int64) -1;
- isKeyed = false;
- stopAfter = I64C(0x7FFFFFFFFFFFFFFF);
- diskSize.set(helper.queryDiskRecordSize());
- variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
- isOpt = (helper.getFlags() & TDRoptional) != 0;
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- if (remote)
- remote->onCreate(_colocalParent);
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (compoundHelper)
- {
- rowLimit = compoundHelper->getRowLimit();
- stopAfter = compoundHelper->getChooseNLimit();
- }
- if (!helper.canMatchAny())
- eof = true;
- else
- {
- if (variableFileName)
- {
- OwnedRoxieString fileName(helper.getFileName());
- varFileInfo.setown(resolveLFN(fileName, isOpt));
- numParts = 0;
- if (varFileInfo)
- numParts = varFileInfo->getNumParts();
- }
- if (!numParts)
- {
- eof = true;
- }
- else if (useRemote())
- {
- remote->onStart(parentExtractSize, parentExtract);
- remote->setLimits(rowLimit, (unsigned __int64) -1, stopAfter);
- unsigned fileNo = 0;
- // Translation into a message per channel done elsewhere....
- remote->getMem(0, fileNo, 0);
- remote->flush();
- remote->senddone();
- }
- else
- {
- if (variableFileName)
- {
- unsigned channel = isLocal ? factory->queryQueryFactory().queryChannel() : 0;
- varFiles.setown(varFileInfo->getIFileIOArray(isOpt, channel));
- manager.setown(varFileInfo->getIndexManager(isOpt, channel, varFiles, diskSize, false, 0));
- }
- assertex(manager != NULL);
- helper.createSegmentMonitors(this);
- if (cursor)
- {
- isKeyed = cursor->selectKey();
- cursor->reset();
- }
- if (!isKeyed)
- {
- reader.setown(manager->createReader(0, 0, 1));
- deserializeSource.setStream(reader);
- prefetcher.setown(diskSize.queryOriginal()->createDiskPrefetcher(ctx->queryCodeContext(), activityId));
- }
- helper.setCallback(reader ? reader->queryThorDiskCallback() : cursor);
- }
- }
- }
- virtual void append(IKeySegmentMonitor *segment)
- {
- if (!segment->isWild())
- {
- if (!cursor)
- cursor.setown(manager->createCursor());
- cursor->append(segment);
- }
- }
- virtual unsigned ordinality() const
- {
- return cursor ? cursor->ordinality() : 0;
- }
- virtual IKeySegmentMonitor *item(unsigned idx) const
- {
- return cursor ? cursor->item(idx) : 0;
- }
- virtual void setMergeBarrier(unsigned barrierOffset)
- {
- // no merging so no issue...
- }
- virtual void stop()
- {
- if (useRemote())
- remote->onStop();
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- if (useRemote())
- {
- processed = remote->processed;
- remote->processed = 0;
- remote->onReset();
- }
- varFileInfo.clear();
- eof = false;
- if (cursor)
- cursor->reset();
- deserializeSource.clearStream();
- CRoxieServerActivity::reset();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- assertex(compoundHelper);
- if (isKeyed) // MORE does this exist for diskread? should it?
- {
- if (helper.getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(true);
- }
- else
- {
- UNIMPLEMENTED;
- //compoundHelper->onKeyedLimitExceeded(); Doesn't exist - though the flags do... interesting...
- }
- }
- else
- {
- if (helper.getFlags() & (TDRlimitskips|TDRlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(false);
- }
- else
- compoundHelper->onLimitExceeded();
- }
- }
- virtual const void * createLimitFailRow(bool isKeyed)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- IHThorSourceLimitTransformExtra *limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(helper.selectInterface(TAIsourcelimittransformextra_1));
- assertex(limitTransformExtra);
- size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- return NULL;
- }
- };
- class CRoxieServerDiskReadActivity : public CRoxieServerDiskReadBaseActivity
- {
- IHThorCompoundReadExtra * readHelper;
- ConstPointerArray readrows;
- bool readAheadDone;
- unsigned readIndex;
- public:
- CRoxieServerDiskReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
- {
- compoundHelper = (IHThorDiskReadArg *)&helper;
- readHelper = (IHThorDiskReadArg *)&helper;
- readAheadDone = false;
- readIndex = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- rowLimit = compoundHelper->getRowLimit();
- stopAfter = compoundHelper->getChooseNLimit();
- CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- readAheadDone = false;
- readIndex = 0;
- }
- virtual void reset()
- {
- roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
- readrows.kill();
- readAheadDone = false;
- readIndex = 0;
- CRoxieServerDiskReadBaseActivity::reset();
- }
- virtual const void *nextRow()
- {
- if (eof)
- return NULL;
- else if (useRemote())
- return remote->nextRow();
- else if (maySkip)
- {
- if (!readAheadDone)
- {
- unsigned preprocessed = 0;
- while (!eof)
- {
- const void *row = _nextRow();
- if (row)
- preprocessed++;
- if (preprocessed > rowLimit)
- {
- ReleaseRoxieRow(row);
- roxiemem::ReleaseRoxieRowRange(readrows.getArray(), readIndex, readrows.ordinality());
- readrows.kill();
- readIndex = 0;
- eof = true;
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if (helper.getFlags() & TDRlimitskips)
- return NULL;
- else if (helper.getFlags() & TDRlimitcreates)
- return createLimitFailRow(false);
- else
- throwUnexpected();
- }
- if (preprocessed > stopAfter) // MORE - bit of a strange place to check
- {
- eof = true;
- ReleaseRoxieRow(row);
- break;
- }
- readrows.append(row);
- }
- readAheadDone = true;
- }
- if (readrows.isItem(readIndex))
- {
- const void *ret = readrows.item(readIndex++);
- if (ret)
- processed++;
- return ret;
- }
- else
- {
- eof = true;
- return NULL;
- }
- }
- else
- {
- const void *ret = _nextRow();
- if (ret)
- {
- processed++;
- if (processed > rowLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- ReleaseRoxieRow(ret);
- compoundHelper->onLimitExceeded();
- throwUnexpected(); // onLimitExceeded is not supposed to return
- }
- if (processed > stopAfter) // MORE - bit of a strange place to check
- {
- eof = true;
- ReleaseRoxieRow(ret);
- return NULL;
- }
- }
- return ret;
- }
- }
- const void *_nextRow()
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned transformedSize = 0;
- if (isKeyed)
- {
- loop
- {
- const void *nextCandidate = cursor->nextMatch();
- if (!nextCandidate)
- {
- eof = true;
- return NULL;
- }
- transformedSize = readHelper->transform(rowBuilder, nextCandidate);
- if (transformedSize)
- break;
- }
- }
- else // use reader...
- {
- assertex(reader != NULL);
- loop
- {
- if (deserializeSource.eos())
- {
- eof = true;
- return NULL;
- }
- prefetcher->readAhead(deserializeSource);
- const byte *nextRec = deserializeSource.queryRow();
- if (cursor && cursor->isFiltered(nextRec))
- transformedSize = 0;
- else
- transformedSize = readHelper->transform(rowBuilder, nextRec);
- deserializeSource.finishedRow();
- if (transformedSize)
- break;
- }
- }
- return rowBuilder.finalizeRowClear(transformedSize);
- }
- };
- class CRoxieServerXmlReadActivity : public CRoxieServerDiskReadBaseActivity, implements IXMLSelect, implements IThorDiskCallback
- {
- IHThorXmlReadArg * readHelper;
- Owned<IXmlToRowTransformer> rowTransformer;
- Owned<IXMLParse> xmlParser;
- Owned<IColumnProvider> lastMatch;
- unsigned __int64 fileoffset;
- public:
- IMPLEMENT_IINTERFACE_USING(CRoxieServerDiskReadBaseActivity)
- CRoxieServerXmlReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager)
- {
- compoundHelper = NULL;
- readHelper = (IHThorXmlReadArg *)&helper;
- fileoffset = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- rowLimit = readHelper->getRowLimit();
- stopAfter = readHelper->getChooseNLimit();
- CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- if (!useRemote())
- {
- rowTransformer.set(readHelper->queryTransformer());
- assertex(reader != NULL);
- OwnedRoxieString xmlIterator(readHelper->getXmlIteratorPath());
- if (factory->getKind()==TAKjsonread)
- xmlParser.setown(createJSONParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
- else
- xmlParser.setown(createXMLParse(*reader->querySimpleStream(), xmlIterator, *this, (0 != (TDRxmlnoroot & readHelper->getFlags()))?ptr_noRoot:ptr_none, (readHelper->getFlags() & TDRusexmlcontents) != 0));
- }
- }
- virtual void reset()
- {
- CRoxieServerDiskReadBaseActivity::reset();
- rowTransformer.clear();
- xmlParser.clear();
- }
- virtual void match(IColumnProvider &entry, offset_t startOffset, offset_t endOffset)
- {
- fileoffset = startOffset;
- lastMatch.set(&entry);
- }
- //interface IThorDiskCallback
- virtual unsigned __int64 getFilePosition(const void * row)
- {
- return fileoffset;
- }
- virtual unsigned __int64 getLocalFilePosition(const void * row)
- {
- return reader->makeFilePositionLocal(fileoffset);
- }
- virtual const char * queryLogicalFilename(const void * row)
- {
- return reader->queryThorDiskCallback()->queryLogicalFilename(row);
- }
- virtual const void *nextRow()
- {
- if (eof)
- return NULL;
- else if (useRemote())
- return remote->nextRow();
- assertex(xmlParser != NULL);
- try
- {
- while (!eof)
- {
- //call to next() will callback on the IXmlSelect interface
- bool gotNext = false;
- gotNext = xmlParser->next();
- if(!gotNext)
- eof = true;
- else if (lastMatch)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned sizeGot = rowTransformer->transform(rowBuilder, lastMatch, this);
- lastMatch.clear();
- fileoffset = 0;
- if (sizeGot)
- {
- OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(sizeGot);
- if (processed > rowLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- readHelper->onLimitExceeded();
- throwUnexpected(); // onLimitExceeded is not supposed to return
- }
- processed++;
- if (processed > stopAfter) // MORE - bit of a strange place to check
- {
- eof = true;
- return NULL;
- }
- return ret.getClear();
- }
- }
- }
- return NULL;
- }
- catch(IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- };
- class CRoxieServerCsvReadActivity : public CRoxieServerDiskReadBaseActivity
- {
- IHThorCsvReadArg *readHelper;
- ICsvParameters * csvInfo;
- unsigned headerLines;
- unsigned maxDiskSize;
- CSVSplitter csvSplitter;
- unsigned __int64 localOffset;
- const char *quotes;
- const char *separators;
- const char *terminators;
- const char *escapes;
- size32_t maxRowSize;
- public:
- CRoxieServerCsvReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- unsigned _numParts, bool _isLocal, bool _sorted, bool _maySkip, IInMemoryIndexManager *_manager,
- const char *_quotes, const char *_separators, const char *_terminators, const char *_escapes, size32_t _maxRowSize)
- : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, _maySkip, _manager),
- quotes(_quotes), separators(_separators), terminators(_terminators), escapes(_escapes), maxRowSize(_maxRowSize)
- {
- compoundHelper = NULL;
- readHelper = (IHThorCsvReadArg *)&helper;
- rowLimit = readHelper->getRowLimit();
- stopAfter = readHelper->getChooseNLimit();
- csvInfo = readHelper->queryCsvParameters();
- maxDiskSize = csvInfo->queryMaxSize();
- localOffset = 0;
- headerLines = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- rowLimit = readHelper->getRowLimit();
- stopAfter = readHelper->getChooseNLimit();
- CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- if (!useRemote())
- {
- headerLines = csvInfo->queryHeaderLen();
- if (headerLines && isLocal && reader->queryFilePart() != 1)
- 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...
- if (!eof)
- {
- if (varFileInfo)
- {
- const IPropertyTree *options = varFileInfo->queryProperties();
- if (options)
- {
- quotes = options->queryProp("@csvQuote");
- separators = options->queryProp("@csvSeparate");
- terminators = options->queryProp("@csvTerminate");
- escapes = options->queryProp("@csvEscape");
- }
- }
- csvSplitter.init(readHelper->getMaxColumns(), csvInfo, quotes, separators, terminators, escapes);
- }
- }
- }
- virtual const void *nextRow()
- {
- if (eof)
- return NULL;
- else if (useRemote())
- return remote->nextRow();
- try
- {
- while (!eof)
- {
- if (reader->eos())
- {
- eof = true;
- break;
- }
- // MORE - there are rumours of a csvSplitter that operates on a stream... if/when it exists, this should use it
- size32_t rowSize = 4096; // MORE - make configurable
- size32_t thisLineLength;
- loop
- {
- size32_t avail;
- const void *peek = reader->peek(rowSize, avail);
- thisLineLength = csvSplitter.splitLine(avail, (const byte *)peek);
- if (thisLineLength < rowSize || avail < rowSize)
- break;
- if (rowSize == maxRowSize)
- throw MakeStringException(0, "File contained a line of length greater than %d bytes.", maxRowSize);
- if (rowSize >= maxRowSize/2)
- rowSize = maxRowSize;
- else
- rowSize += rowSize;
- }
- if (headerLines)
- {
- headerLines--;
- reader->skip(thisLineLength);
- }
- else
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned transformedSize = readHelper->transform(rowBuilder, csvSplitter.queryLengths(), (const char * *)csvSplitter.queryData());
- reader->skip(thisLineLength);
- if (transformedSize)
- {
- OwnedConstRoxieRow ret = rowBuilder.finalizeRowClear(transformedSize);
- if (processed > rowLimit)
- {
- readHelper->onLimitExceeded();
- throwUnexpected(); // onLimitExceeded is not supposed to return
- }
- processed++;
- if (processed > stopAfter) // MORE - bit of a strange place to check
- {
- eof = true;
- return NULL;
- }
- return ret.getClear();
- }
- }
- }
- return NULL;
- }
- catch(IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- virtual void reset()
- {
- CRoxieServerDiskReadBaseActivity::reset();
- csvSplitter.reset();
- localOffset = 0;
- }
- virtual unsigned __int64 getFilePosition(const void * row)
- {
- UNIMPLEMENTED; // we know offset in the reader but not sure it helps us much
- }
- virtual unsigned __int64 getLocalFilePosition(const void * row)
- {
- UNIMPLEMENTED;
- }
- };
- class CRoxieServerDiskNormalizeActivity : public CRoxieServerDiskReadBaseActivity
- {
- IHThorDiskNormalizeArg *normalizeHelper;
- bool firstPending;
- public:
- CRoxieServerDiskNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, bool _sorted, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _sorted, false, _manager)
- {
- compoundHelper = (IHThorDiskNormalizeArg *)&helper;
- normalizeHelper = (IHThorDiskNormalizeArg *)&helper;
- firstPending = true;
- }
- virtual void reset()
- {
- firstPending = true;
- CRoxieServerDiskReadBaseActivity::reset();
- }
- virtual const void *nextRow()
- {
- if (eof)
- return NULL;
- else if (useRemote())
- return remote->nextRow();
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned transformedSize = 0;
- if (isKeyed)
- {
- loop
- {
- while (firstPending)
- {
- const void *nextCandidate = cursor->nextMatch();
- if (!nextCandidate)
- {
- eof = true;
- return NULL;
- }
- if (normalizeHelper->first(nextCandidate))
- {
- firstPending = false;
- break;
- }
- }
- transformedSize = normalizeHelper->transform(rowBuilder);
- firstPending = !normalizeHelper->next();
- if (transformedSize)
- break;
- }
- }
- else
- {
- assertex(reader != NULL);
- loop
- {
- while (firstPending)
- {
- if (deserializeSource.eos())
- {
- eof = true;
- return NULL;
- }
- prefetcher->readAhead(deserializeSource);
- const byte *nextRec = deserializeSource.queryRow();
- if (!cursor || !cursor->isFiltered(nextRec))
- {
- if (normalizeHelper->first(nextRec))
- firstPending = false;
- }
- deserializeSource.finishedRow();
- }
- transformedSize = normalizeHelper->transform(rowBuilder);
- firstPending = !normalizeHelper->next();
- if (transformedSize)
- break;
- }
- }
- OwnedConstRoxieRow recBuffer = rowBuilder.finalizeRowClear(transformedSize);
- processed++;
- if (processed > rowLimit)
- {
- compoundHelper->onLimitExceeded();
- throwUnexpected(); // onLimitExceeded is not supposed to return
- }
- if (processed > stopAfter) // MORE - bit of a strange place to check
- {
- eof = true;
- return NULL;
- }
- return recBuffer.getClear();
- }
- };
- class CRoxieServerDiskAggregateBaseActivity : public CRoxieServerDiskReadBaseActivity
- {
- protected:
- bool done;
- public:
- CRoxieServerDiskAggregateBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, false, false, _manager),
- done(false)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerDiskReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL: this;
- }
- };
- class CRoxieServerDiskCountActivity : public CRoxieServerDiskAggregateBaseActivity
- {
- IHThorDiskCountArg & countHelper;
- unsigned __int64 choosenLimit;
- IHThorSourceCountLimit *limitHelper;
- unsigned __int64 getSkippedCount()
- {
- unsigned flags = countHelper.getFlags();
- if (flags & TDRlimitskips)
- return 0;
- else if (flags & TDRlimitcreates)
- return 1;
- else
- {
- assertex(limitHelper);
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- limitHelper->onLimitExceeded();
- throwUnexpected(); // onLimitExceeded should always throw exception
- }
- }
- public:
- CRoxieServerDiskCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
- countHelper((IHThorDiskCountArg &)basehelper)
- {
- limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
- choosenLimit = 0;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- choosenLimit = countHelper.getChooseNLimit();
- if (limitHelper)
- {
- rowLimit = limitHelper->getRowLimit();
- // keyedLimit = limitHelper->getKeyedLimit(); // more - should there be one?
- }
- CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- done = true;
- unsigned __int64 totalCount = 0;
- if (helper.canMatchAny() && !eof)
- {
- if (useRemote())
- {
- loop
- {
- const void * next = remote->nextRow();
- if (!next)
- break;
- if (meta.getFixedSize() == 1)
- totalCount += *(byte *)next;
- else
- totalCount += *(unsigned __int64 *)next;
- ReleaseRoxieRow(next);
- if (totalCount > rowLimit)
- {
- totalCount = getSkippedCount();
- break;
- }
- else if (totalCount >= choosenLimit)
- {
- totalCount = choosenLimit;
- break;
- }
- }
- }
- else
- {
- if (isKeyed)
- {
- loop
- {
- const void *nextCandidate = cursor->nextMatch();
- if (!nextCandidate)
- break;
- totalCount += countHelper.numValid(nextCandidate);
- if (totalCount > rowLimit)
- {
- totalCount = getSkippedCount();
- break;
- }
- else if (totalCount >= choosenLimit)
- {
- totalCount = choosenLimit;
- break;
- }
- }
- }
- else
- {
- assertex(reader != NULL);
- while (!deserializeSource.eos())
- {
- prefetcher->readAhead(deserializeSource);
- const byte *nextRec = deserializeSource.queryRow();
- if (!cursor || !cursor->isFiltered(nextRec))
- {
- totalCount += countHelper.numValid(nextRec);
- }
- deserializeSource.finishedRow();
- if (totalCount > rowLimit)
- {
- totalCount = getSkippedCount();
- break;
- }
- else if (totalCount >= choosenLimit)
- {
- totalCount = choosenLimit;
- break;
- }
- }
- }
- }
- }
- size32_t rowSize = meta.getFixedSize();
- void * result = rowAllocator->createRow();
- if (rowSize == 1)
- *(byte *)result = (byte)totalCount;
- else
- {
- assertex(rowSize == sizeof(unsigned __int64));
- *(unsigned __int64 *)result = totalCount;
- }
- return rowAllocator->finalizeRow(rowSize, result, rowSize);
- }
- };
- class CRoxieServerDiskAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
- {
- IHThorCompoundAggregateExtra & aggregateHelper;
- public:
- CRoxieServerDiskAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
- aggregateHelper((IHThorDiskAggregateArg &)basehelper)
- {
- }
- const void * gatherMerged()
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
- size32_t finalSize = 0;
- if (useRemote())
- {
- const void * firstRow = remote->nextRow();
- if (!firstRow)
- {
- rowBuilder.ensureRow();
- finalSize = aggregateHelper.clearAggregate(rowBuilder);
- }
- else
- {
- // NOTE need to clone this because going to modify below, could special case 1 row only
- finalSize = cloneRow(rowBuilder, firstRow, meta);
- ReleaseRoxieRow(firstRow);
- }
- loop
- {
- const void * next = remote->nextRow();
- if (!next)
- break;
- finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
- ReleaseRoxieRow(next);
- }
- }
- else
- {
- aggregateHelper.clearAggregate(rowBuilder);
- if (helper.canMatchAny() && !eof)
- {
- if (isKeyed)
- {
- loop
- {
- const void *next = cursor->nextMatch();
- if (!next)
- break;
- aggregateHelper.processRow(rowBuilder, next);
- }
- }
- else
- {
- assertex(reader != NULL);
- while (!deserializeSource.eos())
- {
- prefetcher->readAhead(deserializeSource);
- const byte *nextRec = deserializeSource.queryRow();
- if (!cursor || !cursor->isFiltered(nextRec))
- {
- aggregateHelper.processRow(rowBuilder, nextRec);
- }
- deserializeSource.finishedRow();
- }
- }
- }
- finalSize = meta.getRecordSize(rowBuilder.getSelf());
- }
- return rowBuilder.finalizeRowClear(finalSize);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- const void * ret = gatherMerged();
- done = true;
- return ret;
- }
- };
- class CRoxieServerDiskGroupAggregateActivity : public CRoxieServerDiskAggregateBaseActivity
- {
- IHThorDiskGroupAggregateArg & aggregateHelper;
- RowAggregator resultAggregator;
- bool gathered;
- public:
- CRoxieServerDiskGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _numParts, bool _isLocal, IInMemoryIndexManager *_manager)
- : CRoxieServerDiskAggregateBaseActivity(_ctx, _factory, _probeManager, _remoteId, _numParts, _isLocal, _manager),
- aggregateHelper((IHThorDiskGroupAggregateArg &)basehelper),
- resultAggregator(aggregateHelper, aggregateHelper),
- gathered(false)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- gathered= false;
- CRoxieServerDiskAggregateBaseActivity::start(parentExtractSize, parentExtract, paused);
- resultAggregator.start(rowAllocator);
- }
- virtual void reset()
- {
- resultAggregator.reset();
- CRoxieServerDiskAggregateBaseActivity::reset();
- }
- void gatherMerged()
- {
- if (useRemote())
- {
- loop
- {
- const void * next = remote->nextRow();
- if (!next)
- break;
- resultAggregator.mergeElement(next);
- ReleaseRoxieRow(next);
- }
- }
- else
- {
- if (helper.canMatchAny() && !eof)
- {
- Owned<IInMemoryFileProcessor> processor = isKeyed ?
- createKeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper) :
- createUnkeyedGroupAggregateRecordProcessor(cursor, resultAggregator, aggregateHelper, manager->createReader(0, 0, 1),
- ctx->queryCodeContext(), activityId);
- processor->doQuery(NULL, 0, 0, 0);
- }
- }
- gathered = true;
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done)
- return NULL;
- if (!gathered)
- gatherMerged();
- Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
- if (next)
- {
- processed++;
- return next->finalizeRowClear();
- }
- done = true;
- return NULL;
- }
- };
- class CRoxieServerDiskReadActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- RemoteActivityId remoteId;
- bool isLocal;
- bool sorted;
- bool maySkip;
- bool variableFileName;
- Owned<IFileIOArray> files;
- Owned<IInMemoryIndexManager> manager;
- Owned<const IResolvedFile> datafile;
- const char *quotes;
- const char *separators;
- const char *terminators;
- const char *escapes;
- size32_t maxCsvRowSize;
- CRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
- {
- isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
- Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
- sorted = (helper->getFlags() & TDRunsorted) == 0;
- variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) != 0);
- maySkip = (helper->getFlags() & (TDRkeyedlimitskips|TDRkeyedlimitcreates|TDRlimitskips|TDRlimitcreates)) != 0;
- quotes = separators = terminators = escapes = NULL;
- if (!variableFileName)
- {
- bool isOpt = (helper->getFlags() & TDRoptional) != 0;
- OwnedRoxieString fileName(helper->getFileName());
- datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, _queryFactory.queryWorkUnit(), true));
- bool isSimple = (datafile && datafile->getNumParts()==1 && !_queryFactory.queryOptions().disableLocalOptimizations);
- if (isLocal || isSimple)
- {
- if (datafile)
- {
- unsigned channel = isLocal ? queryFactory.queryChannel() : 0;
- files.setown(datafile->getIFileIOArray(isOpt, channel));
- manager.setown(datafile->getIndexManager(isOpt, channel, files, helper->queryDiskRecordSize(), _graphNode.getPropBool("att[@name=\"preload\"]/@value", false), _graphNode.getPropInt("att[@name=\"_preloadSize\"]/@value", 0)));
- const IPropertyTree *options = datafile->queryProperties();
- if (options)
- {
- quotes = options->queryProp("@csvQuote");
- separators = options->queryProp("@csvSeparate");
- terminators = options->queryProp("@csvTerminate");
- escapes = options->queryProp("@csvEscape");
- }
- }
- else
- manager.setown(getEmptyIndexManager());
- }
- }
- switch (kind)
- {
- case TAKcsvread:
- {
- maxCsvRowSize = defaultMaxCsvRowSize * 1024 * 1024;
- IConstWorkUnit *workunit = _queryFactory.queryWorkUnit();
- if (workunit)
- maxCsvRowSize = workunit->getDebugValueInt(OPT_MAXCSVROWSIZE, defaultMaxCsvRowSize) * 1024 * 1024;
- break;
- }
- default:
- maxCsvRowSize = 0; // unused
- }
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- unsigned numParts = datafile ? datafile->getNumParts() : 0;
- switch (kind)
- {
- case TAKcsvread:
- return new CRoxieServerCsvReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager,
- quotes, separators, terminators, escapes, maxCsvRowSize);
- case TAKxmlread:
- case TAKjsonread:
- return new CRoxieServerXmlReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
- case TAKdiskread:
- return new CRoxieServerDiskReadActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, maySkip, manager);
- case TAKdisknormalize:
- return new CRoxieServerDiskNormalizeActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, sorted, manager);
- case TAKdiskcount:
- return new CRoxieServerDiskCountActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
- case TAKdiskaggregate:
- return new CRoxieServerDiskAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
- case TAKdiskgroupaggregate:
- return new CRoxieServerDiskGroupAggregateActivity(_ctx, this, _probeManager, remoteId, numParts, isLocal, manager);
- }
- throwUnexpected();
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for %s activity", getActivityText(kind));
- }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- if (datafile)
- addXrefFileInfo(reply, datafile);
- else
- {
- // Temporarily resolve the file
- Owned<IHThorDiskReadBaseArg> helper = (IHThorDiskReadBaseArg *) helperFactory();
- if ((helper->getFlags() & (TDXvarfilename|TDXdynamicfilename)) == 0)
- {
- OwnedRoxieString fileName(helper->getFileName());
- Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
- if (temp)
- addXrefFileInfo(reply, temp);
- }
- }
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return diskStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDiskReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerDiskReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //=================================================================================
- class CRoxieServerIndexActivity : public CRoxieServerActivity, implements IRoxieServerErrorHandler
- {
- protected:
- IHThorIndexReadBaseArg &indexHelper;
- IHThorSteppedSourceExtra * steppedExtra;
- Linked<IKeyArray> keySet;
- Linked<TranslatorArray> translators;
- CSkippableRemoteResultAdaptor remote;
- CIndexTransformCallback callback;
- bool sorted;
- bool variableFileName;
- bool variableInfoPending;
- bool isOpt;
- bool isLocal;
- unsigned __int64 rowLimit;
- unsigned __int64 keyedLimit;
- unsigned __int64 choosenLimit;
- unsigned accepted;
- unsigned rejected;
- unsigned seekGEOffset;
- Owned<IKeyManager> tlk;
- Owned<const IResolvedFile> varFileInfo;
- const RemoteActivityId &remoteId;
- void setVariableFileInfo()
- {
- OwnedRoxieString indexName(indexHelper.getFileName());
- varFileInfo.setown(resolveLFN(indexName, isOpt));
- if (varFileInfo)
- {
- translators.setown(new TranslatorArray) ;
- keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
- }
- variableInfoPending = false;
- }
- public:
- CRoxieServerIndexActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- keySet(_keySet),
- translators(_translators),
- indexHelper((IHThorIndexReadBaseArg &)basehelper),
- remote(_ctx, this, _remoteId, meta.queryOriginal(), indexHelper, *this, _sorted, false, _maySkip),
- remoteId(_remoteId),
- sorted(_sorted),
- isLocal(_isLocal)
- {
- indexHelper.setCallback(&callback);
- steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
- variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((indexHelper.getFlags() & (TIRvarfilename|TIRdynamicfilename)) != 0);
- variableInfoPending = false;
- isOpt = (indexHelper.getFlags() & TIRoptional) != 0;
- seekGEOffset = 0;
- // started = false;
- rejected = accepted = 0;
- rowLimit = choosenLimit = keyedLimit = 0;
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- remote.onCreate(_colocalParent);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- accepted = 0;
- rejected = 0;
- rowLimit = (unsigned __int64) -1;
- keyedLimit = (unsigned __int64 ) -1;
- choosenLimit = I64C(0x7fffffffffffffff);
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- remote.onStart(parentExtractSize, parentExtract);
- variableInfoPending = variableFileName;
- }
- void processAllKeys()
- {
- try
- {
- if (indexHelper.canMatchAny())
- {
- if (variableInfoPending)
- setVariableFileInfo();
- remote.setLimits(rowLimit, keyedLimit, choosenLimit);
- if (keySet)
- {
- // MORE - this recreates the segmonitors per part but not per fileno (which is a little backwards).
- // 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
- // However order is probably better to iterate fileno's inside partnos
- // MORE - also not properly supporting STEPPED I fear.
- // A superkey that mixes single and multipart or tlk and roroot keys might be hard
- for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
- {
- IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
- if (thisBase)
- {
- unsigned fileNo = 0;
- IKeyIndex *thisKey = thisBase->queryPart(fileNo);
- if (!thisKey->isTopLevelKey())
- {
- if (keyedLimit != (unsigned __int64) -1)
- {
- if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
- {
- Owned<IKeyManager> countKey;
- countKey.setown(createKeyManager(thisKey, 0, this));
- countKey->setLayoutTranslator(translators->item(fileNo));
- createSegmentMonitors(countKey);
- unsigned __int64 count = countKey->checkCount(keyedLimit);
- if (count > keyedLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- onLimitExceeded(true);
- }
- }
- }
- }
- if (seekGEOffset && !thisKey->isTopLevelKey())
- {
- tlk.setown(createSingleKeyMerger(thisKey, 0, seekGEOffset, this));
- }
- else
- {
- tlk.setown(createKeyManager(thisKey, 0, this));
- tlk->setLayoutTranslator(translators->item(fileNo));
- }
- createSegmentMonitors(tlk);
- if (queryTraceLevel() > 3 || ctx->queryProbeManager())
- {
- StringBuffer out;
- printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
- CTXLOG("Using filter %s", out.str());
- if (ctx->queryProbeManager())
- ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
- }
- tlk->reset();
- loop // for each file part
- {
- //block for TransformCallbackAssociation
- {
- TransformCallbackAssociation associate(callback, tlk);
- if (thisKey->isTopLevelKey())
- {
- if (thisKey->isFullySorted())
- {
- while (tlk->lookup(false))
- {
- unsigned slavePart = (unsigned) tlk->queryFpos();
- if (slavePart)
- {
- accepted++;
- remote.getMem(slavePart, fileNo, 0); // the cached context is all we need to send
- if (sorted && numChannels>1)
- remote.flush(); // don't combine parts if we need result sorted, except on a 1-way
- }
- }
- }
- else
- {
- // MORE - we could check whether there are any matching parts if we wanted.
- // If people are in the habit of sending null values that would be worthwhile
- remote.getMem(0, fileNo, 0);
- }
- }
- else
- {
- if (processSingleKey(thisKey, translators->item(fileNo)))
- break;
- }
- }
- if (++fileNo < thisBase->numParts())
- {
- thisKey = thisBase->queryPart(fileNo);
- tlk->setKey(thisKey);
- tlk->setLayoutTranslator(translators->item(fileNo));
- tlk->reset();
- }
- else
- break;
- }
- tlk->releaseSegmentMonitors();
- tlk->setKey(NULL);
- }
- }
- }
- }
- remote.flush();
- remote.senddone();
- }
- catch (IException *E)
- {
- remote.setException(E);
- }
- }
- virtual void createSegmentMonitors(IKeyManager *key)
- {
- indexHelper.createSegmentMonitors(key);
- key->finishSegmentMonitors();
- }
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans) = 0;
- virtual void reset()
- {
- if (accepted)
- noteStatistic(StNumIndexAccepted, accepted);
- if (rejected)
- noteStatistic(StNumIndexRejected, rejected);
- remote.onReset();
- CRoxieServerActivity::reset();
- if (varFileInfo)
- {
- keySet.clear();
- varFileInfo.clear();
- }
- variableInfoPending = false;
- }
- virtual void stop()
- {
- remote.onStop();
- CRoxieServerActivity::stop();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- };
- class CRoxieServerIndexReadBaseActivity : public CRoxieServerIndexActivity
- {
- IHThorSourceLimitTransformExtra * limitTransformExtra;
- public:
- CRoxieServerIndexReadBaseActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip)
- : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip)
- {
- limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
- }
- virtual void reset()
- {
- remote.onReset();
- CRoxieServerIndexActivity::reset();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- try
- {
- const void *ret = remote.nextRow();
- if (ret)
- processed++;
- return ret;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- protected:
- virtual const void * createLimitFailRow(bool isKeyed)
- {
- ensureRowAllocator();
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = isKeyed ? limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder) : limitTransformExtra->transformOnLimitExceeded(rowBuilder);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- return NULL;
- }
- };
- class CRoxieServerIndexReadActivity : public CRoxieServerIndexReadBaseActivity, implements IIndexReadActivityInfo
- {
- protected:
- IHThorCompoundReadExtra & readHelper;
- ISteppingMeta *rawMeta = nullptr;
- CSteppingMeta steppingMeta;
- unsigned * seekSizes = nullptr;
- bool optimizeSteppedPostFilter;
- ISteppingMeta * projectedMeta = nullptr;
- unsigned maxSeekLookahead;
- public:
- CRoxieServerIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal, bool _maySkip, unsigned _maxSeekLookahead)
- : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, _maySkip),
- readHelper((IHThorIndexReadArg &)basehelper)
- {
- rawMeta = readHelper.queryRawSteppingMeta();
- unsigned flags = indexHelper.getFlags();
- optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
- seekSizes = NULL;
- maxSeekLookahead = _maxSeekLookahead;
- if (rawMeta)
- {
- const CFieldOffsetSize * fields = rawMeta->queryFields();
- unsigned maxFields = rawMeta->getNumFields();
- seekGEOffset = fields[0].offset;
- seekSizes = new unsigned[maxFields];
- seekSizes[0] = fields[0].size;
- for (unsigned i=1; i < maxFields; i++)
- seekSizes[i] = seekSizes[i-1] + fields[i].size;
- projectedMeta = readHelper.queryProjectedSteppingMeta();
- ISteppingMeta *useMeta = projectedMeta ? projectedMeta : rawMeta;
- remote.setMergeInfo(useMeta); // also need to consider superfile case where there is a mix of multiway and singleparts.. ?
- bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
- steppingMeta.init(useMeta, hasPostFilter);
- }
- }
- ~CRoxieServerIndexReadActivity()
- {
- delete [] seekSizes;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- steppingMeta.setDistributed();
- if (steppedExtra)
- steppingMeta.setExtra(steppedExtra);
- rowLimit = readHelper.getRowLimit();
- keyedLimit = readHelper.getKeyedLimit();
- choosenLimit = readHelper.getChooseNLimit();
- if (!paused)
- processAllKeys();
- }
- class LazyLocalKeyReader : implements IMessageUnpackCursor, implements IMessageResult, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- virtual IMessageUnpackCursor *getCursor(roxiemem::IRowManager *rowMgr) const
- {
- Link();
- return const_cast<LazyLocalKeyReader*> (this);
- }
- virtual const void *getMessageHeader(unsigned &length) const
- {
- length = 0;
- return NULL;
- }
- virtual const void *getMessageMetadata(unsigned &length) const
- {
- length = 0;
- return NULL;
- }
- virtual void discard() const
- {
- // nothing to do.
- }
- unsigned keyedCount;
- unsigned matched;
- bool EOFseen;
- Owned<IKeyIndexSet> keySet;
- Owned<IKeyManager> tlk;
- CRoxieServerIndexReadActivity &owner;
- LazyLocalKeyReader(CRoxieServerIndexReadActivity &_owner, IKeyIndex *key, IRecordLayoutTranslator * trans)
- : owner(_owner)
- {
- keyedCount = 0;
- matched = 0;
- EOFseen = false;
- keySet.setown(createKeyIndexSet());
- keySet->addIndex(LINK(key));
- if (owner.seekGEOffset)
- tlk.setown(createKeyMerger(keySet, 0, owner.seekGEOffset, &owner));
- else
- tlk.setown(createKeyManager(keySet->queryPart(0), 0, &owner));
- tlk->setLayoutTranslator(trans);
- owner.indexHelper.createSegmentMonitors(tlk);
- tlk->finishSegmentMonitors();
- tlk->reset();
- }
- virtual const void *getNext(int length)
- {
- TransformCallbackAssociation associate(owner.callback, tlk);
- while (tlk->lookup(true))
- {
- keyedCount++;
- if (keyedCount > owner.keyedLimit)
- {
- owner.onLimitExceeded(true); // Should throw exception
- throwUnexpected();
- }
- size32_t transformedSize;
- RtlDynamicRowBuilder rowBuilder(owner.rowAllocator);
- byte const * keyRow = tlk->queryKeyBuffer(owner.callback.getFPosRef());
- try
- {
- transformedSize = owner.readHelper.transform(rowBuilder, keyRow);
- owner.callback.finishedRow();
- }
- catch (IException *E)
- {
- throw owner.makeWrappedException(E);
- }
- if (transformedSize)
- {
- OwnedConstRoxieRow result = rowBuilder.finalizeRowClear(transformedSize);
- matched++;
- if (matched > owner.rowLimit)
- {
- owner.onLimitExceeded(false); // Should throw exception
- throwUnexpected();
- }
- if (matched > owner.choosenLimit) // MORE - bit of a strange place to check
- {
- break;
- }
- owner.accepted++;
- return result.getClear();
- }
- else
- owner.rejected++;
- }
- EOFseen = true;
- return NULL;
- }
- virtual bool atEOF() const
- {
- return EOFseen;
- }
- virtual bool isSerialized() const
- {
- return false;
- }
- };
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
- {
- ensureRowAllocator();
- remote.injectResult(new LazyLocalKeyReader(*this, key, trans));
- return false;
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- {
- if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(true);
- }
- else
- readHelper.onKeyedLimitExceeded();
- }
- else
- {
- if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(false);
- }
- else
- readHelper.onLimitExceeded();
- }
- }
- virtual void serializeSkipInfo(MemoryBuffer &out, unsigned seekLen, const void *rawSeek, unsigned numFields, const void * seek, const SmartStepExtra &stepExtra) const
- {
- out.append((unsigned short) numFields);
- out.append((unsigned short) seekLen);
- out.append((unsigned short) stepExtra.queryFlags());
- IMultipleStepSeekInfo *seeks = stepExtra.queryExtraSeeks();
- if (seeks)
- {
- unsigned lookahead = 40000/seekLen;
- if (maxSeekLookahead && (lookahead > maxSeekLookahead))
- lookahead = maxSeekLookahead;
- seeks->ensureFilled(seek, numFields, lookahead);
- out.append(lookahead != seeks->ordinality()); // seeksAreEof flag
- unsigned serialized = 1; // rawseek is always serialized...
- unsigned patchLength = out.length();
- out.append(serialized); // NOTE - we come back and patch with the actual value...
- out.append(seekLen, rawSeek);
- if (seeks->ordinality())
- {
- const void *lastSeek = rawSeek;
- byte *nextSeek = NULL;
- if (projectedMeta)
- nextSeek = (byte *) alloca(seekLen);
- for (unsigned i = 0; i < seeks->ordinality(); i++)
- {
- if (projectedMeta)
- {
- RtlStaticRowBuilder rowBuilder(nextSeek-seekGEOffset, seekGEOffset+seekLen);
- readHelper.mapOutputToInput(rowBuilder, seeks->querySeek(i), numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
- }
- else
- nextSeek = (byte *) seeks->querySeek(i)+seekGEOffset;
- int diff = memcmp(nextSeek, lastSeek, seekLen);
- if (diff > 0)
- {
- serialized++;
- out.append(seekLen, nextSeek);
- lastSeek = (const byte *) out.reserve(0) - seekLen;
- }
- }
- unsigned length = out.length();
- out.setWritePos(patchLength);
- out.append(serialized);
- out.setWritePos(length);
- }
- }
- else
- {
- out.append(false);
- out.append(1);
- out.append(seekLen, rawSeek);
- }
- }
- virtual const void * nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- try
- {
- unsigned seeklen = 0;
- const void *rawSeek = NULL;
- if (seek && numFields)
- {
- seeklen = seekSizes[numFields-1];
- rawSeek = (const byte *)seek + seekGEOffset;
- if (projectedMeta)
- {
- byte * temp = (byte *) alloca(seeklen);
- RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seeklen);
- readHelper.mapOutputToInput(rawBuilder, seek, numFields); // NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
- rawSeek = (byte *)temp;
- }
- }
- const void *ret = remote.nextRowGE(seek, rawSeek, numFields, seeklen, wasCompleteMatch, stepExtra);
- if (ret && wasCompleteMatch) // GH pleas confirm the wasCompleteMatch I just added here is right
- processed++;
- return ret;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- virtual IInputSteppingMeta * querySteppingMeta()
- {
- if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
- return &steppingMeta;
- return NULL;
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- if (variableInfoPending)
- setVariableFileInfo();
- return this;
- }
- virtual IKeyArray *getKeySet() const
- {
- return keySet.getLink();
- }
- virtual const IResolvedFile *getVarFileInfo() const
- {
- return varFileInfo.getLink();
- }
- virtual TranslatorArray *getTranslators() const
- {
- return translators.getLink();
- }
- virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
- {
- indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
- }
- virtual IRoxieServerActivity *queryActivity() { return this; }
- virtual const RemoteActivityId& queryRemoteId() const
- {
- return remoteId;
- }
- };
- class CRoxieServerSimpleIndexReadActivity : public CRoxieServerActivity, implements IIndexReadActivityInfo
- {
- IHThorCompoundReadExtra & readHelper;
- IHThorIndexReadBaseArg & indexHelper;
- IHThorSourceLimitTransformExtra * limitTransformExtra;
- IHThorSteppedSourceExtra * steppedExtra;
- bool eof;
- Linked<IKeyArray>keySet;
- Owned<IKeyIndexSet>keyIndexSet;
- Owned<IKeyManager> tlk;
- Linked<TranslatorArray> translators;
- CIndexTransformCallback callback;
- unsigned __int64 keyedLimit;
- unsigned rowLimit;
- unsigned chooseNLimit;
- unsigned accepted;
- unsigned rejected;
- unsigned keyedCount;
- ISteppingMeta * rawMeta;
- ISteppingMeta * projectedMeta;
- size32_t seekGEOffset;
- unsigned * seekSizes;
- CSteppingMeta steppingMeta;
- Owned<const IResolvedFile> varFileInfo;
- const RemoteActivityId &remoteId;
- bool firstRead;
- bool variableFileName;
- bool variableInfoPending;
- bool isOpt;
- bool isLocal;
- bool optimizeSteppedPostFilter;
- // MORE there may be enough in common between this and CRoxieServerIndexActivity to warrant some refactoring
- void initKeySet()
- {
- if ((keySet->length() > 1 || rawMeta != NULL) && translators->needsTranslation())
- {
- throw MakeStringException(ROXIE_UNIMPLEMENTED_ERROR, "Layout translation is not available when merging key parts or smart-stepping, as it may change record order");
- }
- keyIndexSet.setown(createKeyIndexSet());
- for (unsigned part = 0; part < keySet->length(); part++)
- {
- IKeyIndexBase *kib = keySet->queryKeyPart(part);
- if (kib)
- {
- for (unsigned subpart = 0; subpart < kib->numParts(); subpart++)
- {
- IKeyIndex *k = kib->queryPart(subpart);
- if (k)
- {
- assertex(!k->isTopLevelKey());
- keyIndexSet->addIndex(LINK(k));
- }
- }
- }
- }
- }
- void setVariableFileInfo()
- {
- OwnedRoxieString indexName(indexHelper.getFileName());
- varFileInfo.setown(resolveLFN(indexName, isOpt));
- translators.setown(new TranslatorArray) ;
- keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, isOpt, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
- initKeySet();
- variableInfoPending = false;
- }
- void onEOF()
- {
- callback.setManager(NULL);
- eof = true;
- tlk.clear();
- }
- public:
- CRoxieServerSimpleIndexReadActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray *_keyArray, TranslatorArray *_translatorArray, bool _isLocal)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- readHelper((IHThorIndexReadArg &)basehelper),
- indexHelper((IHThorIndexReadArg &)basehelper),
- translators(_translatorArray),
- keySet(_keyArray),
- isLocal(_isLocal),
- remoteId(_remoteId)
- {
- rowLimit = 0;
- keyedLimit = 0;
- chooseNLimit = 0;
- indexHelper.setCallback(&callback);
- steppedExtra = static_cast<IHThorSteppedSourceExtra *>(indexHelper.selectInterface(TAIsteppedsourceextra_1));
- limitTransformExtra = static_cast<IHThorSourceLimitTransformExtra *>(indexHelper.selectInterface(TAIsourcelimittransformextra_1));
- unsigned flags = indexHelper.getFlags();
- variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
- variableInfoPending = false;
- isOpt = (flags & TIRoptional) != 0;
- optimizeSteppedPostFilter = (flags & TIRunfilteredtransform) != 0;
- firstRead = true;
- accepted = 0;
- rejected = 0;
- keyedCount = 0;
- eof = false;
- rawMeta = readHelper.queryRawSteppingMeta();
- projectedMeta = readHelper.queryProjectedSteppingMeta();
- seekGEOffset = 0;
- seekSizes = NULL;
- if (rawMeta)
- {
- // MORE - should check all keys in maxFields list can actually be keyed.
- const CFieldOffsetSize * fields = rawMeta->queryFields();
- unsigned maxFields = rawMeta->getNumFields();
- seekGEOffset = fields[0].offset;
- seekSizes = new unsigned[maxFields];
- seekSizes[0] = fields[0].size;
- for (unsigned i=1; i < maxFields; i++)
- seekSizes[i] = seekSizes[i-1] + fields[i].size;
- bool hasPostFilter = readHelper.transformMayFilter() && optimizeSteppedPostFilter;
- if (projectedMeta)
- steppingMeta.init(projectedMeta, hasPostFilter);
- else
- steppingMeta.init(rawMeta, hasPostFilter);
- }
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- ~CRoxieServerSimpleIndexReadActivity()
- {
- delete [] seekSizes;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- firstRead = true;
- accepted = 0;
- rejected = 0;
- keyedCount = 0;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (steppedExtra)
- steppingMeta.setExtra(steppedExtra);
- eof = !indexHelper.canMatchAny();
- if (variableFileName)
- variableInfoPending = true;
- else
- {
- variableInfoPending = false;
- if (!keyIndexSet)
- initKeySet();
- }
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- if (variableInfoPending)
- setVariableFileInfo();
- return this;
- }
- virtual IKeyArray *getKeySet() const
- {
- return keySet.getLink();
- }
- virtual const IResolvedFile *getVarFileInfo() const
- {
- return varFileInfo.getLink();
- }
- virtual TranslatorArray *getTranslators() const
- {
- return translators.getLink();
- }
- virtual void mergeSegmentMonitors(IIndexReadContext *irc) const
- {
- indexHelper.createSegmentMonitors(irc); // NOTE: they will merge
- }
- virtual IRoxieServerActivity *queryActivity() { return this; }
- virtual const RemoteActivityId& queryRemoteId() const
- {
- return remoteId;
- }
-
- const void *nextRow()
- {
- bool matched = true;
- return nextRowGE(NULL, 0, matched, dummySmartStepExtra);
- }
- unsigned __int64 checkCount(unsigned __int64 limit)
- {
- unsigned numParts = keyIndexSet->numParts();
- unsigned __int64 result = 0;
- for (unsigned i = 0; i < numParts; i++)
- {
- Owned<IKeyManager> countTlk = createKeyManager(keyIndexSet->queryPart(i), 0, this);
- countTlk->setLayoutTranslator(translators->item(i));
- indexHelper.createSegmentMonitors(countTlk);
- countTlk->finishSegmentMonitors();
- result += countTlk->checkCount(limit-result);
- if (result > limit)
- break;
- }
- return result;
- }
- virtual const void *nextRowGE(const void * seek, unsigned numFields, bool &wasCompleteMatch, const SmartStepExtra & stepExtra)
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (firstRead)
- {
- if (variableInfoPending)
- setVariableFileInfo();
- rowLimit = (unsigned) readHelper.getRowLimit();
- chooseNLimit = (unsigned) readHelper.getChooseNLimit();
- unsigned numParts = keyIndexSet->numParts();
- if (!numParts)
- {
- onEOF();
- return NULL;
- }
- if (numParts > 1 || seekGEOffset)
- {
- tlk.setown(createKeyMerger(keyIndexSet, 0, seekGEOffset, this));
- // note that we don't set up translator because we don't support it. If that ever changes...
- }
- else
- {
- tlk.setown(createKeyManager(keyIndexSet->queryPart(0), 0, this));
- tlk->setLayoutTranslator(translators->item(0));
- }
- indexHelper.createSegmentMonitors(tlk);
- tlk->finishSegmentMonitors();
- if (queryTraceLevel() > 3 || ctx->queryProbeManager())
- {
- StringBuffer out;
- printKeyedValues(out, tlk, indexHelper.queryDiskRecordSize());
- CTXLOG("Using filter %s", out.str());
- if (ctx->queryProbeManager())
- ctx->queryProbeManager()->setNodeProperty(this, "filter", out.str());
- }
- tlk->reset();
- callback.setManager(tlk);
- keyedLimit = readHelper.getKeyedLimit();
- if (keyedLimit != (unsigned __int64) -1)
- {
- if ((indexHelper.getFlags() & TIRcountkeyedlimit) != 0)
- {
- unsigned __int64 count = checkCount(keyedLimit);
- if (count > keyedLimit)
- {
- if ((indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0)
- readHelper.onKeyedLimitExceeded();
- const void * ret = NULL;
- if (indexHelper.getFlags() & TIRkeyedlimitcreates)
- ret = createKeyedLimitOnFailRow();
- onEOF();
- return ret;
- }
- keyedLimit = (unsigned __int64) -1;
- }
- }
- firstRead = false;
- }
- if (accepted == chooseNLimit)
- {
- onEOF();
- return NULL;
- }
-
- const byte * rawSeek = NULL;
- unsigned seekSize = 0;
- if (seek)
- {
- seekSize = seekSizes[numFields-1];
- rawSeek = (const byte *)seek + seekGEOffset;
- if (projectedMeta)
- {
- byte *temp = (byte *) alloca(seekSize);
- RtlStaticRowBuilder rawBuilder(temp-seekGEOffset, seekGEOffset+seekSize);
- readHelper.mapOutputToInput(rawBuilder, seek, numFields);// NOTE - weird interface to mapOutputToInput means that it STARTS writing at seekGEOffset...
- rawSeek = (byte *)temp;
- }
- #ifdef _DEBUG
- // StringBuffer seekStr;
- // for (unsigned i = 0; i < seekSize; i++)
- // {
- // seekStr.appendf("%02x ", ((unsigned char *) rawSeek)[i]);
- // }
- // DBGLOG("nextRowGE can skip offset %d size %d value %s", seekGEOffset, seekSize, seekStr.str());
- #endif
- }
- const byte * originalRawSeek = rawSeek;
- RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
- while (rawSeek ? tlk->lookupSkip(rawSeek, seekGEOffset, seekSize) : tlk->lookup(true))
- {
- checkAbort();
- keyedCount++;
- if (keyedCount > keyedLimit)
- {
- readHelper.onKeyedLimitExceeded();
- break;
- }
- byte const * keyRow = tlk->queryKeyBuffer(callback.getFPosRef());
- #ifdef _DEBUG
- // StringBuffer recstr;
- // unsigned size = (tlk->queryRecordSize()<80) ? tlk->queryRecordSize() : 80;
- // for (unsigned i = 0; i < size; i++)
- // {
- // recstr.appendf("%02x ", ((unsigned char *) keyRow)[i]);
- // }
- // DBGLOG("nextRowGE Got %s", recstr.str());
- if (originalRawSeek && memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) < 0)
- assertex(!"smart seek failure");
- #endif
- size32_t transformedSize;
- rowBuilder.ensureRow();
- try
- {
- transformedSize = readHelper.transform(rowBuilder, keyRow);
- //if the post filter causes a mismatch, and the stepping condition no longer matches
- //then return a mismatch record - so the join code can start seeking on the other input.
- if (transformedSize == 0 && optimizeSteppedPostFilter && stepExtra.returnMismatches())
- {
- if (memcmp(keyRow + seekGEOffset, originalRawSeek, seekSize) != 0)
- {
- transformedSize = readHelper.unfilteredTransform(rowBuilder, keyRow);
- if (transformedSize != 0)
- wasCompleteMatch = false;
- }
- }
- callback.finishedRow();
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- if (transformedSize)
- {
- accepted++;
- if (accepted > rowLimit)
- {
- if ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates)) != 0)
- {
- throwUnexpected(); // should not have used simple variant if maySkip set...
- }
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- readHelper.onLimitExceeded();
- break;
- }
- processed++;
- #ifdef _DEBUG
- // const byte *ret = (const byte *) out.get();
- // CommonXmlWriter xmlwrite(XWFnoindent|XWFtrim|XWFopt);
- // queryOutputMeta()->toXML(ret, xmlwrite);
- // DBGLOG("ROW: {%p} %s", ret, xmlwrite.str());
- #endif
- return rowBuilder.finalizeRowClear(transformedSize);
- }
- else
- rejected++;
- rawSeek = NULL;
- }
- onEOF();
- return NULL;
- }
- virtual void reset()
- {
- onEOF();
- if (accepted)
- noteStatistic(StNumIndexAccepted, accepted);
- if (rejected)
- noteStatistic(StNumIndexRejected, rejected);
- if (variableFileName)
- {
- varFileInfo.clear();
- translators.clear();
- }
- variableInfoPending = false;
- CRoxieServerActivity::reset();
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() called for source activity");
- }
- virtual IInputSteppingMeta * querySteppingMeta()
- {
- if (rawMeta && steppingEnabled && ((indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates)) == 0))
- return &steppingMeta;
- return NULL;
- }
- protected:
- const void * createKeyedLimitOnFailRow()
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t outSize = limitTransformExtra->transformOnKeyedLimitExceeded(rowBuilder);
- if (outSize)
- return rowBuilder.finalizeRowClear(outSize);
- return NULL;
- }
- };
- class CRoxieServerBaseIndexActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- Owned<IKeyArray> keySet;
- Owned<TranslatorArray> translatorArray;
- Owned<IDefRecordMeta> activityMeta;
- RemoteActivityId remoteId;
- bool isSimple;
- bool isLocal;
- bool maySkip;
- bool sorted;
- bool variableFileName;
- bool enableFieldTranslation;
- unsigned maxSeekLookahead;
- Owned<const IResolvedFile> indexfile;
- CRoxieServerSideCache *cache;
- CRoxieServerBaseIndexActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
- {
- Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
- unsigned flags = indexHelper->getFlags();
- sorted = (flags & TIRunordered) == 0;
- isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
- rtlDataAttr indexLayoutMeta;
- size32_t indexLayoutSize;
- if(!indexHelper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
- assertex(indexLayoutSize==0);
- MemoryBuffer m;
- m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
- activityMeta.setown(deserializeRecordMeta(m, true));
- enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
- translatorArray.setown(new TranslatorArray);
- variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((flags & (TIRvarfilename|TIRdynamicfilename)) != 0);
- if (!variableFileName)
- {
- bool isOpt = (flags & TIRoptional) != 0;
- OwnedRoxieString indexName(indexHelper->getFileName());
- indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
- if (indexfile)
- keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
- }
- isSimple = isLocal;
- maySkip = (flags & (TIRkeyedlimitskips|TIRlimitskips|TIRlimitcreates|TIRkeyedlimitcreates)) != 0;
- if (keySet && keySet->length()==1 && !isLocal && (flags & (TIRlimitskips|TIRlimitcreates|TIRkeyedlimitskips|TIRkeyedlimitcreates))==0)
- {
- IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
- if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
- isSimple = true;
- }
- int cacheSize = _graphNode.getPropInt("hint[@name='cachehits']/@value", serverSideCacheSize);
- cache = cacheSize ? new CRoxieServerSideCache(cacheSize) : NULL;
- maxSeekLookahead = _graphNode.getPropInt("hint[@name='maxseeklookahead']/@value", 0);
- }
- ~CRoxieServerBaseIndexActivityFactory()
- {
- delete cache;
- }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- if (indexfile)
- addXrefFileInfo(reply, indexfile);
- else
- {
- Owned<IHThorIndexReadBaseArg> indexHelper = (IHThorIndexReadBaseArg *) helperFactory();
- if ((indexHelper->getFlags() & (TIRvarfilename|TIRdynamicfilename)) == 0)
- {
- OwnedRoxieString indexName(indexHelper->getFileName());
- Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true);
- if (temp)
- addXrefFileInfo(reply, temp);
- }
- }
- }
- virtual void setInput(unsigned idx, unsigned source, unsigned sourceidx)
- {
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() should not be called for indexread activity");
- }
- virtual IRoxieServerSideCache *queryServerSideCache() const
- {
- return cache;
- }
- virtual bool getEnableFieldTranslation() const
- {
- return enableFieldTranslation;
- }
- virtual IDefRecordMeta *queryActivityMeta() const
- {
- return activityMeta;
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return indexStatistics;
- }
- };
- class CRoxieServerIndexReadActivityFactory : public CRoxieServerBaseIndexActivityFactory
- {
- public:
- CRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (!variableFileName && (keySet==NULL || keySet->length()==0))
- return new CRoxieServerNullActivity(_ctx, this, _probeManager);
- else if (isSimple && !maySkip)
- return new CRoxieServerSimpleIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
- else
- return new CRoxieServerIndexReadActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal, maySkip, maxSeekLookahead);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexReadActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerIndexReadActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //--------------------------------------------------------------------------------------------------------------------------
- class CRoxieServerNullCountActivity : public CRoxieServerActivity
- {
- bool done;
- public:
- CRoxieServerNullCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager)
- {
- done = false;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- done = true;
- size32_t rowSize = meta.getFixedSize();
- void * nullRow = rowAllocator->createRow();
- if (rowSize == 1)
- *(byte *)nullRow = 0;
- else
- {
- assertex(rowSize == sizeof(unsigned __int64));
- *(unsigned __int64 *)nullRow = 0;
- }
- return rowAllocator->finalizeRow(rowSize, nullRow, rowSize);
- }
- };
- class CRoxieServerIndexCountActivity : public CRoxieServerIndexActivity
- {
- IHThorCompoundCountExtra & countHelper;
- IHThorSourceCountLimit * limitHelper;
- bool done;
- public:
- CRoxieServerIndexCountActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
- : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
- countHelper((IHThorIndexCountArg &)basehelper),
- done(false)
- {
- limitHelper = static_cast<IHThorSourceCountLimit *>(basehelper.selectInterface(TAIsourcecountlimit_1));
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
- choosenLimit = countHelper.getChooseNLimit();
- if (limitHelper)
- {
- rowLimit = limitHelper->getRowLimit();
- keyedLimit = limitHelper->getKeyedLimit();
- }
- if (!paused)
- processAllKeys();
- }
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
- {
- unsigned __int64 count = 0;
- if (countHelper.hasFilter())
- {
- while (tlk->lookup(true))
- {
- try
- {
- count += countHelper.numValid(tlk->queryKeyBuffer(callback.getFPosRef()));
- callback.finishedRow();
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- accepted++;
- if (count >= choosenLimit) // MORE - what about limit?
- break;
- }
- }
- else
- count = tlk->getCount(); //MORE: GH->RKC There should be value in providing a max limit to getCount()
- if (count)
- {
- Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), false);
- if (count > choosenLimit)
- count = choosenLimit;
- void * recBuffer = rowAllocator->createRow();
- if (meta.getFixedSize() == 1)
- *(byte *)recBuffer = (byte)count;
- else
- {
- assertex(meta.getFixedSize() == sizeof(unsigned __int64));
- *(unsigned __int64 *)recBuffer = count;
- }
- recBuffer = rowAllocator->finalizeRow(meta.getFixedSize(), recBuffer, meta.getFixedSize());
- result->append(recBuffer);
- remote.injectResult(result.getClear());
- //GH->RKC for count(,choosen)/exists passing in the previous count would short-circuit this much earlier
- if (count >= choosenLimit)
- return true;
- }
- return false;
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- {
- if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(true);
- }
- else
- {
- assertex(limitHelper); // Should not be able to generate exception if there was not one...
- limitHelper->onKeyedLimitExceeded();
- }
- }
- else
- {
- if (indexHelper.getFlags() & (TIRlimitskips|TIRlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(false);
- }
- else
- {
- assertex(limitHelper);
- limitHelper->onLimitExceeded();
- }
- }
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- throwUnexpected();
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- done = true;
- unsigned __int64 totalCount = 0;
- bool hasLimit = rowLimit != (unsigned __int64) -1;
- try
- {
- loop
- {
- const void * next = remote.nextRow();
- if (!next)
- break;
- if (meta.getFixedSize() == 1)
- totalCount += *(byte *)next;
- else
- totalCount += *(unsigned __int64 *) next;
- ReleaseRoxieRow(next);
- if (totalCount > rowLimit || (totalCount > choosenLimit && !hasLimit)) // can't break out early if there is a possibility of later slave throwing limit exception
- break;
- }
- if (totalCount > rowLimit)
- {
- unsigned flags = indexHelper.getFlags();
- if (flags & TIRlimitskips)
- totalCount = 0;
- else if (flags & TIRlimitcreates)
- totalCount = 1;
- else
- {
- assertex(limitHelper);
- limitHelper->onLimitExceeded();
- }
- }
- else if (totalCount > choosenLimit)
- totalCount = choosenLimit;
- }
- catch (IException *E)
- {
- if (QUERYINTERFACE(E, LimitSkipException))
- {
- totalCount = 0;
- unsigned flags = indexHelper.getFlags();
- if (E->errorCode() == KeyedLimitSkipErrorCode)
- {
- if (flags & TIRkeyedlimitcreates)
- totalCount++;
- }
- else
- {
- if (flags & TIRlimitcreates)
- totalCount++;
- }
- if (totalCount > choosenLimit)
- totalCount = choosenLimit; // would have to be weird code (and escape the optimizer...)
- E->Release();
- }
- else
- throw ;
- }
- void * result = rowAllocator->createRow();
- if (meta.getFixedSize() == 1)
- *(byte *)result = (byte)totalCount;
- else
- {
- assertex(meta.getFixedSize() == sizeof(unsigned __int64));
- *(unsigned __int64 *)result = totalCount;
- }
- return rowAllocator->finalizeRow(meta.getFixedSize(), result, meta.getFixedSize());
- }
- };
- class CRoxieServerIndexCountActivityFactory : public CRoxieServerBaseIndexActivityFactory
- {
- public:
- CRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (!variableFileName && (keySet==NULL || keySet->length()==0))
- return new CRoxieServerNullCountActivity(_ctx, this, _probeManager);
- // else if (isSimple)
- // return new CRoxieServerSimpleIndexCountActivity(this, keySet->queryKeyPart(0)->queryPart(0));
- else
- return new CRoxieServerIndexCountActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexCountActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerIndexCountActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //--------------------------------------------------------------------------------------------------------------------------
- class CRoxieServerNullIndexAggregateActivity : public CRoxieServerActivity
- {
- IHThorIndexAggregateArg &aggregateHelper;
- bool done;
- public:
- CRoxieServerNullIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- aggregateHelper((IHThorIndexAggregateArg &)basehelper)
- {
- done = false;
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- done = true;
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t thisSize = aggregateHelper.clearAggregate(rowBuilder);
- return rowBuilder.finalizeRowClear(thisSize);
- }
- };
- class CRoxieServerIndexAggregateActivity : public CRoxieServerIndexActivity
- {
- IHThorCompoundAggregateExtra & aggregateHelper;
- bool done;
- public:
- CRoxieServerIndexAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
- : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
- aggregateHelper((IHThorIndexAggregateArg &)basehelper),
- done(false)
- {
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- done = false;
- CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
- if (!paused)
- processAllKeys();
- }
- virtual bool needsAllocator() const { return true; }
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
- while (tlk->lookup(true))
- {
- if (!rowBuilder.exists())
- {
- rowBuilder.ensureRow();
- aggregateHelper.clearAggregate(rowBuilder);
- }
- try
- {
- aggregateHelper.processRow(rowBuilder, tlk->queryKeyBuffer(callback.getFPosRef()));
- callback.finishedRow();
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- accepted++;
- }
- if (aggregateHelper.processedAnyRows())
- {
- size32_t size = meta.getRecordSize(rowBuilder.getSelf());
- const void * recBuffer = rowBuilder.finalizeRowClear(size);
- Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
- result->append(recBuffer);
- remote.injectResult(result.getClear());
- }
- return false;
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- throwUnexpected();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- throwUnexpected();
- }
- const void * gatherMerged()
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
- const void * firstRow = remote.nextRow();
- size32_t finalSize = 0;
- if (!firstRow)
- {
- rowBuilder.ensureRow();
- finalSize = aggregateHelper.clearAggregate(rowBuilder);
- }
- else
- {
- // NOTE need to clone this because going to modify below, could special case 1 row only
- finalSize = cloneRow(rowBuilder, firstRow, meta);
- ReleaseRoxieRow(firstRow);
- }
- loop
- {
- const void * next = remote.nextRow();
- if (!next)
- break;
- finalSize = aggregateHelper.mergeAggregate(rowBuilder, next);
- ReleaseRoxieRow(next);
- }
- return rowBuilder.finalizeRowClear(finalSize);
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (done) return NULL;
- const void * ret = gatherMerged();
- done = true;
- return ret;
- }
- };
- class CRoxieServerIndexAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
- {
- public:
- CRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (!variableFileName && (keySet==NULL || keySet->length()==0))
- return new CRoxieServerNullIndexAggregateActivity(_ctx, this, _probeManager);
- // else if (isSimple)
- // return new CRoxieServerSimpleIndexAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
- else
- return new CRoxieServerIndexAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerIndexAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //--------------------------------------------------------------------------------------------------------------------------
- class CRoxieServerIndexGroupAggregateActivity : public CRoxieServerIndexActivity, implements IHThorGroupAggregateCallback
- {
- IHThorCompoundGroupAggregateExtra & aggregateHelper;
- RowAggregator singleAggregator;
- RowAggregator resultAggregator;
- unsigned groupSegCount;
- bool gathered;
- bool eof;
- public:
- CRoxieServerIndexGroupAggregateActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _isLocal)
- : CRoxieServerIndexActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, false, _isLocal, false),
- aggregateHelper((IHThorIndexGroupAggregateArg &)basehelper),
- singleAggregator(aggregateHelper, aggregateHelper),
- resultAggregator(aggregateHelper, aggregateHelper),
- gathered(false), eof(true)
- {
- groupSegCount = 0;
- }
- IMPLEMENT_IINTERFACE_USING(CRoxieServerIndexActivity)
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- gathered= false;
- CRoxieServerIndexActivity::start(parentExtractSize, parentExtract, paused);
- groupSegCount = 0;
- if (!paused)
- processAllKeys();
- resultAggregator.start(rowAllocator);
- }
- virtual bool needsAllocator() const { return true; }
- virtual void reset()
- {
- resultAggregator.reset();
- CRoxieServerIndexActivity::reset();
- }
- virtual void processRow(const void * next)
- {
- singleAggregator.addRow(next);
- }
- virtual void createSegmentMonitors(IKeyManager *key)
- {
- unsigned groupSegSize;
- ThorActivityKind kind = factory->getKind();
- if ((kind==TAKindexgroupcount || kind==TAKindexgroupexists))
- groupSegSize = aggregateHelper.getGroupSegmentMonitorsSize();
- else
- groupSegSize = 0;
- if (groupSegSize)
- {
- key->setMergeBarrier(groupSegSize);
- CRoxieServerIndexActivity::createSegmentMonitors(key);
- unsigned numSegs = tlk->ordinality();
- for (unsigned segNo = 0; segNo < numSegs; segNo++)
- {
- IKeySegmentMonitor *seg = tlk->item(segNo);
- if (seg->getOffset()+seg->getSize()==groupSegSize)
- {
- groupSegCount = segNo+1;
- break;
- }
- }
- assertex(groupSegCount);
- }
- else
- CRoxieServerIndexActivity::createSegmentMonitors(key);
- }
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
- {
- Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
- singleAggregator.start(rowAllocator);
- ThorActivityKind kind = factory->getKind();
- while (tlk->lookup(true))
- {
- try
- {
- if (groupSegCount && !trans)
- {
- AggregateRowBuilder &rowBuilder = singleAggregator.addRow(tlk->queryKeyBuffer(callback.getFPosRef()));
- callback.finishedRow();
- if (kind==TAKindexgroupcount)
- {
- unsigned __int64 count = tlk->getCurrentRangeCount(groupSegCount);
- aggregateHelper.processCountGrouping(rowBuilder, count-1);
- }
- if (!tlk->nextRange(groupSegCount))
- break;
- }
- else
- {
- aggregateHelper.processRow(tlk->queryKeyBuffer(callback.getFPosRef()), this);
- callback.finishedRow();
- }
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- accepted++;
- }
- loop
- {
- Owned<AggregateRowBuilder> next = singleAggregator.nextResult();
- if (!next)
- break;
- size32_t size = next->querySize();
- result->append(next->finalizeRowClear());
- }
- remote.injectResult(result.getClear());
- singleAggregator.reset();
- return false;
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- throwUnexpected();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- throwUnexpected();
- }
- void gatherMerged()
- {
- gathered = true;
- loop
- {
- const void * next = remote.nextRow();
- if (!next)
- break;
- resultAggregator.mergeElement(next);
- ReleaseRoxieRow(next);
- }
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if (eof)
- return NULL;
- if (!gathered)
- gatherMerged();
- Owned<AggregateRowBuilder> next = resultAggregator.nextResult();
- if (next)
- {
- processed++;
- return next->finalizeRowClear();
- }
- eof = true;
- return NULL;
- }
- };
- class CRoxieServerIndexGroupAggregateActivityFactory : public CRoxieServerBaseIndexActivityFactory
- {
- public:
- CRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (!variableFileName && (keySet==NULL || keySet->length()==0))
- return new CRoxieServerNullActivity(_ctx, this, _probeManager);
- // else if (isSimple)
- // return new CRoxieServerSimpleIndexGroupAggregateActivity(this, keySet->queryKeyPart(0)->queryPart(0));
- else
- return new CRoxieServerIndexGroupAggregateActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, isLocal);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexGroupAggregateActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerIndexGroupAggregateActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //--------------------------------------------------------------------------------------------------------------------------
- class CRoxieServerIndexNormalizeActivity : public CRoxieServerIndexReadBaseActivity
- {
- IHThorCompoundNormalizeExtra & readHelper;
- public:
- CRoxieServerIndexNormalizeActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId,
- IKeyArray * _keySet, TranslatorArray *_translators, bool _sorted, bool _isLocal)
- : CRoxieServerIndexReadBaseActivity(_ctx, _factory, _probeManager, _remoteId, _keySet, _translators, _sorted, _isLocal, false),
- readHelper((IHThorIndexNormalizeArg &)basehelper)
- {
- }
- virtual bool needsAllocator() const { return true; }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerIndexReadBaseActivity::start(parentExtractSize, parentExtract, paused);
- rowLimit = readHelper.getRowLimit();
- keyedLimit = readHelper.getKeyedLimit();
- choosenLimit = readHelper.getChooseNLimit();
- if (!paused)
- processAllKeys();
- }
- virtual bool processSingleKey(IKeyIndex *key, IRecordLayoutTranslator * trans)
- {
- unsigned keyedCount = 0;
- RtlDynamicRowBuilder rowBuilder(rowAllocator, false);
- while (tlk->lookup(true))
- {
- keyedCount++;
- if (keyedCount > keyedLimit)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d line = %d", activityId, __LINE__);
- onLimitExceeded(true);
- break;
- }
- size32_t transformedSize;
-
- if (readHelper.first(tlk->queryKeyBuffer(callback.getFPosRef())))
- {
- Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), meta.isVariableSize());
- do
- {
- if (accepted>=choosenLimit)
- break;
- rowBuilder.ensureRow();
- try
- {
- transformedSize = readHelper.transform(rowBuilder);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- if (transformedSize)
- {
- // MORE - would be a good idea to stop these asap if rowlimit exceeded
- result->append(rowBuilder.finalizeRowClear(transformedSize));
- accepted++;
- }
- else
- rejected++;
- } while (readHelper.next());
- remote.injectResult(result.getClear());
- callback.finishedRow();
- if (accepted>=choosenLimit)
- return true;
- }
- }
- return false;
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- {
- if (indexHelper.getFlags() & (TIRkeyedlimitskips|TIRkeyedlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(true);
- }
- else
- readHelper.onKeyedLimitExceeded();
- }
- else
- {
- if (indexHelper.getFlags() & (TIRlimitskips||TIRlimitcreates))
- {
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- throw makeLimitSkipException(false);
- }
- else
- readHelper.onLimitExceeded();
- }
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- UNIMPLEMENTED;
- }
- };
- class CRoxieServerIndexNormalizeActivityFactory : public CRoxieServerBaseIndexActivityFactory
- {
- public:
- CRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerBaseIndexActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (!variableFileName && (keySet==NULL || keySet->length()==0))
- return new CRoxieServerNullActivity(_ctx, this, _probeManager);
- else
- return new CRoxieServerIndexNormalizeActivity(_ctx, this, _probeManager, remoteId, keySet, translatorArray, sorted, isLocal);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerIndexNormalizeActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerIndexNormalizeActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- //=================================================================================
- class CRoxieServerFetchActivity : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
- {
- IHThorFetchBaseArg &helper;
- IHThorFetchContext * fetchContext;
- Linked<IFilePartMap> map;
- CRemoteResultAdaptor remote;
- RecordPullerThread puller;
- bool needsRHS;
- bool variableFileName;
- bool isOpt;
- Owned<const IResolvedFile> varFileInfo;
- public:
- CRoxieServerFetchActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IFilePartMap *_map)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorFetchBaseArg &)basehelper), map(_map), remote(_ctx, this, _remoteId, meta.queryOriginal(), helper, *this, true, true), puller(false)
- {
- fetchContext = static_cast<IHThorFetchContext *>(helper.selectInterface(TAIfetchcontext_1));
- needsRHS = helper.transformNeedsRhs();
- variableFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
- isOpt = (fetchContext->getFetchFlags() & FFdatafileoptional) != 0;
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- remote.onCreate(_colocalParent);
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (idx)
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- puller.setInput(this, _sourceIdx, _in);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- puller.connectInputStreams(ctx, consumerOrdered);
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return puller.queryInput();
- else
- return NULL;
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- remote.onStart(parentExtractSize, parentExtract);
- remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
- if (variableFileName)
- {
- OwnedRoxieString fname(fetchContext->getFileName());
- varFileInfo.setown(resolveLFN(fname, isOpt));
- if (varFileInfo)
- map.setown(varFileInfo->getFileMap());
- }
- puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fetchPreload, false, ctx);
- }
- virtual void stop()
- {
- // Called from remote, so no need to call back to it....
- puller.stop();
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- processed = remote.processed;
- remote.processed = 0;
- puller.reset();
- if (variableFileName)
- {
- varFileInfo.clear();
- map.clear();
- }
- CRoxieServerActivity::reset();
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL : &remote;
- }
- virtual void processRow(const void *row)
- {
- // called from puller thread
- offset_t rp = fetchContext->extractPosition(row);
- unsigned partNo;
- if (isLocalFpos(rp))
- partNo = getLocalFposPart(rp) + 1;
- else
- partNo = map->mapOffset(rp);
- if (needsRHS)
- {
- Owned<IEngineRowAllocator> extractAllocator = createRowAllocator(helper.queryExtractedSize());
- RtlDynamicRowBuilder rb(extractAllocator, true);
- unsigned rhsSize = helper.extractJoinFields(rb, row);
- char * block = (char *) remote.getMem(partNo, 0, sizeof(rp) + sizeof(rhsSize) + rhsSize); // MORE - superfiles
- *(offset_t *) block = rp;
- block += sizeof(rp);
- *(unsigned *) block = rhsSize;
- block += sizeof(rhsSize);
- memcpy(block, rb.row(), rhsSize);
- }
- else
- *(offset_t *) remote.getMem(partNo, 0, sizeof(rp)) = rp; // MORE - superfiles
- ReleaseRoxieRow(row);
- }
- void processEOG()
- {
- #ifdef FETCH_PRESERVES_GROUPING
- UNIMPLEMENTED;
- #endif
- // else discard is correct
- }
- void processGroup(const ConstPointerArray &)
- {
- throwUnexpected();
- }
- void processDone()
- {
- // called from puller thread
- remote.flush();
- remote.senddone();
- }
- virtual bool fireException(IException *e)
- {
- return remote.fireException(e);
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- throwUnexpected();
- helper.onLimitExceeded();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- UNIMPLEMENTED;
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CRoxieServerFetchActivityFactory : public CRoxieServerActivityFactory
- {
- RemoteActivityId remoteId;
- Owned<IFilePartMap> map;
- bool variableFileName;
- Owned<const IResolvedFile> datafile;
- public:
- CRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), remoteId(_remoteId)
- {
- Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
- IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
- variableFileName = allFilesDynamic || _queryFactory.isDynamic() || ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
- if (!variableFileName)
- {
- OwnedRoxieString fname(fetchContext->getFileName());
- datafile.setown(_queryFactory.queryPackage().lookupFileName(fname,
- (fetchContext->getFetchFlags() & FFdatafileoptional) != 0,
- true, true,
- _queryFactory.queryWorkUnit(), true));
- if (datafile)
- map.setown(datafile->getFileMap());
- }
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerFetchActivity(_ctx, this, _probeManager, remoteId, map);
- }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- if (datafile)
- addXrefFileInfo(reply, datafile);
- else
- {
- // Temporarily resolve the file
- Owned<IHThorFetchBaseArg> helper = (IHThorFetchBaseArg *) helperFactory();
- IHThorFetchContext *fetchContext = static_cast<IHThorFetchContext *>(helper->selectInterface(TAIfetchcontext_1));
- if ((fetchContext->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) == 0)
- {
- OwnedRoxieString fileName(fetchContext->getFileName());
- Owned<const IResolvedFile> temp = queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true);
- if (temp)
- addXrefFileInfo(reply, temp);
- }
- }
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return diskStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerFetchActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId)
- {
- return new CRoxieServerFetchActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId);
- }
- // MORE - is there any point keeping this now?
- class CRoxieServerDummyActivityFactory : public CRoxieServerActivityFactory // not a real activity - just used to properly link files
- {
- public:
- Owned<const IResolvedFile> indexfile;
- Owned<const IResolvedFile> datafile;
- StringAttr fileName;
- StringAttr indexName;
- Owned<IKeyArray> keySet;
- Owned<IFileIOArray> files;
- TranslatorArray layoutTranslators;
- CRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- try // does not want any missing file errors to be fatal, or throw traps - just log it
- {
- if (_graphNode.getPropBool("att[@name='_isSpill']/@value", false) || _graphNode.getPropBool("att[@name='_isSpillGlobal']/@value", false))
- return; // ignore 'spills'
- bool isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
- ThorActivityKind kind = getActivityKind(_graphNode);
- if (kind != TAKdiskwrite && kind != TAKindexwrite && kind != TAKpiperead && kind != TAKpipewrite)
- {
- fileName.set(queryNodeFileName(_graphNode, kind));
- indexName.set(queryNodeIndexName(_graphNode, kind));
- if (indexName && !allFilesDynamic && !queryFactory.isDynamic())
- {
- bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isIndexOpt']/@value");
- indexfile.setown(queryFactory.queryPackage().lookupFileName(indexName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
- if (indexfile)
- keySet.setown(indexfile->getKeyArray(NULL, &layoutTranslators, isOpt, isLocal ? queryFactory.queryChannel() : 0, false));
- }
- if (fileName && !allFilesDynamic && !queryFactory.isDynamic())
- {
- bool isOpt = pretendAllOpt || _graphNode.getPropBool("att[@name='_isOpt']/@value");
- datafile.setown(_queryFactory.queryPackage().lookupFileName(fileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
- if (datafile)
- {
- if (isLocal)
- files.setown(datafile->getIFileIOArray(isOpt, queryFactory.queryChannel()));
- }
- }
- }
- }
- catch(IException *E)
- {
- StringBuffer errors;
- E->errorMessage(errors);
- DBGLOG("%s File error = %s", (isLoadDataOnly) ? "LOADDATAONLY" : "SUSPENDED QUERY", errors.str());
- E->Release();
- }
- }
- 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__); }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- if (!allFilesDynamic)
- {
- if (datafile)
- addXrefFileInfo(reply, datafile);
- if (indexfile)
- addXrefFileInfo(reply, indexfile);
- }
- else
- {
- Owned<const IResolvedFile> temp;
- if (fileName.length())
- {
- temp.setown(queryFactory.queryPackage().lookupFileName(fileName, true, true, false, queryFactory.queryWorkUnit(), true));
- if (temp)
- addXrefFileInfo(reply, temp);
- }
- if (indexName.length())
- {
- temp.setown(queryFactory.queryPackage().lookupFileName(indexName, true, true, false, queryFactory.queryWorkUnit(), true));
- if (temp)
- addXrefFileInfo(reply, temp);
- }
- }
- }
- };
- IRoxieServerActivityFactory *createRoxieServerDummyActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool isLoadDataOnly)
- {
- return new CRoxieServerDummyActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, isLoadDataOnly);
- }
- //=====================================================================================================
- // Keyed joins...
- //
- // Input records are pulled by a puller thread, which checks each LHS record to determine which (if any) channels it
- // may have RHS matches on, and sends the relevant fields to the relevant slaves.
- // 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
- // the transform and returns rows that are created.
- // 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)
- //
- //=====================================================================================================
- class CJoinGroup;
- interface IJoinProcessor
- {
- virtual void processEOG() = 0;
- virtual CJoinGroup *createJoinGroup(const void *row) = 0;
- virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount) = 0;
- virtual bool fireException(IException *E) = 0;
- virtual void processCompletedGroups() = 0;
- };
- //------------------------------------------------------------------------------------------------------
- // Class CJoinGroup has a record per LHS row, plus (if preserving grouping) a 'head of group' record
- // It gathers all the corresponding RHS rows, keeping track of how may slave transactions are pending in endMarkersPending
- // If preserving groups, the 'head of group' record keeps track of how many LHS records in the group are still incomplete.
- // CJoinGroup records are allocated out of the Roxie row memory manager by overloading operator new, so that they are included in the
- // per-query limits etc (Note that the pointer array block is not though).
- // Because of that, the exact size is significant - especially whether fit just under or just over a chunking threshold...
- //
- // There are two phases to the life of a JoinGroup - it is created by the puller thread that is also firing off slave requests
- // notePending will be called once for every slave request. Puller thread calls noteEndReceived(0) once when done - this corresponds to the
- // initial count when created.
- // Slave replies and are noted by the consumer thread calling addRightMatch() and noteEndReceived(n).
- // Once endMarkersPending reaches 0, JoinGroup is complete. Last thread to call noteEndReceived will process the rows and destroy the group.
- // There is no need for a critsec because although multiple threads will access at different times, only the consumer thread will
- // access any modifiable member variables while endMarkersPending != 0 (i.e. complete() is false). Once complete returns true there is a single
- // remaining reference and the JoinGroup will be processed and destroyed.
- //
- //------------------------------------------------------------------------------------------------------
- class CJoinGroup : public CInterface
- {
- protected:
- const void *left; // LHS row
- PointerArrayOf<KeyedJoinHeader> rows; // matching RHS rows
- atomic_t endMarkersPending; // How many slave responses still waiting for
- CJoinGroup *groupStart; // Head of group, or NULL if not grouping
- unsigned lastPartNo;
- unsigned pos;
- unsigned candidates; // Number of RHS keyed candidates - note this may not be the same as rows.ordinality()
- public:
- #undef new
- void *operator new(size_t size, IRowManager *a, unsigned activityId)
- {
- return a->allocate(size, activityId);
- }
- #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
- #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
- #endif
- void operator delete(void *ptr, IRowManager *a, unsigned activityId)
- {
- ReleaseRoxieRow(ptr);
- }
- void operator delete(void *ptr)
- {
- ReleaseRoxieRow(ptr);
- }
- public:
- CJoinGroup(const void *_left, CJoinGroup *_groupStart)
- {
- #ifdef TRACE_JOINGROUPS
- DBGLOG("Creating joinGroup %p, groupstart %p", this, _groupStart);
- #endif
- candidates = 0;
- lastPartNo = 0;
- pos = 0;
- left = _left;
- groupStart = _groupStart;
- if (_groupStart)
- {
- atomic_inc(&_groupStart->endMarkersPending);
- }
- atomic_set(&endMarkersPending, 1);
- }
- ~CJoinGroup()
- {
- #ifdef TRACE_JOINGROUPS
- DBGLOG("Destroying joinGroup %p", this);
- #endif
- if (left)
- {
- ReleaseRoxieRow(left);
- roxiemem::ReleaseRoxieRowArray(rows.ordinality(), (const void * *)rows.getArray());
- rows.kill();
- }
- }
- inline bool isHeadRecord() const
- {
- return left==NULL;
- }
- inline bool complete() const
- {
- return atomic_read(&endMarkersPending) == 0;
- }
- #ifdef TRACE_JOINGROUPS
- inline void notePending(unsigned lineNo)
- #else
- inline void notePending()
- #endif
- {
- assert(!complete());
- atomic_inc(&endMarkersPending);
- #ifdef TRACE_JOINGROUPS
- DBGLOG("CJoinGroup::notePending %p from %d, count became %d group count %d", this, lineNo, atomic_read(&endMarkersPending), groupStart ? atomic_read(&groupStart->endMarkersPending) : 0);
- #endif
- }
- inline bool inGroup(CJoinGroup *leader) const
- {
- return groupStart==leader;
- }
- inline const KeyedJoinHeader *queryRow(unsigned idx) const
- {
- // Single threaded by now
- assert(complete());
- return rows.item(idx);
- }
- #ifdef TRACE_JOINGROUPS
- bool noteEndReceived(unsigned candidateCount, unsigned lineNo)
- #else
- bool noteEndReceived(unsigned candidateCount)
- #endif
- {
- assert(!complete());
- if (candidateCount)
- {
- candidates += candidateCount;
- }
- #ifdef TRACE_JOINGROUPS
- 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);
- #endif
- // NOTE - as soon as endMarkersPending and groupStart->endMarkersPending are decremented to zero this object may get released asynchronously by other threads
- // There must therefore be nothing in this method after them that acceses member variables. Think of it as a delete this...
- // In particular, we can't safely reference groupStart after the dec_and_test of endMarkersPending, hence copy local first
- CJoinGroup *localGroupStart = groupStart;
- if (atomic_dec_and_test(&endMarkersPending))
- {
- if (localGroupStart)
- return atomic_dec_and_test(&localGroupStart->endMarkersPending);
- else
- return true;
- }
- else
- return false;
- }
- inline const void *queryLeft() const
- {
- return left;
- }
- void addRightMatch(KeyedJoinHeader *right)
- {
- assert(!complete());
- unsigned short partNo = right->partNo;
- if (partNo != lastPartNo)
- {
- // MORE - should we binchop? If we did we would need to be careful to find LAST match
- if (partNo > lastPartNo)
- pos = rows.length();
- while (pos>0)
- {
- if (rows.item(pos-1)->partNo <= partNo)
- break;
- pos--;
- }
- lastPartNo = partNo;
- }
- rows.add(right, pos);
- pos++;
- }
- inline unsigned rowsSeen() const
- {
- assert(complete());
- return rows.length();
- }
- inline unsigned candidateCount() const
- {
- assert(complete());
- return candidates;
- }
- };
- #ifdef TRACE_JOINGROUPS
- #define notePending() notePending(__LINE__)
- #define noteEndReceived(a) noteEndReceived(a, __LINE__)
- #endif
- class KeyedJoinRemoteAdaptor : public CRemoteResultAdaptor // MORE - not sure it should be derived from this - makes processed all wrong, for example
- {
- private:
- SafeQueueOf<const void, true> ready;
- public:
- IHThorKeyedJoinArg &helper;
- unsigned joinProcessed;
- bool isFullKey;
- bool eof;
- bool isSimple;
- bool allPulled;
- ActivityTimeAccumulator totalCycles;
- unsigned activityId;
- RecordPullerThread &puller;
- SafeQueueOf<const void, true> injected; // Used in isSimple mode
- Owned<IEngineRowAllocator> ccdRecordAllocator;
- IJoinProcessor &processor;
- KeyedJoinRemoteAdaptor(IRoxieSlaveContext *_ctx, IRoxieServerErrorHandler *_errorHandler, const RemoteActivityId &_remoteId, IHThorKeyedJoinArg &_helper,
- IRoxieServerActivity &_activity, bool _isFullKey, bool _isSimple,
- RecordPullerThread &_puller, IJoinProcessor &_processor)
- : helper(_helper),
- CRemoteResultAdaptor(_ctx, _errorHandler, _remoteId, 0, _helper, _activity, true, true),
- isFullKey(_isFullKey),
- isSimple(_isSimple),
- puller(_puller),
- processor(_processor),
- activityId(_activity.queryId())
- {
- joinProcessed = 0;
- allPulled = false;
- eof = false;
- }
- virtual void onCreate(IHThorArg *_colocalArg)
- {
- CRemoteResultAdaptor::onCreate(_colocalArg);
- ccdRecordAllocator.setown(activity.createRowAllocator(helper.queryJoinFieldsRecordSize()));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- joinProcessed = 0;
- totalCycles.totalCycles = 0;
- allPulled = false;
- assertex(ready.ordinality()==0);
- CRemoteResultAdaptor::start(parentExtractSize, parentExtract, paused);
- }
- virtual void reset()
- {
- CRemoteResultAdaptor::reset();
- while (ready.ordinality())
- {
- const void *goer = ready.dequeue();
- if (goer)
- ReleaseRoxieRow(goer);
- }
- while (injected.ordinality())
- {
- const void *goer = injected.dequeue();
- if (goer)
- ReleaseRoxieRow(goer);
- }
- }
- inline void addResult(const void *row)
- {
- ready.enqueue(row);
- }
- virtual unsigned __int64 queryTotalCycles() const
- {
- return totalCycles.totalCycles;
- }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- loop
- {
- if (eof)
- return NULL;
- processSlaveResults();
- if (ready.ordinality())
- {
- const void *result = ready.dequeue();
- if (result)
- joinProcessed++;
- return result;
- }
- else
- eof = true;
- }
- }
- private:
- void processSlaveResults()
- {
- while (!ready.ordinality())
- {
- KeyedJoinHeader *fetchedData;
- if (isSimple)
- {
- while (!allPulled && !injected.ordinality())
- {
- if (!puller.pullRecords(1))
- {
- puller.done();
- allPulled = true;
- }
- }
- fetchedData = (KeyedJoinHeader *) injected.dequeue();
- }
- else
- fetchedData = (KeyedJoinHeader *) CRemoteResultAdaptor::nextRow();
- if (fetchedData)
- {
- CJoinGroup *thisGroup = fetchedData->thisGroup;
- if (fetchedData->partNo == (unsigned short) -1)
- {
- #ifdef TRACE_JOINGROUPS
- CTXLOG("Got end for group %p", thisGroup);
- #endif
- unsigned candidateCount = (unsigned) fetchedData->fpos;
- ReleaseRoxieRow(fetchedData);
- processor.noteEndReceived(thisGroup, candidateCount); // note - this can throw exception. So release fetchdata before calling
- }
- else
- {
- #ifdef TRACE_JOINGROUPS
- CTXLOG("Reading another %d bytes for group %p data", ccdRecordSize, thisGroup);
- #endif
- thisGroup->addRightMatch(fetchedData);
- if (isFullKey)
- {
- #ifdef TRACE_JOINGROUPS
- CTXLOG("Calling noteEndReceived for record returned from FETCH of full keyed join");
- #endif
- processor.noteEndReceived(thisGroup, 0); // note - this can throw exception. So release fetchdata before calling
- }
- }
- }
- else
- break;
- }
- }
- };
- class CRoxieServerFullKeyedJoinHead: public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler
- {
- IHThorKeyedJoinArg &helper;
- Owned<IKeyManager> tlk;
- Linked<IKeyArray> keySet;
- Linked<TranslatorArray> translators;
- CRemoteResultAdaptor remote;
- RecordPullerThread puller;
- IOutputMetaData *indexReadMeta;
- IJoinProcessor *joinHandler;
- bool variableIndexFileName;
- bool indexReadInputRecordVariable;
- bool isLocal;
- Owned<IEngineRowAllocator> indexReadAllocator;
- Owned<const IResolvedFile> varFileInfo;
- IFinalRoxieInput *indexReadInput;
- unsigned indexReadIdx = 0;
- IIndexReadActivityInfo *rootIndex;
- public:
- CRoxieServerFullKeyedJoinHead(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta, IJoinProcessor *_joinHandler, bool _isLocal)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorKeyedJoinArg &)basehelper),
- tlk(createKeyManager(NULL, 0, this)),
- translators(_translators),
- keySet(_keySet),
- remote(_ctx, this, _remoteId, 0, helper, *this, true, true),
- indexReadMeta(_indexReadMeta),
- joinHandler(_joinHandler),
- puller(false),
- isLocal(_isLocal)
- {
- variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
- indexReadInputRecordVariable = indexReadMeta->isVariableSize();
- indexReadInput = NULL;
- rootIndex = NULL;
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- remote.onCreate(_colocalParent);
- indexReadAllocator.setown(createRowAllocator(indexReadMeta));
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (!idx)
- puller.setInput(this, _sourceIdx, _in);
- else if (idx==1)
- {
- indexReadInput = _in;
- indexReadIdx = _sourceIdx;
- }
- else
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- puller.connectInputStreams(ctx, consumerOrdered);
- //No rows are read from indexReadInput, so no need to extract the streams
- return CRoxieServerActivity::getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- switch (idx)
- {
- case 0:
- return puller.queryInput();
- case 1:
- return indexReadInput;
- default:
- return NULL;
- }
- }
- virtual void serializeExtra(MemoryBuffer &out)
- {
- if (helper.getJoinFlags() & JFindexfromactivity)
- {
- assertex(rootIndex);
- const RemoteActivityId& indexId = rootIndex->queryRemoteId();
- indexId.serialize(out);
- // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
- MemoryBuffer tmp;
- rootIndex->queryActivity()->serializeCreateStartContext(tmp);
- if (rootIndex->queryActivity()->queryVarFileInfo())
- {
- rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
- tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
- }
- unsigned ctxlen = tmp.length();
- out.append(ctxlen).append(tmp);
- }
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (indexReadInput)
- {
- indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
- rootIndex = indexReadInput->queryIndexReadActivity();
- if (!rootIndex)
- throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
- }
- remote.onStart(parentExtractSize, parentExtract);
- remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
- if (rootIndex)
- {
- varFileInfo.setown(rootIndex->getVarFileInfo());
- translators.setown(rootIndex->getTranslators());
- keySet.setown(rootIndex->getKeySet());
- }
- else if (variableIndexFileName)
- {
- OwnedRoxieString indexFileName(helper.getIndexFileName());
- varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
- if (varFileInfo)
- {
- translators.setown(new TranslatorArray);
- keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation)); // MORE - isLocal?
- }
- }
- puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().fullKeyedJoinPreload, false, ctx);
- }
- virtual void stop()
- {
- puller.stop();
- CRoxieServerActivity::stop();
- }
- virtual void reset()
- {
- CRoxieServerActivity::reset();
- puller.reset();
- if (varFileInfo)
- {
- keySet.clear();
- varFileInfo.clear();
- }
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL : &remote;
- }
- virtual void processRow(const void *row)
- {
- // MORE - this code seems to be pretty much duplicated below in half-keyed....
- // called from front puller thread
- // buffer up an IndexRead request
- if (helper.leftCanMatch(row))
- {
- RtlDynamicRowBuilder extractedBuilder(indexReadAllocator);
- unsigned indexReadSize = helper.extractIndexReadFields(extractedBuilder, row);
- OwnedConstRoxieRow extracted;
- if (indexReadSize)
- extracted.setown(extractedBuilder.finalizeRowClear(indexReadSize));
- CJoinGroup *jg = joinHandler->createJoinGroup(row);
- for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
- {
- IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
- if (thisBase)
- {
- unsigned fileNo = 0;
- IKeyIndex *thisKey = thisBase->queryPart(fileNo);
- try
- {
- tlk->setKey(thisKey);
- tlk->setLayoutTranslator(translators->item(fileNo));
- helper.createSegmentMonitors(tlk, extracted);
- if (rootIndex)
- rootIndex->mergeSegmentMonitors(tlk);
- tlk->finishSegmentMonitors();
- tlk->reset();
- loop
- {
- typedef const void * cvp;
- if (thisKey->isTopLevelKey())
- {
- bool locallySorted = !thisKey->isFullySorted();
- while (locallySorted || tlk->lookup(false))
- {
- unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
- if (locallySorted || slavePart)
- {
- cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
- *outputBuffer++ = jg;
- if (indexReadInputRecordVariable)
- {
- *(unsigned *) outputBuffer = indexReadSize;
- outputBuffer = (cvp*) (((unsigned *) outputBuffer) + 1);
- }
- jg->notePending();
- memcpy(outputBuffer, extracted, indexReadSize);
- if (locallySorted)
- {
- for (unsigned i = 1; i < numChannels; i++)
- jg->notePending();
- break;
- }
- }
- }
- }
- else
- {
- // MORE - this code seems to be duplicated in half keyed
- unsigned accepted = 0;
- unsigned rejected = 0;
- Owned<CRowArrayMessageResult> result = new CRowArrayMessageResult(ctx->queryRowManager(), true);
- jg->notePending();
- unsigned candidateCount = 0;
- while (tlk->lookup(true))
- {
- candidateCount++;
- atomic_inc(&indexRecordsRead);
- KLBlobProviderAdapter adapter(tlk);
- offset_t recptr;
- const byte *indexRow = tlk->queryKeyBuffer(recptr);
- if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
- {
- KeyedJoinHeader *rhs = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
- rhs->fpos = recptr;
- rhs->thisGroup = jg;
- rhs->partNo = partNo;
- result->append(rhs);
- }
- else
- {
- rejected++;
- atomic_inc(&postFiltered);
- }
- }
- // output an end marker for the matches to this group
- KeyedJoinHeader *endMarker = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
- endMarker->fpos = (offset_t) candidateCount;
- endMarker->thisGroup = jg;
- endMarker->partNo = (unsigned short) -1;
- result->append(endMarker);
- remote.injectResult(result.getClear());
- if (accepted)
- noteStatistic(StNumIndexAccepted, accepted);
- if (rejected)
- noteStatistic(StNumIndexRejected, rejected);
- }
- if (++fileNo < thisBase->numParts())
- {
- thisKey = thisBase->queryPart(fileNo);
- tlk->setKey(thisKey);
- tlk->setLayoutTranslator(translators->item(fileNo));
- tlk->reset();
- }
- else
- break;
- }
- tlk->releaseSegmentMonitors();
- tlk->setKey(NULL);
- }
- catch (...)
- {
- tlk->releaseSegmentMonitors();
- tlk->setKey(NULL);
- throw;
- }
- }
- }
- joinHandler->noteEndReceived(jg, 0);
- }
- else
- {
- joinHandler->noteEndReceived(joinHandler->createJoinGroup(row), 0);
- }
- }
- void processGroup(const ConstPointerArray &)
- {
- throwUnexpected();
- }
- virtual void processEOG()
- {
- joinHandler->processEOG();
- }
- virtual void processDone()
- {
- // called from puller thread
- remote.flush();
- remote.senddone();
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- throwUnexpected();
- helper.onLimitExceeded();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- throwUnexpected();
- }
- virtual bool fireException(IException *e)
- {
- // called from puller thread on failure
- remote.fireException(LINK(e));
- return joinHandler->fireException(e);
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CRoxieServerKeyedJoinBase : public CRoxieServerActivity, implements IRecordPullerCallback, implements IRoxieServerErrorHandler, implements IJoinProcessor
- {
- protected:
- IHThorKeyedJoinArg &helper;
- KeyedJoinRemoteAdaptor remote;
- RecordPullerThread puller;
- OwnedConstRoxieRow defaultRight;
- Owned<IEngineRowAllocator> defaultRightAllocator;
- unsigned joinFlags;
- unsigned atMost;
- unsigned atmostsTriggered;
- unsigned abortLimit;
- unsigned keepLimit;
- bool limitFail;
- bool limitOnFail;
- bool preserveGroups;
- bool cloneLeft;
- bool isSimple;
- bool isLocal;
- ThorActivityKind activityKind;
- CJoinGroup *groupStart;
- CriticalSection groupsCrit;
- QueueOf<CJoinGroup, false> groups;
- IFinalRoxieInput *indexReadInput;
- unsigned indexReadIdx = 0;
- Owned<IStrandJunction> indexReadJunction;
- IEngineRowStream *indexReadStream = NULL; // Never actually pulled
- IIndexReadActivityInfo *rootIndex;
- void createDefaultRight()
- {
- if (!defaultRight)
- {
- if (!defaultRightAllocator)
- defaultRightAllocator.setown(createRowAllocator(helper.queryJoinFieldsRecordSize()));
- RtlDynamicRowBuilder rowBuilder(defaultRightAllocator);
- size32_t thisSize = helper.createDefaultRight(rowBuilder);
- defaultRight.setown(rowBuilder.finalizeRowClear(thisSize));
- }
- }
- public:
- CRoxieServerKeyedJoinBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, unsigned _joinFlags
- , bool isFull, bool _isSimple, bool _isLocal)
- : CRoxieServerActivity(_ctx, _factory, _probeManager),
- helper((IHThorKeyedJoinArg &)basehelper),
- remote(_ctx, this, _remoteId, helper, *this, isFull, _isSimple, puller, *this),
- joinFlags(_joinFlags),
- preserveGroups(meta.isGrouped()),
- puller(false),
- isSimple(_isSimple),
- isLocal(_isLocal),
- abortLimit(0),
- keepLimit(0),
- atMost(0),
- limitFail(false),
- limitOnFail(false),
- cloneLeft(false)
- {
- groupStart = NULL;
- activityKind = _factory->getKind();
- indexReadInput = NULL;
- rootIndex = NULL;
- atmostsTriggered = 0;
- // MORE - code would be easier to read if I got more values from helper rather than passing from factory
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerActivity::onCreate(_colocalParent);
- remote.onCreate(_colocalParent);
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- if (!idx)
- puller.setInput(this, _sourceIdx, _in);
- else if (idx==1)
- {
- indexReadInput = _in;
- indexReadIdx = _sourceIdx;
- }
- else
- throw MakeStringException(ROXIE_SET_INPUT, "Internal error: setInput() parameter out of bounds at %s(%d)", sanitizeSourceFile(__FILE__), __LINE__);
- }
- virtual void connectInputStreams(bool consumerOrdered)
- {
- CRoxieServerActivity::connectInputStreams(consumerOrdered);
- puller.connectInputStreams(ctx, consumerOrdered);
- if (indexReadInput)
- indexReadStream = connectSingleStream(ctx, indexReadInput, indexReadIdx, indexReadJunction, consumerOrdered); // We never actually pull the stream
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- if (indexReadInput)
- {
- indexReadInput->start(parentExtractSize, parentExtract, true); // paused=true because we don't want to actually run the index read
- rootIndex = indexReadInput->queryIndexReadActivity();
- if (!rootIndex)
- throw MakeStringException(ROXIE_INTERNAL_ERROR,"Index in keyed join %d could not be resolved", queryId());
- }
- remote.onStart(parentExtractSize, parentExtract);
- remote.setLimits(helper.getRowLimit(), (unsigned __int64) -1, I64C(0x7FFFFFFFFFFFFFFF));
- atmostsTriggered = 0;
- atMost = helper.getJoinLimit();
- if (atMost == 0) atMost = (unsigned)-1;
- abortLimit = helper.getMatchAbortLimit();
- if (abortLimit == 0 || atMost != (unsigned) -1) abortLimit = (unsigned)-1;
- keepLimit = helper.getKeepLimit();
- if (keepLimit == 0) keepLimit = (unsigned)-1;
- getLimitType(joinFlags, limitFail, limitOnFail);
- cloneLeft = (joinFlags & JFtransformmatchesleft) != 0;
- if (joinFlags & JFleftouter || limitOnFail)
- createDefaultRight();
- }
- virtual void stop()
- {
- puller.stop();
- if (indexReadStream)
- indexReadStream->stop(); // Could probably do this as soon as re have fetched rootIndex?
- CRoxieServerActivity::stop();
- }
- virtual unsigned __int64 queryLocalCycles() const
- {
- __int64 localCycles = remote.totalCycles.totalCycles;
- localCycles -= puller.queryTotalCycles(); // MORE - debatable... but probably fair.
- if (localCycles < 0)
- localCycles = 0;
- return localCycles;
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- if (idx==0)
- return puller.queryInput();
- else if (idx==1)
- return indexReadInput;
- else
- return NULL;
- }
- virtual void reset()
- {
- totalCycles.totalCycles = remote.totalCycles.totalCycles;
- remote.totalCycles.totalCycles = 0;
- processed = remote.joinProcessed;
- remote.joinProcessed = 0;
- defaultRight.clear();
- if (indexReadInput)
- indexReadInput->reset();
- if (atmostsTriggered)
- noteStatistic(StNumAtmostTriggered, atmostsTriggered);
- CRoxieServerActivity::reset();
- puller.reset();
- while (groups.ordinality())
- {
- ::Release(groups.dequeue());
- }
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- if (idx==(unsigned)-1)
- idx = 0;
- return idx ? NULL : &remote;
- }
- #undef new
- virtual CJoinGroup *createJoinGroup(const void *row)
- {
- // NOTE - we need to protect access to queue, since it's also modified by consumer thread. Groupstart is only modified by puller thread.
- CriticalBlock c(groupsCrit);
- if (preserveGroups && !groupStart)
- {
- groupStart = new (&ctx->queryRowManager(), activityId) CJoinGroup(NULL, NULL);
- groups.enqueue(groupStart);
- }
- CJoinGroup *jg = new (&ctx->queryRowManager(), activityId) CJoinGroup(row, groupStart);
- groups.enqueue(jg);
- return jg;
- }
- #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
- #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
- #endif
- void endGroup()
- {
- CriticalBlock c(groupsCrit);
- if (groupStart)
- noteEndReceived(groupStart, 0);
- groupStart = NULL;
- }
- virtual void noteEndReceived(CJoinGroup *jg, unsigned candidateCount)
- {
- if (jg->noteEndReceived(candidateCount))
- processCompletedGroups();
- }
- void processCompletedGroups()
- {
- CriticalBlock c(groupsCrit);
- while (groups.ordinality())
- {
- if (!groups.head()->complete())
- break;
- Owned<CJoinGroup> head = groups.dequeue();
- if (preserveGroups)
- {
- assert(head->isHeadRecord());
- assert(groups.head()->inGroup(head));
- unsigned joinGroupSize = 0;
- while (groups.ordinality() && groups.head()->inGroup(head))
- {
- Owned<CJoinGroup> finger = groups.dequeue();
- joinGroupSize += doJoinGroup(finger);
- }
- if (joinGroupSize)
- remote.addResult(NULL);
- }
- else
- doJoinGroup(head);
- }
- }
- void failLimit(const void * left)
- {
- helper.onMatchAbortLimitExceeded();
- CommonXmlWriter xmlwrite(0);
- if (input && input->queryOutputMeta() && input->queryOutputMeta()->hasXML())
- {
- input->queryOutputMeta()->toXML((byte *) left, xmlwrite);
- }
- throw MakeStringException(ROXIE_JOIN_ERROR, "More than %d match candidates in keyed join %d for row %s", abortLimit, queryId(), xmlwrite.str());
- }
- virtual bool needsAllocator() const { return true; }
- unsigned doTransform(const void *left, const void *right, offset_t fpos_or_count, IException *except, const void **group, unsigned counter)
- {
- if (cloneLeft && !except)
- {
- LinkRoxieRow(left);
- remote.addResult((void *) left);
- return 1;
- }
-
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- unsigned outSize;
- try
- {
- outSize = except ? helper.onFailTransform(rowBuilder, left, right, fpos_or_count, except) :
- (activityKind == TAKkeyeddenormalizegroup) ? helper.transform(rowBuilder, left, right, (unsigned) fpos_or_count, group) :
- helper.transform(rowBuilder, left, right, fpos_or_count, counter);
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- if (outSize)
- {
- const void *shrunk = rowBuilder.finalizeRowClear(outSize);
- remote.addResult(shrunk);
- return 1;
- }
- else
- return 0;
- }
- unsigned doJoinGroup(CJoinGroup *jg)
- {
- unsigned matched = jg->rowsSeen();
- unsigned added = 0;
- const void *left = jg->queryLeft();
- if (jg->candidateCount() > abortLimit)
- {
- if (limitFail)
- failLimit(left);
- if (ctx->queryDebugContext())
- ctx->queryDebugContext()->checkBreakpoint(DebugStateLimit, NULL, static_cast<IActivityBase *>(this));
- if (limitOnFail)
- {
- Owned<IException> except;
- try
- {
- failLimit(left);
- }
- catch(IException * e)
- {
- except.setown(e);
- }
- added = doTransform(left, defaultRight, 0, except, NULL, 0);
- }
- }
- else if (!matched || jg->candidateCount() > atMost)
- {
- if (jg->candidateCount() > atMost)
- atmostsTriggered++;
- switch (joinFlags & JFtypemask)
- {
- case JFleftouter:
- case JFleftonly:
- switch (activityKind)
- {
- case TAKkeyedjoin:
- case TAKkeyeddenormalizegroup:
- added = doTransform(left, defaultRight, 0, NULL, NULL, 0);
- break;
- case TAKkeyeddenormalize:
- LinkRoxieRow(left);
- remote.addResult((void *) left);
- added++;
- break;
- }
- break;
- }
- }
- else if (!(joinFlags & JFexclude))
- {
- unsigned idx = 0;
- switch (activityKind)
- {
- case TAKkeyedjoin:
- while (idx < matched)
- {
- const KeyedJoinHeader *rhs = jg->queryRow(idx);
- added += doTransform(left, &rhs->rhsdata, rhs->fpos, NULL, NULL, idx+1);
- if (added==keepLimit)
- break;
- idx++;
- }
- break;
- case TAKkeyeddenormalize:
- {
- OwnedConstRoxieRow newLeft;
- newLeft.set(left);
- unsigned rowSize = 0;
- unsigned rightAdded = 0;
- while (idx < matched)
- {
- const KeyedJoinHeader *rhs = jg->queryRow(idx);
- try
- {
- RtlDynamicRowBuilder rowBuilder(rowAllocator);
- size32_t transformedSize = helper.transform(rowBuilder, newLeft, &rhs->rhsdata, rhs->fpos, idx+1);
- if (transformedSize)
- {
- rowSize = transformedSize;
- newLeft.setown(rowBuilder.finalizeRowClear(rowSize));
- rightAdded++;
- if (rightAdded==keepLimit)
- break;
- }
- idx++;
- }
- catch (IException *E)
- {
- throw makeWrappedException(E);
- }
- }
- if (rowSize)
- {
- remote.addResult(newLeft.getClear());
- added++;
- }
- }
- break;
- case TAKkeyeddenormalizegroup:
- {
- ConstPointerArray extractedRows;
- while (idx < matched && idx < keepLimit)
- {
- const KeyedJoinHeader *rhs = jg->queryRow(idx);
- extractedRows.append((void *) &rhs->rhsdata);
- idx++;
- }
- added += doTransform(left, extractedRows.item(0), extractedRows.ordinality(), NULL, (const void * *)extractedRows.getArray(), 0);
- }
- break;
- }
- }
- return added;
- }
- virtual void processDone()
- {
- // called from puller thread
- remote.flush();
- remote.senddone();
- }
- virtual void onLimitExceeded(bool isKeyed)
- {
- if (traceLevel > 4)
- DBGLOG("activityid = %d isKeyed = %d line = %d", activityId, isKeyed, __LINE__);
- if (isKeyed)
- throwUnexpected();
- helper.onLimitExceeded();
- }
- virtual const void *createLimitFailRow(bool isKeyed)
- {
- throwUnexpected();
- }
- virtual bool fireException(IException *e)
- {
- // called from puller thread on failure
- return remote.fireException(e);
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- #ifdef _MSC_VER
- #pragma warning ( push )
- #pragma warning ( disable: 4355 )
- #endif
- class CRoxieServerKeyedJoinActivity : public CRoxieServerKeyedJoinBase
- {
- CRoxieServerFullKeyedJoinHead head;
- Owned<IEngineRowAllocator> fetchInputAllocator;
- Linked<IFilePartMap> map;
- bool variableFetchFileName;
- Owned<const IResolvedFile> varFetchFileInfo;
- CachedOutputMetaData fetchInputFields;
- public:
- CRoxieServerKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_headId, IKeyArray * _key, TranslatorArray *_translators, IOutputMetaData *_indexReadMeta,
- const RemoteActivityId &_tailId, IFilePartMap *_map, unsigned _joinFlags, bool _isLocal)
- : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _tailId, _joinFlags, true, false, _isLocal),
- head(_ctx, _factory, _probeManager, _headId, _key, _translators, _indexReadMeta, this, _isLocal),
- map(_map)
- {
- CRoxieServerKeyedJoinBase::setInput(0, 0, head.queryOutput(0));
- variableFetchFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
- }
-
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFetchFileInfo;
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
- head.onCreate(_colocalParent);
- fetchInputFields.set(helper.queryFetchInputRecordSize());
- fetchInputAllocator.setown(createRowAllocator(helper.queryFetchInputRecordSize()));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
- if (variableFetchFileName)
- {
- bool isFetchOpt = (helper.getFetchFlags() & FFdatafileoptional) != 0;
- OwnedRoxieString fname(helper.getFileName());
- varFetchFileInfo.setown(resolveLFN(fname, isFetchOpt));
- if (varFetchFileInfo)
- map.setown(varFetchFileInfo->getFileMap());
- }
- puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, false, ctx);
- }
- virtual void setInput(unsigned idx, unsigned _sourceIdx, IFinalRoxieInput *_in)
- {
- head.setInput(idx, _sourceIdx, _in);
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- connectInputStreams(consumerOrdered);
- return head.getOutputStreams(ctx, idx, streams, consumerOptions, consumerOrdered, orderedCallbacks);
- }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- return head.queryInput(idx);
- }
- virtual void processRow(const void *_rhs)
- {
- // called from puller thread
- KeyedJoinHeader *rhs = (KeyedJoinHeader *) _rhs;
- CJoinGroup *jg = rhs->thisGroup;
- if (rhs->partNo != (unsigned short) -1)
- {
- unsigned partNo = map->mapOffset(rhs->fpos);
- RtlDynamicRowBuilder fetchBuilder(fetchInputAllocator, true);
- size32_t fisize = helper.extractFetchFields(fetchBuilder, jg->queryLeft());
- if (fetchInputFields.isVariableSize())
- {
- KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize + sizeof(fisize)));
- memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
- ReleaseRoxieRow(rhs);
- jg->notePending();
- memcpy(&outRow->rhsdata, &fisize, sizeof(fisize));
- memcpy((&outRow->rhsdata)+sizeof(fisize), fetchBuilder.row(), fisize);
- }
- else
- {
- KeyedJoinHeader *outRow = (KeyedJoinHeader *) remote.getMem(partNo, 0, KEYEDJOIN_RECORD_SIZE(fisize));
- memcpy(outRow, rhs, KEYEDJOIN_RECORD_SIZE(0)); // MORE - copy constructor might be more appropriate....
- ReleaseRoxieRow(rhs);
- jg->notePending();
- memcpy(&outRow->rhsdata, fetchBuilder.row(), fisize);
- }
- }
- else
- {
- unsigned candidateCount = (unsigned) rhs->fpos;
- // CTXLOG("Full keyed join - all results back from index");
- ReleaseRoxieRow(rhs);
- noteEndReceived(jg, candidateCount); // may throw exception - so release row before calling
- }
- }
- virtual void processEOG()
- {
- // called from front puller thread
- if (preserveGroups)
- endGroup();
- }
- void processGroup(const ConstPointerArray &)
- {
- throwUnexpected();
- }
- };
- #ifdef _MSC_VER
- #pragma warning ( pop )
- #endif
- class CRoxieServerHalfKeyedJoinActivity : public CRoxieServerKeyedJoinBase
- {
- IOutputMetaData *indexReadMeta;
- Owned<IEngineRowAllocator> indexReadAllocator;
- Owned<IKeyManager> tlk;
- bool variableIndexFileName;
- bool indexReadInputRecordVariable;
- Owned<const IResolvedFile> varFileInfo;
- Linked<TranslatorArray> translators;
- Linked<IKeyArray> keySet;
- Owned<IOutputMetaData> joinPrefixedMeta;
- Owned<IEngineRowAllocator> joinFieldsAllocator;
- public:
- CRoxieServerHalfKeyedJoinActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager, const RemoteActivityId &_remoteId, IKeyArray * _keySet, TranslatorArray *_translators,
- IOutputMetaData *_indexReadMeta, unsigned _joinFlags, bool _isSimple, bool _isLocal)
- : CRoxieServerKeyedJoinBase(_ctx, _factory, _probeManager, _remoteId, _joinFlags, false, _isSimple, _isLocal),
- indexReadMeta(_indexReadMeta),
- tlk(createKeyManager(NULL, 0, this)),
- keySet(_keySet),
- translators(_translators)
- {
- variableIndexFileName = allFilesDynamic || factory->queryQueryFactory().isDynamic() || ((helper.getJoinFlags() & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
- indexReadInputRecordVariable = indexReadMeta->isVariableSize();
- }
- virtual void serializeExtra(MemoryBuffer &out)
- {
- if (helper.getJoinFlags() & JFindexfromactivity)
- {
- assertex(rootIndex);
- const RemoteActivityId& indexId = rootIndex->queryRemoteId();
- indexId.serialize(out);
- // could mess about reserving space for length then patching it again, to avoid copy, but probably not worth it
- MemoryBuffer tmp;
- rootIndex->queryActivity()->serializeCreateStartContext(tmp);
- if (rootIndex->queryActivity()->queryVarFileInfo())
- {
- rootIndex->queryActivity()->queryVarFileInfo()->queryTimeStamp().serialize(tmp);
- tmp.append(rootIndex->queryActivity()->queryVarFileInfo()->queryCheckSum());
- }
- unsigned ctxlen = tmp.length();
- out.append(ctxlen).append(tmp);
- }
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- CRoxieServerKeyedJoinBase::onCreate(_colocalParent);
- indexReadAllocator.setown(createRowAllocator(indexReadMeta));
- IOutputMetaData *joinFieldsMeta = helper.queryJoinFieldsRecordSize();
- joinPrefixedMeta.setown(new CPrefixedOutputMeta(KEYEDJOIN_RECORD_SIZE(0), joinFieldsMeta)); // MORE - not sure if we really need this
- joinFieldsAllocator.setown(createRowAllocator(joinPrefixedMeta));
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- CRoxieServerKeyedJoinBase::start(parentExtractSize, parentExtract, paused);
- if (rootIndex)
- {
- varFileInfo.setown(rootIndex->getVarFileInfo());
- translators.setown(rootIndex->getTranslators());
- keySet.setown(rootIndex->getKeySet());
- }
- else if (variableIndexFileName)
- {
- OwnedRoxieString indexFileName(helper.getIndexFileName());
- varFileInfo.setown(resolveLFN(indexFileName, (helper.getJoinFlags() & JFindexoptional) != 0));
- if (varFileInfo)
- {
- translators.setown(new TranslatorArray);
- keySet.setown(varFileInfo->getKeyArray(factory->queryActivityMeta(), translators, false, isLocal ? factory->queryQueryFactory().queryChannel() : 0, factory->queryQueryFactory().queryOptions().enableFieldTranslation));
- }
- }
- puller.start(parentExtractSize, parentExtract, paused, ctx->queryOptions().keyedJoinPreload, isSimple, ctx);
- }
- virtual const IResolvedFile *queryVarFileInfo() const
- {
- return varFileInfo;
- }
- virtual void reset()
- {
- CRoxieServerKeyedJoinBase::reset();
- if (varFileInfo)
- {
- keySet.clear();
- varFileInfo.clear();
- }
- }
- virtual void processRow(const void *row)
- {
- // called from front puller thread
- // buffer up an IndexRead request
- if (helper.leftCanMatch(row) && keySet)
- {
- RtlDynamicRowBuilder extractBuilder(indexReadAllocator);
- unsigned indexReadRecordSize = helper.extractIndexReadFields(extractBuilder, row);
- OwnedConstRoxieRow extracted;
- if (indexReadRecordSize)
- extracted.setown(extractBuilder.finalizeRowClear(indexReadRecordSize));
- CJoinGroup *jg = createJoinGroup(row);
- for (unsigned partNo = 0; partNo < keySet->length(); partNo++)
- {
- IKeyIndexBase *thisBase = keySet->queryKeyPart(partNo);
- if (thisBase)
- {
- unsigned fileNo = 0;
- IKeyIndex *thisKey = thisBase->queryPart(fileNo);
- tlk->setKey(thisKey);
- tlk->setLayoutTranslator(translators->item(fileNo));
- helper.createSegmentMonitors(tlk, extracted);
- if (rootIndex)
- rootIndex->mergeSegmentMonitors(tlk);
- tlk->finishSegmentMonitors();
- try
- {
- tlk->reset();
- loop
- {
- typedef const void * cvp;
- if (thisKey && thisKey->isTopLevelKey())
- {
- bool locallySorted = (!thisKey->isFullySorted());
- while (locallySorted || tlk->lookup(false))
- {
- unsigned slavePart = locallySorted ? 0 : (unsigned) tlk->queryFpos();
- if (locallySorted || slavePart)
- {
- cvp *outputBuffer = (cvp *) remote.getMem(slavePart, fileNo, indexReadRecordSize + sizeof(cvp) + (indexReadInputRecordVariable ? sizeof(unsigned) : 0));
- *outputBuffer++ = jg;
- if (indexReadInputRecordVariable)
- {
- *(unsigned *) outputBuffer = indexReadRecordSize;
- outputBuffer = (cvp *) (((unsigned *) outputBuffer) + 1);
- }
- jg->notePending();
- memcpy(outputBuffer, extracted, indexReadRecordSize);
- if (locallySorted)
- {
- for (unsigned i = 1; i < numChannels; i++)
- jg->notePending();
- break;
- }
- }
- }
- }
- else
- {
- unsigned accepted = 0;
- unsigned rejected = 0;
- Owned<CRowArrayMessageResult> result;
- if (!isSimple)
- result.setown(new CRowArrayMessageResult(ctx->queryRowManager(), true));
- // MORE - This code seems to be duplicated in keyedJoinHead
- jg->notePending();
- unsigned candidateCount = 0;
- while (tlk->lookup(true))
- {
- candidateCount++;
- atomic_inc(&indexRecordsRead);
- KLBlobProviderAdapter adapter(tlk);
- offset_t recptr;
- const byte *indexRow = tlk->queryKeyBuffer(recptr);
- if (helper.indexReadMatch(extracted, indexRow, recptr, &adapter))
- {
- RtlDynamicRowBuilder rb(joinFieldsAllocator, true);
- CPrefixedRowBuilder pb(KEYEDJOIN_RECORD_SIZE(0), rb);
- accepted++;
- KLBlobProviderAdapter adapter(tlk);
- size32_t joinFieldsSize = helper.extractJoinFields(pb, indexRow, recptr, &adapter);
- KeyedJoinHeader *rec = (KeyedJoinHeader *) rb.getUnfinalizedClear(); // lack of finalize ok as unserialized data here.
- rec->fpos = recptr;
- rec->thisGroup = jg;
- rec->partNo = partNo;
- if (isSimple)
- remote.injected.enqueue(rec);
- else
- result->append(rec);
- }
- else
- {
- rejected++;
- atomic_inc(&postFiltered);
- }
- }
- // output an end marker for the matches to this group
- KeyedJoinHeader *rec = (KeyedJoinHeader *) ctx->queryRowManager().allocate(KEYEDJOIN_RECORD_SIZE(0), activityId);
- rec->fpos = (offset_t) candidateCount;
- rec->thisGroup = jg;
- rec->partNo = (unsigned short) -1;
- if (isSimple)
- remote.injected.enqueue(rec);
- else
- {
- result->append(rec);
- remote.injectResult(result.getClear());
- }
- if (accepted)
- noteStatistic(StNumIndexAccepted, accepted);
- if (rejected)
- noteStatistic(StNumIndexRejected, rejected);
- }
- if (++fileNo < thisBase->numParts())
- {
- thisKey = thisBase->queryPart(fileNo);
- tlk->setKey(thisKey);
- tlk->setLayoutTranslator(translators->item(fileNo));
- tlk->reset();
- }
- else
- break;
- }
- tlk->releaseSegmentMonitors();
- tlk->setKey(NULL);
- }
- catch (...)
- {
- tlk->releaseSegmentMonitors();
- tlk->setKey(NULL);
- throw;
- }
- }
- }
- noteEndReceived(jg, 0);
- }
- else
- {
- noteEndReceived(createJoinGroup(row), 0);
- }
- }
- virtual void processEOG()
- {
- // called from front puller thread
- if (preserveGroups)
- endGroup();
- }
- void processGroup(const ConstPointerArray &)
- {
- throwUnexpected();
- }
- };
- class CRoxieServerKeyedJoinActivityFactory : public CRoxieServerMultiInputFactory
- {
- Owned<const IResolvedFile> indexfile;
- Owned<const IResolvedFile> datafile;
- Owned<IKeyArray> keySet;
- Owned<TranslatorArray> translatorArray;
- Owned<IDefRecordMeta> activityMeta;
- RemoteActivityId headId;
- RemoteActivityId tailId;
- IOutputMetaData *indexReadMeta;
- Owned<IFilePartMap> map;
- Owned<IFileIOArray> files;
- unsigned joinFlags;
- bool isHalfKeyed;
- bool isLocal;
- bool enableFieldTranslation;
- bool variableFetchFileName;
- bool variableIndexFileName;
- bool isSimple;
- public:
- CRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_headId, const RemoteActivityId &_tailId)
- : CRoxieServerMultiInputFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), headId(_headId), tailId(_tailId)
- {
- Owned<IHThorKeyedJoinArg> helper = (IHThorKeyedJoinArg *) helperFactory();
- isLocal = _graphNode.getPropBool("att[@name='local']/@value") && queryFactory.queryChannel()!=0;
- isSimple = isLocal;
- rtlDataAttr indexLayoutMeta;
- size32_t indexLayoutSize;
- if(!helper->getIndexLayout(indexLayoutSize, indexLayoutMeta.refdata()))
- assertex(indexLayoutSize== 0);
- MemoryBuffer m;
- m.setBuffer(indexLayoutSize, indexLayoutMeta.getdata());
- activityMeta.setown(deserializeRecordMeta(m, true));
- enableFieldTranslation = queryFactory.queryOptions().enableFieldTranslation;
- translatorArray.setown(new TranslatorArray);
- joinFlags = helper->getJoinFlags();
- variableIndexFileName = allFilesDynamic || _queryFactory.isDynamic() || ((joinFlags & (JFvarindexfilename|JFdynamicindexfilename|JFindexfromactivity)) != 0);
- variableFetchFileName = allFilesDynamic || _queryFactory.isDynamic() || ((helper->getFetchFlags() & (FFvarfilename|FFdynamicfilename)) != 0);
- if (!variableIndexFileName)
- {
- bool isOpt = (joinFlags & JFindexoptional) != 0;
- OwnedRoxieString indexFileName(helper->getIndexFileName());
- indexfile.setown(queryFactory.queryPackage().lookupFileName(indexFileName, isOpt, true, true, queryFactory.queryWorkUnit(), true));
- if (indexfile)
- keySet.setown(indexfile->getKeyArray(activityMeta, translatorArray, isOpt, isLocal ? queryFactory.queryChannel() : 0, enableFieldTranslation));
- }
- if (keySet && keySet->length()==1 && !isSimple)
- {
- IKeyIndexBase *thisBase = keySet->queryKeyPart(0);
- if (thisBase->numParts()==1 && !thisBase->queryPart(0)->isTopLevelKey() && !_queryFactory.queryOptions().disableLocalOptimizations)
- isSimple = true;
- // MORE - if it's a variable filename then it MAY be simple, we don't know. Tough.
- }
- if (!simpleLocalKeyedJoins)
- isSimple = false;
- isHalfKeyed = !helper->diskAccessRequired();
- indexReadMeta = QUERYINTERFACE(helper->queryIndexReadInputRecordSize(), IOutputMetaData);
- if (!isHalfKeyed && !variableFetchFileName)
- {
- bool isFetchOpt = (helper->getFetchFlags() & FFdatafileoptional) != 0;
- datafile.setown(_queryFactory.queryPackage().lookupFileName(queryNodeFileName(_graphNode, _kind), isFetchOpt, true, true, _queryFactory.queryWorkUnit(), true));
- if (datafile)
- {
- if (isLocal)
- files.setown(datafile->getIFileIOArray(isFetchOpt, queryFactory.queryChannel()));
- else
- map.setown(datafile->getFileMap());
- }
- }
- }
- virtual bool getEnableFieldTranslation() const
- {
- return enableFieldTranslation;
- }
- virtual IDefRecordMeta *queryActivityMeta() const
- {
- return activityMeta;
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- if (isHalfKeyed)
- return new CRoxieServerHalfKeyedJoinActivity(_ctx, this, _probeManager,
- headId, keySet, translatorArray, indexReadMeta, joinFlags, isSimple, isLocal);
- else
- return new CRoxieServerKeyedJoinActivity(_ctx, this, _probeManager,
- headId, keySet, translatorArray, indexReadMeta,
- tailId, map, joinFlags, isLocal);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return keyedJoinStatistics;
- }
- virtual void getXrefInfo(IPropertyTree &reply, const IRoxieContextLogger &logctx) const
- {
- if (datafile)
- addXrefFileInfo(reply, datafile);
- if (indexfile)
- addXrefFileInfo(reply, indexfile);
- }
- };
- IRoxieServerActivityFactory *createRoxieServerKeyedJoinActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, const RemoteActivityId &_remoteId, const RemoteActivityId &_remoteId2)
- {
- return new CRoxieServerKeyedJoinActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _remoteId, _remoteId2);
- }
- //=================================================================================
- class CRoxieServerSoapActivityBase : public CRoxieServerActivity, implements ISoapCallRowProvider, implements IRoxieAbortMonitor
- {
- protected:
- Owned<ISoapCallHelper> soaphelper;
- IHThorSoapActionArg & helper;
- StringBuffer authToken;
- bool eof;
- CriticalSection crit;
- ClientCertificate *pClientCert;
- public:
- IMPLEMENT_IINTERFACE_USING(CRoxieServerActivity)
- CRoxieServerSoapActivityBase(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerActivity(_ctx, _factory, _probeManager), helper((IHThorSoapActionArg &)basehelper)
- {
- eof = false;
- if (clientCert.certificate.length() > 0 && clientCert.privateKey.length() > 0 && clientCert.passphrase.length() > 0)
- pClientCert = &clientCert;
- else
- pClientCert = NULL;
- }
- // ISoapCallRowProvider
- virtual IHThorSoapActionArg * queryActionHelper() { return &helper; };
- virtual IHThorSoapCallArg * queryCallHelper() { return NULL; };
- virtual const void * getNextRow() { return NULL; };
- virtual void releaseRow(const void * r) { ReleaseRoxieRow(r); };
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- eof = false;
- CRoxieServerActivity::start(parentExtractSize, parentExtract, paused);
- authToken.append(ctx->queryAuthToken());
- }
- virtual void reset()
- {
- // MORE - Shouldn't we make sure thread is stopped etc???
- soaphelper.clear();
- CRoxieServerActivity::reset();
- }
- // IRoxieAbortMonitor
- virtual void checkForAbort() { checkAbort(); }
- };
- //---------------------------------------------------------------------------
- class CRoxieServerSoapRowCallActivity : public CRoxieServerSoapActivityBase
- {
- IHThorSoapCallArg & callHelper;
- public:
- CRoxieServerSoapRowCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
- {
- }
- virtual IHThorSoapCallArg * queryCallHelper()
- {
- return &callHelper;
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if(eof) return NULL;
- if (soaphelper == NULL)
- {
- if (factory->getKind()==TAKhttp_rowdataset)
- soaphelper.setown(createHttpCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
- else
- soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCrow, pClientCert, *this, this));
- soaphelper->start();
- }
- OwnedConstRoxieRow ret = soaphelper->getRow();
- if (!ret)
- {
- eof = true;
- return NULL;
- }
- ++processed;
- return ret.getClear();
- }
- };
- class CRoxieServerSoapRowCallActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSoapRowCallActivity(_ctx, this, _probeManager);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return soapStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSoapRowCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSoapRowCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //---------------------------------------------------------------------------
- class CRoxieServerSoapRowActionActivity : public CRoxieServerSoapActivityBase
- {
- public:
- CRoxieServerSoapRowActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
- {}
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- //MORE: parentExtract not passed to start - although shouldn't be a problem.
- soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCrow, pClientCert, *this, this));
- soaphelper->start();
- soaphelper->waitUntilDone();
- IException *e = soaphelper->getError();
- soaphelper.clear();
- if (e)
- throw e;
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- return NULL;
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CRoxieServerSoapRowActionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSoapRowActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return soapStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSoapRowActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerSoapRowActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //---------------------------------------------------------------------------
- class CRoxieServerSoapDatasetCallActivity : public CRoxieServerSoapActivityBase
- {
- IHThorSoapCallArg & callHelper;
- public:
- CRoxieServerSoapDatasetCallActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager), callHelper((IHThorSoapCallArg &)basehelper)
- {
- }
- virtual IHThorSoapCallArg * queryCallHelper()
- {
- return &callHelper;
- }
- virtual const void *getNextRow()
- {
- CriticalBlock b(crit); // MORE - why ?
- return inputStream->ungroupedNextRow();
- }
- virtual bool needsAllocator() const { return true; }
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, timeActivities);
- if(eof) return NULL;
- if (soaphelper == NULL)
- {
- soaphelper.setown(createSoapCallHelper(this, rowAllocator, authToken.str(), SCdataset, pClientCert, *this, this));
- soaphelper->start();
- }
- OwnedConstRoxieRow ret = soaphelper->getRow();
- if (!ret)
- {
- eof = true;
- return NULL;
- }
- ++processed;
- return ret.getClear();
- }
- };
- class CRoxieServerSoapDatasetCallActivityFactory : public CRoxieServerActivityFactory
- {
- public:
- CRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSoapDatasetCallActivity(_ctx, this, _probeManager);
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return soapStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSoapDatasetCallActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode)
- {
- return new CRoxieServerSoapDatasetCallActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode);
- }
- //---------------------------------------------------------------------------
- class CRoxieServerSoapDatasetActionActivity : public CRoxieServerSoapActivityBase
- {
- public:
- CRoxieServerSoapDatasetActionActivity(IRoxieSlaveContext *_ctx, const IRoxieServerActivityFactory *_factory, IProbeManager *_probeManager)
- : CRoxieServerSoapActivityBase(_ctx, _factory, _probeManager)
- {}
- virtual const void *getNextRow()
- {
- CriticalBlock b(crit); // MORE - Why?
- const void *nextrec = inputStream->ungroupedNextRow();
- if (nextrec)
- processed++;
- return nextrec;
- }
- virtual void execute(unsigned parentExtractSize, const byte * parentExtract)
- {
- try
- {
- start(parentExtractSize, parentExtract, false);
- soaphelper.setown(createSoapCallHelper(this, NULL, ctx->queryAuthToken(), SCdataset, pClientCert, *this, this));
- soaphelper->start();
- soaphelper->waitUntilDone();
- IException *e = soaphelper->getError();
- soaphelper.clear();
- if (e)
- throw e;
- stop();
- }
- catch (IException *E)
- {
- ctx->notifyAbort(E);
- abort();
- throw;
- }
- catch(...)
- {
- Owned<IException> E = MakeStringException(ROXIE_INTERNAL_ERROR, "Unknown exception caught at %s:%d", sanitizeSourceFile(__FILE__), __LINE__);
- ctx->notifyAbort(E);
- abort();
- throw;
- }
- }
- virtual IFinalRoxieInput *queryOutput(unsigned idx)
- {
- return NULL;
- }
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CRoxieServerSoapDatasetActionActivityFactory : public CRoxieServerActivityFactory
- {
- bool isRoot;
- public:
- CRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- : CRoxieServerActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode), isRoot(_isRoot)
- {
- }
- virtual IRoxieServerActivity *createActivity(IRoxieSlaveContext *_ctx, IProbeManager *_probeManager) const
- {
- return new CRoxieServerSoapDatasetActionActivity(_ctx, this, _probeManager);
- }
- virtual bool isSink() const
- {
- return isRoot;
- }
- virtual const StatisticsMapping &queryStatsMapping() const
- {
- return soapStatistics;
- }
- };
- IRoxieServerActivityFactory *createRoxieServerSoapDatasetActionActivityFactory(unsigned _id, unsigned _subgraphId, IQueryFactory &_queryFactory, HelperFactory *_helperFactory, ThorActivityKind _kind, IPropertyTree &_graphNode, bool _isRoot)
- {
- return new CRoxieServerSoapDatasetActionActivityFactory(_id, _subgraphId, _queryFactory, _helperFactory, _kind, _graphNode, _isRoot);
- }
- //=====================================================================================================
- class CGraphResults : implements IRoxieGraphResults, public CInterface
- {
- IArrayOf<IGraphResult> results;
- CriticalSection cs;
- IGraphResult & select(unsigned idx)
- {
- CriticalBlock procedure(cs);
- if (idx >= results.ordinality())
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", idx);
- return results.item(idx);
- }
- public:
- IMPLEMENT_IINTERFACE
- void clear()
- {
- CriticalBlock procedure(cs);
- results.kill();
- }
- virtual IEngineRowStream * createIterator(unsigned id)
- {
- return select(id).createIterator();
- }
- virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
- {
- select(id).getLinkedResult(count, ret);
- }
- virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
- {
- select(id).getLinkedResult(count, ret);
- }
- virtual const void * getLinkedRowResult(unsigned id)
- {
- return select(id).getLinkedRowResult();
- }
- void setResult(unsigned id, IGraphResult * result)
- {
- CriticalBlock procedure(cs);
- if (results.ordinality() <= id)
- {
- while (results.ordinality() < id)
- results.append(*new CGraphResult);
- results.append(*LINK(result));
- }
- else
- results.replace(*LINK(result), id);
- }
- void appendResult(IGraphResult * result)
- {
- CriticalBlock procedure(cs);
- results.append(*LINK(result));
- }
- };
- //===================================================================================================================
- class CPseudoArg : implements IHThorArg, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE
- virtual IOutputMetaData * queryOutputMeta() { return NULL; }
- };
- class CPseudoActivity : public CRoxieServerActivity
- {
- public:
- CPseudoActivity(IRoxieSlaveContext *_ctx, IHThorArg & _helper) : CRoxieServerActivity(_ctx, _helper) {}
- virtual const void *nextRow()
- {
- throwUnexpected(); // I am nobody's input
- }
- };
- class CActivityGraph : implements IActivityGraph, implements IThorChildGraph, implements ILocalGraphEx, implements IRoxieServerChildGraph, public CInterface
- {
- protected:
- class ActivityGraphSlaveContext : public IndirectSlaveContext
- {
- SpinLock abortLock;
- bool aborted;
- Owned<IException> exception;
- public:
- ActivityGraphSlaveContext(IRoxieSlaveContext *_ctx, const IRoxieContextLogger &_logctx) : IndirectSlaveContext(_ctx), logctx(_logctx), loopCounter(0), codeContext(NULL)
- {
- aborted = false;
- }
- // Note - we must track exceptions at the child level in case there is a CATCH in parent
- virtual void notifyAbort(IException *E)
- {
- SpinBlock b(abortLock);
- if (!aborted && QUERYINTERFACE(E, InterruptedSemaphoreException) == NULL)
- {
- aborted = true;
- exception.set(E);
- }
- }
- virtual void checkAbort()
- {
- if (aborted) // NOTE - don't bother getting lock before reading this (for speed) - a false read is very unlikely and not a problem
- {
- SpinBlock b(abortLock);
- if (!exception)
- exception.setown(MakeStringException(ROXIE_INTERNAL_ERROR, "Query was aborted"));
- throw exception.getLink();
- }
- IndirectSlaveContext::checkAbort();
- }
- virtual ICodeContext *queryCodeContext()
- {
- return codeContext;
- }
- void setCodeContext(ICodeContext * _codeContext)
- {
- codeContext = _codeContext;
- }
- void setLoopCounter(unsigned _loopCounter)
- {
- loopCounter = _loopCounter;
- }
- virtual void noteChildGraph(unsigned id, IActivityGraph *childGraph)
- {
- childGraphs.setValue(id, childGraph);
- }
- virtual IActivityGraph * queryChildGraph(unsigned id)
- {
- if (queryTraceLevel() > 10)
- CTXLOG("resolveChildGraph %d", id);
- IActivityGraph *childGraph = childGraphs.getValue(id);
- assertex(childGraph);
- return childGraph;
- }
- // 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
- virtual StringBuffer &getLogPrefix(StringBuffer &ret) const
- {
- logctx.getLogPrefix(ret);
- if (loopCounter)
- ret.appendf("{%u}", loopCounter);
- return ret;
- }
- protected:
- const IRoxieContextLogger &logctx;
- unsigned loopCounter;
- ICodeContext * codeContext;
- MapXToMyClass<unsigned, unsigned, IActivityGraph> childGraphs;
- } graphSlaveContext;
- class ActivityGraphCodeContext : public IndirectCodeContext
- {
- public:
- virtual IEclGraphResults * resolveLocalQuery(__int64 activityId)
- {
- if ((unsigned) activityId == container->queryId())
- return container;
- IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
- if (match)
- return match->queryLocalGraph();
- return IndirectCodeContext::resolveLocalQuery(activityId);
- }
- virtual IThorChildGraph * resolveChildQuery(__int64 activityId, IHThorArg * colocal)
- {
- IActivityGraph * match = slaveContext->queryChildGraph((unsigned) activityId);
- return LINK(match->queryChildGraph());
- }
- virtual unsigned getGraphLoopCounter() const
- {
- return container->queryLoopCounter(); // only called if value is valid
- }
- void setContainer(IRoxieSlaveContext * _slaveContext, CActivityGraph * _container)
- {
- slaveContext = _slaveContext;
- container = _container;
- }
- protected:
- IRoxieSlaveContext * slaveContext;
- CActivityGraph * container;
- } graphCodeContext;
- // NOTE - destructor order is significant - need to destroy graphCodeContext and graphSlaveContext last
- IArrayOf<IRoxieServerActivity> activities;
- IArrayOf<IRoxieProbe> probes;
- IRoxieServerActivityCopyArray sinks;
- StringAttr graphName;
- Owned<CGraphResults> results;
- CGraphResults graphLoopResults;
- ActivityArray & graphDefinition;
- CriticalSection evaluateCrit;
- IProbeManager *probeManager;
- unsigned id;
- unsigned loopCounter;
- public:
- IMPLEMENT_IINTERFACE;
- CActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx)
- : probeManager(_probeManager), graphDefinition(x), graphName(_graphName), graphSlaveContext(_ctx, _logctx)
- {
- id = x.getLibraryGraphId();
- if (!id)
- id = _id;
- loopCounter = 0;
- graphSlaveContext.setCodeContext(&graphCodeContext);
- graphCodeContext.setContainer(&graphSlaveContext, this);
- }
- ~CActivityGraph()
- {
- if (probeManager)
- probeManager->deleteGraph((IArrayOf<IActivityBase>*)&activities, (IArrayOf<IInputBase>*)&probes);
- }
- virtual const char *queryName() const
- {
- return graphName.get();
- }
- virtual IRoxieServerActivity *queryActivity(unsigned _activityId)
- {
- unsigned idx = graphDefinition.recursiveFindActivityIndex(_activityId);
- if (idx==NotFound)
- return nullptr;
- assertex(activities.isItem(idx));
- IRoxieServerActivity *activity = &activities.item(idx);
- if (activity->queryId() == _activityId)
- return activity;
- return activity->queryChildActivity(_activityId);
- }
- void createGraph(IRoxieSlaveContext *_ctx)
- {
- if (graphDefinition.isMultiInstance())
- {
- graphCodeContext.set(_ctx->queryCodeContext());
- _ctx = &graphSlaveContext;
- }
- ForEachItemIn(idx, graphDefinition)
- {
- IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx);
- IRoxieServerActivity &activity = *donor.createActivity(_ctx, probeManager);
- activities.append(activity);
- if (donor.isSink())
- {
- sinks.append(activity);
- if (probeManager)
- probeManager->noteSink(&activity);
- }
- }
- ForEachItemIn(idx1, graphDefinition)
- {
- IRoxieServerActivityFactory &donor = graphDefinition.serverItem(idx1);
- IRoxieServerActivity &activity = activities.item(idx1);
- unsigned inputidx = 0;
- loop
- {
- unsigned outputidx;
- unsigned source = donor.getInput(inputidx, outputidx);
- if (source==(unsigned) -1)
- break;
- connectInput(idx1, inputidx, source, outputidx, 0);
- inputidx++;
- }
- IntArray &dependencies = donor.queryDependencies();
- IntArray &dependencyIndexes = donor.queryDependencyIndexes();
- IntArray &dependencyControlIds = donor.queryDependencyControlIds();
- StringArray &dependencyEdgeIds = donor.queryDependencyEdgeIds();
- ForEachItemIn(idx2, dependencies)
- {
- IRoxieServerActivity &dependencySourceActivity = activities.item(dependencies.item(idx2));
- unsigned dependencySourceIndex = dependencyIndexes.item(idx2);
- unsigned dependencyControlId = dependencyControlIds.item(idx2);
- activity.addDependency(dependencySourceActivity, dependencySourceIndex, dependencyControlId);
- if (probeManager)
- probeManager->noteDependency( &dependencySourceActivity, dependencySourceIndex, dependencyControlId, dependencyEdgeIds.item(idx2), &activity);
- }
- }
- ForEachItemIn(idx2, sinks)
- {
- IRoxieServerActivity &sink = sinks.item(idx2);
- sink.connectInputStreams(true);
- }
- }
- void connectInput(unsigned target, unsigned targetIdx, unsigned source, unsigned sourceIdx, unsigned iteration)
- {
- IRoxieServerActivity &targetActivity = activities.item(target);
- IRoxieServerActivity &sourceActivity = activities.item(source);
- IFinalRoxieInput * output = sourceActivity.queryOutput(sourceIdx);
- if (probeManager)
- {
- IRoxieProbe * inputProbe = probeManager->createProbe(static_cast<IInputBase*>(output), &sourceActivity, &targetActivity, sourceIdx, targetIdx, iteration);
- probes.append(*LINK(inputProbe));
- output = &dynamic_cast<IFinalRoxieInput &>(inputProbe->queryInput());
- }
- targetActivity.setInput(targetIdx, sourceIdx, output);
- }
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- ForEachItemIn(idx, activities)
- {
- IRoxieServerActivity *activity = &activities.item(idx);
- if (activity)
- activity->onCreate(_colocalParent);
- }
- }
- virtual void abort()
- {
- ForEachItemIn(idx, sinks)
- {
- IRoxieServerActivity &sink = sinks.item(idx);
- sink.abort();
- }
- }
- virtual void reset()
- {
- ForEachItemIn(idx, sinks)
- {
- IRoxieServerActivity &sink = sinks.item(idx);
- sink.reset();
- }
- }
- Linked<IException> exception;
- CriticalSection eCrit;
- virtual void noteException(IException *E)
- {
- CriticalBlock b(eCrit);
- if (!exception)
- {
- if (graphSlaveContext.queryDebugContext())
- {
- graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateException, NULL, exception);
- }
- exception.set(E);
- }
- }
- virtual void checkAbort()
- {
- CriticalBlock b(eCrit);
- if (exception)
- throw exception.getLink();
- }
- virtual void execute()
- {
- results.setown(new CGraphResults);
- doExecute(0, NULL);
- }
- //New child query code...
- virtual IThorChildGraph * queryChildGraph()
- {
- return this;
- }
- virtual IEclGraphResults * queryLocalGraph()
- {
- return this;
- }
- virtual IRoxieServerChildGraph * queryLoopGraph()
- {
- return this;
- }
- inline unsigned queryId() const
- {
- return id;
- }
- inline unsigned queryLoopCounter() const
- {
- return loopCounter;
- }
- void doExecute(unsigned parentExtractSize, const byte * parentExtract)
- {
- if (sinks.ordinality()==1)
- sinks.item(0).execute(parentExtractSize, parentExtract);
- #ifdef PARALLEL_EXECUTE
- else if (!probeManager && !graphDefinition.isSequential())
- {
- class casyncfor: public CAsyncFor
- {
- public:
- IActivityGraph &parent;
- unsigned parentExtractSize;
- const byte * parentExtract;
- casyncfor(IRoxieServerActivityCopyArray &_sinks, IActivityGraph &_parent, unsigned _parentExtractSize, const byte * _parentExtract) :
- sinks(_sinks), parent(_parent), parentExtractSize(_parentExtractSize), parentExtract(_parentExtract) { }
- void Do(unsigned i)
- {
- try
- {
- sinks.item(i).execute(parentExtractSize, parentExtract);
- }
- catch (IException *E)
- {
- parent.noteException(E);
- throw;
- }
- }
- private:
- IRoxieServerActivityCopyArray &sinks;
- } afor(sinks, *this, parentExtractSize, parentExtract);
- afor.For(sinks.ordinality(), sinks.ordinality());
- }
- #endif
- else
- {
- ForEachItemIn(idx, sinks)
- {
- IRoxieServerActivity &sink = sinks.item(idx);
- sink.execute(parentExtractSize, parentExtract);
- }
- }
- }
- virtual IEclGraphResults *evaluate(unsigned parentExtractSize, const byte * parentExtract)
- {
- CriticalBlock block(evaluateCrit);
- results.setown(new CGraphResults);
- try
- {
- doExecute(parentExtractSize, parentExtract);
- }
- catch (...)
- {
- DBGLOG("Exception thrown in child query - cleaning up");
- reset();
- throw;
- }
- reset();
- return results.getClear();
- }
- //interface IRoxieServerChildGraph
- virtual void beforeExecute()
- {
- results.setown(new CGraphResults);
- }
- virtual IFinalRoxieInput * startOutput(unsigned id, unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- IFinalRoxieInput * ret = selectOutput(id);
- ret->start(parentExtractSize, parentExtract, paused);
- return ret;
- }
- virtual IFinalRoxieInput * selectOutput(unsigned id)
- {
- ForEachItemIn(i, sinks)
- {
- IFinalRoxieInput * ret = sinks.item(i).querySelectOutput(id);
- if (ret)
- return ret;
- }
- throwUnexpected();
- return NULL;
- }
- virtual void setInputResult(unsigned id, IGraphResult * result)
- {
- results->setResult(id, result);
- }
- virtual bool querySetInputResult(unsigned id, unsigned _sourceIdx, IFinalRoxieInput * input)
- {
- ForEachItemIn(i, activities)
- {
- if (activities.item(i).querySetStreamInput(id, _sourceIdx, input))
- return true;
- }
- return false;
- }
- virtual void stopUnusedOutputs()
- {
- //Hmm not sure how to do this...
- }
- virtual void afterExecute()
- {
- ForEachItemIn(i, sinks)
- {
- sinks.item(i).stop();
- }
- if (graphSlaveContext.queryDebugContext())
- {
- graphSlaveContext.queryDebugContext()->checkBreakpoint(DebugStateGraphFinished, NULL, NULL);
- }
- reset();
- }
- virtual IRoxieGraphResults * execute(size32_t parentExtractSize, const byte *parentExtract)
- {
- doExecute(parentExtractSize, parentExtract);
- return LINK(results);
- }
- virtual void getLinkedResult(unsigned & count, byte * * & ret, unsigned id)
- {
- results->getLinkedResult(count, ret, id);
- }
- virtual void getDictionaryResult(unsigned & count, byte * * & ret, unsigned id)
- {
- results->getLinkedResult(count, ret, id);
- }
- virtual const void * getLinkedRowResult(unsigned id)
- {
- return results->getLinkedRowResult(id);
- }
- virtual void setResult(unsigned id, IGraphResult * result)
- {
- results->setResult(id, result);
- }
- virtual IEngineRowStream * createResultIterator(unsigned id)
- {
- return results->createIterator(id);
- }
- virtual void setGraphLoopResult(IGraphResult * result)
- {
- graphLoopResults.appendResult(result);
- }
- virtual IEngineRowStream * createGraphLoopResultIterator(unsigned id)
- {
- try
- {
- return graphLoopResults.createIterator(id);
- }
- catch (IException * e)
- {
- e->Release();
- throw MakeStringException(ROXIE_GRAPH_PROCESSING_ERROR, "Error reading graph result %d before it is calculated", id);
- }
- }
- virtual void clearGraphLoopResults()
- {
- graphLoopResults.clear();
- }
- virtual void executeGraphLoop(size32_t parentExtractSize, const byte *parentExtract)
- {
- doExecute(parentExtractSize, parentExtract);
- }
- virtual void setGraphLoopResult(unsigned id, IGraphResult * result)
- {
- graphLoopResults.setResult(id, result);
- }
- virtual IEngineRowStream * getGraphLoopResult(unsigned id)
- {
- return graphLoopResults.createIterator(id);
- }
- virtual void getProbeResponse(IPropertyTree *query)
- {
- if (probeManager)
- probeManager->getProbeResponse(query);
- }
- virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
- {
- throwUnexpected();
- }
- virtual CGraphIterationInfo *selectGraphLoopOutput()
- {
- return NULL;
- }
- virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
- {
- throwUnexpected();
- }
- virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
- {
- throwUnexpected();
- }
- };
- class CProxyActivityGraph : implements IActivityGraph, implements IThorChildGraph, public CInterface
- {
- public:
- IMPLEMENT_IINTERFACE;
- CProxyActivityGraph(IRoxieSlaveContext *_ctx, const char *_graphName, unsigned _id, ActivityArray &_graphDefinition, const IRoxieContextLogger &_logctx, unsigned _numParallel)
- : ctx(_ctx), graphName(_graphName), id(_id), graphDefinition(_graphDefinition), logctx(_logctx), numParallel(_numParallel)
- {
- }
- virtual void abort() { throwUnexpected(); }
- virtual void reset() { throwUnexpected(); }
- virtual void execute() { throwUnexpected(); }
- virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
- virtual void onCreate(IHThorArg *_colocalArg)
- {
- colocalArg = _colocalArg;
- }
- virtual void noteException(IException *E) { throwUnexpected(); }
- virtual void checkAbort() { throwUnexpected(); }
- virtual IThorChildGraph * queryChildGraph() { return this; }
- virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
- virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
- virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx) { throwUnexpected(); }
- virtual const char *queryName() const { throwUnexpected(); }
- virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
- virtual IEclGraphResults * evaluate(unsigned parentExtractSize, const byte * parentExtract)
- {
- Owned<CActivityGraph> realGraph;
- {
- CriticalBlock b(graphCrit);
- if (stack.length())
- realGraph.setown(&stack.popGet());
- }
- if (!realGraph)
- {
- realGraph.setown(new CActivityGraph(ctx, graphName, id, graphDefinition, NULL, logctx));
- realGraph->createGraph(ctx);
- realGraph->onCreate(colocalArg);
- }
- Owned<IEclGraphResults> results = realGraph->evaluate(parentExtractSize, parentExtract);
- {
- CriticalBlock b(graphCrit);
- stack.append(*realGraph.getClear());
- }
- return results.getClear();
- }
- protected:
- IRoxieSlaveContext *ctx;
- StringAttr graphName;
- unsigned id;
- ActivityArray &graphDefinition;
- const IRoxieContextLogger &logctx;
- unsigned numParallel;
- IHThorArg *colocalArg = nullptr;
- CriticalSection graphCrit;
- CIArrayOf<CActivityGraph> stack;
- };
- class CIterationActivityGraph : public CActivityGraph
- {
- IHThorArg * colocalParent;
- unsigned fixedParentExtractSize;
- const byte * fixedParentExtract;
- unsigned graphOutputActivityIndex;
- public:
- CIterationActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager,
- unsigned _loopCounter, IRoxieSlaveContext *_ctx, IHThorArg * _colocalParent, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &_logctx)
- : CActivityGraph(_ctx, _graphName, _id, x, _probeManager, _logctx)
- {
- graphOutputActivityIndex = 0;
- loopCounter = _loopCounter;
- colocalParent = _colocalParent;
- graphSlaveContext.setLoopCounter(loopCounter);
- graphCodeContext.set(_ctx->queryCodeContext());
- fixedParentExtractSize = parentExtractSize;
- fixedParentExtract = parentExtract;
- }
- void createIterationGraph(IRoxieSlaveContext *_ctx)
- {
- Owned<IRoxieServerActivity> pseudoActivity = new CPseudoActivity(_ctx, *new CPseudoArg);
- ForEachItemIn(idx1, graphDefinition)
- activities.append(*LINK(pseudoActivity));
- graphOutputActivityIndex = queryGraphOutputIndex();
- recursiveCreateGraph(_ctx, graphOutputActivityIndex);
- }
- unsigned queryGraphOutputIndex() const
- {
- ForEachItemIn(i, graphDefinition)
- if (graphDefinition.serverItem(i).getKind() == TAKgraphloopresultwrite)
- return i;
- throwUnexpected();
- }
- void recursiveCreateGraph(IRoxieSlaveContext *_ctx, unsigned whichActivity)
- {
- //Check to see if already created
- IRoxieServerActivity & prevActivity = activities.item(whichActivity);
- if (prevActivity.queryId() != 0)
- {
- prevActivity.noteOutputUsed(); //We need to patch up the number of outputs for splitters.
- return;
- }
- IRoxieServerActivityFactory &donor = graphDefinition.serverItem(whichActivity);
- IRoxieServerActivity * activity = NULL;
- if (donor.isGraphInvariant())
- {
- ThorActivityKind kind = donor.getKind();
- switch (kind)
- {
- case TAKif:
- case TAKchildif:
- case TAKcase:
- case TAKchildcase: // MORE RKC->GH - what about FILTER with a graph-invariant condition and other latestart activities?
- {
- Owned<IHThorArg> helper = &donor.getHelper();
- helper->onCreate(&graphCodeContext, colocalParent, NULL);
- helper->onStart(fixedParentExtract, NULL);
- unsigned branch;
- switch (kind)
- {
- case TAKif: case TAKchildif:
- branch = static_cast<IHThorIfArg *>(helper.get())->getCondition() ? 0 : 1;
- break;
- case TAKcase: case TAKchildcase:
- branch = static_cast<IHThorCaseArg *>(helper.get())->getBranch();
- if (branch >= donor.numInputs())
- branch = donor.numInputs() - 1;
- break;
- default:
- throwUnexpected();
- }
- helper.clear();
- unsigned outputidx;
- unsigned source = donor.getInput(branch, outputidx);
- if (source ==(unsigned) -1)
- activity = createRoxieServerNullActivity(&graphSlaveContext, &donor, probeManager);
- else
- activity = createRoxieServerPassThroughActivity(&graphSlaveContext, &donor, probeManager);
- activities.replace(*activity, whichActivity);
- activity->onCreate(colocalParent);
- if (source ==(unsigned) -1)
- return;
- recursiveCreateGraph(_ctx, source);
- connectInput(whichActivity, 0, source, outputidx, loopCounter);
- break;
- }
- }
- }
- if (!activity)
- {
- activity = donor.createActivity(&graphSlaveContext, probeManager);
- activities.replace(*activity, whichActivity);
- activity->onCreate(colocalParent);
- activity->resetOutputsUsed();
- unsigned inputidx = 0;
- loop
- {
- unsigned outputidx;
- unsigned source = donor.getInput(inputidx, outputidx);
- if (source==(unsigned) -1)
- break;
- recursiveCreateGraph(_ctx, source);
- connectInput(whichActivity, inputidx, source, outputidx, loopCounter);
- inputidx++;
- }
- }
- IntArray &dependencies = donor.queryDependencies();
- IntArray &dependencyIndexes = donor.queryDependencyIndexes();
- IntArray &dependencyControlIds = donor.queryDependencyControlIds();
- ForEachItemIn(idx2, dependencies)
- {
- unsigned input = dependencies.item(idx2);
- recursiveCreateGraph(_ctx, input);
- activity->addDependency(activities.item(input),dependencyIndexes.item(idx2),dependencyControlIds.item(idx2));
- }
- }
- virtual CGraphIterationInfo *selectGraphLoopOutput()
- {
- IRoxieServerActivity &sourceActivity = activities.item(graphOutputActivityIndex);
- IFinalRoxieInput *sourceInput = sourceActivity.queryOutput(0);
- return new CGraphIterationInfo(&sourceActivity, sourceInput, 0, loopCounter);
- }
- virtual void gatherIterationUsage(IRoxieServerLoopResultProcessor & processor)
- {
- ForEachItemIn(i, activities)
- activities.item(i).gatherIterationUsage(processor, fixedParentExtractSize, fixedParentExtract);
- }
- virtual void associateIterationOutputs(IRoxieServerLoopResultProcessor & processor)
- {
- ForEachItemIn(i, activities)
- activities.item(i).associateIterationOutputs(processor, fixedParentExtractSize, fixedParentExtract, probeManager, probes);
- }
- };
- class CDelayedActivityGraph : implements IActivityGraph, public CInterface
- {
- StringAttr graphName;
- ActivityArray & graphDefinition;
- IProbeManager *probeManager;
- unsigned id;
- IRoxieSlaveContext * ctx;
- IHThorArg * colocalParent;
- public:
- IMPLEMENT_IINTERFACE;
- CDelayedActivityGraph(const char *_graphName, unsigned _id, ActivityArray &x, IProbeManager *_probeManager)
- : probeManager(_probeManager), graphDefinition(x)
- {
- graphName.set(_graphName);
- id = _id;
- ctx = NULL;
- colocalParent = NULL;
- }
- virtual const char *queryName() const { return graphName.get(); }
- virtual void abort() { throwUnexpected(); }
- virtual void reset() { }
- virtual void execute() { throwUnexpected(); }
- virtual void getProbeResponse(IPropertyTree *query) { throwUnexpected(); }
- virtual void noteException(IException *E) { throwUnexpected(); }
- virtual void checkAbort() { throwUnexpected(); }
- virtual IThorChildGraph * queryChildGraph() { throwUnexpected(); }
- virtual IEclGraphResults * queryLocalGraph() { throwUnexpected(); }
- virtual IRoxieServerChildGraph * queryLoopGraph() { throwUnexpected(); }
- virtual IRoxieServerActivity *queryActivity(unsigned _activityId) { return nullptr; } // MORE - may need something here!?
- virtual void onCreate(IHThorArg *_colocalParent)
- {
- colocalParent = _colocalParent;
- }
- virtual IRoxieServerChildGraph * createGraphLoopInstance(IRoxieSlaveContext *ctx, unsigned loopCounter, unsigned parentExtractSize, const byte * parentExtract, const IRoxieContextLogger &logctx)
- {
- Owned<CIterationActivityGraph> ret = new CIterationActivityGraph(graphName, id, graphDefinition, probeManager, loopCounter, ctx, colocalParent, parentExtractSize, parentExtract, logctx);
- ret->createIterationGraph(ctx);
- return ret.getClear();
- }
- };
- IActivityGraph *createActivityGraph(IRoxieSlaveContext *ctx, const char *_graphName, unsigned id, ActivityArray &childFactories, IRoxieServerActivity *parentActivity, IProbeManager *_probeManager, const IRoxieContextLogger &_logctx, unsigned numParallel)
- {
- if (childFactories.isDelayed())
- {
- assertex(numParallel==1);
- return new CDelayedActivityGraph(_graphName, id, childFactories, _probeManager);
- }
- else
- {
- if (numParallel==1 || _probeManager != nullptr)
- {
- Owned<IProbeManager> childProbe;
- if (_probeManager)
- childProbe.setown(_probeManager->startChildGraph(id, parentActivity));
- Owned<CActivityGraph> ret = new CActivityGraph(ctx, _graphName, id, childFactories, childProbe, _logctx);
- ret->createGraph(ctx);
- if (_probeManager)
- _probeManager->endChildGraph(childProbe, parentActivity);
- return ret.getClear();
- }
- else
- return new CProxyActivityGraph(ctx, _graphName, id, childFactories, _logctx, numParallel);
- }
- }
- //================================================================================================================
- #ifdef _USE_CPPUNIT
- #include "unittests.hpp"
- // 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...
- #if _MSC_VER==1200
- #undef protected
- #endif
- static const char *sortAlgorithm;
- class TestMetaData : public CInterface, implements IOutputMetaData
- {
- public:
- IMPLEMENT_IINTERFACE;
- virtual size32_t getRecordSize(const void *) { return 10; }
- virtual size32_t getMinRecordSize() const { return 10; }
- virtual size32_t getFixedSize() const { return 10; }
- virtual void toXML(const byte * self, IXmlWriter & out) {}
- virtual unsigned getVersion() const { return OUTPUTMETADATA_VERSION; }
- virtual unsigned getMetaFlags() { return 0; }
- virtual void destruct(byte * self) {}
- virtual IOutputRowSerializer * createDiskSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputRowDeserializer * createDiskDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual ISourceRowPrefetcher * createDiskPrefetcher(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputMetaData * querySerializedDiskMeta() { return NULL; }
- virtual IOutputRowSerializer * createInternalSerializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual IOutputRowDeserializer * createInternalDeserializer(ICodeContext * ctx, unsigned activityId) { return NULL; }
- virtual void walkIndirectMembers(const byte * self, IIndirectMemberVisitor & visitor) {}
- virtual IOutputMetaData * queryChildMeta(unsigned i) { return NULL; }
- } testMeta;
- class TestInput : public CInterface, implements IFinalRoxieInput, implements IEngineRowStream
- {
- char const * const *input;
- IRoxieSlaveContext *ctx;
- unsigned endSeen;
- bool eof;
- unsigned count;
- ActivityTimeAccumulator totalCycles;
- size32_t recordSize;
- unsigned activityId;
- public:
- enum { STATEreset, STATEstarted, STATEstopped } state;
- bool allRead;
- unsigned repeat;
- IMPLEMENT_IINTERFACE;
- TestInput(IRoxieSlaveContext *_ctx, char const * const *_input)
- {
- ctx = _ctx;
- input = _input;
- count = 0;
- eof = false;
- allRead = false;
- endSeen = 0;
- recordSize = testMeta.getFixedSize();
- state = STATEreset;
- activityId = 1;
- repeat = 0;
- }
- virtual IOutputMetaData * queryOutputMeta() const { return &testMeta; }
- virtual void prestart(unsigned parentExtractSize, const byte *parentExtract)
- {
- ASSERT(state == STATEreset);
- }
- virtual void start(unsigned parentExtractSize, const byte *parentExtract, bool paused)
- {
- ASSERT(state == STATEreset);
- state = STATEstarted;
- }
- virtual IStrandJunction *getOutputStreams(IRoxieSlaveContext *ctx, unsigned idx, PointerArrayOf<IEngineRowStream> &streams, const StrandOptions * consumerOptions, bool consumerOrdered, IOrderedCallbackCollection * orderedCallbacks)
- {
- streams.append(this);
- return NULL;
- }
- virtual IEngineRowStream *queryConcreteOutputStream(unsigned whichInput) { assertex(whichInput==0); return this; }
- virtual IStrandJunction *queryConcreteOutputJunction(unsigned idx) const { assertex(idx==0); return nullptr; }
- virtual IRoxieServerActivity *queryActivity()
- {
- throwUnexpected();
- }
- virtual IIndexReadActivityInfo *queryIndexReadActivity()
- {
- throwUnexpected();
- }
- virtual void stop()
- {
- state = STATEstopped;
- }
- virtual void reset()
- {
- ASSERT(state == STATEstopped);
- eof = false; count = 0; endSeen = 0; allRead = false; state = STATEreset;
- }
- virtual void resetEOF()
- {
- throwUnexpected();
- }
- virtual void checkAbort() {}
- virtual unsigned queryId() const { return activityId; };
- virtual const void *nextRow()
- {
- ActivityTimer t(totalCycles, ctx->queryOptions().timeActivities);
- ASSERT(state == STATEstarted);
- ASSERT(allRead || !eof);
- if (eof)
- return NULL;
- again:
- const char *nextSource = input[count++];
- if (nextSource)
- {
- endSeen = 0;
- void *ret = ctx->queryRowManager().ALLOCATE(recordSize);
- memset(ret, 0, recordSize);
- strncpy((char *) ret, nextSource, recordSize);
- return ret;
- }
- else if (repeat)
- {
- repeat--;
- count = 0;
- goto again;
- }
- else
- {
- endSeen++;
- if (endSeen==2)
- eof = true;
- return NULL;
- }
- }
- virtual bool nextGroup(ConstPointerArray & group)
- {
- const void * next;
- while ((next = nextRow()) != NULL)
- group.append(next);
- if (group.ordinality())
- return true;
- return false;
- }
- virtual unsigned __int64 queryTotalCycles() const { return totalCycles.totalCycles; }
- virtual unsigned __int64 queryLocalCycles() const { return totalCycles.totalCycles; }
- virtual IFinalRoxieInput *queryInput(unsigned idx) const
- {
- return NULL;
- }
- };
- struct SortActivityTest : public ccdserver_hqlhelper::CThorSortArg {
- public:
- struct CompareClass : public ICompare {
- virtual int docompare(const void * _left, const void * _right) const {
- return memcmp(_left, _right, 5);
- }
- } compare;
- virtual ICompare * queryCompare() { return &compare; }
- virtual IOutputMetaData * queryOutputMeta()
- {
- return &testMeta;
- }
- virtual unsigned getAlgorithmFlags() { return TAFunstable; }
- virtual const char * getAlgorithm() { return sortAlgorithm; }
- };
- extern "C" IHThorArg * sortActivityTestFactory() { return new SortActivityTest; }
- struct MergeActivityTest : public ccdserver_hqlhelper::CThorMergeArg {
- static bool isDedup;
- public:
- struct CompareClass : public ICompare {
- virtual int docompare(const void * _left, const void * _right) const {
- return memcmp(_left, _right, 5);
- }
- } compare;
- virtual ICompare * queryCompare() { return &compare; }
- virtual IOutputMetaData * queryOutputMeta()
- {
- return &testMeta;
- }
- virtual bool dedup() { return isDedup; }
- };
- bool MergeActivityTest::isDedup = false;
- extern "C" IHThorArg * mergeActivityTestFactory() { return new MergeActivityTest; }
- struct SplitActivityTest : public ccdserver_hqlhelper::CThorSplitArg {
- public:
- virtual unsigned numBranches() { return 2; }
- virtual IOutputMetaData * queryOutputMeta()
- {
- return &testMeta;
- }
- };
- extern "C" IHThorArg * splitActivityTestFactory() { return new SplitActivityTest; }
- class CcdServerTest : public CppUnit::TestFixture
- {
- CPPUNIT_TEST_SUITE(CcdServerTest);
- CPPUNIT_TEST(testSetup);
- CPPUNIT_TEST(testHeapSort);
- CPPUNIT_TEST(testQuickSort);
- CPPUNIT_TEST(testMerge);
- CPPUNIT_TEST(testMergeDedup);
- CPPUNIT_TEST(testMiscellaneous);
- CPPUNIT_TEST(testSplitter);
- CPPUNIT_TEST(testCleanup);
- CPPUNIT_TEST_SUITE_END();
- protected:
- SlaveContextLogger logctx;
- Owned<const IQueryDll> queryDll;
- Owned<IRoxiePackage> package;
- Owned<IPropertyTree> stateInfo;
- Owned<IQueryFactory> queryFactory;
- Owned<IRoxieSlaveContext> ctx;
- void testSetup()
- {
- selfTestMode = true;
- roxiemem::setTotalMemoryLimit(false, true, false, 100 * 1024 * 1024, 0, NULL, NULL);
- }
- void testCleanup()
- {
- roxiemem::releaseRoxieHeap();
- }
- void init()
- {
- package.setown(createRoxiePackage(NULL, NULL));
- queryDll.setown(createExeQueryDll("roxie"));
- stateInfo.setown(createPTreeFromXMLString("<test memoryLimit='50000000'/>"));
- queryFactory.setown(createServerQueryFactory("test", queryDll.getLink(), *package, stateInfo, false, false));
- ctx.setown(createSlaveContext(queryFactory, logctx, NULL, false));
- queryActiveTimer()->reset();
- }
- void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *output)
- {
- testActivity(activity, input, NULL, output);
- }
- void testActivity(IRoxieServerActivity *activity, char const * const *input, char const * const *input2, char const * const *output, unsigned outputIdx = 0)
- {
- TestInput in(ctx, input);
- TestInput in2(ctx, input2);
- activity->setInput(0, 0, &in);
- if (input2)
- activity->setInput(1, 0, &in2);
- IFinalRoxieInput *out = activity->queryOutput(outputIdx);
- IEngineRowStream *outStream = connectSingleStream(ctx, out, outputIdx, true);
- IOutputMetaData *meta = out->queryOutputMeta();
- void *buf = alloca(meta->getFixedSize());
- for (unsigned iteration = 0; iteration < 8; iteration++)
- {
- // 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)
- // This should be true whether we read all, some, or none of the data.
- // Should not matter if an activity is not started
- if (iteration % 4 == 0)
- activity->onCreate(NULL);
- unsigned count = 0;
- if (iteration % 4 != 3)
- {
- activity->start(0, NULL, false);
- ASSERT(in.state == TestInput::STATEstarted);
- ASSERT(!input2 || in2.state == TestInput::STATEstarted);
- loop
- {
- const void *next = outStream->nextRow();
- if (!next)
- {
- ASSERT(output[count++] == NULL);
- next = outStream->nextRow();
- if (!next)
- {
- ASSERT(output[count++] == NULL);
- break;
- }
- }
- ASSERT(output[count] != NULL);
- unsigned outsize = meta->getRecordSize(next);
- memset(buf, 0, outsize);
- strncpy((char *) buf, output[count++], outsize);
- ASSERT(memcmp(next, buf, outsize) == 0);
- ReleaseRoxieRow(next);
- if (iteration % 4 == 2)
- break;
- }
- if (iteration % 4 != 2)
- {
- // Check that reading after end is harmless
- in.allRead = true;
- const void *next = outStream->nextRow();
- ASSERT(next == NULL);
- }
- }
- activity->stop();
- ASSERT(in.state == TestInput::STATEstopped);
- ASSERT(!input2 || in2.state == TestInput::STATEstopped);
- activity->reset();
- ASSERT(in.state == TestInput::STATEreset);
- ASSERT(!input2 || in2.state == TestInput::STATEreset);
- ctx->queryRowManager().reportLeaks();
- ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
- }
- }
- void testSplitActivity(IRoxieServerActivityFactory *factory, char const * const *input, char const * const *output, unsigned numOutputs, unsigned repeat)
- {
- Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
- TestInput in(ctx, input);
- in.repeat = repeat;
- activity->setInput(0, 0, &in);
- ArrayOf<IFinalRoxieInput *> out;
- for (unsigned i = 0; i < numOutputs; i++)
- {
- out.append(activity->queryOutput(i));
- }
- activity->onCreate(NULL);
- class casyncfor: public CAsyncFor
- {
- public:
- casyncfor(CcdServerTest *_parent, IRoxieServerActivity *_activity, ArrayOf<IFinalRoxieInput *> &_outputs, char const * const *_input, char const * const *_output, unsigned _repeat)
- : parent(_parent), activity(_activity), outputs(_outputs), input(_input), output(_output), repeat(_repeat)
- {}
- void Do(unsigned i)
- {
- IFinalRoxieInput *out = outputs.item(i);
- IEngineRowStream *outStream = connectSingleStream(NULL, out, 0, true);
- out->start(0, NULL, false);
- IOutputMetaData *meta = out->queryOutputMeta();
- void *buf = alloca(meta->getFixedSize());
- unsigned count = 0;
- unsigned repeats = repeat;
- loop
- {
- const void *next = outStream->nextRow();
- if (!next)
- {
- ASSERT(repeats==0);
- ASSERT(output[count] == NULL);
- count++;
- next = outStream->nextRow();
- if (!next)
- {
- ASSERT(output[count] == NULL);
- count++;
- break;
- }
- }
- if (output[count] == NULL && repeats)
- {
- repeats--;
- count = 0;
- }
- ASSERT(output[count] != NULL);
- unsigned outsize = meta->getRecordSize(next);
- memset(buf, 0, outsize);
- strncpy((char *) buf, output[count++], outsize);
- ASSERT(memcmp(next, buf, outsize) == 0);
- ReleaseRoxieRow(next);
- }
- outStream->stop();
- }
- private:
- IRoxieServerActivity *activity;
- ArrayOf<IFinalRoxieInput *> &outputs;
- char const * const *input;
- char const * const *output;
- unsigned repeat;
- CcdServerTest *parent;
- } afor(this, activity, out, input, output, repeat);
- afor.For(numOutputs, numOutputs);
- ASSERT(in.state == TestInput::STATEstopped);
- for (unsigned i2 = 0; i2 < numOutputs; i2++)
- {
- out.item(i2)->reset();
- }
- ASSERT(in.state == TestInput::STATEreset);
- ctx->queryRowManager().reportLeaks();
- ASSERT(ctx->queryRowManager().numPagesAfterCleanup(true) == 0);
- }
- static int compareFunc(const void *l, const void *r)
- {
- return strcmp(*(char **) l, *(char **) r);
- }
- void testSort(unsigned type)
- {
- init();
- sortAlgorithm = NULL;
- if (type==2)
- sortAlgorithm = "heapSort";
- else
- sortAlgorithm = "quickSort";
- DBGLOG("Testing %s activity", sortAlgorithm);
- Owned<IPropertyTree> dummyNode = createPTree("node");
- Owned <IRoxieServerActivityFactory> factory = createRoxieServerSortActivityFactory(1, 1, *queryFactory, sortActivityTestFactory, TAKsort, *dummyNode);
- Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
- const char * test[] = { NULL, NULL };
- const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
- const char * test54321[] = { "5", "4", "3", "2", "1", NULL, NULL };
- const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
- const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
- const char * test11111_54321[] = { "1", "1", "1", "1", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
- const char * test54321_54321[] = { "5", "4", "3", "2", "1", NULL, "5", "4", "3", "2", "1", NULL, NULL };
- const char * test12345_12345[] = { "1", "2", "3", "4", "5", NULL, "1", "2", "3", "4", "5", NULL, NULL };
- testActivity(activity, test, test);
- testActivity(activity, test12345, test12345);
- testActivity(activity, test54321, test12345);
- testActivity(activity, test11111, test11111);
- testActivity(activity, test11111_12345, test11111_12345);
- testActivity(activity, test11111_54321, test11111_12345);
- testActivity(activity, test54321_54321, test12345_12345);
- // A few larger tests
- char *input[2002];
- char *output[2002];
- input[2000] = input[2001] = output[2000] = output[2001] = NULL;
- unsigned i;
- // identical
- for (i=0; i<2000; i++)
- {
- input[i] = new char[11];
- output[i] = new char[11];
- sprintf(input[i], "1");
- sprintf(output[i], "1");
- }
- testActivity(activity, input, output);
- // Ascending
- for (i=0; i<2000; i++)
- {
- sprintf(input[i], "%04d", i);
- sprintf(output[i], "%04d", i);
- }
- testActivity(activity, input, output);
- // Almost sorted
- for (i=0; i<20; i++)
- {
- unsigned h = i*100;
- sprintf(input[h], "%04d", 1900-h);
- }
- testActivity(activity, input, output);
- // Descending
- for (i=0; i<2000; i++)
- {
- sprintf(input[i], "%04d", 1999-i);
- sprintf(output[i], "%04d", i);
- }
- testActivity(activity, input, output);
- // Random
- for (i=0; i<2000; i++)
- {
- unsigned r = rand() % 1500;
- sprintf(input[i], "%04d", r);
- sprintf(output[i], "%04d", r);
- }
- qsort(output, 2000, sizeof(output[0]), compareFunc);
- testActivity(activity, input, output);
- unsigned __int64 us = cycle_to_nanosec(factory->queryLocalCycles()/1000);
- DBGLOG("Simple %s sorts: activity time %u.%u ms", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"), (int)(us/1000), (int)(us%1000));
- factory->resetNodeProgressInfo();
- if (type)
- {
- // Other than quicksort, it's supposed to be stable. Let's check that it is
- // All sort identical
- for (i=0; i<2000; i++)
- {
- sprintf(input[i], "1 %d", i);
- sprintf(output[i], "1 %d", i);
- }
- testActivity(activity, input, output);
- // Already sorted
- for (i=0; i<2000; i++)
- {
- sprintf(input[i], "%04d %d", i / 10, i);
- sprintf(output[i], "%04d %d", i / 10, i);
- }
- testActivity(activity, input, output);
- // Reverse order
- for (i=0; i<2000; i++)
- {
- sprintf(input[i], "%04d %d", 199 - (i / 10), i%10);
- sprintf(output[i], "%04d %d", i / 10, i%10);
- }
- testActivity(activity, input, output);
- }
- for (i=0; i<2000; i++)
- {
- delete [] input[i];
- delete [] output[i];
- }
- DBGLOG("Finished testing %s sort", type==2?"Heap" : (type==1 ? "Insertion" : "Quick"));
- }
- void testQuickSort()
- {
- testSort(0);
- }
- void testHeapSort()
- {
- testSort(2);
- }
- void testMerge()
- {
- DBGLOG("testMerge");
- init();
- Owned<IPropertyTree> splitterNode = createPTree();
- Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
- factory->setInput(0,0,0);
- factory->setInput(1,0,0);
- Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
- const char * test[] = { NULL, NULL };
- const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
- const char * test1122334455[] = { "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", NULL, NULL };
- const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
- const char * test1111111111[] = { "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", NULL, NULL };
- const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
- const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
- 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 };
-
- testActivity(activity, test, test, test);
- testActivity(activity, test12345, test, test12345);
- testActivity(activity, test, test12345, test12345);
- testActivity(activity, test12345, test12345, test1122334455);
- testActivity(activity, test11111, test, test11111);
- testActivity(activity, test, test11111, test11111);
- testActivity(activity, test11111, test11111, test1111111111);
- testActivity(activity, test11111_12345, test, test1111112345);
- testActivity(activity, test11111_12345, test11111_12345, test11111111111122334455);
- // Should really test WHICH side gets kept...
- // Should test with more than 2 inputs...
- DBGLOG("testMerge done");
- }
- void testMergeDedup()
- {
- DBGLOG("testMergeDedup");
- init();
- MergeActivityTest::isDedup = true;
- Owned<IPropertyTree> splitterNode = createPTree();
- Owned <IRoxieServerActivityFactory> factory = createRoxieServerMergeActivityFactory(1, 1, *queryFactory, mergeActivityTestFactory, TAKmerge, *splitterNode);
- factory->setInput(0,0,0);
- factory->setInput(1,0,0);
- Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
- const char * test[] = { NULL, NULL };
- const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
- const char * test11111[] = { "1", "1", "1", "1", "1", NULL, NULL };
- const char * test11111_12345[] = { "1", "1", "1", "1", "1", NULL, "1", "2", "3", "4", "5", NULL, NULL };
- const char * test1111112345[] = { "1", "1", "1", "1", "1", "1", "2", "3", "4", "5", NULL, NULL };
-
- testActivity(activity, test11111, test, test11111); // No dedup within a stream
- testActivity(activity, test11111, test11111, test11111); // No dedup within a stream
- testActivity(activity, test, test11111, test11111);
- testActivity(activity, test, test, test);
- testActivity(activity, test12345, test, test12345);
- testActivity(activity, test, test12345, test12345);
- testActivity(activity, test12345, test12345, test12345);
- testActivity(activity, test11111_12345, test, test1111112345);
- testActivity(activity, test11111_12345, test11111_12345, test1111112345);
- // Should really test WHICH side gets kept...
- // Should test with more than 2 inputs...
- DBGLOG("testMergeDedup done");
- }
- void doTestSplitter(unsigned numOutputs)
- {
- DBGLOG("testSplit %d", numOutputs);
- init();
- Owned<IPropertyTree> splitterNode = createPTree();
- Owned <IRoxieServerActivityFactory> factory = createRoxieServerThroughSpillActivityFactory(*queryFactory, splitActivityTestFactory, numOutputs, *splitterNode);
- factory->setInput(0,0,0);
- Owned <IRoxieServerActivity> activity = factory->createActivity(ctx, NULL);
- const char * test[] = { NULL, NULL };
- const char * test12345[] = { "1", "2", "3", "4", "5", NULL, NULL };
- unsigned start = msTick();
- testSplitActivity(factory, test, test, numOutputs, 0);
- testSplitActivity(factory, test12345, test12345, numOutputs, 0);
- testSplitActivity(factory, test12345, test12345, numOutputs, 100);
- unsigned elapsed = msTick() - start;
- DBGLOG("testSplit %d done in %dms", numOutputs, elapsed);
- }
- void testSplitter()
- {
- doTestSplitter(1);
- doTestSplitter(2);
- doTestSplitter(3);
- doTestSplitter(10);
- }
- void testMiscellaneous()
- {
- DBGLOG("sizeof(CriticalSection)=%u", (unsigned) sizeof(CriticalSection));
- DBGLOG("sizeof(SpinLock)=%u", (unsigned) sizeof(SpinLock));
- DBGLOG("sizeof(CJoinGroup)=%u", (unsigned) sizeof(CJoinGroup));
- ASSERT(sizeof(CJoinGroup) <= 120);
- }
- };
- CPPUNIT_TEST_SUITE_REGISTRATION( CcdServerTest );
- CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( CcdServerTest, "CcdServerTest" );
- #endif
|