workunit.cpp 468 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include <string>
  14. #include <unordered_set>
  15. #include "jlib.hpp"
  16. #include "workunit.hpp"
  17. #include "jprop.hpp"
  18. #include "jmisc.hpp"
  19. #include "jexcept.hpp"
  20. #include "jiter.ipp"
  21. #include "jptree.hpp"
  22. #include "jtime.ipp"
  23. #include "jencrypt.hpp"
  24. #include "junicode.hpp"
  25. #include "jlzw.hpp"
  26. #include "jregexp.hpp"
  27. #include "eclrtl.hpp"
  28. #include "deftype.hpp"
  29. #include <time.h>
  30. #include "mpbase.hpp"
  31. #include "daclient.hpp"
  32. #include "dadfs.hpp"
  33. #include "dafdesc.hpp"
  34. #include "dasds.hpp"
  35. #include "danqs.hpp"
  36. #include "dautils.hpp"
  37. #include "dllserver.hpp"
  38. #include "thorplugin.hpp"
  39. #include "thorhelper.hpp"
  40. #include "workflow.hpp"
  41. #include "nbcd.hpp"
  42. #include "seclib.hpp"
  43. #include "wuerror.hpp"
  44. #include "wujobq.hpp"
  45. #ifndef _CONTAINERIZED
  46. #include "environment.hpp"
  47. #endif
  48. #include "daqueue.hpp"
  49. #include "workunit.ipp"
  50. #include "digisign.hpp"
  51. #include <list>
  52. #include <string>
  53. #include <algorithm>
  54. using namespace cryptohelper;
  55. static int workUnitTraceLevel = 1;
  56. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  57. {
  58. // MORE - can fold in the date
  59. return wuRoot.append("/WorkUnits/").append(wuid);
  60. }
  61. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  62. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  63. {
  64. #ifdef _WIN32
  65. suffix.append("W");
  66. #else
  67. suffix.append("L");
  68. #endif
  69. #ifdef __64BIT__
  70. suffix.append("64");
  71. #else
  72. suffix.append("32");
  73. #endif
  74. return suffix;
  75. }
  76. typedef MapStringTo<bool> UniqueScopes;
  77. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  78. {
  79. StringBuffer err;
  80. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  81. if (wuid)
  82. err.append(" workunit:").append(wuid);
  83. if (wuscope)
  84. err.append(" scope:").append(wuscope);
  85. //MORE - we would need more information passed in from outside if we want to make the audit message format the same as from higher level ESP calls
  86. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  87. if (log)
  88. LOG(MCuserError, "%s", err.str());
  89. if (excpt)
  90. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  91. }
  92. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  93. {
  94. if (!secmgr || !secuser)
  95. return true;
  96. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  97. if (!ret && (log || excpt))
  98. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  99. return ret;
  100. }
  101. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  102. {
  103. if (!scopes)
  104. return true;
  105. bool ret=true;
  106. if (wuscope)
  107. {
  108. Owned<ISecResource> res=scopes->getResource(wuscope);
  109. if (!res || res->getAccessFlags()<required)
  110. ret=false;
  111. }
  112. else
  113. {
  114. for (int seq=0; ret && seq<scopes->count(); seq++)
  115. {
  116. ISecResource *res=scopes->queryResource(seq);
  117. if (res && res->getAccessFlags()<required)
  118. return false;
  119. }
  120. }
  121. if (!ret && (log || excpt))
  122. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  123. return ret;
  124. }
  125. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  126. {
  127. if (!secmgr || !secuser)
  128. return true;
  129. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  130. if (!ret && (log || excpt))
  131. {
  132. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  133. }
  134. return ret;
  135. }
  136. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  137. {
  138. if (!secmgr || !secuser)
  139. return true;
  140. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  141. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  142. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw->queryWuScope())>=required;
  143. if (!ret && (log || excpt))
  144. {
  145. wuAccessError(secuser->getName(), action, cw->queryWuScope(), cw->queryWuid(), excpt, log);
  146. }
  147. return ret;
  148. }
  149. void doDescheduleWorkkunit(char const * wuid)
  150. {
  151. StringBuffer xpath;
  152. xpath.append("*/*/*/");
  153. ncnameEscape(wuid, xpath);
  154. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  155. if(!conn) return;
  156. Owned<IPropertyTree> root = conn->getRoot();
  157. bool more;
  158. do more = root->removeProp(xpath.str()); while(more);
  159. }
  160. //======================================================
  161. /*
  162. * Graph progress support
  163. */
  164. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, unsigned wfid, const char * _rootScope, unsigned _id)
  165. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  166. {
  167. StatsScopeId graphScopeId;
  168. verifyex(graphScopeId.setScopeText(_rootScope));
  169. StatsScopeId rootScopeId(SSTworkflow,wfid);
  170. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  171. collector->beginScope(graphScopeId);
  172. }
  173. void CWuGraphStats::beforeDispose()
  174. {
  175. Owned<IStatisticCollection> stats = collector->getResult();
  176. MemoryBuffer compressed;
  177. {
  178. MemoryBuffer serialized;
  179. serializeStatisticCollection(serialized, stats);
  180. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  181. }
  182. unsigned minActivity = 0;
  183. unsigned maxActivity = 0;
  184. stats->getMinMaxActivity(minActivity, maxActivity);
  185. StringBuffer tag;
  186. tag.append("sg").append(id);
  187. //Replace the particular subgraph statistics added by this creator
  188. IPropertyTree * subgraph = progress->setPropTree(tag);
  189. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  190. subgraph->setProp("@creator", creator);
  191. subgraph->setPropInt("@minActivity", minActivity);
  192. subgraph->setPropInt("@maxActivity", maxActivity);
  193. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  194. if (!progress->getPropBool("@stats", false))
  195. progress->setPropBool("@stats", true);
  196. }
  197. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  198. {
  199. return *collector;
  200. }
  201. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  202. {
  203. public:
  204. IMPLEMENT_IINTERFACE;
  205. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  206. {
  207. if (!progress)
  208. progress.setown(createPTree());
  209. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  210. }
  211. virtual IPropertyTree * getProgressTree()
  212. {
  213. if (progress->getPropBool("@stats"))
  214. return createProcessTreeFromStats(); // Should we cache that?
  215. return LINK(progress);
  216. }
  217. virtual unsigned queryFormatVersion()
  218. {
  219. return formatVersion;
  220. }
  221. protected:
  222. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  223. {
  224. formatVersion = PROGRESS_FORMAT_V;
  225. }
  226. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  227. {
  228. StringBuffer formattedValue;
  229. unsigned numStats = collection.getNumStatistics();
  230. for (unsigned i=0; i < numStats; i++)
  231. {
  232. StatisticKind kind;
  233. unsigned __int64 value;
  234. collection.getStatistic(kind, value, i);
  235. formatStatistic(formattedValue.clear(), value, kind);
  236. target->setProp(queryTreeTag(kind), formattedValue);
  237. }
  238. }
  239. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  240. {
  241. expandStats(target, *collection);
  242. StringBuffer scopeName;
  243. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL, false);
  244. ForEach(*activityIter)
  245. {
  246. IStatisticCollection & cur = activityIter->query();
  247. cur.getScope(scopeName.clear());
  248. const char * id = scopeName.str();
  249. const char * tag;
  250. IPropertyTree * curTarget = target;
  251. switch (cur.queryScopeType())
  252. {
  253. case SSTedge:
  254. tag = "edge";
  255. id += strlen(EdgeScopePrefix);
  256. break;
  257. case SSTactivity:
  258. tag = "node";
  259. id += strlen(ActivityScopePrefix);
  260. break;
  261. case SSTsubgraph:
  262. //All subgraphs are added a root elements in the progress tree
  263. curTarget = rootTarget;
  264. tag = "node";
  265. id += strlen(SubGraphScopePrefix);
  266. break;
  267. case SSTchildgraph:
  268. case SSTworkflow:
  269. case SSTgraph:
  270. // SSTworkflow and SSTgraph may be safely ignored. They are not required to produce the statistics.
  271. expandProcessTreeFromStats(rootTarget, target, &cur);
  272. continue;
  273. case SSTfunction:
  274. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  275. continue;
  276. default:
  277. throwUnexpected();
  278. }
  279. IPropertyTree * next = curTarget->addPropTree(tag);
  280. next->setProp("@id", id);
  281. expandProcessTreeFromStats(rootTarget, next, &cur);
  282. }
  283. }
  284. IPropertyTree * createProcessTreeFromStats()
  285. {
  286. MemoryBuffer compressed;
  287. MemoryBuffer serialized;
  288. Owned<IPropertyTree> progressTree = createPTree();
  289. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  290. ForEach(*iter)
  291. {
  292. IPropertyTree & curSubGraph = iter->query();
  293. curSubGraph.getPropBin("Stats", compressed.clear());
  294. //Protect against updates that delete the stats while we are iterating
  295. if (compressed.length())
  296. {
  297. decompressToBuffer(serialized.clear(), compressed);
  298. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  299. expandProcessTreeFromStats(progressTree, progressTree, collection);
  300. }
  301. }
  302. return progressTree.getClear();
  303. }
  304. protected:
  305. Linked<IPropertyTree> progress;
  306. StringAttr wuid, graphName;
  307. unsigned formatVersion;
  308. };
  309. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  310. {
  311. return new CConstGraphProgress(_wuid, _graphName, _progress);
  312. }
  313. //--------------------------------------------------------------------------------------------------------------------
  314. /*
  315. * Create a user friendly description a scope/stats combination. Only currently used for elapsed time for root subgraphs
  316. */
  317. static void createDefaultDescription(StringBuffer & description, StatisticKind kind, StatisticScopeType scopeType, const char * scope)
  318. {
  319. switch (kind)
  320. {
  321. case StTimeElapsed:
  322. {
  323. if (scopeType != SSTsubgraph)
  324. break;
  325. //Create a default description for a root subgraph
  326. const char * colon = strchr(scope, ':');
  327. if (!colon)
  328. break;
  329. const char * subgraph = colon+1;
  330. //Check for nested subgraph
  331. if (strchr(subgraph, ':'))
  332. break;
  333. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  334. StringAttr graphname;
  335. graphname.set(scope, colon - scope);
  336. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  337. formatGraphTimerLabel(description, graphname, 0, subId);
  338. return;
  339. }
  340. }
  341. describeScope(description, scope);
  342. }
  343. /* Represents a single statistic */
  344. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  345. {
  346. public:
  347. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  348. {
  349. if (!description && createDefault)
  350. {
  351. StringBuffer desc;
  352. createDefaultDescription(desc, kind, scopeType, scope);
  353. str.set(desc);
  354. return str;
  355. }
  356. str.set(description);
  357. return str;
  358. }
  359. virtual IStringVal & getCreator(IStringVal & str) const
  360. {
  361. str.set(creator);
  362. return str;
  363. }
  364. virtual const char * queryScope() const
  365. {
  366. return scope ? scope : "";
  367. }
  368. virtual IStringVal & getFormattedValue(IStringVal & str) const
  369. {
  370. StringBuffer formatted;
  371. formatStatistic(formatted, value, measure);
  372. str.set(formatted);
  373. return str;
  374. }
  375. virtual StatisticMeasure getMeasure() const
  376. {
  377. return measure;
  378. }
  379. virtual StatisticKind getKind() const
  380. {
  381. return kind;
  382. }
  383. virtual StatisticCreatorType getCreatorType() const
  384. {
  385. return creatorType;
  386. }
  387. virtual StatisticScopeType getScopeType() const
  388. {
  389. return scopeType;
  390. }
  391. virtual unsigned __int64 getValue() const
  392. {
  393. return value;
  394. }
  395. virtual unsigned __int64 getCount() const
  396. {
  397. return count;
  398. }
  399. virtual unsigned __int64 getMax() const
  400. {
  401. return max;
  402. }
  403. virtual unsigned __int64 getTimestamp() const
  404. {
  405. return timeStamp;
  406. }
  407. public:
  408. StringBuffer creator;
  409. StringBuffer description;
  410. StringBuffer scope;
  411. StatisticMeasure measure;
  412. StatisticKind kind;
  413. StatisticCreatorType creatorType;
  414. StatisticScopeType scopeType;
  415. unsigned __int64 value;
  416. unsigned __int64 count;
  417. unsigned __int64 max;
  418. unsigned __int64 timeStamp;
  419. };
  420. //---------------------------------------------------------------------------------------------------------------------
  421. /*
  422. * The following compare functions are used to ensure that comparison are consistent with
  423. * compareScopeName() in jstats. This ensures that the scope iterators from different sources
  424. * are processed in a consistent order
  425. */
  426. static int compareGraphNode(IInterface * const *ll, IInterface * const *rr)
  427. {
  428. IPropertyTree *l = (IPropertyTree *) *ll;
  429. IPropertyTree *r = (IPropertyTree *) *rr;
  430. unsigned lwfid = l->getPropInt("@wfid");
  431. unsigned rwfid = r->getPropInt("@wfid");
  432. if (lwfid != rwfid)
  433. return lwfid > rwfid ? +1 : -1;
  434. const char * lname = l->queryName();
  435. const char * rname = r->queryName();
  436. return compareScopeName(lname, rname);
  437. }
  438. static int compareSubGraphStatsNode(IInterface * const *ll, IInterface * const *rr)
  439. {
  440. IPropertyTree *l = (IPropertyTree *) *ll;
  441. IPropertyTree *r = (IPropertyTree *) *rr;
  442. return compareScopeName(l->queryName(), r->queryName());
  443. }
  444. static int compareSubGraphNode(IInterface * const *ll, IInterface * const *rr)
  445. {
  446. IPropertyTree *l = (IPropertyTree *) *ll;
  447. IPropertyTree *r = (IPropertyTree *) *rr;
  448. return l->getPropInt("@id") - r->getPropInt("@id");
  449. }
  450. static int compareActivityNode(IInterface * const *ll, IInterface * const *rr)
  451. {
  452. IPropertyTree *l = (IPropertyTree *) *ll;
  453. IPropertyTree *r = (IPropertyTree *) *rr;
  454. return l->getPropInt("@id") - r->getPropInt("@id");
  455. }
  456. static int compareEdgeNode(IInterface * const *ll, IInterface * const *rr)
  457. {
  458. IPropertyTree *l = (IPropertyTree *) *ll;
  459. IPropertyTree *r = (IPropertyTree *) *rr;
  460. //MORE: Edge needs more work
  461. const char * leftId = l->queryProp("@id");
  462. const char * rightId = r->queryProp("@id");
  463. unsigned leftAc = atoi(leftId);
  464. unsigned rightAc = atoi(rightId);
  465. if (leftAc != rightAc)
  466. return (int)(leftAc - rightAc);
  467. const char * leftSep = strchr(leftId, '_');
  468. const char * rightSep = strchr(rightId, '_');
  469. assertex(leftSep && rightSep);
  470. return atoi(leftSep+1) - atoi(rightSep+1);
  471. }
  472. //---------------------------------------------------------------------------------------------------------------------
  473. /*
  474. * A class for implementing a scope iterator that walks through graph progress information
  475. */
  476. class CConstGraphProgressScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  477. {
  478. public:
  479. CConstGraphProgressScopeIterator(const char * wuid, const ScopeFilter & _filter, __uint64 _minVersion) : filter(_filter), minVersion(_minVersion)
  480. {
  481. //Examine the filter, and determine if we only need to look at a single graph/subgraph
  482. StringAttr singleGraph;
  483. const StringArray & scopesToMatch = filter.queryScopes();
  484. if (scopesToMatch)
  485. {
  486. bool seenGraph = false;
  487. bool seenSubGraph = false;
  488. ForEachItemIn(iScope, scopesToMatch)
  489. {
  490. StringArray ids;
  491. ids.appendList(scopesToMatch.item(iScope), ":");
  492. ForEachItemIn(i, ids)
  493. {
  494. const char * curId = ids.item(i);
  495. StatsScopeId id(curId);
  496. switch (id.queryScopeType())
  497. {
  498. case SSTgraph:
  499. if (seenGraph)
  500. {
  501. if (singleGraph && !streq(singleGraph, curId))
  502. singleGraph.clear();
  503. }
  504. else
  505. {
  506. if (!id.isWildcard())
  507. singleGraph.set(curId);
  508. seenGraph = true;
  509. }
  510. break;
  511. case SSTsubgraph:
  512. if (seenSubGraph)
  513. {
  514. if (singleSubGraph && !streq(singleSubGraph, curId))
  515. singleSubGraph.clear();
  516. }
  517. else
  518. {
  519. if (!id.isWildcard())
  520. singleSubGraph.set(curId);
  521. seenSubGraph = true;
  522. }
  523. break;
  524. }
  525. }
  526. }
  527. }
  528. rootPath.append("/GraphProgress/").append(wuid).append('/');
  529. if (singleGraph)
  530. rootPath.append(singleGraph).append("/");
  531. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  532. if (daliClientActive())
  533. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  534. if (conn && !singleGraph)
  535. {
  536. graphIter.setown(conn->queryRoot()->getElements("*"));
  537. graphIter.setown(createSortedIterator(*graphIter, compareGraphNode));
  538. }
  539. valid = false;
  540. }
  541. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IConstWUScopeIterator>)
  542. virtual bool first()
  543. {
  544. valid = false;
  545. if (!conn)
  546. return false;
  547. if (graphIter && !graphIter->first())
  548. return false;
  549. if (!firstSubGraph())
  550. {
  551. if (!nextGraph())
  552. return false;
  553. }
  554. valid = true;
  555. return true;
  556. }
  557. virtual bool next()
  558. {
  559. if (!nextChildScope())
  560. {
  561. if (!nextSubGraph())
  562. {
  563. if (!nextGraph())
  564. {
  565. valid = false;
  566. return false;
  567. }
  568. }
  569. }
  570. return true;
  571. }
  572. virtual bool nextSibling() override
  573. {
  574. if (collections.ordinality() == 0)
  575. return false;
  576. assertex(childIterators.ordinality() < collections.ordinality());
  577. collections.pop();
  578. //next will call childIterator.next() - walking the next sibling
  579. return next();
  580. }
  581. virtual bool nextParent() override
  582. {
  583. if (collections.ordinality() == 0)
  584. return false;
  585. assertex(childIterators.ordinality() < collections.ordinality());
  586. collections.pop();
  587. if (collections.ordinality() == 0)
  588. return false;
  589. //Finish with this node - so next will move onto the sibling of the parent node.
  590. finishCollection();
  591. return next();
  592. }
  593. virtual bool isValid()
  594. {
  595. return valid;
  596. }
  597. protected:
  598. bool firstSubGraph()
  599. {
  600. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  601. const char * xpath = "sg*";
  602. StringBuffer childXpath;
  603. if (singleSubGraph)
  604. {
  605. childXpath.append(singleSubGraph);
  606. xpath = childXpath.str();
  607. }
  608. subgraphIter.setown(graphNode.getElements(xpath));
  609. if (subgraphIter)
  610. {
  611. if (!singleSubGraph)
  612. subgraphIter.setown(createSortedIterator(*subgraphIter, compareSubGraphStatsNode));
  613. }
  614. else
  615. subgraphIter.setown(graphNode.getElements("sg0"));
  616. if (!subgraphIter->first())
  617. return false;
  618. if (firstStat())
  619. return true;
  620. return nextSubGraph();
  621. }
  622. bool nextSubGraph()
  623. {
  624. for (;;)
  625. {
  626. if (!subgraphIter->next())
  627. return false;
  628. if (firstStat())
  629. return true;
  630. }
  631. }
  632. bool nextGraph()
  633. {
  634. if (!graphIter)
  635. return false;
  636. for (;;)
  637. {
  638. if (!graphIter->next())
  639. return false;
  640. if (firstSubGraph())
  641. return true;
  642. }
  643. }
  644. bool firstStat()
  645. {
  646. IPropertyTree & curSubGraph = subgraphIter->query();
  647. if (!checkSubGraph())
  648. return false;
  649. curSubGraph.getPropBin("Stats", compressed.clear());
  650. //Don't crash on old format progress...
  651. if (compressed.length() == 0)
  652. return false;
  653. decompressToBuffer(serialized.clear(), compressed);
  654. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  655. statsIterator.timeStamp = collection->queryWhenCreated();
  656. if (!beginCollection(*collection))
  657. return false;
  658. // When workflow is root element, it is just a container. Ignore the workflow element here
  659. // as WorkUnitStatisticsScopeIterator will produce workflow scope - don't want duplicates.
  660. // (Note: workflow element never contains stats).
  661. if (collections.tos().queryScopeType() == SSTworkflow)
  662. {
  663. if (!next())
  664. return false;
  665. }
  666. //The root element of a collection is a graph - but it is only there to nest the subgraphs in.
  667. //Do not iterate it as a separate element - unless it has some stats.
  668. IStatisticCollection & curCollection = collections.tos();
  669. if ((curCollection.queryScopeType() != SSTgraph) || (curCollection.getNumStatistics() != 0))
  670. return true;
  671. return next();
  672. }
  673. bool beginCollection(IStatisticCollection & collection)
  674. {
  675. collections.append(OLINK(collection));
  676. curScopeType = collection.queryScopeType();
  677. collection.getFullScope(curScopeName.clear());
  678. ScopeCompare result = filter.compare(curScopeName);
  679. if (result & SCequal)
  680. return true;
  681. //If this scope cannot be the parent of a match then discard it.
  682. if (!(result & SCparent))
  683. collections.pop();
  684. //walk the next element
  685. return nextChildScope();
  686. }
  687. bool nextChildScope()
  688. {
  689. for (;;)
  690. {
  691. if (collections.ordinality() == 0)
  692. return false;
  693. IStatisticCollection * curCollection = &collections.tos();
  694. if (childIterators.ordinality() < collections.ordinality())
  695. {
  696. ScopeCompare result = filter.compare(curScopeName);
  697. //Do not walk children scopes if it is unrelated
  698. if (result & SCparent)
  699. {
  700. //Start iterating the children for the current collection
  701. childIterators.append(curCollection->getScopes(NULL, true));
  702. if (!childIterators.tos().first())
  703. {
  704. finishCollection();
  705. continue;
  706. }
  707. }
  708. else
  709. {
  710. //Don't walk the child scopes
  711. collections.pop();
  712. continue;
  713. }
  714. }
  715. else if (!childIterators.tos().next())
  716. {
  717. finishCollection();
  718. continue;
  719. }
  720. if (beginCollection(childIterators.tos().query()))
  721. return true;
  722. }
  723. }
  724. void finishCollection()
  725. {
  726. collections.pop();
  727. childIterators.pop();
  728. }
  729. bool checkSubGraph()
  730. {
  731. IPropertyTree & curSubGraph = subgraphIter->query();
  732. StatisticCreatorType creatorType = queryCreatorType(curSubGraph.queryProp("@c"), SCTnone);
  733. const char * creator = curSubGraph.queryProp("@creator");
  734. //MORE: Check minVersion and allow early filtering
  735. //MORE: Potentially filter by creator type??
  736. // if (!filter->matches(creatorType, creator, SSTall, NULL, SMeasureAll, StKindAll, AnyStatisticValue))
  737. // return false;
  738. statsIterator.creatorType = creatorType;
  739. statsIterator.creator.set(creator);
  740. return true;
  741. }
  742. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  743. {
  744. if ((whichProperties & PTstatistics))
  745. {
  746. /*
  747. MORE: Code from the statsIterator class should be inlined here - code will be much simpler
  748. but it currently needs an implementation of the IConstWUStatistic 3rd parameter
  749. IStatisticCollection & collection = collections.tos();
  750. ForEachItemIn(i, collection)
  751. {
  752. StatisticKind kind;
  753. unsigned __int64 value;
  754. collection->getStatistic(kind, value, i);
  755. visitor.noteStatistic(kind, value, *this);
  756. }
  757. */
  758. statsIterator.reset(curScopeName, curScopeType, collections.tos());
  759. ForEach(statsIterator)
  760. statsIterator.play(visitor);
  761. }
  762. }
  763. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  764. {
  765. return collections.tos().getStatistic(kind, value);
  766. }
  767. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  768. {
  769. return nullptr;
  770. }
  771. virtual const char * queryHint(const char * kind) const override
  772. {
  773. return nullptr;
  774. }
  775. virtual const char * queryScope() const override
  776. {
  777. return curScopeName;
  778. }
  779. virtual StatisticScopeType getScopeType() const override
  780. {
  781. return curScopeType;
  782. }
  783. private:
  784. class ScopeStatisticsIterator : public CInterfaceOf<IConstWUStatistic>
  785. {
  786. friend class CConstGraphProgressScopeIterator; // cleaner if this was removed + setScope() functions added.
  787. public:
  788. void reset(const char * _scopeName, StatisticScopeType _scopeType, IStatisticCollection & _collection)
  789. {
  790. scope.set(_scopeName);
  791. scopeType = _scopeType;
  792. collection = &_collection;
  793. numStats = collection->getNumStatistics();
  794. }
  795. // interface IConstWUStatisticIterator
  796. IConstWUStatistic & query()
  797. {
  798. return *this;
  799. }
  800. bool first()
  801. {
  802. curStatIndex = 0;
  803. if (curStatIndex >= numStats)
  804. return false;
  805. collection->getStatistic(kind, value, curStatIndex);
  806. //MORE: Allow filtering:
  807. /*
  808. * if (filter && !filter->matches(SCTall, NULL, SSTall, NULL, queryMeasure(kind), kind, value))
  809. continue;
  810. */
  811. return true;
  812. }
  813. bool next()
  814. {
  815. for (;;)
  816. {
  817. ++curStatIndex;
  818. if (curStatIndex >= numStats)
  819. return false;
  820. collection->getStatistic(kind, value, curStatIndex);
  821. //MORE: Allow stats filtering
  822. return true;
  823. }
  824. }
  825. bool isValid()
  826. {
  827. return curStatIndex < numStats;
  828. }
  829. //interface IConstWUStatistic
  830. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const override
  831. {
  832. if (createDefault)
  833. {
  834. StringBuffer description;
  835. createDefaultDescription(description, kind, scopeType, scope);
  836. str.set(description);
  837. }
  838. return str;
  839. }
  840. virtual IStringVal & getCreator(IStringVal & str) const override
  841. {
  842. str.set(creator);
  843. return str;
  844. }
  845. virtual const char * queryScope() const override
  846. {
  847. return scope;
  848. }
  849. virtual IStringVal & getFormattedValue(IStringVal & str) const override
  850. {
  851. StringBuffer formatted;
  852. formatStatistic(formatted, value, kind);
  853. str.set(formatted);
  854. return str;
  855. }
  856. virtual StatisticMeasure getMeasure() const override
  857. {
  858. return queryMeasure(kind);
  859. }
  860. virtual StatisticKind getKind() const override
  861. {
  862. return kind;
  863. }
  864. virtual StatisticCreatorType getCreatorType() const override
  865. {
  866. return creatorType;
  867. }
  868. virtual StatisticScopeType getScopeType() const override
  869. {
  870. return scopeType;
  871. }
  872. virtual unsigned __int64 getValue() const override
  873. {
  874. return value;
  875. }
  876. virtual unsigned __int64 getCount() const override
  877. {
  878. return 1;
  879. }
  880. virtual unsigned __int64 getMax() const override
  881. {
  882. return 0;
  883. }
  884. virtual unsigned __int64 getTimestamp() const override
  885. {
  886. return timeStamp;
  887. }
  888. void play(IWuScopeVisitor & visitor)
  889. {
  890. visitor.noteStatistic(kind, value, *this);
  891. }
  892. protected:
  893. IStatisticCollection * collection = nullptr;
  894. StringBuffer creator;
  895. StringBuffer scope;
  896. StatisticKind kind;
  897. StatisticCreatorType creatorType;
  898. StatisticScopeType scopeType;
  899. unsigned __int64 value = 0;
  900. unsigned __int64 timeStamp;
  901. unsigned curStatIndex = 0;
  902. unsigned numStats = 0;
  903. } statsIterator;
  904. Owned<IRemoteConnection> conn;
  905. StringBuffer curScopeName;
  906. StatisticScopeType curScopeType = SSTnone;
  907. __uint64 minVersion;
  908. const ScopeFilter & filter;
  909. StringBuffer rootPath;
  910. StringAttr singleSubGraph;
  911. Owned<IPropertyTreeIterator> graphIter;
  912. Owned<IPropertyTreeIterator> subgraphIter;
  913. IArrayOf<IStatisticCollection> collections;
  914. IArrayOf<IStatisticCollectionIterator> childIterators; // Iterator(n) through collections(n) - created once iterating children
  915. MemoryBuffer compressed;
  916. MemoryBuffer serialized;
  917. bool valid;
  918. };
  919. int compareNoteScopeOrder(IConstWUException & left, IConstWUException & right)
  920. {
  921. return compareScopeName(left.queryScope(), right.queryScope());
  922. }
  923. int compareNoteScopeOrder(IInterface * const * left, IInterface * const * right)
  924. {
  925. return compareNoteScopeOrder(*static_cast<IConstWUException *>(*left), *static_cast<IConstWUException *>(*right));
  926. }
  927. class NotesIterator : public CInterfaceOf<IConstWUScopeIterator>
  928. {
  929. public:
  930. NotesIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter)
  931. {
  932. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  933. ForEach(*exceptions)
  934. {
  935. IConstWUException & exception = exceptions->query();
  936. if (exception.queryScope()!=nullptr)
  937. notes.append(OLINK(exception));
  938. }
  939. notes.sort(compareNoteScopeOrder);
  940. }
  941. virtual bool first() override
  942. {
  943. baseIndex = 0;
  944. return updateCurrent();
  945. }
  946. virtual bool next() override
  947. {
  948. baseIndex += numCurrentScope;
  949. return updateCurrent();
  950. }
  951. virtual bool isValid() override
  952. {
  953. return notes.isItem(baseIndex);
  954. }
  955. virtual bool nextSibling() override
  956. {
  957. //Search until the current scope is not a child of the previous scope
  958. StringBuffer savedScope(queryScope());
  959. for (;;)
  960. {
  961. if (!next())
  962. return false;
  963. if (compareScopes(queryScope(), savedScope) != SCchild)
  964. return true;
  965. }
  966. }
  967. virtual bool nextParent() override
  968. {
  969. //Search until the current scope is not a child of the previous parent scope
  970. StringBuffer parentScope;
  971. if (getParentScope(parentScope, queryScope()))
  972. {
  973. for (;;)
  974. {
  975. if (!next())
  976. return false;
  977. if (compareScopes(queryScope(), parentScope) != SCchild)
  978. return true;
  979. }
  980. }
  981. else
  982. {
  983. finish();
  984. return false;
  985. }
  986. }
  987. virtual const char * queryScope() const override
  988. {
  989. const char * scope = notes.item(baseIndex).queryScope();
  990. return scope ? scope : "";
  991. }
  992. virtual StatisticScopeType getScopeType() const override
  993. {
  994. const char * tail = queryScopeTail(queryScope());
  995. StatsScopeId id(tail);
  996. return id.queryScopeType();
  997. }
  998. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) override
  999. {
  1000. if (whichProperties & PTnotes)
  1001. {
  1002. for (unsigned i=0; i < numCurrentScope; i++)
  1003. {
  1004. IConstWUException & cur = notes.item(baseIndex + i);
  1005. visitor.noteException(cur);
  1006. }
  1007. }
  1008. }
  1009. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1010. {
  1011. return false;
  1012. }
  1013. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1014. {
  1015. return nullptr;
  1016. }
  1017. virtual const char * queryHint(const char * kind) const override
  1018. {
  1019. return nullptr;
  1020. }
  1021. private:
  1022. bool updateCurrent()
  1023. {
  1024. if (!notes.isItem(baseIndex))
  1025. return false;
  1026. // set numCurrentScope to number of notes in the current scope
  1027. unsigned next = baseIndex+1;
  1028. while (next < notes.ordinality())
  1029. {
  1030. if (compareNoteScopeOrder(notes.item(baseIndex), notes.item(next)) != 0)
  1031. break;
  1032. next++;
  1033. }
  1034. numCurrentScope = (next - baseIndex);
  1035. return true;
  1036. }
  1037. void finish()
  1038. {
  1039. baseIndex = notes.ordinality();
  1040. }
  1041. unsigned baseIndex = 0;
  1042. unsigned numCurrentScope = 0;
  1043. IArrayOf<IConstWUException> notes;
  1044. };
  1045. int compareStatisticScopes(IConstWUStatistic & left, IConstWUStatistic & right)
  1046. {
  1047. return compareScopeName(left.queryScope(), right.queryScope());
  1048. }
  1049. int compareStatisticScopes(IInterface * const * left, IInterface * const * right)
  1050. {
  1051. return compareStatisticScopes(*static_cast<IConstWUStatistic *>(*left), *static_cast<IConstWUStatistic *>(*right));
  1052. }
  1053. /*
  1054. * An implementation of IConstWUScopeIterator for global workunit statistics.
  1055. */
  1056. class WorkUnitStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1057. {
  1058. public:
  1059. WorkUnitStatisticsScopeIterator(const IArrayOf<IConstWUStatistic> & _statistics, const ScopeFilter & _filter)
  1060. {
  1061. ForEachItemIn(i, _statistics)
  1062. {
  1063. IConstWUStatistic & cur = _statistics.item(i);
  1064. if (_filter.compare(cur.queryScope()) & SCequal)
  1065. statistics.append(OLINK(cur));
  1066. }
  1067. statistics.sort(compareStatisticScopes);
  1068. }
  1069. virtual bool first() override
  1070. {
  1071. curIndex = 0;
  1072. return initScope();
  1073. }
  1074. virtual bool next() override
  1075. {
  1076. curIndex += numStatistics;
  1077. return initScope();
  1078. }
  1079. virtual bool nextSibling() override
  1080. {
  1081. //Search until the current scope is not a child of the previous scope
  1082. StringBuffer savedScope(queryScope());
  1083. for (;;)
  1084. {
  1085. if (!next())
  1086. return false;
  1087. if (compareScopes(queryScope(), savedScope) != SCchild)
  1088. return true;
  1089. }
  1090. }
  1091. virtual bool nextParent() override
  1092. {
  1093. //Search until the current scope is not a child of the previous parent scope
  1094. StringBuffer parentScope;
  1095. if (getParentScope(parentScope, queryScope()))
  1096. {
  1097. for (;;)
  1098. {
  1099. if (!next())
  1100. return false;
  1101. if (compareScopes(queryScope(), parentScope) != SCchild)
  1102. return true;
  1103. }
  1104. }
  1105. else
  1106. {
  1107. finish();
  1108. return false;
  1109. }
  1110. }
  1111. virtual bool isValid() override
  1112. {
  1113. return statistics.isItem(curIndex);
  1114. }
  1115. virtual const char * queryScope() const override
  1116. {
  1117. return statistics.item(curIndex).queryScope();
  1118. }
  1119. virtual StatisticScopeType getScopeType() const override
  1120. {
  1121. return statistics.item(curIndex).getScopeType();
  1122. }
  1123. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1124. {
  1125. if (whichProperties & PTstatistics)
  1126. {
  1127. for (unsigned i=0; i < numStatistics; i++)
  1128. {
  1129. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1130. visitor.noteStatistic(cur.getKind(), cur.getValue(), cur);
  1131. }
  1132. }
  1133. }
  1134. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1135. {
  1136. for (unsigned i=0; i < numStatistics; i++)
  1137. {
  1138. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1139. if (cur.getKind() == kind)
  1140. {
  1141. value = cur.getValue();
  1142. return true;
  1143. }
  1144. }
  1145. return false;
  1146. }
  1147. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1148. {
  1149. return nullptr;
  1150. }
  1151. virtual const char * queryHint(const char * kind) const
  1152. {
  1153. return nullptr;
  1154. }
  1155. protected:
  1156. inline IConstWUStatistic & queryStatistic(unsigned i)
  1157. {
  1158. return statistics.item(curIndex + i);
  1159. }
  1160. bool initScope()
  1161. {
  1162. if (!statistics.isItem(curIndex))
  1163. return false;
  1164. unsigned next = curIndex+1;
  1165. while (next < statistics.ordinality())
  1166. {
  1167. if (compareStatisticScopes(statistics.item(curIndex), statistics.item(next)) != 0)
  1168. break;
  1169. next++;
  1170. }
  1171. numStatistics = (next - curIndex);
  1172. return true;
  1173. }
  1174. void finish()
  1175. {
  1176. curIndex = statistics.ordinality();
  1177. }
  1178. protected:
  1179. IArrayOf<IConstWUStatistic> statistics;
  1180. unsigned curIndex = 0;
  1181. unsigned numStatistics = 1;
  1182. };
  1183. /*
  1184. * An implementation of IConstWUScopeIterator for the query graphs.
  1185. */
  1186. class GraphScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1187. {
  1188. private:
  1189. //This uses a state machine - this enumeration contains the different states.
  1190. enum State
  1191. {
  1192. //Following are the states which represent valid scopes
  1193. SGraph,
  1194. SChildGraph,
  1195. SSubGraph,
  1196. SEdge,
  1197. SActivity,
  1198. //The following are internal states.
  1199. SGraphFirstEdge,
  1200. SGraphFirstSubGraph,
  1201. SGraphFirst,
  1202. SGraphEnd,
  1203. SGraphNext,
  1204. SSubGraphFirstEdge,
  1205. SSubGraphFirstActivity,
  1206. SSubGraphEnd,
  1207. SSubGraphNext,
  1208. SEdgeNext,
  1209. SEdgeEnd,
  1210. SActivityNext,
  1211. SActivityEnd,
  1212. SChildGraphFirstEdge,
  1213. SChildGraphFirstSubGraph,
  1214. SChildGraphFirst,
  1215. SChildGraphNext,
  1216. SChildGraphEnd,
  1217. SDone
  1218. };
  1219. State state = SDone;
  1220. State nextState = SDone;
  1221. public:
  1222. GraphScopeIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter) : graphIter(&wu->getGraphs(GraphTypeAny)), filter(_filter)
  1223. {
  1224. }
  1225. virtual bool first() override
  1226. {
  1227. state = SGraphFirst;
  1228. return nextScope();
  1229. }
  1230. virtual bool next() override
  1231. {
  1232. if (!selectNext())
  1233. return false;
  1234. return nextScope();
  1235. }
  1236. virtual bool nextSibling() override
  1237. {
  1238. if (!selectNextSibling())
  1239. return false;
  1240. return nextScope();
  1241. }
  1242. virtual bool nextParent() override
  1243. {
  1244. if (!selectNextParent())
  1245. return false;
  1246. return nextScope();
  1247. }
  1248. virtual bool isValid() override
  1249. {
  1250. return graphIter->isValid();
  1251. }
  1252. virtual const char * queryScope() const override
  1253. {
  1254. return curScopeName.str();
  1255. }
  1256. virtual StatisticScopeType getScopeType() const override
  1257. {
  1258. return scopeType;
  1259. }
  1260. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1261. {
  1262. switch (scopeType)
  1263. {
  1264. case SSTgraph:
  1265. return;
  1266. }
  1267. IPropertyTree & cur = treeIters.tos().query();
  1268. switch (scopeType)
  1269. {
  1270. case SSTgraph:
  1271. break;
  1272. case SSTsubgraph:
  1273. break;
  1274. case SSTactivity:
  1275. {
  1276. if (whichProperties & PTattributes)
  1277. {
  1278. playAttribute(visitor, WaLabel);
  1279. Owned<IPropertyTreeIterator> attrs = cur.getElements("att");
  1280. ForEach(*attrs)
  1281. {
  1282. IPropertyTree & cur = attrs->query();
  1283. WuAttr attr = queryGraphChildAttToWuAttr(cur.queryProp("@name"));
  1284. if (attr != WaNone)
  1285. visitor.noteAttribute(attr, cur.queryProp("@value"));
  1286. }
  1287. }
  1288. if (whichProperties & PThints)
  1289. {
  1290. Owned<IPropertyTreeIterator> hints = cur.getElements("hint");
  1291. ForEach(*hints)
  1292. {
  1293. IPropertyTree & cur = hints->query();
  1294. visitor.noteHint(cur.queryProp("@name"), cur.queryProp("@value"));
  1295. }
  1296. }
  1297. break;
  1298. }
  1299. case SSTedge:
  1300. if (whichProperties & PTattributes)
  1301. {
  1302. //MORE This will eventually need to walk the attributes and map the names.
  1303. //Need to be careful if they need to be mapped differently depending on the context.
  1304. playAttribute(visitor, WaLabel);
  1305. playAttribute(visitor, WaIdSource);
  1306. playAttribute(visitor, WaIdTarget);
  1307. playAttribute(visitor, WaSourceIndex);
  1308. playAttribute(visitor, WaTargetIndex);
  1309. playAttribute(visitor, WaIsDependency);
  1310. }
  1311. break;
  1312. }
  1313. }
  1314. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1315. {
  1316. return false;
  1317. }
  1318. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1319. {
  1320. if (!treeIters.ordinality())
  1321. return nullptr;
  1322. //MORE - check that the attribute is value for the current scope type (to prevent defaults being returned)
  1323. return queryAttributeValue(treeIters.tos().query(), attr, scratchpad);
  1324. }
  1325. virtual const char * queryHint(const char * kind) const override
  1326. {
  1327. //MORE: Needs to be implemented!
  1328. return nullptr;
  1329. }
  1330. private:
  1331. void playAttribute(IWuScopeVisitor & visitor, WuAttr kind)
  1332. {
  1333. StringBuffer scratchpad;
  1334. const char * value = queryAttributeValue(treeIters.tos().query(), kind, scratchpad);
  1335. if (value)
  1336. visitor.noteAttribute(kind, value);
  1337. }
  1338. void pushIterator(IPropertyTreeIterator * iter, State state)
  1339. {
  1340. treeIters.append(*LINK(iter));
  1341. stateStack.append(state);
  1342. }
  1343. State popIterator()
  1344. {
  1345. treeIters.pop();
  1346. return (State)stateStack.popGet();
  1347. }
  1348. void pushScope(const char * id)
  1349. {
  1350. scopeLengths.append(curScopeName.length());
  1351. curScopeName.append(":").append(id);
  1352. }
  1353. void popScope()
  1354. {
  1355. curScopeName.setLength(scopeLengths.popGet());
  1356. }
  1357. bool doNextScope()
  1358. {
  1359. for(;;)
  1360. {
  1361. switch (state)
  1362. {
  1363. case SGraph:
  1364. {
  1365. IConstWUGraph & graph = graphIter->query();
  1366. unsigned wfid = graph.getWfid();
  1367. curScopeName.clear();
  1368. if (wfid != 0)
  1369. curScopeName.append(WorkflowScopePrefix).append(wfid).append(':');
  1370. graph.getName(StringBufferAdaptor(curScopeName));
  1371. scopeType = SSTgraph;
  1372. return true;
  1373. }
  1374. case SSubGraph:
  1375. scopeId.set(SubGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1376. pushScope(scopeId);
  1377. scopeType = SSTsubgraph;
  1378. return true;
  1379. case SEdge:
  1380. scopeId.set(EdgeScopePrefix).append(treeIters.tos().query().queryProp("@id"));
  1381. pushScope(scopeId);
  1382. scopeType = SSTedge;
  1383. return true;
  1384. case SActivity:
  1385. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph)
  1386. {
  1387. state = SActivityNext;
  1388. break;
  1389. }
  1390. scopeId.set(ActivityScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1391. pushScope(scopeId);
  1392. scopeType = SSTactivity;
  1393. return true;
  1394. case SChildGraph:
  1395. {
  1396. #ifdef _DEBUG
  1397. assertex(treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph);
  1398. unsigned numIters = treeIters.ordinality();
  1399. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1400. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1401. assertex(parentId == parentActivityId);
  1402. #endif
  1403. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1404. pushScope(scopeId);
  1405. scopeType = SSTchildgraph;
  1406. return true;
  1407. }
  1408. //Graph iteration
  1409. case SGraphFirst:
  1410. if (!graphIter->first())
  1411. state = SDone;
  1412. else
  1413. state = SGraph;
  1414. break;
  1415. case SGraphEnd:
  1416. state = SGraphNext;
  1417. break;
  1418. case SGraphNext:
  1419. if (!graphIter->next())
  1420. state = SDone;
  1421. else
  1422. state = SGraph;
  1423. break;
  1424. //Edge iteration
  1425. case SGraphFirstEdge:
  1426. {
  1427. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1428. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1429. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1430. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1431. if (treeIter && treeIter->first())
  1432. {
  1433. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1434. treeIter->first();
  1435. pushIterator(treeIter, SGraphFirstSubGraph);
  1436. state = SEdge;
  1437. }
  1438. else
  1439. state = SGraphFirstSubGraph;
  1440. break;
  1441. }
  1442. case SChildGraphFirstEdge:
  1443. {
  1444. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1445. if (treeIter && treeIter->first())
  1446. {
  1447. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1448. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1449. state = SEdge;
  1450. }
  1451. else
  1452. state = SChildGraphFirstSubGraph;
  1453. break;
  1454. }
  1455. case SEdgeEnd:
  1456. popScope();
  1457. state = SEdgeNext;
  1458. break;
  1459. case SEdgeNext:
  1460. if (treeIters.tos().next())
  1461. state = SEdge;
  1462. else
  1463. state = popIterator();
  1464. break;
  1465. //Subgraph iteration
  1466. case SGraphFirstSubGraph:
  1467. {
  1468. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1469. if (treeIter && treeIter->first())
  1470. {
  1471. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1472. treeIter->first();
  1473. pushIterator(treeIter, SGraphNext);
  1474. state = SSubGraph;
  1475. }
  1476. else
  1477. state = SGraphNext;
  1478. break;
  1479. }
  1480. case SChildGraphFirstSubGraph:
  1481. {
  1482. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1483. if (treeIter && treeIter->first())
  1484. {
  1485. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1486. pushIterator(treeIter, SChildGraphEnd);
  1487. state = SSubGraph;
  1488. }
  1489. else
  1490. state = SChildGraphEnd;
  1491. break;
  1492. }
  1493. case SSubGraphFirstEdge:
  1494. {
  1495. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1496. if (treeIter && treeIter->first())
  1497. {
  1498. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1499. pushIterator(treeIter, SSubGraphFirstActivity);
  1500. state = SEdge;
  1501. }
  1502. else
  1503. state = SSubGraphFirstActivity;
  1504. break;
  1505. }
  1506. case SSubGraphFirstActivity:
  1507. {
  1508. //Walk the contents of each subgraph once, splitting the entries into activities and child graphs
  1509. IArrayOf<IPropertyTree> activities;
  1510. IArrayOf<IPropertyTree> childGraphs;
  1511. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1512. ForEach(*treeIter)
  1513. {
  1514. IPropertyTree & cur = treeIter->get();
  1515. if (cur.getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1516. activities.append(cur);
  1517. else
  1518. childGraphs.append(cur);
  1519. }
  1520. if (activities.ordinality())
  1521. {
  1522. //Create an iterator for the child graphs in this subgraph which is iterated in order as the activities are processed
  1523. Owned<IPropertyTreeIterator> graphIter = createSortedIterator(childGraphs, compareSubGraphNode);
  1524. graphIter->first();
  1525. childGraphIters.append(*graphIter.getClear());
  1526. Owned<IPropertyTreeIterator> activityIter = createSortedIterator(activities, compareActivityNode);
  1527. pushIterator(activityIter, SSubGraphEnd);
  1528. state = SActivity;
  1529. }
  1530. else
  1531. state = SSubGraphEnd;
  1532. break;
  1533. }
  1534. case SSubGraphEnd:
  1535. popScope();
  1536. state = SSubGraphNext;
  1537. break;
  1538. case SChildGraphEnd:
  1539. popScope();
  1540. state = SChildGraphNext;
  1541. break;
  1542. case SSubGraphNext:
  1543. if (treeIters.tos().next())
  1544. state = SSubGraph;
  1545. else
  1546. state = popIterator();
  1547. break;
  1548. case SActivityEnd:
  1549. popScope();
  1550. state = SActivityNext;
  1551. break;
  1552. case SActivityNext:
  1553. if (treeIters.tos().next())
  1554. state = SActivity;
  1555. else
  1556. {
  1557. assertex(!childGraphIters.tos().isValid());
  1558. childGraphIters.pop();
  1559. state = popIterator();
  1560. }
  1561. break;
  1562. case SChildGraphNext:
  1563. if (treeIters.tos().next())
  1564. state = SChildGraph;
  1565. else
  1566. state = popIterator();
  1567. break;
  1568. case SChildGraphFirst:
  1569. {
  1570. unsigned parentActivityId = treeIters.tos().query().getPropInt("@id");
  1571. IArrayOf<IPropertyTree> childGraphs;
  1572. IPropertyTreeIterator & allGraphs = childGraphIters.tos();
  1573. while (allGraphs.isValid())
  1574. {
  1575. IPropertyTree & cur = allGraphs.query();
  1576. unsigned parentId = cur.getPropInt("att[@name='_parentActivity']/@value");
  1577. if (parentId != parentActivityId)
  1578. break;
  1579. childGraphs.append(OLINK(cur));
  1580. allGraphs.next();
  1581. }
  1582. if (childGraphs.ordinality())
  1583. {
  1584. Owned<IPropertyTreeIterator> treeIter = createSortedIterator(childGraphs, compareSubGraphNode);
  1585. pushIterator(treeIter, SActivityEnd);
  1586. state = SChildGraph;
  1587. }
  1588. else
  1589. state = SActivityEnd;
  1590. break;
  1591. }
  1592. case SDone:
  1593. return false;
  1594. default:
  1595. throwUnexpected();
  1596. }
  1597. }
  1598. }
  1599. bool nextScope()
  1600. {
  1601. for(;;)
  1602. {
  1603. if (!doNextScope())
  1604. return false;
  1605. ScopeCompare cmp = filter.compare(curScopeName);
  1606. if (cmp & SCequal)
  1607. return true;
  1608. //MORE: Optimize next based on result of compare
  1609. if (!selectNext())
  1610. return false;
  1611. }
  1612. }
  1613. bool selectNext()
  1614. {
  1615. switch (state)
  1616. {
  1617. case SGraph:
  1618. state = SGraphFirstEdge;
  1619. break;
  1620. case SChildGraph:
  1621. state = SChildGraphFirstEdge;
  1622. break;
  1623. case SSubGraph:
  1624. state = SSubGraphFirstEdge;
  1625. break;
  1626. case SEdge:
  1627. state = SEdgeEnd;
  1628. break;
  1629. case SActivity:
  1630. state = SChildGraphFirst;
  1631. break;
  1632. case SDone:
  1633. return false;
  1634. default:
  1635. throwUnexpected();
  1636. }
  1637. return true;
  1638. }
  1639. bool selectNextSibling()
  1640. {
  1641. switch (state)
  1642. {
  1643. case SGraph:
  1644. state = SGraphEnd;
  1645. break;
  1646. case SChildGraph:
  1647. state = SChildGraphEnd;
  1648. break;
  1649. case SSubGraph:
  1650. state = SSubGraphEnd;
  1651. break;
  1652. case SEdge:
  1653. state = SEdgeEnd;
  1654. break;
  1655. case SActivity:
  1656. state = SActivityEnd;
  1657. break;
  1658. case SDone:
  1659. return false;
  1660. default:
  1661. throwUnexpected();
  1662. }
  1663. return true;
  1664. }
  1665. bool selectNextParent()
  1666. {
  1667. switch (state)
  1668. {
  1669. case SGraph:
  1670. state = SDone;
  1671. break;
  1672. case SActivity:
  1673. childGraphIters.pop();
  1674. //fall through
  1675. case SChildGraph:
  1676. case SSubGraph:
  1677. case SEdge:
  1678. popScope();
  1679. state = popIterator();
  1680. break;
  1681. case SDone:
  1682. return false;
  1683. default:
  1684. throwUnexpected();
  1685. }
  1686. return true;
  1687. }
  1688. protected:
  1689. const ScopeFilter & filter;
  1690. Owned<IConstWUGraphIterator> graphIter;
  1691. Owned<IPropertyTree> curGraph;
  1692. IArrayOf<IPropertyTreeIterator> treeIters;
  1693. IArrayOf<IPropertyTreeIterator> childGraphIters;
  1694. UnsignedArray scopeLengths;
  1695. UnsignedArray stateStack;
  1696. StringBuffer curScopeName;
  1697. StringBuffer scopeId;
  1698. StatisticScopeType scopeType = SSTnone;
  1699. };
  1700. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1701. {
  1702. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1703. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1704. return left->queryWfid() - right->queryWfid();
  1705. }
  1706. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1707. /*
  1708. * An implementation of IConstWUScopeIterator for the workflow information.
  1709. */
  1710. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1711. {
  1712. public:
  1713. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1714. {
  1715. ForEach(*wfIter)
  1716. workflow.append(*LINK(wfIter->query()));
  1717. workflow.sort(compareWorkflow);
  1718. }
  1719. virtual bool first() override
  1720. {
  1721. if (workflow.empty())
  1722. return false;
  1723. curWorkflow = 0;
  1724. return initWorkflowItem();
  1725. }
  1726. virtual bool next() override
  1727. {
  1728. if (!workflow.isItem(++curWorkflow))
  1729. return false;
  1730. return initWorkflowItem();
  1731. }
  1732. virtual bool nextSibling() override
  1733. {
  1734. return next();
  1735. }
  1736. virtual bool nextParent() override
  1737. {
  1738. curWorkflow = NotFound;
  1739. return false;
  1740. }
  1741. virtual bool isValid() override
  1742. {
  1743. return workflow.isItem(curWorkflow);
  1744. }
  1745. virtual const char * queryScope() const override
  1746. {
  1747. return curScope.str();
  1748. }
  1749. virtual StatisticScopeType getScopeType() const override
  1750. {
  1751. return SSTworkflow;
  1752. }
  1753. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1754. {
  1755. if (whichProperties & PTattributes)
  1756. {
  1757. {
  1758. StringBuffer scratchpad;
  1759. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1760. ForEach(*depends)
  1761. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1762. }
  1763. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1764. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1765. }
  1766. }
  1767. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1768. {
  1769. return false;
  1770. }
  1771. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1772. {
  1773. auto wf = &workflow.item(curWorkflow);
  1774. StringBufferAdaptor adaptor(scratchpad);
  1775. switch (attr)
  1776. {
  1777. case WaIdDependencyList:
  1778. {
  1779. bool first = true;
  1780. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1781. ForEach(*depends)
  1782. {
  1783. if (first)
  1784. scratchpad.append("[");
  1785. else
  1786. scratchpad.append(",");
  1787. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1788. first = false;
  1789. }
  1790. if (first)
  1791. return nullptr;
  1792. scratchpad.append("]");
  1793. return scratchpad.str();
  1794. }
  1795. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1796. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1797. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1798. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1799. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1800. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1801. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1802. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1803. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1804. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1805. case WaState: return queryWorkflowStateText(wf->queryState());
  1806. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1807. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1808. /*
  1809. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1810. virtual bool isScheduledNow() const = 0;
  1811. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1812. virtual unsigned querySchedulePriority() const = 0;
  1813. virtual bool hasScheduleCount() const = 0;
  1814. virtual unsigned queryScheduleCount() const = 0;
  1815. virtual unsigned queryRetriesAllowed() const = 0;
  1816. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1817. virtual bool queryPersistRefresh() const = 0;
  1818. virtual unsigned queryScheduleCountRemaining() const = 0;
  1819. virtual unsigned queryRetriesRemaining() const = 0;
  1820. virtual int queryFailCode() const = 0;
  1821. virtual const char * queryFailMessage() const = 0;
  1822. virtual const char * queryEventName() const = 0;
  1823. virtual const char * queryEventExtra() const = 0;
  1824. */
  1825. }
  1826. return nullptr;
  1827. }
  1828. virtual const char * queryHint(const char * kind) const
  1829. {
  1830. return nullptr;
  1831. }
  1832. protected:
  1833. bool initWorkflowItem()
  1834. {
  1835. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1836. return true;
  1837. }
  1838. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1839. {
  1840. return scratchpad.clear().append(prefix).append(value).str();
  1841. }
  1842. const char * queryOptString(IStringVal & value) const
  1843. {
  1844. const char * text = value.str();
  1845. if (!text || !*text)
  1846. return nullptr;
  1847. return text;
  1848. }
  1849. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1850. {
  1851. if (!value)
  1852. return nullptr;
  1853. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1854. }
  1855. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1856. {
  1857. StringBuffer scratchpad;
  1858. for (auto attr : attrs)
  1859. {
  1860. const char * value = queryAttribute(attr, scratchpad.clear());
  1861. if (value)
  1862. visitor.noteAttribute(attr, value);
  1863. }
  1864. }
  1865. protected:
  1866. IArrayOf<IConstWorkflowItem> workflow;
  1867. unsigned curWorkflow = 0;
  1868. StringBuffer curScope;
  1869. };
  1870. /*
  1871. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1872. */
  1873. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1874. {
  1875. class VisitorMapper : implements IWuScopeVisitor
  1876. {
  1877. public:
  1878. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1879. filter(_filter), visitor(_visitor)
  1880. {}
  1881. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1882. {
  1883. if (filter.includeStatistic(kind))
  1884. visitor.noteStatistic(kind, value, extra);
  1885. }
  1886. virtual void noteAttribute(WuAttr attr, const char * value) override
  1887. {
  1888. if (filter.includeAttribute(attr))
  1889. visitor.noteAttribute(attr, value);
  1890. }
  1891. virtual void noteHint(const char * kind, const char * value) override
  1892. {
  1893. if (filter.includeHint(kind))
  1894. visitor.noteHint(kind, value);
  1895. }
  1896. virtual void noteException(IConstWUException & exception) override
  1897. {
  1898. visitor.noteException(exception);
  1899. }
  1900. protected:
  1901. const WuScopeFilter & filter;
  1902. IWuScopeVisitor & visitor;
  1903. };
  1904. public:
  1905. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1906. {
  1907. }
  1908. void addIter(IConstWUScopeIterator * iter)
  1909. {
  1910. if (iter)
  1911. {
  1912. iters.append(OLINK(*iter));
  1913. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1914. }
  1915. }
  1916. virtual bool first() override
  1917. {
  1918. activeIterMask = 0;
  1919. ForEachItemIn(i, iters)
  1920. {
  1921. if (iters.item(i).first())
  1922. activeIterMask |= (1U << i);
  1923. }
  1924. return findNextScope();
  1925. }
  1926. virtual bool next() override
  1927. {
  1928. selectNext();
  1929. return findNextScope();
  1930. }
  1931. virtual bool nextSibling() override
  1932. {
  1933. selectNextSibling();
  1934. return findNextScope();
  1935. }
  1936. virtual bool nextParent() override
  1937. {
  1938. selectNextParent();
  1939. return findNextScope();
  1940. }
  1941. virtual bool isValid() override
  1942. {
  1943. return (activeIterMask != 0);
  1944. }
  1945. virtual const char * queryScope() const override
  1946. {
  1947. return iters.item(firstMatchIter).queryScope();
  1948. }
  1949. virtual StatisticScopeType getScopeType() const override
  1950. {
  1951. return iters.item(firstMatchIter).getScopeType();
  1952. }
  1953. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1954. {
  1955. VisitorMapper mappedVisitor(filter, visitor);
  1956. whichProperties &= filter.properties;
  1957. ForEachItemIn(i, iters)
  1958. {
  1959. if (iterMatchesCurrentScope(i))
  1960. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1961. }
  1962. }
  1963. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1964. {
  1965. ForEachItemIn(i, iters)
  1966. {
  1967. if (iterMatchesCurrentScope(i))
  1968. {
  1969. if (iters.item(i).getStat(kind, value))
  1970. return true;
  1971. }
  1972. }
  1973. return false;
  1974. }
  1975. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1976. {
  1977. ForEachItemIn(i, iters)
  1978. {
  1979. if (iterMatchesCurrentScope(i))
  1980. {
  1981. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1982. if (value)
  1983. return value;
  1984. }
  1985. }
  1986. return nullptr;
  1987. }
  1988. virtual const char * queryHint(const char * kind) const override
  1989. {
  1990. ForEachItemIn(i, iters)
  1991. {
  1992. if (iterMatchesCurrentScope(i))
  1993. {
  1994. const char * value = iters.item(i).queryHint(kind);
  1995. if (value)
  1996. return value;
  1997. }
  1998. }
  1999. return nullptr;
  2000. }
  2001. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  2002. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  2003. protected:
  2004. //Calculate which iterators contain the scope that should come next
  2005. bool findNextScope()
  2006. {
  2007. for(;;)
  2008. {
  2009. if (activeIterMask == 0)
  2010. return false;
  2011. unsigned mask = 0;
  2012. const char * scope = nullptr;
  2013. ForEachItemIn(i, iters)
  2014. {
  2015. if (isAlive(i))
  2016. {
  2017. const char * iterScope = iters.item(i).queryScope();
  2018. if (mask)
  2019. {
  2020. int compare = compareScopeName(scope, iterScope);
  2021. if (compare == 0)
  2022. {
  2023. mask |= (1U << i);
  2024. }
  2025. else if (compare > 0)
  2026. {
  2027. scope = iterScope;
  2028. mask = (1U << i);
  2029. firstMatchIter = i;
  2030. }
  2031. }
  2032. else
  2033. {
  2034. scope = iterScope;
  2035. mask = (1U << i);
  2036. firstMatchIter = i;
  2037. }
  2038. }
  2039. }
  2040. matchIterMask = mask;
  2041. while (activeScopes)
  2042. {
  2043. const char * activeScope = activeScopes.tos();
  2044. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2045. if (compareScopes(scope, activeScope) & SCchild)
  2046. break;
  2047. activeScopes.pop();
  2048. }
  2049. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2050. bool include = false;
  2051. if (activeScopes)
  2052. {
  2053. const char * activeScope = activeScopes.tos();
  2054. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2055. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2056. if (nesting <= filter.include.nestedDepth)
  2057. include = true;
  2058. }
  2059. //Check to see if this is a new match
  2060. if (filter.compareMatchScopes(scope) & SCequal)
  2061. {
  2062. if (!include)
  2063. include = filter.include.matchedScope;
  2064. //Only add it to the list of active scopes if it can match child elements
  2065. if (filter.include.nestedDepth != 0)
  2066. activeScopes.append(scope);
  2067. }
  2068. if (include && !filter.includeScope(scope))
  2069. include = false;
  2070. if (include && filter.requiredStats.size())
  2071. {
  2072. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2073. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2074. {
  2075. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2076. unsigned __int64 value;
  2077. if (getStat(cur.queryKind(), value))
  2078. {
  2079. if (!cur.matches(value))
  2080. include = false;
  2081. }
  2082. else
  2083. include = false;
  2084. }
  2085. }
  2086. if (include && filter.requiredAttrs.size())
  2087. {
  2088. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2089. StringBuffer temp;
  2090. for (unsigned iReq=0; iReq < filter.requiredAttrs.size(); iReq++)
  2091. {
  2092. const AttributeValueFilter & cur = filter.requiredAttrs[iReq];
  2093. const char * value = queryAttribute(cur.queryKind(), temp.clear());
  2094. if (!value || !cur.matches(value))
  2095. {
  2096. include = false;
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. if (include)
  2102. return true;
  2103. //MORE: Optimize based on filter.compareScope()
  2104. selectNext();
  2105. }
  2106. }
  2107. void checkScopeOrder(unsigned input, const char * prevScope)
  2108. {
  2109. if (isAlive(input))
  2110. {
  2111. const char * curScope = iters.item(input).queryScope();
  2112. int compare = compareScopeName(prevScope, curScope);
  2113. if (compare >= 0)
  2114. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2115. }
  2116. }
  2117. void selectNext()
  2118. {
  2119. ForEachItemIn(i, iters)
  2120. {
  2121. if (iterMatchesCurrentScope(i))
  2122. {
  2123. #ifdef _DEBUG
  2124. StringBuffer prevScope(iters.item(i).queryScope());
  2125. #endif
  2126. if (!iters.item(i).next())
  2127. activeIterMask &= ~(1U << i);
  2128. #ifdef _DEBUG
  2129. checkScopeOrder(i, prevScope);
  2130. #endif
  2131. }
  2132. }
  2133. }
  2134. void selectNextSibling()
  2135. {
  2136. ForEachItemIn(i, iters)
  2137. {
  2138. if (iterMatchesCurrentScope(i))
  2139. {
  2140. #ifdef _DEBUG
  2141. StringBuffer prevScope(iters.item(i).queryScope());
  2142. #endif
  2143. if (!iters.item(i).nextSibling())
  2144. activeIterMask &= ~(1U << i);
  2145. #ifdef _DEBUG
  2146. checkScopeOrder(i, prevScope);
  2147. #endif
  2148. }
  2149. }
  2150. }
  2151. void selectNextParent()
  2152. {
  2153. ForEachItemIn(i, iters)
  2154. {
  2155. if (iterMatchesCurrentScope(i))
  2156. {
  2157. #ifdef _DEBUG
  2158. StringBuffer prevScope(iters.item(i).queryScope());
  2159. #endif
  2160. if (!iters.item(i).nextParent())
  2161. activeIterMask &= ~(1U << i);
  2162. #ifdef _DEBUG
  2163. checkScopeOrder(i, prevScope);
  2164. #endif
  2165. }
  2166. }
  2167. }
  2168. protected:
  2169. const WuScopeFilter & filter;
  2170. IArrayOf<IConstWUScopeIterator> iters;
  2171. unsigned curIter = 0;
  2172. unsigned firstMatchIter = 0;
  2173. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2174. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2175. StringArray activeScopes;
  2176. };
  2177. //---------------------------------------------------------------------------------------------------------------------
  2178. class AggregateFilter
  2179. {
  2180. public:
  2181. AggregateFilter(StatisticKind _search) : search(_search) {}
  2182. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2183. {
  2184. return (kind == search);
  2185. }
  2186. protected:
  2187. StatisticKind search;
  2188. //MORE: Allow filtering by scope?
  2189. };
  2190. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2191. {
  2192. public:
  2193. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2194. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2195. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2196. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2197. protected:
  2198. AggregateFilter filter;
  2199. };
  2200. class SimpleAggregator : public StatisticAggregator
  2201. {
  2202. public:
  2203. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2204. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2205. {
  2206. if (filter.matches(kind, value, extra))
  2207. summary.noteValue(value);
  2208. }
  2209. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2210. //with a noteAggregate(value, variant, value, grouping)?
  2211. protected:
  2212. StatsAggregation summary;
  2213. };
  2214. class SimpleReferenceAggregator : public StatisticAggregator
  2215. {
  2216. public:
  2217. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2218. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2219. {
  2220. if (filter.matches(kind, value, extra))
  2221. summary.noteValue(value);
  2222. }
  2223. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2224. //with a noteAggregate(value, variant, value, grouping)?
  2225. protected:
  2226. StatsAggregation & summary;
  2227. };
  2228. class GroupedAggregator : public StatisticAggregator
  2229. {
  2230. public:
  2231. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2232. {
  2233. if (filter.matches(kind, value, extra))
  2234. {
  2235. StatsAggregation & match = summary; // look up in hash table.
  2236. match.noteValue(value);
  2237. }
  2238. }
  2239. protected:
  2240. //HashTable of (possible groupings->summary)
  2241. StatsAggregation summary;
  2242. };
  2243. class CompoundAggregator : implements StatisticAggregator
  2244. {
  2245. public:
  2246. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2247. {
  2248. ForEachItemIn(i, aggregators)
  2249. aggregators.item(i).noteStatistic(kind, value, extra);
  2250. }
  2251. protected:
  2252. IArrayOf<StatisticAggregator> aggregators;
  2253. };
  2254. // Aggregate costs excluding all hThor costs
  2255. // Note: the only reason that this class is required is that it is not possible to determine the creator
  2256. // of a scope when iterating with IConstWUScopeIterator. (When this functionlity becomes available,
  2257. // consider filtering within aggregateCost and eliminating this class.)
  2258. class CostAggregatorExcludeHThor : public CInterfaceOf<IWuScopeVisitor>
  2259. {
  2260. public:
  2261. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2262. {
  2263. if (extra.getCreatorType() != SCThthor)
  2264. totalCost += value;
  2265. }
  2266. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2267. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2268. virtual void noteException(IConstWUException & exception) { throwUnexpected(); }
  2269. virtual cost_type getTotalCost() const { return totalCost; }
  2270. protected:
  2271. cost_type totalCost = 0;
  2272. };
  2273. // Aggregrate Thor or hThor costs
  2274. cost_type aggregateCost(const IConstWorkUnit * wu, const char *scope, bool excludeHThor)
  2275. {
  2276. // depth 1: workflow, depth 2: graph, depth 3: subgraph
  2277. WuScopeFilter filter;
  2278. if (scope && *scope) // All costs under specified scope (used to calculate all costs for a workflow)
  2279. {
  2280. filter.addScope(scope);
  2281. filter.setIncludeNesting(3);
  2282. filter.addOutputStatistic(StCostExecute);
  2283. filter.addRequiredStat(StCostExecute);
  2284. }
  2285. else
  2286. filter.addFilter("stat[CostExecute],depth[1..3],nested[0],where[CostExecute]");
  2287. filter.addSource("global");
  2288. filter.finishedFilter();
  2289. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  2290. // Note: use of CostAggregatorExcludeHThor will be a slower, so use only when necessary
  2291. if (excludeHThor)
  2292. {
  2293. CostAggregatorExcludeHThor aggregator;
  2294. for (it->first(); it->isValid(); )
  2295. {
  2296. it->playProperties(aggregator);
  2297. stat_type value;
  2298. if (it->getStat(StCostExecute, value))
  2299. it->nextSibling();
  2300. else
  2301. it->next();
  2302. }
  2303. return aggregator.getTotalCost();
  2304. }
  2305. else
  2306. {
  2307. cost_type totalCost = 0;
  2308. for (it->first(); it->isValid(); )
  2309. {
  2310. stat_type value = 0.0;
  2311. if (it->getStat(StCostExecute, value))
  2312. {
  2313. totalCost += value;
  2314. it->nextSibling();
  2315. }
  2316. else
  2317. it->next();
  2318. }
  2319. return totalCost;
  2320. }
  2321. }
  2322. //---------------------------------------------------------------------------------------------------------------------
  2323. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2324. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2325. {
  2326. const char * start = finger;
  2327. if (!*start)
  2328. return false;
  2329. const char * cur = start;
  2330. const char * bra = nullptr;
  2331. const char * end = nullptr;
  2332. unsigned braDepth = 0;
  2333. char next;
  2334. arg.clear();
  2335. for (;;)
  2336. {
  2337. next = *cur;
  2338. if (!next || ((next == ',') && (braDepth == 0)))
  2339. break;
  2340. switch (next)
  2341. {
  2342. case '[':
  2343. if (braDepth == 0)
  2344. {
  2345. if (bra)
  2346. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2347. bra = cur;
  2348. }
  2349. braDepth++;
  2350. break;
  2351. case ']':
  2352. if (braDepth > 0)
  2353. {
  2354. if (--braDepth == 0)
  2355. {
  2356. end = cur;
  2357. arg.append(cur - (bra+1), bra+1);
  2358. }
  2359. }
  2360. break;
  2361. }
  2362. cur++;
  2363. }
  2364. if (braDepth != 0)
  2365. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2366. option.clear();
  2367. if (bra)
  2368. {
  2369. if (cur != end+1)
  2370. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2371. option.append(bra-start, start);
  2372. }
  2373. else
  2374. option.append(cur-start, start);
  2375. if (next)
  2376. finger = cur+1;
  2377. else
  2378. finger = cur;
  2379. return true;
  2380. }
  2381. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2382. {
  2383. if (start == end)
  2384. return dft;
  2385. char * next;
  2386. unsigned value = (unsigned)strtoll(start, &next, 10);
  2387. if (next != end)
  2388. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2389. return value;
  2390. }
  2391. static unsigned readValue(const char * start, const char * type)
  2392. {
  2393. if (*start == '\0')
  2394. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2395. char * next;
  2396. unsigned value = (unsigned)strtoll(start, &next, 10);
  2397. if (*next != '\0')
  2398. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2399. return value;
  2400. }
  2401. StringBuffer & AttributeValueFilter::describe(StringBuffer & out) const
  2402. {
  2403. out.append(queryWuAttributeName(attr));
  2404. if (value)
  2405. out.append("=").append(value);
  2406. return out;
  2407. }
  2408. /*
  2409. Scope service matching Syntax: * indicates
  2410. Which items are matched:
  2411. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2412. depth[n | low..high] - range of depths to search for a match
  2413. source[global|stats|graph|all]* - which sources to search within the workunit
  2414. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2415. Which items are include in the results:
  2416. matched[true|false] - are the matched scopes returned?
  2417. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2418. includetype[<scope-type>] - which scope types should be included?
  2419. Which properties of the items are returned:
  2420. properties[statistics|hints|attributes|scope|all]
  2421. statistic[<statistic-kind>|none|all] - include statistic
  2422. attribute[<attribute-name>|none|all] - include attribute
  2423. hint[<hint-name>] - include hint
  2424. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2425. measure[<measure>] - all statistics with a particular measure
  2426. version[<version>] - minimum version to return
  2427. */
  2428. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2429. //Some of the following contains aliases for the same option e.g. stat and statistic
  2430. static constexpr EnumMapping filterOptions[] = {
  2431. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2432. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2433. { FOmatched, "matched" }, { FOnested, "nested" },
  2434. { FOinclude, "include" }, { FOinclude, "includetype" },
  2435. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2436. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2437. { FOproperty, "prop" }, { FOproperty, "property" },
  2438. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2439. static constexpr EnumMapping sourceMappings[] = {
  2440. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2441. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2442. static constexpr EnumMapping propertyMappings[] = {
  2443. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2444. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2445. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2446. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2447. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2448. WuScopeFilter::WuScopeFilter(const char * filter)
  2449. {
  2450. addFilter(filter);
  2451. finishedFilter();
  2452. }
  2453. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2454. {
  2455. checkModifiable();
  2456. if (!filter)
  2457. return *this;
  2458. StringBuffer option;
  2459. StringBuffer arg;
  2460. while (extractOption(filter, option, arg))
  2461. {
  2462. switch (getEnum(option, filterOptions, FOunknown))
  2463. {
  2464. case FOscope:
  2465. addScope(arg);
  2466. break;
  2467. case FOstype:
  2468. addScopeType(arg);
  2469. break;
  2470. case FOid:
  2471. addId(arg);
  2472. break;
  2473. case FOdepth:
  2474. {
  2475. //Allow depth[n], depth[a,b] or depth[a..b]
  2476. const char * comma = strchr(arg, ',');
  2477. const char * dotdot = strstr(arg, "..");
  2478. if (comma)
  2479. {
  2480. unsigned low = readOptValue(arg, comma, 0, "depth");
  2481. if (comma[1])
  2482. {
  2483. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2484. }
  2485. else
  2486. scopeFilter.setDepth(low, UINT_MAX);
  2487. }
  2488. else if (dotdot)
  2489. {
  2490. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2491. if (dotdot[2])
  2492. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2493. else
  2494. scopeFilter.setDepth(low, UINT_MAX);
  2495. }
  2496. else
  2497. {
  2498. scopeFilter.setDepth(readValue(arg, "depth"));
  2499. }
  2500. break;
  2501. }
  2502. case FOsource:
  2503. addSource(arg);
  2504. break;
  2505. case FOwhere: // where[stat<op>value]
  2506. addRequiredStat(arg);
  2507. break;
  2508. case FOmatched:
  2509. setIncludeMatch(strToBool(arg));
  2510. break;
  2511. case FOnested:
  2512. if (strieq(arg, "all"))
  2513. setIncludeNesting(UINT_MAX);
  2514. else if (isdigit(*arg))
  2515. setIncludeNesting(atoi(arg));
  2516. else
  2517. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2518. break;
  2519. case FOinclude:
  2520. setIncludeScopeType(arg);
  2521. break;
  2522. case FOproperties:
  2523. {
  2524. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2525. if (prop == PTunknown)
  2526. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2527. addOutputProperties(prop);
  2528. break;
  2529. }
  2530. case FOstatistic:
  2531. addOutputStatistic(arg);
  2532. break;
  2533. case FOattribute:
  2534. addOutputAttribute(arg);
  2535. break;
  2536. case FOhint:
  2537. addOutputHint(arg);
  2538. break;
  2539. case FOproperty:
  2540. addOutput(arg);
  2541. break;
  2542. case FOmeasure:
  2543. setMeasure(arg);
  2544. break;
  2545. case FOversion:
  2546. if (isdigit(*arg))
  2547. minVersion = atoi64(arg);
  2548. else
  2549. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2550. break;
  2551. default:
  2552. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2553. }
  2554. }
  2555. return *this;
  2556. }
  2557. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2558. {
  2559. checkModifiable();
  2560. if (scope)
  2561. {
  2562. validateScope(scope);
  2563. scopeFilter.addScope(scope);
  2564. }
  2565. return *this;
  2566. }
  2567. WuScopeFilter & WuScopeFilter::addScopeType(StatisticScopeType scopeType)
  2568. {
  2569. checkModifiable();
  2570. scopeFilter.addScopeType(scopeType);
  2571. return *this;
  2572. }
  2573. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2574. {
  2575. checkModifiable();
  2576. if (scopeType)
  2577. {
  2578. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2579. if (sst == SSTmax)
  2580. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2581. scopeFilter.addScopeType(sst);
  2582. }
  2583. return *this;
  2584. }
  2585. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2586. {
  2587. checkModifiable();
  2588. validateScopeId(id);
  2589. scopeFilter.addId(id);
  2590. return *this;
  2591. }
  2592. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2593. {
  2594. checkModifiable();
  2595. WuAttr attr = queryWuAttribute(prop, WaNone);
  2596. if (attr != WaNone)
  2597. {
  2598. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2599. if (singleKindAttr != WaNone)
  2600. addOutputAttribute(singleKindAttr);
  2601. else
  2602. addOutputAttribute(attr);
  2603. } else if (queryStatisticKind(prop, StMax) != StMax)
  2604. addOutputStatistic(prop);
  2605. else
  2606. addOutputHint(prop);
  2607. return *this;
  2608. }
  2609. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2610. {
  2611. checkModifiable();
  2612. if (!prop)
  2613. return *this;
  2614. StatisticKind kind = queryStatisticKind(prop, StMax);
  2615. if (kind == StMax)
  2616. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2617. return addOutputStatistic(kind);
  2618. }
  2619. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2620. {
  2621. checkModifiable();
  2622. if (stat != StKindNone)
  2623. {
  2624. if (stat != StKindAll)
  2625. desiredStats.append(stat);
  2626. else
  2627. desiredStats.kill();
  2628. properties |= PTstatistics;
  2629. }
  2630. else
  2631. properties &= ~PTstatistics;
  2632. return *this;
  2633. }
  2634. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2635. {
  2636. checkModifiable();
  2637. if (!prop)
  2638. return *this;
  2639. WuAttr attr = queryWuAttribute(prop, WaMax);
  2640. if (attr == WaMax)
  2641. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2642. return addOutputAttribute(attr);
  2643. }
  2644. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2645. {
  2646. checkModifiable();
  2647. if (attr != WaNone)
  2648. {
  2649. if (attr != WaAll)
  2650. desiredAttrs.append(attr);
  2651. else
  2652. desiredAttrs.kill();
  2653. properties |= PTattributes;
  2654. }
  2655. else
  2656. properties &= ~PTattributes;
  2657. return *this;
  2658. }
  2659. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2660. {
  2661. checkModifiable();
  2662. if (strieq(prop, "none"))
  2663. {
  2664. desiredHints.kill();
  2665. properties &= ~PThints;
  2666. }
  2667. else
  2668. {
  2669. if (!strieq(prop, "all"))
  2670. desiredHints.append(prop);
  2671. else
  2672. desiredHints.kill();
  2673. properties |= PThints;
  2674. }
  2675. return *this;
  2676. }
  2677. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2678. {
  2679. checkModifiable();
  2680. include.matchedScope = value;
  2681. return *this;
  2682. }
  2683. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2684. {
  2685. checkModifiable();
  2686. include.nestedDepth = depth;
  2687. return *this;
  2688. }
  2689. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2690. {
  2691. checkModifiable();
  2692. if (scopeType)
  2693. {
  2694. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2695. if (sst == SSTmax)
  2696. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2697. include.scopeTypes.append(sst);
  2698. }
  2699. return *this;
  2700. }
  2701. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2702. {
  2703. checkModifiable();
  2704. if (measure)
  2705. {
  2706. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2707. if (desiredMeasure == SMeasureNone)
  2708. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2709. properties |= PTstatistics;
  2710. }
  2711. return *this;
  2712. }
  2713. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2714. {
  2715. checkModifiable();
  2716. if (properties == PTnone)
  2717. properties = mask;
  2718. else
  2719. properties |= mask;
  2720. return *this;
  2721. }
  2722. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2723. {
  2724. checkModifiable();
  2725. requiredStats.emplace_back(statKind, lowValue, highValue);
  2726. return *this;
  2727. }
  2728. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2729. {
  2730. checkModifiable();
  2731. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2732. return *this;
  2733. }
  2734. WuScopeFilter & WuScopeFilter::addRequiredAttr(WuAttr attr, const char * value)
  2735. {
  2736. checkModifiable();
  2737. requiredAttrs.emplace_back(attr, value);
  2738. return *this;
  2739. }
  2740. //process a filter in one of the following forms:
  2741. // <statistic-name>
  2742. // <statistic-name> (=|<|<=|>|>=) <value>
  2743. // <statistic-name>=[<low>]..[<high>]
  2744. void WuScopeFilter::addRequiredStat(const char * filter)
  2745. {
  2746. checkModifiable();
  2747. const char * stat = filter;
  2748. const char * cur = stat;
  2749. while (isalpha(*cur))
  2750. cur++;
  2751. StringBuffer statisticName(cur-stat, stat);
  2752. //Skip any spaces before a comparison operator.
  2753. while (*cur && isspace(*cur))
  2754. cur++;
  2755. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2756. if (statKind == StKindNone)
  2757. {
  2758. WuAttr attr = queryWuAttribute(statisticName, WaNone);
  2759. if (attr == WaNone)
  2760. throw makeStringExceptionV(0, "Unknown property name '%s'", statisticName.str());
  2761. if (*cur == '=')
  2762. requiredAttrs.emplace_back(attr, cur+1);
  2763. else if (*cur == '\0')
  2764. requiredAttrs.emplace_back(attr, nullptr);
  2765. else
  2766. throw makeStringExceptionV(0, "Unknown attribute comparison '%s'", cur);
  2767. return;
  2768. }
  2769. //Save the operator, and skip over any non digits.
  2770. const char * op = cur;
  2771. switch (*op)
  2772. {
  2773. case '=':
  2774. cur++;
  2775. break;
  2776. case '<':
  2777. case '>':
  2778. if (op[1] == '=')
  2779. cur += 2;
  2780. else
  2781. cur++;
  2782. break;
  2783. case '\0':
  2784. break;
  2785. default:
  2786. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2787. }
  2788. const char * next;
  2789. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2790. stat_type lowValue = 0;
  2791. stat_type highValue = MaxStatisticValue;
  2792. switch (op[0])
  2793. {
  2794. case '=':
  2795. {
  2796. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2797. if (next[0] == ',')
  2798. {
  2799. lowValue = value;
  2800. next++;
  2801. if (*next != '\0')
  2802. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2803. }
  2804. else if (strncmp(next, "..", 2) == 0)
  2805. {
  2806. lowValue = value;
  2807. next += 2;
  2808. if (*next != '\0')
  2809. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2810. }
  2811. else
  2812. {
  2813. lowValue = value;
  2814. highValue = value;
  2815. }
  2816. break;
  2817. }
  2818. case '<':
  2819. if (op[1] == '=')
  2820. highValue = value;
  2821. else
  2822. highValue = value-1;
  2823. break;
  2824. case '>':
  2825. if (op[1] == '=')
  2826. lowValue = value;
  2827. else
  2828. lowValue = value+1;
  2829. break;
  2830. }
  2831. if (*next)
  2832. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2833. requiredStats.emplace_back(statKind, lowValue, highValue);
  2834. }
  2835. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2836. {
  2837. checkModifiable();
  2838. WuScopeSourceFlags mask = querySource(source);
  2839. if (mask == SSFunknown)
  2840. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2841. if (!mask)
  2842. sourceFlags = mask;
  2843. else
  2844. sourceFlags |= mask;
  2845. return *this;
  2846. }
  2847. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2848. {
  2849. checkModifiable();
  2850. scopeFilter.setDepth(low, high);
  2851. return *this;
  2852. }
  2853. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2854. {
  2855. //If there is a post filter on the scopeType, then check if it matches
  2856. if (include.scopeTypes.ordinality() == 1)
  2857. return (include.scopeTypes.item(0) == scopeType);
  2858. //If filter doesn't match nested items, then check if the scope filter matches.
  2859. if (include.nestedDepth == 0)
  2860. {
  2861. if (scopeFilter.matchOnly(scopeType))
  2862. return true;
  2863. }
  2864. return false;
  2865. }
  2866. void WuScopeFilter::reportModifyTooLate()
  2867. {
  2868. throw makeStringException(WUERR_ModifyFilterAfterFinalize, "Attempting to modify WuScopefilter after finish() has been called");
  2869. }
  2870. //Called once the filter has been updated to optimize the filter
  2871. void WuScopeFilter::finishedFilter()
  2872. {
  2873. if (optimized)
  2874. throw makeStringException(WUERR_FinalizeAfterFinalize, "Calling finishedFilter() more than once");
  2875. scopeFilter.finishedFilter();
  2876. if ((include.nestedDepth == 0) && !include.matchedScope)
  2877. include.nestedDepth = UINT_MAX;
  2878. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2879. if (scopeFilter.canAlwaysPreFilter())
  2880. preFilterScope = true;
  2881. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2882. if (!sourceFlags)
  2883. {
  2884. sourceFlags = SSFsearchAll;
  2885. //Use the other options to reduce the number of elements that are searched.
  2886. //If not interested in scopes on their own then...
  2887. if (!(properties & PTscope))
  2888. {
  2889. //Global stats and graph stats only contain stats => remove if not interested in them
  2890. if (!(properties & PTstatistics) && (requiredStats.size() == 0))
  2891. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2892. //graph, workflow only contains attributes and hints => remove if not interested
  2893. if (!(properties & (PTattributes|PThints)) && (requiredAttrs.size() == 0))
  2894. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2895. }
  2896. if (!(properties & PTnotes))
  2897. sourceFlags &= ~SSFsearchExceptions;
  2898. }
  2899. //Optimize sources if they haven't been explicitly specified
  2900. //Most of the following are dependent on internal knowledge of the way that information is represented
  2901. if (matchOnly(SSTworkflow))
  2902. {
  2903. //Workflow is not nested within a graph
  2904. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2905. setDepth(1, 1);
  2906. }
  2907. else if (matchOnly(SSTgraph))
  2908. {
  2909. //Graph starts are stored globally, not in the graph stats.
  2910. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2911. if (!(properties & (PTattributes|PThints)))
  2912. sourceFlags &= ~(SSFsearchGraph);
  2913. //This should really be setDepth(2,2) but workunits prior to 7.4 did not have graph ids prefixed by the wfid
  2914. //Remove once 7.2 is a distant memory (see HPCC-22887)
  2915. setDepth(1, 2);
  2916. }
  2917. else if (matchOnly(SSTsubgraph))
  2918. {
  2919. sourceFlags &= ~(SSFsearchWorkflow);
  2920. }
  2921. else if (matchOnly(SSTcompilestage))
  2922. {
  2923. //compile stages are not stored in the graph
  2924. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2925. }
  2926. else if (matchOnly(SSTactivity))
  2927. {
  2928. //information about activities is not stored globally
  2929. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2930. }
  2931. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2932. if (include.nestedDepth == 0)
  2933. {
  2934. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2935. sourceFlags &= ~(SSFsearchGraphStats);
  2936. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2937. {
  2938. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2939. //then do not include the subgraph timings
  2940. if (desiredStats.ordinality())
  2941. {
  2942. bool needGraphStats = false;
  2943. ForEachItemIn(i, desiredStats)
  2944. {
  2945. unsigned stat = desiredStats.item(i);
  2946. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2947. needGraphStats = true;
  2948. }
  2949. if (!needGraphStats)
  2950. {
  2951. sourceFlags &= ~(SSFsearchGraphStats);
  2952. if (matchOnly(SSTsubgraph))
  2953. sourceFlags &= SSFsearchGlobalStats;
  2954. }
  2955. }
  2956. }
  2957. }
  2958. if (scopeFilter.compareDepth(1) < 0)
  2959. {
  2960. //If minimum match depth is > 1 then it will never match workflow
  2961. sourceFlags &= ~(SSFsearchWorkflow);
  2962. }
  2963. //The xml graph is never updated, so do not check it if minVersion != 0
  2964. if (minVersion != 0)
  2965. {
  2966. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2967. }
  2968. optimized = true;
  2969. }
  2970. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2971. {
  2972. if (!(properties & PTstatistics))
  2973. return false;
  2974. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2975. return false;
  2976. if (desiredStats.empty())
  2977. return true;
  2978. return desiredStats.contains(kind);
  2979. }
  2980. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2981. {
  2982. if (!(properties & PTattributes))
  2983. return false;
  2984. if (desiredAttrs.empty())
  2985. return true;
  2986. return desiredAttrs.contains(attr);
  2987. }
  2988. bool WuScopeFilter::includeHint(const char * kind) const
  2989. {
  2990. if (!(properties & PThints))
  2991. return false;
  2992. if (desiredHints.empty())
  2993. return true;
  2994. return desiredHints.contains(kind);
  2995. }
  2996. bool WuScopeFilter::includeScope(const char * scope) const
  2997. {
  2998. if (include.scopeTypes)
  2999. {
  3000. const char * tail = queryScopeTail(scope);
  3001. StatsScopeId id(tail);
  3002. if (!include.scopeTypes.contains(id.queryScopeType()))
  3003. return false;
  3004. }
  3005. return true;
  3006. }
  3007. const static ScopeFilter nullScopeFilter {};
  3008. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  3009. {
  3010. if (preFilterScope)
  3011. return scopeFilter;
  3012. else
  3013. return nullScopeFilter;
  3014. }
  3015. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  3016. {
  3017. return scopeFilter.compare(scope);
  3018. }
  3019. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  3020. {
  3021. scopeFilter.describe(out);
  3022. if (requiredStats.size() || requiredAttrs.size())
  3023. {
  3024. out.append(",where[");
  3025. bool first = false;
  3026. for (const auto & stat : requiredStats)
  3027. {
  3028. if (!first)
  3029. out.append(",");
  3030. stat.describe(out);
  3031. first = false;
  3032. }
  3033. for (const auto & attr : requiredAttrs)
  3034. {
  3035. if (!first)
  3036. out.append(",");
  3037. attr.describe(out);
  3038. first = false;
  3039. }
  3040. out.append("]");
  3041. }
  3042. {
  3043. StringBuffer sources;
  3044. for (unsigned mask=1; mask; mask *= 2)
  3045. {
  3046. if (sourceFlags & mask)
  3047. {
  3048. const char * source = querySourceText((WuScopeSourceFlags)mask);
  3049. if (source)
  3050. sources.append(",").append(source);
  3051. }
  3052. }
  3053. if (sources)
  3054. out.append(",source[").append(sources.str()+1).append("]");
  3055. }
  3056. if (include.nestedDepth != UINT_MAX)
  3057. out.appendf(",nested[%u]", include.nestedDepth);
  3058. if (include.scopeTypes)
  3059. {
  3060. out.append(",include[");
  3061. ForEachItemIn(i, include.scopeTypes)
  3062. {
  3063. if (i)
  3064. out.append(",");
  3065. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  3066. }
  3067. out.append("]");
  3068. }
  3069. {
  3070. StringBuffer props;
  3071. if (properties == PTnone)
  3072. props.append(",none");
  3073. else if (properties == PTall)
  3074. props.append(",all");
  3075. else
  3076. {
  3077. if (properties & PTstatistics)
  3078. props.append(",stat");
  3079. if (properties & PTattributes)
  3080. props.append(",attr");
  3081. if (properties & PThints)
  3082. props.append(",hint");
  3083. if (properties & PTscope)
  3084. props.append(",scope");
  3085. if (properties & PTnotes)
  3086. props.append(",note");
  3087. }
  3088. out.append(",properties[").append(props.str()+1).append("]");
  3089. }
  3090. if (desiredStats)
  3091. {
  3092. out.append(",stat[");
  3093. ForEachItemIn(i, desiredStats)
  3094. {
  3095. if (i)
  3096. out.append(",");
  3097. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  3098. }
  3099. out.append("]");
  3100. }
  3101. if (desiredAttrs)
  3102. {
  3103. out.append(",attr[");
  3104. ForEachItemIn(i, desiredAttrs)
  3105. {
  3106. if (i)
  3107. out.append(",");
  3108. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  3109. }
  3110. out.append("]");
  3111. }
  3112. if (desiredHints)
  3113. {
  3114. out.append(",hint[");
  3115. ForEachItemIn(i, desiredHints)
  3116. {
  3117. if (i)
  3118. out.append(",");
  3119. out.append(desiredHints.item(i));
  3120. }
  3121. out.append("]");
  3122. }
  3123. if (desiredMeasure != SMeasureAll)
  3124. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  3125. if (minVersion != 0)
  3126. out.appendf(",version(%" I64F "u)", minVersion);
  3127. return out;
  3128. }
  3129. //--------------------------------------------------------------------------------------------------------------------
  3130. EnumMapping states[] = {
  3131. { WUStateUnknown, "unknown" },
  3132. { WUStateCompiled, "compiled" },
  3133. { WUStateRunning, "running" },
  3134. { WUStateCompleted, "completed" },
  3135. { WUStateFailed, "failed" },
  3136. { WUStateArchived, "archived" },
  3137. { WUStateAborting, "aborting" },
  3138. { WUStateAborted, "aborted" },
  3139. { WUStateBlocked, "blocked" },
  3140. { WUStateSubmitted, "submitted" },
  3141. { WUStateScheduled, "scheduled" },
  3142. { WUStateCompiling, "compiling" },
  3143. { WUStateWait, "wait" },
  3144. { WUStateUploadingFiles, "uploading_files" },
  3145. { WUStateDebugPaused, "debugging" },
  3146. { WUStateDebugRunning, "debug_running" },
  3147. { WUStatePaused, "paused" },
  3148. { WUStateSize, NULL }
  3149. };
  3150. EnumMapping actions[] = {
  3151. { WUActionUnknown, "unknown" },
  3152. { WUActionCompile, "compile" },
  3153. { WUActionCheck, "check" },
  3154. { WUActionRun, "run" },
  3155. { WUActionExecuteExisting, "execute" },
  3156. { WUActionPause, "pause" },
  3157. { WUActionPauseNow, "pausenow" },
  3158. { WUActionResume, "resume" },
  3159. { WUActionSize, NULL },
  3160. };
  3161. EnumMapping priorityClasses[] = {
  3162. { PriorityClassUnknown, "unknown" },
  3163. { PriorityClassLow, "low" },
  3164. { PriorityClassNormal, "normal" },
  3165. { PriorityClassHigh, "high" },
  3166. { PriorityClassSize, NULL },
  3167. };
  3168. const char * getWorkunitStateStr(WUState state)
  3169. {
  3170. dbgassertex(state < WUStateSize);
  3171. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3172. }
  3173. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3174. {
  3175. const char *defval = map->str;
  3176. while (map->str)
  3177. {
  3178. if (value==map->val)
  3179. {
  3180. p->setProp(propname, map->str);
  3181. return;
  3182. }
  3183. map++;
  3184. }
  3185. assertex(!"Unexpected value in setEnum");
  3186. p->setProp(propname, defval);
  3187. }
  3188. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3189. {
  3190. return getEnum(p->queryProp(propname),map);
  3191. }
  3192. const char * getWorkunitActionStr(WUAction action)
  3193. {
  3194. return getEnumText(action, actions);
  3195. }
  3196. WUAction getWorkunitAction(const char *actionStr)
  3197. {
  3198. return (WUAction) getEnum(actionStr, actions);
  3199. }
  3200. //==========================================================================================
  3201. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3202. {
  3203. public:
  3204. CLightweightWorkunitInfo(IPropertyTree &p)
  3205. {
  3206. wuid.set(p.queryName());
  3207. user.set(p.queryProp("@submitID"));
  3208. jobName.set(p.queryProp("@jobName"));
  3209. clusterName.set(p.queryProp("@clusterName"));
  3210. timeScheduled.set(p.queryProp("@timeScheduled"));
  3211. state = (WUState) getEnum(&p, "@state", states);
  3212. action = (WUAction) getEnum(&p, "Action", actions);
  3213. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3214. priorityLevel = calcPriorityValue(&p);
  3215. wuscope.set(p.queryProp("@scope"));
  3216. appvalues.loadBranch(&p,"Application");
  3217. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3218. _isProtected = p.getPropBool("@protected", false);
  3219. }
  3220. virtual const char *queryWuid() const { return wuid.str(); }
  3221. virtual const char *queryUser() const { return user.str(); }
  3222. virtual const char *queryJobName() const { return jobName.str(); }
  3223. virtual const char *queryClusterName() const { return clusterName.str(); }
  3224. virtual const char *queryWuScope() const { return wuscope.str(); }
  3225. virtual WUState getState() const { return state; }
  3226. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3227. virtual WUAction getAction() const { return action; }
  3228. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3229. virtual WUPriorityClass getPriority() const { return priority; }
  3230. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3231. virtual int getPriorityLevel() const { return priorityLevel; }
  3232. virtual bool isProtected() const { return _isProtected; }
  3233. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3234. {
  3235. if (timeScheduled.length())
  3236. val.setGmtString(timeScheduled.str());
  3237. return val;
  3238. }
  3239. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3240. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3241. protected:
  3242. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3243. mutable CachedWUAppValues appvalues;
  3244. unsigned totalThorTime;
  3245. WUState state;
  3246. WUAction action;
  3247. WUPriorityClass priority;
  3248. int priorityLevel;
  3249. bool _isProtected;
  3250. };
  3251. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3252. {
  3253. return new CLightweightWorkunitInfo(p);
  3254. }
  3255. class CDaliWuGraphStats : public CWuGraphStats
  3256. {
  3257. public:
  3258. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3259. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3260. {
  3261. }
  3262. protected:
  3263. Owned<IRemoteConnection> conn;
  3264. };
  3265. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3266. {
  3267. abortId = 0;
  3268. stateId = 0;
  3269. actionId = 0;
  3270. assertex((flags & ~SubscribeOptionAbort) == 0);
  3271. if (flags & SubscribeOptionAbort)
  3272. {
  3273. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3274. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3275. }
  3276. }
  3277. CWorkUnitWatcher::~CWorkUnitWatcher()
  3278. {
  3279. assertex(abortId==0 && stateId==0 && actionId==0);
  3280. }
  3281. void CWorkUnitWatcher::unsubscribe()
  3282. {
  3283. CriticalBlock b(crit);
  3284. if (abortId)
  3285. querySDS().unsubscribe(abortId);
  3286. if (stateId)
  3287. querySDS().unsubscribe(stateId);
  3288. if (actionId)
  3289. querySDS().unsubscribe(actionId);
  3290. abortId = 0;
  3291. stateId = 0;
  3292. actionId = 0;
  3293. }
  3294. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3295. {
  3296. CriticalBlock b(crit);
  3297. if (id==stateId)
  3298. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3299. else if (id==actionId)
  3300. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3301. else if (id==abortId)
  3302. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3303. }
  3304. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3305. {
  3306. public:
  3307. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3308. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3309. {
  3310. if (flags & SubscribeOptionState)
  3311. {
  3312. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3313. stateId = querySDS().subscribe(xpath.str(), *this);
  3314. }
  3315. if (flags & SubscribeOptionAction)
  3316. {
  3317. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3318. actionId = querySDS().subscribe(xpath.str(), *this);
  3319. }
  3320. }
  3321. };
  3322. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3323. {
  3324. CriticalBlock block(crit);
  3325. assertex(options==SubscribeOptionAbort);
  3326. if (!abortWatcher)
  3327. {
  3328. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3329. abortDirty = true;
  3330. }
  3331. }
  3332. void CPersistedWorkUnit::unsubscribe()
  3333. {
  3334. CriticalBlock block(crit);
  3335. if (abortWatcher)
  3336. {
  3337. abortWatcher->unsubscribe();
  3338. abortWatcher.clear();
  3339. }
  3340. }
  3341. bool CPersistedWorkUnit::aborting() const
  3342. {
  3343. CriticalBlock block(crit);
  3344. if (abortDirty)
  3345. {
  3346. StringBuffer apath;
  3347. apath.append("/WorkUnitAborts/").append(p->queryName());
  3348. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3349. if (acon)
  3350. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3351. else
  3352. abortState = false;
  3353. abortDirty = false;
  3354. }
  3355. return abortState;
  3356. }
  3357. class CDaliWorkUnit : public CPersistedWorkUnit
  3358. {
  3359. public:
  3360. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3361. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3362. {
  3363. loadPTree(connection->getRoot());
  3364. }
  3365. ~CDaliWorkUnit()
  3366. {
  3367. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3368. // We use the beforeDispose() in base class to help ensure this
  3369. p.clear();
  3370. }
  3371. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3372. {
  3373. Owned<IRemoteConnection> conn = getProgressConnection();
  3374. if (conn)
  3375. {
  3376. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3377. if (progress)
  3378. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3379. }
  3380. return NULL;
  3381. }
  3382. virtual WUGraphState queryGraphState(const char *graphName) const
  3383. {
  3384. Owned<IRemoteConnection> conn = getProgressConnection();
  3385. if (conn)
  3386. {
  3387. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3388. if (progress)
  3389. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3390. }
  3391. return WUGraphUnknown;
  3392. }
  3393. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3394. {
  3395. Owned<IRemoteConnection> conn = getProgressConnection();
  3396. if (conn)
  3397. {
  3398. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3399. if (progress)
  3400. {
  3401. StringBuffer path;
  3402. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3403. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3404. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3405. }
  3406. }
  3407. return WUGraphUnknown;
  3408. }
  3409. virtual void clearGraphProgress() const
  3410. {
  3411. CriticalBlock block(crit);
  3412. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3413. StringBuffer path("/GraphProgress/");
  3414. path.append(p->queryName());
  3415. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3416. if (delconn)
  3417. delconn->close(true);
  3418. }
  3419. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3420. {
  3421. Owned<IRemoteConnection> conn = getProgressConnection();
  3422. if (!conn)
  3423. return false;
  3424. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3425. if (name)
  3426. {
  3427. graphName.set(name);
  3428. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3429. return true;
  3430. }
  3431. else
  3432. return false;
  3433. }
  3434. virtual void forceReload()
  3435. {
  3436. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3437. CriticalBlock block(crit);
  3438. clearCached(true);
  3439. connection->reload();
  3440. progressConnection.clear();
  3441. abortDirty = true;
  3442. p.setown(connection->getRoot());
  3443. }
  3444. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3445. {
  3446. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3447. clearGraphProgress();
  3448. connection->close(true);
  3449. connection.clear();
  3450. }
  3451. virtual void commit()
  3452. {
  3453. CPersistedWorkUnit::commit();
  3454. if (connection)
  3455. connection->commit();
  3456. }
  3457. virtual void _lockRemote()
  3458. {
  3459. StringBuffer wuRoot;
  3460. getXPath(wuRoot, p->queryName());
  3461. if (connection)
  3462. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3463. else
  3464. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3465. if (!connection)
  3466. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3467. clearCached(true);
  3468. p.setown(connection->getRoot());
  3469. }
  3470. virtual void _unlockRemote()
  3471. {
  3472. if (connection)
  3473. {
  3474. try
  3475. {
  3476. try
  3477. {
  3478. connection->commit();
  3479. }
  3480. catch (IException *e)
  3481. {
  3482. EXCLOG(e, "Error during workunit commit");
  3483. connection->rollback();
  3484. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3485. throw;
  3486. }
  3487. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3488. }
  3489. catch (IException *E)
  3490. {
  3491. StringBuffer s;
  3492. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3493. throw;
  3494. }
  3495. }
  3496. }
  3497. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3498. {
  3499. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3500. conn->queryRoot()->setPropInt("@_state", state);
  3501. }
  3502. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3503. {
  3504. CriticalBlock block(crit);
  3505. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3506. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3507. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3508. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3509. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3510. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3511. IPropertyTree *node = progress->queryPropTree(path.str());
  3512. if (!node)
  3513. {
  3514. node = progress->addPropTree("node");
  3515. node->setPropInt64("@id", nodeId);
  3516. }
  3517. node->setPropInt("@_state", (unsigned)state);
  3518. switch (state)
  3519. {
  3520. case WUGraphRunning:
  3521. {
  3522. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3523. running->setProp("@graph", graphName);
  3524. running->setPropInt64("@subId", nodeId);
  3525. break;
  3526. }
  3527. case WUGraphComplete:
  3528. {
  3529. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3530. break;
  3531. }
  3532. }
  3533. }
  3534. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3535. {
  3536. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3537. }
  3538. virtual void import(IPropertyTree *wuTree, IPropertyTree *graphProgressTree)
  3539. {
  3540. connection->queryRoot()->setPropTree(nullptr, LINK(wuTree));
  3541. loadPTree(connection->getRoot());
  3542. if (!graphProgressTree)
  3543. return;
  3544. VStringBuffer xpath("/GraphProgress/%s", queryWuid());
  3545. Owned<IRemoteConnection> progressConn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  3546. if (!progressConn)
  3547. throw MakeStringException(0, "Failed to access %s.", xpath.str());
  3548. progressConn->queryRoot()->setPropTree(nullptr, LINK(graphProgressTree));
  3549. }
  3550. protected:
  3551. IRemoteConnection *getProgressConnection() const
  3552. {
  3553. CriticalBlock block(crit);
  3554. if (!progressConnection)
  3555. {
  3556. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3557. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3558. }
  3559. return progressConnection.getLink();
  3560. }
  3561. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3562. {
  3563. CriticalBlock block(crit);
  3564. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3565. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3566. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3567. IPropertyTree * root = conn->queryRoot();
  3568. assertex(wfid);
  3569. if (!root->hasProp("@wfid"))
  3570. {
  3571. root->setPropInt("@wfid", wfid);
  3572. }
  3573. else
  3574. {
  3575. //Ideally the following code would check that the wfids are passed consistently.
  3576. //However there is an obscure problem with out of line functions being called from multiple workflow
  3577. //ids, and possibly library graphs.
  3578. //Stats for library graphs should be nested below the library call activity
  3579. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3580. }
  3581. return conn.getClear();
  3582. }
  3583. IPropertyTree *getGraphProgressTree() const
  3584. {
  3585. Owned<IRemoteConnection> conn = getProgressConnection();
  3586. if (conn)
  3587. {
  3588. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3589. mergePTree(tmp,conn->queryRoot());
  3590. return tmp.getClear();
  3591. }
  3592. return NULL;
  3593. }
  3594. Owned<IRemoteConnection> connection;
  3595. mutable Owned<IRemoteConnection> progressConnection;
  3596. };
  3597. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3598. {
  3599. public:
  3600. Owned<CLocalWorkUnit> c;
  3601. IMPLEMENT_IINTERFACE;
  3602. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3603. ~CLockedWorkUnit()
  3604. {
  3605. if (workUnitTraceLevel > 1)
  3606. DBGLOG("Releasing locked workunit %s", queryWuid());
  3607. if (c)
  3608. {
  3609. try
  3610. {
  3611. c->unlockRemote();
  3612. }
  3613. catch (IException *E)
  3614. {
  3615. // Exceptions here should be very uncommon - but there's also not a lot we can do if we get one
  3616. // Allowing them to be thrown out of the destructor is going to terminate the program which is NOT what we want.
  3617. EXCLOG(E);
  3618. ::Release(E);
  3619. }
  3620. }
  3621. }
  3622. virtual IConstWorkUnit * unlock()
  3623. {
  3624. c->unlockRemote();
  3625. return c.getClear();
  3626. }
  3627. virtual bool aborting() const
  3628. { return c->aborting(); }
  3629. virtual void forceReload()
  3630. { }
  3631. virtual WUAction getAction() const
  3632. { return c->getAction(); }
  3633. virtual const char *queryActionDesc() const
  3634. { return c->queryActionDesc(); }
  3635. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3636. { return c->getApplicationValue(application, propname, str); }
  3637. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3638. { return c->getApplicationValueInt(application, propname, defVal); }
  3639. virtual IConstWUAppValueIterator & getApplicationValues() const
  3640. { return c->getApplicationValues(); }
  3641. virtual bool hasWorkflow() const
  3642. { return c->hasWorkflow(); }
  3643. virtual unsigned queryEventScheduledCount() const
  3644. { return c->queryEventScheduledCount(); }
  3645. virtual IPropertyTree * queryWorkflowTree() const
  3646. { return c->queryWorkflowTree(); }
  3647. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3648. { return c->getWorkflowItems(); }
  3649. virtual IWorkflowItemArray * getWorkflowClone() const
  3650. { return c->getWorkflowClone(); }
  3651. virtual bool requiresLocalFileUpload() const
  3652. { return c->requiresLocalFileUpload(); }
  3653. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3654. { return c->getLocalFileUploads(); }
  3655. virtual bool getIsQueryService() const
  3656. { return c->getIsQueryService(); }
  3657. virtual bool getCloneable() const
  3658. { return c->getCloneable(); }
  3659. virtual IUserDescriptor * queryUserDescriptor() const
  3660. { return c->queryUserDescriptor(); }
  3661. virtual const char *queryClusterName() const
  3662. { return c->queryClusterName(); }
  3663. virtual unsigned getCodeVersion() const
  3664. { return c->getCodeVersion(); }
  3665. virtual unsigned getWuidVersion() const
  3666. { return c->getWuidVersion(); }
  3667. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3668. { c->getBuildVersion(buildVersion, eclVersion); }
  3669. virtual bool hasDebugValue(const char * propname) const
  3670. { return c->hasDebugValue(propname); }
  3671. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3672. { return c->getDebugValue(propname, str); }
  3673. virtual int getDebugValueInt(const char * propname, int defVal) const
  3674. { return c->getDebugValueInt(propname, defVal); }
  3675. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3676. { return c->getDebugValueInt64(propname, defVal); }
  3677. virtual double getDebugValueReal(const char * propname, double defVal) const
  3678. { return c->getDebugValueReal(propname, defVal); }
  3679. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3680. { return c->getDebugValueBool(propname, defVal); }
  3681. virtual IStringIterator & getDebugValues() const
  3682. { return c->getDebugValues(NULL); }
  3683. virtual IStringIterator & getDebugValues(const char *prop) const
  3684. { return c->getDebugValues(prop); }
  3685. virtual unsigned getExceptionCount() const
  3686. { return c->getExceptionCount(); }
  3687. virtual IConstWUExceptionIterator & getExceptions() const
  3688. { return c->getExceptions(); }
  3689. virtual unsigned getGraphCount() const
  3690. { return c->getGraphCount(); }
  3691. virtual unsigned getSourceFileCount() const
  3692. { return c->getSourceFileCount(); }
  3693. virtual unsigned getResultCount() const
  3694. { return c->getResultCount(); }
  3695. virtual unsigned getVariableCount() const
  3696. { return c->getVariableCount(); }
  3697. virtual unsigned getApplicationValueCount() const
  3698. { return c->getApplicationValueCount(); }
  3699. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3700. { return c->getGraphs(type); }
  3701. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3702. { return c->getGraphsMeta(type); }
  3703. virtual IConstWUGraph * getGraph(const char *name) const
  3704. { return c->getGraph(name); }
  3705. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3706. { return c->getGraphProgress(name); }
  3707. virtual const char *queryJobName() const
  3708. { return c->queryJobName(); }
  3709. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3710. { return c->getPluginByName(name); }
  3711. virtual IConstWUPluginIterator & getPlugins() const
  3712. { return c->getPlugins(); }
  3713. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3714. { return c->getLibraryByName(name); }
  3715. virtual IConstWULibraryIterator & getLibraries() const
  3716. { return c->getLibraries(); }
  3717. virtual WUPriorityClass getPriority() const
  3718. { return c->getPriority(); }
  3719. virtual const char *queryPriorityDesc() const
  3720. { return c->queryPriorityDesc(); }
  3721. virtual int getPriorityLevel() const
  3722. { return c->getPriorityLevel(); }
  3723. virtual int getPriorityValue() const
  3724. { return c->getPriorityValue(); }
  3725. virtual IConstWUQuery * getQuery() const
  3726. { return c->getQuery(); }
  3727. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3728. { return c->getWebServicesInfo(); }
  3729. virtual bool getRescheduleFlag() const
  3730. { return c->getRescheduleFlag(); }
  3731. virtual IConstWUResult * getResultByName(const char * name) const
  3732. { return c->getResultByName(name); }
  3733. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3734. { return c->getResultBySequence(seq); }
  3735. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3736. { return c->getQueryResultByName(name); }
  3737. virtual unsigned getResultLimit() const
  3738. { return c->getResultLimit(); }
  3739. virtual IConstWUResultIterator & getResults() const
  3740. { return c->getResults(); }
  3741. virtual IStringVal & getScope(IStringVal & str) const
  3742. { return c->getScope(str); }
  3743. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3744. { return c->getWorkunitDistributedAccessToken(str); }
  3745. virtual WUState getState() const
  3746. { return c->getState(); }
  3747. virtual IStringVal & getStateEx(IStringVal & str) const
  3748. { return c->getStateEx(str); }
  3749. virtual __int64 getAgentSession() const
  3750. { return c->getAgentSession(); }
  3751. virtual unsigned getAgentPID() const
  3752. { return c->getAgentPID(); }
  3753. virtual const char *queryStateDesc() const
  3754. { return c->queryStateDesc(); }
  3755. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3756. { return c->getRunningGraph(graphName, subId); }
  3757. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3758. { return c->getScopeIterator(filter); }
  3759. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3760. { return c->getStatistic(value, scope, kind); }
  3761. virtual IStringVal & getSnapshot(IStringVal & str) const
  3762. { return c->getSnapshot(str); }
  3763. virtual const char *queryUser() const
  3764. { return c->queryUser(); }
  3765. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3766. { return c->getWarningSeverity(code, defaultSeverity); }
  3767. virtual const char *queryWuScope() const
  3768. { return c->queryWuScope(); }
  3769. virtual const char *queryWuid() const
  3770. { return c->queryWuid(); }
  3771. virtual IConstWUResult * getGlobalByName(const char * name) const
  3772. { return c->getGlobalByName(name); }
  3773. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3774. { return c->getTemporaryByName(name); }
  3775. virtual IConstWUResultIterator & getTemporaries() const
  3776. { return c->getTemporaries(); }
  3777. virtual IConstWUResult * getVariableByName(const char * name) const
  3778. { return c->getVariableByName(name); }
  3779. virtual IConstWUResultIterator & getVariables() const
  3780. { return c->getVariables(); }
  3781. virtual bool isProtected() const
  3782. { return c->isProtected(); }
  3783. virtual bool isPausing() const
  3784. { return c->isPausing(); }
  3785. virtual IWorkUnit & lock()
  3786. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3787. virtual bool reload()
  3788. { UNIMPLEMENTED; }
  3789. virtual void subscribe(WUSubscribeOptions options)
  3790. { c->subscribe(options); }
  3791. virtual void requestAbort()
  3792. { c->requestAbort(); }
  3793. virtual unsigned calculateHash(unsigned prevHash)
  3794. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3795. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3796. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3797. virtual IPropertyTree *queryPTree() const
  3798. { return queryExtendedWU(c)->queryPTree(); }
  3799. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3800. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3801. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3802. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3803. virtual unsigned queryFileUsage(const char *filename) const
  3804. { return c->queryFileUsage(filename); }
  3805. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3806. { return c->getFieldUsage(); }
  3807. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3808. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3809. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3810. { return c->getTimeScheduled(val); }
  3811. virtual unsigned getDebugAgentListenerPort() const
  3812. { return c->getDebugAgentListenerPort(); }
  3813. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3814. { return c->getDebugAgentListenerIP(ip); }
  3815. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3816. { return c->getXmlParams(params, hidePasswords); }
  3817. virtual const IPropertyTree *getXmlParams() const
  3818. { return c->getXmlParams(); }
  3819. virtual unsigned __int64 getHash() const
  3820. { return c->getHash(); }
  3821. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3822. { return c->getLogs(type, instance); }
  3823. virtual IStringIterator *getProcesses(const char *type) const
  3824. { return c->getProcesses(type); }
  3825. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3826. { return c->getProcesses(type, instance); }
  3827. virtual unsigned getTotalThorTime() const
  3828. { return c->getTotalThorTime(); }
  3829. virtual WUGraphState queryGraphState(const char *graphName) const
  3830. { return c->queryGraphState(graphName); }
  3831. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3832. { return c->queryNodeState(graphName, nodeId); }
  3833. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3834. { c->setGraphState(graphName, wfid, state); }
  3835. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3836. { c->setNodeState(graphName, nodeId, state); }
  3837. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3838. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3839. virtual void clearGraphProgress() const
  3840. { c->clearGraphProgress(); }
  3841. virtual IStringVal & getAbortBy(IStringVal & str) const
  3842. { return c->getAbortBy(str); }
  3843. virtual unsigned __int64 getAbortTimeStamp() const
  3844. { return c->getAbortTimeStamp(); }
  3845. virtual void import(IPropertyTree *wuTree, IPropertyTree *graphProgressTree)
  3846. { return c->import(wuTree, graphProgressTree); }
  3847. virtual void clearExceptions(const char *source=nullptr)
  3848. { c->clearExceptions(source); }
  3849. virtual void commit()
  3850. { c->commit(); }
  3851. virtual IWUException * createException()
  3852. { return c->createException(); }
  3853. virtual void addProcess(const char *type, const char *instance, unsigned pid, unsigned max, const char *pattern, bool singleLog, const char *log)
  3854. { c->addProcess(type, instance, pid, max, pattern, singleLog, log); }
  3855. virtual void protect(bool protectMode)
  3856. { c->protect(protectMode); }
  3857. virtual void setAction(WUAction action)
  3858. { c->setAction(action); }
  3859. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3860. { c->setApplicationValue(application, propname, value, overwrite); }
  3861. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3862. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3863. virtual void incEventScheduledCount()
  3864. { c->incEventScheduledCount(); }
  3865. virtual void setIsQueryService(bool value)
  3866. { c->setIsQueryService(value); }
  3867. virtual void setCloneable(bool value)
  3868. { c->setCloneable(value); }
  3869. virtual void setIsClone(bool value)
  3870. { c->setIsClone(value); }
  3871. virtual void setClusterName(const char * value)
  3872. { c->setClusterName(value); }
  3873. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3874. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3875. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3876. { c->setDebugValue(propname, value, overwrite); }
  3877. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3878. { c->setDebugValueInt(propname, value, overwrite); }
  3879. virtual void setJobName(const char * value)
  3880. { c->setJobName(value); }
  3881. virtual void setPriority(WUPriorityClass cls)
  3882. { c->setPriority(cls); }
  3883. virtual void setPriorityLevel(int level)
  3884. { c->setPriorityLevel(level); }
  3885. virtual void setRescheduleFlag(bool value)
  3886. { c->setRescheduleFlag(value); }
  3887. virtual void setResultLimit(unsigned value)
  3888. { c->setResultLimit(value); }
  3889. virtual void setState(WUState state)
  3890. { c->setState(state); }
  3891. virtual void setStateEx(const char * text)
  3892. { c->setStateEx(text); }
  3893. virtual void setAgentSession(__int64 sessionId)
  3894. { c->setAgentSession(sessionId); }
  3895. virtual void setStatistic(StatisticCreatorType creatorType, const char * creator, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * optDescription, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction)
  3896. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3897. virtual void setTracingValue(const char * propname, const char * value)
  3898. { c->setTracingValue(propname, value); }
  3899. virtual void setTracingValueInt(const char * propname, int value)
  3900. { c->setTracingValueInt(propname, value); }
  3901. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3902. { c->setTracingValueInt64(propname, value); }
  3903. virtual void setUser(const char * value)
  3904. { c->setUser(value); }
  3905. virtual void setWuScope(const char * value)
  3906. { c->setWuScope(value); }
  3907. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3908. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3909. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3910. { c->syncRuntimeWorkflow(array); }
  3911. virtual IWorkflowItemIterator * updateWorkflowItems()
  3912. { return c->updateWorkflowItems(); }
  3913. virtual void resetWorkflow()
  3914. { c->resetWorkflow(); }
  3915. virtual void schedule()
  3916. { c->schedule(); }
  3917. virtual void deschedule()
  3918. { c->deschedule(); }
  3919. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3920. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3921. virtual IWUResult * updateGlobalByName(const char * name)
  3922. { return c->updateGlobalByName(name); }
  3923. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3924. { c->createGraph(name, label, type, xgmml, wfid); }
  3925. virtual IWUQuery * updateQuery()
  3926. { return c->updateQuery(); }
  3927. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3928. { return c->updateWebServicesInfo(create); }
  3929. virtual IWUPlugin * updatePluginByName(const char * name)
  3930. { return c->updatePluginByName(name); }
  3931. virtual IWULibrary * updateLibraryByName(const char * name)
  3932. { return c->updateLibraryByName(name); }
  3933. virtual IWUResult * updateResultByName(const char * name)
  3934. { return c->updateResultByName(name); }
  3935. virtual IWUResult * updateResultBySequence(unsigned seq)
  3936. { return c->updateResultBySequence(seq); }
  3937. virtual IWUResult * updateTemporaryByName(const char * name)
  3938. { return c->updateTemporaryByName(name); }
  3939. virtual IWUResult * updateVariableByName(const char * name)
  3940. { return c->updateVariableByName(name); }
  3941. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3942. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3943. virtual void noteFileRead(IDistributedFile *file)
  3944. { c->noteFileRead(file); }
  3945. virtual void noteFieldUsage(IPropertyTree * usage)
  3946. { c->noteFieldUsage(usage); }
  3947. virtual void releaseFile(const char *fileName)
  3948. { c->releaseFile(fileName); }
  3949. virtual void resetBeforeGeneration()
  3950. { c->resetBeforeGeneration(); }
  3951. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3952. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3953. virtual void deleteTemporaries()
  3954. { c->deleteTemporaries(); }
  3955. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3956. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3957. virtual IPropertyTree * getDiskUsageStats()
  3958. { return c->getDiskUsageStats(); }
  3959. virtual IPropertyTreeIterator & getFileIterator() const
  3960. { return c->getFileIterator(); }
  3961. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3962. { return c->getFilesReadIterator(); }
  3963. virtual void setSnapshot(const char * value)
  3964. { c->setSnapshot(value); }
  3965. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3966. { c->setWarningSeverity(code, severity); }
  3967. virtual void setTimeScheduled(const IJlibDateTime &val)
  3968. { c->setTimeScheduled(val); }
  3969. virtual void setDebugAgentListenerPort(unsigned port)
  3970. { c->setDebugAgentListenerPort(port); }
  3971. virtual void setDebugAgentListenerIP(const char * ip)
  3972. { c->setDebugAgentListenerIP(ip); }
  3973. virtual void setXmlParams(const char *params)
  3974. { c->setXmlParams(params); }
  3975. virtual void setXmlParams(IPropertyTree *tree)
  3976. { c->setXmlParams(tree); }
  3977. virtual void setHash(unsigned __int64 hash)
  3978. { c->setHash(hash); }
  3979. // ILocalWorkUnit - used for debugging etc
  3980. virtual void serialize(MemoryBuffer &tgt)
  3981. { c->serialize(tgt); }
  3982. virtual void deserialize(MemoryBuffer &src)
  3983. { c->deserialize(src); }
  3984. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3985. { return c->switchThorQueue(cluster,qs); }
  3986. virtual void setAllowedClusters(const char *value)
  3987. { c->setAllowedClusters(value); }
  3988. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3989. { return c->getAllowedClusters(str); }
  3990. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3991. { c->remoteCheckAccess(user,writeaccess); }
  3992. virtual void setAllowAutoQueueSwitch(bool val)
  3993. { c->setAllowAutoQueueSwitch(val); }
  3994. virtual bool getAllowAutoQueueSwitch() const
  3995. { return c->getAllowAutoQueueSwitch(); }
  3996. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3997. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3998. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3999. { c->setResultInt(name, sequence, val); }
  4000. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  4001. { c->setResultUInt(name, sequence, val); }
  4002. virtual void setResultReal(const char *name, unsigned sequence, double val)
  4003. { c->setResultReal(name, sequence, val); }
  4004. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  4005. { c->setResultVarString(stepname, sequence, val); }
  4006. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  4007. { c->setResultVarUnicode(stepname, sequence, val); }
  4008. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  4009. { c->setResultString(stepname, sequence, len, val); }
  4010. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  4011. { c->setResultData(stepname, sequence, len, val); }
  4012. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  4013. { c->setResultRaw(name, sequence, len, val); }
  4014. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  4015. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  4016. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  4017. { c->setResultUnicode(name, sequence, len, val); }
  4018. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  4019. { c->setResultBool(name, sequence, val); }
  4020. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  4021. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  4022. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  4023. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  4024. };
  4025. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  4026. {
  4027. Owned<IPropertyTree> p;
  4028. public:
  4029. IMPLEMENT_IINTERFACE;
  4030. CLocalWUAssociated(IPropertyTree *p);
  4031. virtual WUFileType getType() const;
  4032. virtual IStringVal & getDescription(IStringVal & ret) const;
  4033. virtual IStringVal & getIp(IStringVal & ret) const;
  4034. virtual IStringVal & getName(IStringVal & ret) const;
  4035. virtual IStringVal & getNameTail(IStringVal & ret) const;
  4036. virtual unsigned getCrc() const;
  4037. virtual unsigned getMinActivityId() const;
  4038. virtual unsigned getMaxActivityId() const;
  4039. };
  4040. class CLocalWUQuery : implements IWUQuery, public CInterface
  4041. {
  4042. Owned<IPropertyTree> p;
  4043. mutable IArrayOf<IConstWUAssociatedFile> associated;
  4044. mutable CriticalSection crit;
  4045. mutable bool associatedCached;
  4046. private:
  4047. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  4048. void loadAssociated() const;
  4049. public:
  4050. IMPLEMENT_IINTERFACE;
  4051. CLocalWUQuery(IPropertyTree *p);
  4052. virtual WUQueryType getQueryType() const;
  4053. virtual IStringVal& getQueryText(IStringVal &str) const;
  4054. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  4055. virtual IStringVal& getQueryName(IStringVal &str) const;
  4056. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  4057. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  4058. virtual unsigned getQueryDllCrc() const;
  4059. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  4060. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  4061. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  4062. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  4063. virtual bool isArchive() const;
  4064. virtual bool hasArchive() const
  4065. {
  4066. return p->getPropBool("@hasArchive");
  4067. }
  4068. virtual void setQueryType(WUQueryType qt);
  4069. virtual void setQueryText(const char *pstr);
  4070. virtual void setQueryName(const char *);
  4071. virtual void setQueryMainDefinition(const char * str);
  4072. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  4073. virtual void removeAssociatedFiles();
  4074. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  4075. };
  4076. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  4077. {
  4078. Owned<IPropertyTree> p;
  4079. mutable CriticalSection crit;
  4080. private:
  4081. public:
  4082. IMPLEMENT_IINTERFACE;
  4083. CLocalWUWebServicesInfo(IPropertyTree *p);
  4084. virtual IStringVal& getModuleName(IStringVal &str) const;
  4085. virtual IStringVal& getAttributeName(IStringVal &str) const;
  4086. virtual IStringVal& getDefaultName(IStringVal &str) const;
  4087. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  4088. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  4089. virtual unsigned getWebServicesCRC() const;
  4090. virtual void setModuleName(const char *);
  4091. virtual void setAttributeName(const char *);
  4092. virtual void setDefaultName(const char *);
  4093. virtual void setInfo(const char *name, const char *info);
  4094. virtual void setText(const char *name, const char *info);
  4095. virtual void setWebServicesCRC(unsigned);
  4096. };
  4097. class CLocalWUResult : implements IWUResult, public CInterface
  4098. {
  4099. friend class CLocalWorkUnit;
  4100. mutable CriticalSection crit;
  4101. Owned<IPropertyTree> p;
  4102. Owned<IProperties> xmlns;
  4103. public:
  4104. IMPLEMENT_IINTERFACE;
  4105. CLocalWUResult(IPropertyTree *props);
  4106. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  4107. virtual WUResultStatus getResultStatus() const;
  4108. virtual IStringVal& getResultName(IStringVal &str) const;
  4109. virtual int getResultSequence() const;
  4110. virtual bool isResultScalar() const;
  4111. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  4112. virtual unsigned getResultFetchSize() const;
  4113. virtual __int64 getResultTotalRowCount() const;
  4114. virtual __int64 getResultRowCount() const;
  4115. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  4116. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  4117. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  4118. virtual unsigned getResultRequestedRows() const;
  4119. virtual __int64 getResultInt() const;
  4120. virtual bool getResultBool() const;
  4121. virtual double getResultReal() const;
  4122. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  4123. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4124. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  4125. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  4126. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  4127. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4128. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4129. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  4130. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  4131. virtual __int64 getResultRowLimit() const;
  4132. virtual IStringVal& getResultFilename(IStringVal & str) const;
  4133. virtual WUResultFormat getResultFormat() const;
  4134. virtual unsigned getResultHash() const;
  4135. virtual bool getResultIsAll() const;
  4136. virtual IProperties *queryResultXmlns();
  4137. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  4138. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  4139. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  4140. // interface IWUResult
  4141. virtual void setResultStatus(WUResultStatus status);
  4142. virtual void setResultName(const char *name);
  4143. virtual void setResultSequence(unsigned seq);
  4144. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  4145. virtual void setResultScalar(bool isScalar);
  4146. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  4147. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  4148. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  4149. virtual void setResultRowCount(__int64 rows);
  4150. virtual void setResultDataset(const char *ecl, const char *defs);
  4151. virtual void setResultLogicalName(const char *logicalName);
  4152. virtual void setResultKeyField(const char * name);
  4153. virtual void setResultRequestedRows(unsigned req);
  4154. virtual void setResultRecordSizeEntry(const char * val);
  4155. virtual void setResultTransformerEntry(const char * val);
  4156. virtual void setResultInt(__int64 val);
  4157. virtual void setResultReal(double val);
  4158. virtual void setResultBool(bool val);
  4159. virtual void setResultString(const char * val, unsigned length);
  4160. virtual void setResultUnicode(const void * val, unsigned length);
  4161. virtual void setResultData(const void * val, unsigned length);
  4162. virtual void setResultDecimal(const void * val, unsigned length);
  4163. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  4164. virtual void setResultRowLimit(__int64 value);
  4165. virtual void setResultFilename(const char * name);
  4166. virtual void setResultUInt(unsigned __int64 val);
  4167. virtual void setResultIsAll(bool value);
  4168. virtual void setResultFormat(WUResultFormat format);
  4169. virtual void setResultXML(const char *val);
  4170. virtual void setResultRow(unsigned len, const void * data);
  4171. virtual void setResultXmlns(const char *prefix, const char *uri);
  4172. virtual void setResultFieldOpt(const char *name, const char *value);
  4173. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  4174. virtual IPropertyTree *queryPTree() { return p; }
  4175. };
  4176. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  4177. {
  4178. Owned<IPropertyTree> p;
  4179. public:
  4180. IMPLEMENT_IINTERFACE;
  4181. CLocalWUPlugin(IPropertyTree *p);
  4182. virtual IStringVal& getPluginName(IStringVal &str) const;
  4183. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  4184. virtual void setPluginName(const char *str);
  4185. virtual void setPluginVersion(const char *str);
  4186. };
  4187. class CLocalWULibrary : implements IWULibrary, public CInterface
  4188. {
  4189. Owned<IPropertyTree> p;
  4190. public:
  4191. IMPLEMENT_IINTERFACE;
  4192. CLocalWULibrary(IPropertyTree *p);
  4193. virtual IStringVal & getName(IStringVal & str) const;
  4194. virtual void setName(const char * str);
  4195. };
  4196. class CLocalWUException : implements IWUException, public CInterface
  4197. {
  4198. Owned<IPropertyTree> p;
  4199. public:
  4200. IMPLEMENT_IINTERFACE;
  4201. CLocalWUException(IPropertyTree *p);
  4202. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4203. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4204. virtual unsigned getExceptionCode() const override;
  4205. virtual ErrorSeverity getSeverity() const override;
  4206. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4207. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4208. virtual unsigned getExceptionLineNo() const override;
  4209. virtual unsigned getExceptionColumn() const override;
  4210. virtual unsigned getActivityId() const override;
  4211. virtual unsigned getSequence() const override;
  4212. virtual const char * queryScope() const override;
  4213. virtual unsigned getPriority() const override;
  4214. virtual void setExceptionSource(const char *str) override;
  4215. virtual void setExceptionMessage(const char *str) override;
  4216. virtual void setExceptionCode(unsigned code) override;
  4217. virtual void setSeverity(ErrorSeverity level) override;
  4218. virtual void setTimeStamp(const char * dt) override;
  4219. virtual void setExceptionFileName(const char *str) override;
  4220. virtual void setExceptionLineNo(unsigned r) override;
  4221. virtual void setExceptionColumn(unsigned c) override;
  4222. virtual void setActivityId(unsigned _id) override;
  4223. virtual void setScope(const char * _scope) override;
  4224. virtual void setPriority(unsigned _priority) override;
  4225. };
  4226. //==========================================================================================
  4227. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4228. {
  4229. switch ((int) sequence)
  4230. {
  4231. case ResultSequenceInternal:
  4232. case ResultSequenceOnce:
  4233. case ResultSequencePersist:
  4234. case ResultSequenceStored:
  4235. return true;
  4236. default:
  4237. assertex(sequence <= INT_MAX);
  4238. if ((int) sequence >= LibraryBaseSequence)
  4239. return true;
  4240. return false;
  4241. }
  4242. }
  4243. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4244. {
  4245. unsigned curTreeNum;
  4246. IArrayOf<IPropertyTree> trees;
  4247. Owned<IConstWorkUnitInfo> cur;
  4248. void setCurrent()
  4249. {
  4250. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4251. }
  4252. public:
  4253. IMPLEMENT_IINTERFACE;
  4254. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4255. {
  4256. ForEachItemIn(t, _trees)
  4257. trees.append(*LINK(&_trees.item(t)));
  4258. curTreeNum = 0;
  4259. }
  4260. bool first()
  4261. {
  4262. curTreeNum = 0;
  4263. return next();
  4264. }
  4265. bool isValid()
  4266. {
  4267. return (NULL != cur.get());
  4268. }
  4269. bool next()
  4270. {
  4271. if (curTreeNum >= trees.ordinality())
  4272. {
  4273. cur.clear();
  4274. return false;
  4275. }
  4276. setCurrent();
  4277. ++curTreeNum;
  4278. return true;
  4279. }
  4280. IConstWorkUnitInfo & query() { return *cur; }
  4281. };
  4282. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4283. {
  4284. Owned<IPropertyTree> p;
  4285. public:
  4286. IMPLEMENT_IINTERFACE;
  4287. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4288. virtual const char * queryName() const { return p->queryProp("@name"); }
  4289. };
  4290. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4291. {
  4292. public:
  4293. IMPLEMENT_IINTERFACE;
  4294. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4295. bool first() override { return iter->first(); }
  4296. bool isValid() override { return iter->isValid(); }
  4297. bool next() override { return iter->next(); }
  4298. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4299. private:
  4300. Owned<IPropertyTreeIterator> iter;
  4301. };
  4302. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4303. {
  4304. Owned<IPropertyTree> p;
  4305. public:
  4306. IMPLEMENT_IINTERFACE;
  4307. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4308. virtual const char * queryName() const { return p->queryProp("@name"); }
  4309. virtual const char * queryType() const { return p->queryProp("@type"); }
  4310. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4311. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4312. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4313. };
  4314. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4315. {
  4316. public:
  4317. IMPLEMENT_IINTERFACE;
  4318. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4319. bool first() override { return iter->first(); }
  4320. bool isValid() override { return iter->isValid(); }
  4321. bool next() override { return iter->next(); }
  4322. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4323. private:
  4324. Owned<IPropertyTreeIterator> iter;
  4325. };
  4326. //==========================================================================================
  4327. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4328. {
  4329. Owned<IPropertyTreeIterator> it;
  4330. public:
  4331. IMPLEMENT_IINTERFACE;
  4332. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4333. virtual bool first() { return it->first(); }
  4334. virtual bool next() { return it->next(); }
  4335. virtual bool isValid() { return it->isValid(); }
  4336. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4337. };
  4338. EnumMapping workunitSortFields[] =
  4339. {
  4340. { WUSFuser, "@submitID" },
  4341. { WUSFcluster, "@clusterName" },
  4342. { WUSFjob, "@jobName" },
  4343. { WUSFstate, "@state" },
  4344. { WUSFpriority, "@priorityClass" },
  4345. { WUSFprotected, "@protected" },
  4346. { WUSFwuid, "@" },
  4347. { WUSFecl, "Query/ShortText" },
  4348. { WUSFfileread, "FilesRead/File/@name" },
  4349. { WUSFtotalthortime, "@totalThorTime" },
  4350. { WUSFwuidhigh, "@" },
  4351. { WUSFwildwuid, "@" },
  4352. { WUSFappvalue, "Application" },
  4353. { WUSFfilewritten, "Files/File/@name" },
  4354. { WUSFterm, NULL }
  4355. };
  4356. extern const char *queryFilterXPath(WUSortField field)
  4357. {
  4358. return getEnumText(field, workunitSortFields);
  4359. }
  4360. EnumMapping querySortFields[] =
  4361. {
  4362. { WUQSFId, "@id" },
  4363. { WUQSFwuid, "@wuid" },
  4364. { WUQSFname, "@name" },
  4365. { WUQSFdll, "@dll" },
  4366. { WUQSFmemoryLimit, "@memoryLimit" },
  4367. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4368. { WUQSFtimeLimit, "@timeLimit" },
  4369. { WUQSFtimeLimitHi, "@timeLimit" },
  4370. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4371. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4372. { WUQSFpriority, "@priority" },
  4373. { WUQSFpriorityHi, "@priority" },
  4374. { WUQSFQuerySet, "@querySetId" },
  4375. { WUQSFActivited, "@activated" },
  4376. { WUQSFSuspendedByUser, "@suspended" },
  4377. { WUQSFLibrary, "Library"},
  4378. { WUQSFPublishedBy, "@publishedBy" },
  4379. { WUQSFterm, NULL }
  4380. };
  4381. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4382. {
  4383. StringAttr name;
  4384. public:
  4385. IMPLEMENT_IINTERFACE;
  4386. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4387. {
  4388. }
  4389. void execute()
  4390. {
  4391. PROGLOG("WU removeDll %s", name.get());
  4392. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4393. }
  4394. };
  4395. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4396. {
  4397. RemoteFilename name;
  4398. public:
  4399. IMPLEMENT_IINTERFACE;
  4400. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4401. {
  4402. SocketEndpoint ep(_ip);
  4403. name.setPath(ep, _name);
  4404. }
  4405. void execute()
  4406. {
  4407. Owned<IFile> file = createIFile(name);
  4408. PROGLOG("WU removeDll %s",file->queryFilename());
  4409. file->remove();
  4410. }
  4411. };
  4412. //==========================================================================================
  4413. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4414. {
  4415. unsigned index;
  4416. IArrayOf<IPropertyTree> trees;
  4417. public:
  4418. IMPLEMENT_IINTERFACE;
  4419. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4420. {
  4421. ForEachItemIn(t, _trees)
  4422. trees.append(*LINK(&_trees.item(t)));
  4423. index = 0;
  4424. }
  4425. ~CConstQuerySetQueryIterator()
  4426. {
  4427. trees.kill();
  4428. }
  4429. bool first()
  4430. {
  4431. index = 0;
  4432. return (trees.ordinality()!=0);
  4433. }
  4434. bool next()
  4435. {
  4436. index++;
  4437. return (index<trees.ordinality());
  4438. }
  4439. bool isValid()
  4440. {
  4441. return (index<trees.ordinality());
  4442. }
  4443. IPropertyTree &query()
  4444. {
  4445. return trees.item(index);
  4446. }
  4447. };
  4448. class CSecurityCache
  4449. {
  4450. };
  4451. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4452. {
  4453. public:
  4454. IMPLEMENT_IINTERFACE;
  4455. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4456. : ptreeIter(_ptreeIter)
  4457. {
  4458. }
  4459. bool first()
  4460. {
  4461. if (!ptreeIter->first())
  4462. {
  4463. cur.clear();
  4464. return false;
  4465. }
  4466. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4467. return true;
  4468. }
  4469. bool isValid()
  4470. {
  4471. return (NULL != cur.get());
  4472. }
  4473. bool next()
  4474. {
  4475. if (!ptreeIter->next())
  4476. {
  4477. cur.clear();
  4478. return false;
  4479. }
  4480. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4481. return true;
  4482. }
  4483. IConstWorkUnitInfo & query() { return *cur; }
  4484. private:
  4485. Owned<IConstWorkUnitInfo> cur;
  4486. Owned<IPropertyTreeIterator> ptreeIter;
  4487. };
  4488. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4489. {
  4490. public:
  4491. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4492. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4493. {
  4494. assertex(_secuser && _secmgr);
  4495. }
  4496. bool first()
  4497. {
  4498. if (!parent->first())
  4499. return false;
  4500. return getNext();
  4501. }
  4502. bool next()
  4503. {
  4504. if (!parent->next())
  4505. return false;
  4506. return getNext();
  4507. }
  4508. virtual bool isValid()
  4509. {
  4510. return parent->isValid();
  4511. }
  4512. virtual IConstWorkUnitInfo &query()
  4513. {
  4514. return parent->query();
  4515. }
  4516. private:
  4517. Owned<IConstWorkUnitIterator> parent;
  4518. MapStringTo<int> scopePermissions;
  4519. Linked<ISecManager> secmgr;
  4520. Linked<ISecUser> secuser;
  4521. bool getNext() // scan for a workunit with permissions
  4522. {
  4523. do
  4524. {
  4525. const char *scopeName = parent->query().queryWuScope();
  4526. if (!scopeName || !*scopeName || checkScope(scopeName))
  4527. return true;
  4528. } while (parent->next());
  4529. return false;
  4530. }
  4531. bool checkScope(const char *scopeName)
  4532. {
  4533. int *perms = scopePermissions.getValue(scopeName);
  4534. SecAccessFlags perm;
  4535. if (!perms)
  4536. {
  4537. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4538. scopePermissions.setValue(scopeName, perm);
  4539. }
  4540. else
  4541. perm = (SecAccessFlags)*perms;
  4542. return perm >= SecAccess_Read;
  4543. }
  4544. };
  4545. CWorkUnitFactory::CWorkUnitFactory()
  4546. {
  4547. }
  4548. CWorkUnitFactory::~CWorkUnitFactory()
  4549. {
  4550. }
  4551. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4552. {
  4553. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4554. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4555. if (scope)
  4556. cw->setWuScope(scope); // Note - this may check access rights and throw exception. Is that correct? We might prefer to only check access once, and this will check on the lock too...
  4557. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4558. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4559. ret->setDebugValue("CREATED_BY", app, true);
  4560. ret->setDebugValue("CREATED_FOR", scope, true);
  4561. return ret;
  4562. }
  4563. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4564. {
  4565. StringBuffer wuid("W");
  4566. char result[32];
  4567. time_t ltime;
  4568. time( &ltime );
  4569. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4570. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4571. wuid.append(result);
  4572. if (workUnitTraceLevel > 1)
  4573. DBGLOG("createWorkUnit created %s", wuid.str());
  4574. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4575. if (workUnitTraceLevel > 1)
  4576. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4577. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4578. return ret;
  4579. }
  4580. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4581. {
  4582. if (workUnitTraceLevel > 1)
  4583. DBGLOG("deleteWorkUnit %s", wuid);
  4584. StringBuffer wuRoot;
  4585. getXPath(wuRoot, wuid);
  4586. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4587. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4588. return false;
  4589. if (throwException)
  4590. cw->cleanupAndDelete(true, true);
  4591. else
  4592. {
  4593. try
  4594. {
  4595. cw->cleanupAndDelete(true, true);
  4596. }
  4597. catch (IException *E)
  4598. {
  4599. StringBuffer s;
  4600. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4601. E->Release();
  4602. return false;
  4603. }
  4604. }
  4605. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4606. return true;
  4607. }
  4608. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4609. {
  4610. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4611. }
  4612. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4613. {
  4614. StringBuffer wuidStr(wuid);
  4615. wuidStr.trim();
  4616. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4617. wuidStr.setCharAt(0, 'W');
  4618. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4619. {
  4620. if (workUnitTraceLevel > 1)
  4621. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4622. return NULL;
  4623. }
  4624. if (workUnitTraceLevel > 1)
  4625. DBGLOG("openWorkUnit %s", wuidStr.str());
  4626. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4627. if (wu)
  4628. {
  4629. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4630. return NULL; // Actually throws exception on failure, so won't reach here
  4631. return wu.getClear();
  4632. }
  4633. else
  4634. {
  4635. if (workUnitTraceLevel > 0)
  4636. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4637. return NULL;
  4638. }
  4639. }
  4640. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4641. {
  4642. if (workUnitTraceLevel > 1)
  4643. DBGLOG("updateWorkUnit %s", wuid);
  4644. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4645. if (wu)
  4646. {
  4647. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4648. return NULL;
  4649. return &wu->lockRemote(false);
  4650. }
  4651. else
  4652. {
  4653. if (workUnitTraceLevel > 0)
  4654. IERRLOG("updateWorkUnit %s not found", wuid);
  4655. return NULL;
  4656. }
  4657. }
  4658. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4659. {
  4660. Owned<IPropertyTree> ret;
  4661. IPropertyTree * branch = from->queryPropTree(xpath);
  4662. if(branch)
  4663. {
  4664. ret.setown(createPTreeFromIPT(branch));
  4665. from->removeTree(branch);
  4666. }
  4667. return ret.getClear();
  4668. }
  4669. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4670. {
  4671. StringBuffer path(base);
  4672. addPathSepChar(path).append(wuid).append(".xml");
  4673. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4674. if (!pt)
  4675. return false;
  4676. CDateTime dt;
  4677. dt.setNow();
  4678. StringBuffer dts;
  4679. dt.getString(dts);
  4680. pt->setProp("@restoredDate", dts.str());
  4681. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4682. Owned<IPropertyTree> associatedFiles;
  4683. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4684. if (srcAssociated)
  4685. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4686. // The updating of the repo is implementation specific...
  4687. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4688. return false;
  4689. // now kludge back GeneratedDlls
  4690. if (generatedDlls)
  4691. {
  4692. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4693. for(dlls->first(); dlls->isValid(); dlls->next())
  4694. {
  4695. IPropertyTree & dll = dlls->query();
  4696. char const * name = dll.queryProp("@name");
  4697. char const * kind = dll.queryProp("@kind");
  4698. char const * location = dll.queryProp("@location");
  4699. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4700. if (!got)
  4701. {
  4702. RemoteFilename dstRfn;
  4703. dstRfn.setRemotePath(location);
  4704. StringBuffer srcPath(base);
  4705. addPathSepChar(srcPath);
  4706. dstRfn.getTail(srcPath);
  4707. OwnedIFile srcFile = createIFile(srcPath);
  4708. OwnedIFile dstFile = createIFile(dstRfn);
  4709. copyFile(dstFile, srcFile);
  4710. queryDllServer().registerDll(name, kind, location);
  4711. }
  4712. }
  4713. }
  4714. if (associatedFiles)
  4715. {
  4716. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4717. ForEach(*associated)
  4718. {
  4719. IPropertyTree &file = associated->query();
  4720. const char *filename = file.queryProp("@filename");
  4721. SocketEndpoint ep(file.queryProp("@ip"));
  4722. RemoteFilename rfn;
  4723. rfn.setPath(ep, filename);
  4724. OwnedIFile dstFile = createIFile(rfn);
  4725. StringBuffer srcPath(base), name;
  4726. addPathSepChar(srcPath);
  4727. rfn.getTail(name);
  4728. srcPath.append(name);
  4729. if (generatedDlls)
  4730. {
  4731. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4732. if (generatedDlls->hasProp(gDllPath))
  4733. continue; // generated dlls handled separately - see above
  4734. }
  4735. OwnedIFile srcFile = createIFile(srcPath);
  4736. if (srcFile->exists())
  4737. {
  4738. try
  4739. {
  4740. copyFile(dstFile, srcFile);
  4741. }
  4742. catch (IException *e)
  4743. {
  4744. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4745. EXCLOG(e, msg.str());
  4746. e->Release();
  4747. }
  4748. }
  4749. }
  4750. }
  4751. return true;
  4752. }
  4753. void CWorkUnitFactory::importWorkUnit(const char *zapReportFileName, const char *zapReportPassword,
  4754. const char *importDir, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  4755. {
  4756. class CImportWorkUnitHelper
  4757. {
  4758. StringAttr zapReportFileName, zapReportPassword, importDir, user, wuid, fromWUID, scope;
  4759. StringBuffer unzipDir;
  4760. Owned<IPTree> wuTree, graphProgressTree;
  4761. bool findZAPFile(const char *mask, bool optional, StringBuffer &fileName)
  4762. {
  4763. Owned<IFile> d = createIFile(unzipDir);
  4764. if (!d->exists())
  4765. throw MakeStringException(WUERR_InvalidUserInput, "%s not found.", unzipDir.str());
  4766. Owned<IDirectoryIterator> di = d->directoryFiles(mask, false, false);
  4767. if (!di->first())
  4768. {
  4769. if (optional)
  4770. return false;
  4771. throw MakeStringException(WUERR_InvalidUserInput, "Failed to find %s in %s.", mask, unzipDir.str());
  4772. }
  4773. fileName.set(unzipDir).append(PATHSEPSTR);
  4774. di->getName(fileName);
  4775. if (di->next())
  4776. throw MakeStringException(WUERR_InvalidUserInput, "More than 1 %s files found in %s.", mask, unzipDir.str());
  4777. return true;
  4778. }
  4779. IPTree *readWUXMLFile(const char *pattern, bool optional)
  4780. {
  4781. StringBuffer fileName;
  4782. if (!findZAPFile(pattern, optional, fileName))
  4783. return nullptr;
  4784. Owned<IPTree> tree = createPTreeFromXMLFile(fileName);
  4785. if (!tree)
  4786. throw MakeStringException(WUERR_InvalidUserInput, "Failed to retrieve %s.", pattern);
  4787. Owned<IFile> f = createIFile(fileName);
  4788. f->remove();
  4789. return tree.getClear();
  4790. }
  4791. void updateWUQueryAssociatedFilesAttrs(const char *localIP)
  4792. {
  4793. ICopyArrayOf<IPropertyTree> fileTreesToRemove;
  4794. IPropertyTree *queryAssociatedTreeRoot = wuTree->queryPropTree("Query/Associated");
  4795. Owned<IPropertyTreeIterator> itr = queryAssociatedTreeRoot->getElements("File");
  4796. ForEach (*itr)
  4797. {
  4798. IPropertyTree &fileTree = itr->query();
  4799. const char *fileName = fileTree.queryProp("@filename");
  4800. StringBuffer fileNameWithPath(unzipDir);
  4801. fileNameWithPath.append(PATHSEPSTR).append(pathTail(fileName));
  4802. if (checkFileExists(fileNameWithPath)) //Check if the ZAP report contains this file.
  4803. {
  4804. fileTree.setProp("@ip", localIP);
  4805. fileTree.setProp("@filename", fileNameWithPath);
  4806. }
  4807. else
  4808. fileTreesToRemove.append(fileTree);
  4809. }
  4810. ForEachItemIn(r, fileTreesToRemove)
  4811. queryAssociatedTreeRoot->removeTree(&fileTreesToRemove.item(r));
  4812. }
  4813. void getWUAttributes(IWorkUnit *workunit)
  4814. {
  4815. wuid.set(workunit->queryWuid());
  4816. scope.set(workunit->queryWuScope());
  4817. }
  4818. IPTree *queryWUPTree() const
  4819. {
  4820. return wuTree;
  4821. }
  4822. IPTree *queryGraphProgressPTree() const
  4823. {
  4824. return graphProgressTree;
  4825. }
  4826. void setUNZIPDir()
  4827. { //Set a unique unzip folder inside the component's data folder
  4828. unzipDir.append(importDir).append(PATHSEPSTR).append(wuid.get());
  4829. }
  4830. void unzipZAPReport()
  4831. {
  4832. Owned<IFile> unzipFolder = createIFile(unzipDir);
  4833. if (!unzipFolder->exists())
  4834. unzipFolder->createDirectory();
  4835. else
  4836. {//This should not happen. Just in case.
  4837. throw MakeStringException(WUERR_CannotImportWorkunit, "Workunit %s had been created twice and passed to import()..", wuid.get());
  4838. }
  4839. //Unzip ZAP Report
  4840. VStringBuffer zipCommand("unzip %s -d %s", zapReportFileName.get(), unzipDir.str());
  4841. if (!isEmptyString(zapReportPassword))
  4842. zipCommand.appendf(" -P %s", zapReportPassword.get());
  4843. DWORD runcode;
  4844. bool success = invoke_program(zipCommand.str(), runcode, true);
  4845. if (!success)
  4846. throw MakeStringException(WUERR_CannotImportWorkunit, "Failed in execution : %s.", zipCommand.str());
  4847. if (runcode != 0)
  4848. throw MakeStringException(WUERR_CannotImportWorkunit, "Failed in execution : %s, error(%" I64F "i)", zipCommand.str(), (unsigned __int64) runcode);
  4849. }
  4850. void buildPTreesFromZAPReport()
  4851. {
  4852. wuTree.setown(readWUXMLFile("ZAPReport_W*.xml", false));
  4853. fromWUID.set(wuTree->queryName());
  4854. wuTree->setProp("@scope", scope);
  4855. //update QueryAssociatedFiles in WU XML;
  4856. updateWUQueryAssociatedFilesAttrs(GetCachedHostName());
  4857. graphProgressTree.setown(readWUXMLFile("ZAPReport_*.graphprogress", true));
  4858. }
  4859. void updateJobName(IWorkUnit *workunit)
  4860. {
  4861. StringBuffer newJobName;
  4862. const char *jobName = workunit->queryJobName();
  4863. if (isEmptyString(jobName))
  4864. newJobName.appendf("IMPORTED from %s", fromWUID.get());
  4865. else
  4866. newJobName.appendf("IMPORTED: %s", jobName);
  4867. workunit->setJobName(newJobName);
  4868. }
  4869. void setImportDebugAttribute(IWorkUnit *workunit)
  4870. {
  4871. StringBuffer attr, importDateTime;
  4872. CDateTime dt;
  4873. dt.setNow();
  4874. dt.getString(importDateTime);
  4875. attr.append("FromWUID=").append(fromWUID).append(",");
  4876. attr.append("ImportDT=").append(importDateTime).append(",");
  4877. attr.append("ZAPReport=").append(pathTail(zapReportFileName));
  4878. workunit->setDebugValue("imported", attr, true);
  4879. }
  4880. public:
  4881. CImportWorkUnitHelper(const char *_zapReportFileName, const char *_zapReportPassword, const char *_importDir, const char *_user)
  4882. : zapReportFileName(_zapReportFileName), zapReportPassword(_zapReportPassword), importDir(_importDir), user(_user) { };
  4883. void import(IWorkUnit *workunit)
  4884. {
  4885. getWUAttributes(workunit);
  4886. setUNZIPDir();
  4887. unzipZAPReport();
  4888. buildPTreesFromZAPReport();
  4889. workunit->import(queryWUPTree(), queryGraphProgressPTree());
  4890. setImportDebugAttribute(workunit);
  4891. updateJobName(workunit);
  4892. removeFileTraceIfFail(zapReportFileName);
  4893. }
  4894. };
  4895. Owned<IWorkUnit> newWU = createWorkUnit(app, user, secMgr, secUser);
  4896. CImportWorkUnitHelper helper(zapReportFileName, zapReportPassword, importDir, user);
  4897. helper.import(newWU);
  4898. }
  4899. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4900. {
  4901. if (newLevel)
  4902. DBGLOG("Setting workunit trace level to %d", newLevel);
  4903. int level = workUnitTraceLevel;
  4904. workUnitTraceLevel = newLevel;
  4905. return level;
  4906. }
  4907. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4908. {
  4909. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4910. if(!conn) return;
  4911. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4912. KeptAtomTable entries;
  4913. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4914. StringBuffer wuid;
  4915. for(iter->first(); iter->isValid(); iter->next())
  4916. {
  4917. char const * entry = iter->query().queryName();
  4918. if(!entries.find(entry))
  4919. {
  4920. entries.addAtom(entry);
  4921. ncnameUnescape(entry, wuid.clear());
  4922. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4923. if(wu && (wu->getState() == WUStateWait))
  4924. wu->setState(WUStateCompleted);
  4925. }
  4926. }
  4927. bool more;
  4928. do more = root->removeProp("*"); while(more);
  4929. }
  4930. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4931. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4932. const void *filterbuf, // (appended) string values for filters
  4933. unsigned startoffset,
  4934. unsigned maxnum,
  4935. __int64 *cachehint,
  4936. unsigned *total,
  4937. const MapStringTo<bool> *_subset,
  4938. const MapStringTo<bool> *_suspendedQueriesByCluster)
  4939. {
  4940. struct PostFilters
  4941. {
  4942. WUQueryFilterBoolean activatedFilter;
  4943. WUQueryFilterSuspended suspendedFilter;
  4944. PostFilters()
  4945. {
  4946. activatedFilter = WUQFSAll;
  4947. suspendedFilter = WUQFAllQueries;
  4948. };
  4949. } postFilters;
  4950. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4951. {
  4952. StringAttr querySet;
  4953. StringAttr xPath;
  4954. StringAttr sortOrder;
  4955. PostFilters postFilters;
  4956. StringArray unknownAttributes;
  4957. const MapStringTo<bool> *subset;
  4958. const MapStringTo<bool> *suspendedQueriesByCluster;
  4959. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4960. {
  4961. const char* querySetId = querySetTree->queryProp("@id");
  4962. std::unordered_set<std::string> aliasSet;
  4963. Owned<IPropertyTreeIterator> aliasIter = querySetTree->getElements("Alias");
  4964. ForEach(*aliasIter)
  4965. {
  4966. const char *id = aliasIter->query().queryProp("@id");
  4967. if (!isEmptyString(id))
  4968. aliasSet.insert(id);
  4969. }
  4970. VStringBuffer path("Query%s", xPath.get());
  4971. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4972. ForEach(*iter)
  4973. {
  4974. IPropertyTree &query = iter->query();
  4975. bool activated = false;
  4976. const char* queryId = query.queryProp("@id");
  4977. if (queryId && *queryId)
  4978. {
  4979. if (subset)
  4980. {
  4981. VStringBuffer match("%s/%s", querySetId, queryId);
  4982. if (!subset->getValue(match))
  4983. continue;
  4984. }
  4985. if (aliasSet.find(queryId) != aliasSet.end())
  4986. activated = true;
  4987. }
  4988. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4989. continue;
  4990. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4991. continue;
  4992. bool isSuspendedByUser = query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields));
  4993. bool skip = false;
  4994. switch(postFilters.suspendedFilter)
  4995. {
  4996. case WUQFSUSPDNo:
  4997. if (isSuspendedByUser || checkSuspendedByCluster(querySetId, queryId))
  4998. skip = true;
  4999. break;
  5000. case WUQFSUSPDYes:
  5001. if (!isSuspendedByUser && !checkSuspendedByCluster(querySetId, queryId))
  5002. skip = true;
  5003. break;
  5004. case WUQFSUSPDByUser:
  5005. if (!isSuspendedByUser)
  5006. skip = true;
  5007. break;
  5008. case WUQFSUSPDByFirstNode:
  5009. case WUQFSUSPDByAnyNode:
  5010. if (!checkSuspendedByCluster(querySetId, queryId))
  5011. skip = true;
  5012. break;
  5013. }
  5014. if (skip)
  5015. continue;
  5016. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  5017. queryWithSetId->setProp("@querySetId", querySetId);
  5018. queryWithSetId->setPropBool("@activated", activated);
  5019. }
  5020. }
  5021. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  5022. {
  5023. StringBuffer querySetXPath("QuerySets");
  5024. if (!querySet.isEmpty())
  5025. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  5026. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5027. if (!conn)
  5028. return NULL;
  5029. IPropertyTree *root = conn->queryRoot()->queryBranch(nullptr);
  5030. if (querySet.isEmpty())
  5031. {
  5032. Owned<IPropertyTreeIterator> querySetIter = root->getElements("*");
  5033. ForEach(*querySetIter)
  5034. populateQueryTree(&querySetIter->query(), queryTree);
  5035. }
  5036. else
  5037. populateQueryTree(root, queryTree);
  5038. return conn.getClear();
  5039. }
  5040. bool checkSuspendedByCluster(const char *querySetId, const char *queryId)
  5041. {
  5042. if (!suspendedQueriesByCluster)
  5043. return false;
  5044. VStringBuffer match("%s/%s", querySetId, queryId);
  5045. bool *found = suspendedQueriesByCluster->getValue(match);
  5046. return (found && *found);
  5047. }
  5048. public:
  5049. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5050. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters,
  5051. StringArray& _unknownAttributes, const MapStringTo<bool> *_subset, const MapStringTo<bool> *_suspendedQueriesByCluster)
  5052. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset), suspendedQueriesByCluster(_suspendedQueriesByCluster)
  5053. {
  5054. postFilters.activatedFilter = _postFilters.activatedFilter;
  5055. postFilters.suspendedFilter = _postFilters.suspendedFilter;
  5056. ForEachItemIn(x, _unknownAttributes)
  5057. unknownAttributes.append(_unknownAttributes.item(x));
  5058. }
  5059. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5060. {
  5061. Owned<IPropertyTree> elementTree = createPTree("Queries");
  5062. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  5063. if (!conn)
  5064. return NULL;
  5065. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  5066. if (!iter)
  5067. return NULL;
  5068. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  5069. return conn.getClear();
  5070. }
  5071. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  5072. };
  5073. StringAttr querySet;
  5074. StringBuffer xPath;
  5075. StringBuffer so;
  5076. StringArray unknownAttributes;
  5077. if (filters)
  5078. {
  5079. const char *fv = (const char *)filterbuf;
  5080. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  5081. int fmt = filters[i];
  5082. int subfmt = (fmt&0xff);
  5083. if (subfmt==WUQSFQuerySet)
  5084. querySet.set(fv);
  5085. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  5086. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  5087. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  5088. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  5089. else if (subfmt==WUQSFActivited)
  5090. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  5091. else if (subfmt==WUQSFSuspendedFilter)
  5092. postFilters.suspendedFilter = (WUQueryFilterSuspended) atoi(fv);
  5093. else if (!fv || !*fv)
  5094. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  5095. else {
  5096. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  5097. if (fmt&WUQSFnocase)
  5098. xPath.append('?');
  5099. if (fmt&WUQSFnumeric)
  5100. xPath.append('#');
  5101. if (fmt&WUQSFwild)
  5102. xPath.append('~');
  5103. xPath.append('"').append(fv).append("\"]");
  5104. }
  5105. fv = fv + strlen(fv)+1;
  5106. }
  5107. }
  5108. if (sortorder) {
  5109. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  5110. if (so.length())
  5111. so.append(',');
  5112. int fmt = sortorder[i];
  5113. if (fmt&WUQSFreverse)
  5114. so.append('-');
  5115. if (fmt&WUQSFnocase)
  5116. so.append('?');
  5117. if (fmt&WUQSFnumeric)
  5118. so.append('#');
  5119. so.append(getEnumText(fmt&0xff,querySortFields));
  5120. }
  5121. }
  5122. IArrayOf<IPropertyTree> results;
  5123. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL,
  5124. postFilters, unknownAttributes, _subset, _suspendedQueriesByCluster);
  5125. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  5126. return new CConstQuerySetQueryIterator(results);
  5127. }
  5128. bool CWorkUnitFactory::isAborting(const char *wuid) const
  5129. {
  5130. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  5131. try
  5132. {
  5133. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5134. if (acon)
  5135. return acon->queryRoot()->getPropInt(NULL) != 0;
  5136. }
  5137. catch (IException *E)
  5138. {
  5139. EXCLOG(E);
  5140. E->Release();
  5141. }
  5142. return false;
  5143. }
  5144. void CWorkUnitFactory::clearAborting(const char *wuid)
  5145. {
  5146. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  5147. try
  5148. {
  5149. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5150. if (acon)
  5151. acon->close(true);
  5152. }
  5153. catch (IException *E)
  5154. {
  5155. EXCLOG(E);
  5156. E->Release();
  5157. }
  5158. }
  5159. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  5160. {
  5161. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  5162. bool isEcl = false;
  5163. switch (state)
  5164. {
  5165. case WUStateAborting:
  5166. state = WUStateAborted;
  5167. break;
  5168. case WUStateCompiling:
  5169. isEcl = true;
  5170. // drop into
  5171. default:
  5172. state = WUStateFailed;
  5173. }
  5174. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  5175. wu->setState(state);
  5176. Owned<IWUException> e = wu->createException();
  5177. e->setExceptionCode(isEcl ? 1001 : 1000);
  5178. e->setExceptionMessage(isEcl ? "EclCC terminated unexpectedly" : "Workunit terminated unexpectedly");
  5179. }
  5180. static CriticalSection deleteDllLock;
  5181. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  5182. MODULE_INIT(INIT_PRIORITY_STANDARD)
  5183. {
  5184. return true;
  5185. }
  5186. MODULE_EXIT()
  5187. {
  5188. CriticalBlock b(deleteDllLock);
  5189. if (deleteDllWorkQ)
  5190. ::Release(deleteDllWorkQ);
  5191. deleteDllWorkQ = nullptr;
  5192. }
  5193. static void asyncRemoveDll(const char * name)
  5194. {
  5195. CriticalBlock b(deleteDllLock);
  5196. if (!deleteDllWorkQ)
  5197. deleteDllWorkQ = createWorkQueueThread();
  5198. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  5199. }
  5200. static void asyncRemoveFile(const char * ip, const char * name)
  5201. {
  5202. CriticalBlock b(deleteDllLock);
  5203. if (!deleteDllWorkQ)
  5204. deleteDllWorkQ = createWorkQueueThread();
  5205. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  5206. }
  5207. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  5208. {
  5209. public:
  5210. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  5211. CDaliWorkUnitFactory()
  5212. {
  5213. // Assumes dali client configuration has already been done
  5214. sdsManager = &querySDS();
  5215. session = myProcessSession();
  5216. addShutdownHook(*this);
  5217. }
  5218. ~CDaliWorkUnitFactory()
  5219. {
  5220. removeShutdownHook(*this);
  5221. }
  5222. virtual bool initializeStore()
  5223. {
  5224. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5225. }
  5226. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5227. {
  5228. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  5229. }
  5230. virtual unsigned validateRepository(bool fixErrors)
  5231. {
  5232. return 0;
  5233. }
  5234. virtual void deleteRepository(bool recreate)
  5235. {
  5236. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  5237. if (conn)
  5238. conn->close(true);
  5239. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  5240. if (conn)
  5241. conn->close(true);
  5242. }
  5243. virtual void createRepository()
  5244. {
  5245. // Nothing to do
  5246. }
  5247. virtual const char *queryStoreType() const
  5248. {
  5249. return "Dali";
  5250. }
  5251. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5252. {
  5253. StringBuffer wuRoot;
  5254. getXPath(wuRoot, wuid);
  5255. IRemoteConnection *conn;
  5256. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  5257. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5258. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  5259. conn->queryRoot()->setProp("@totalThorTime", "");
  5260. return new CDaliWorkUnit(conn, secmgr, secuser);
  5261. }
  5262. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5263. {
  5264. StringBuffer wuRoot;
  5265. getXPath(wuRoot, wuid);
  5266. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5267. if (conn)
  5268. return new CDaliWorkUnit(conn, secmgr, secuser);
  5269. else
  5270. return NULL;
  5271. }
  5272. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  5273. {
  5274. Owned<IPTree> pt(_pt);
  5275. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  5276. StringBuffer wuRoot;
  5277. getXPath(wuRoot, wuid);
  5278. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5279. if (!conn)
  5280. {
  5281. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  5282. return false;
  5283. }
  5284. IPropertyTree *root = conn->queryRoot();
  5285. if (root->hasChildren())
  5286. {
  5287. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  5288. return false;
  5289. }
  5290. root->setPropTree(NULL, pt.getClear());
  5291. conn.clear();
  5292. // now kludge back GraphProgress
  5293. if (gprogress)
  5294. {
  5295. VStringBuffer xpath("/GraphProgress/%s", wuid);
  5296. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  5297. if (conn)
  5298. {
  5299. IPropertyTree *groot = conn->queryRoot();
  5300. if (groot->hasChildren())
  5301. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  5302. groot->setPropTree(NULL, gprogress.getClear());
  5303. }
  5304. }
  5305. return true;
  5306. }
  5307. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5308. {
  5309. StringBuffer wuRoot;
  5310. getXPath(wuRoot, wuid);
  5311. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5312. if (conn)
  5313. return new CDaliWorkUnit(conn, secmgr, secuser);
  5314. else
  5315. return NULL;
  5316. }
  5317. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5318. {
  5319. // MORE - should it check security?
  5320. StringBuffer wuRoot;
  5321. getXPath(wuRoot, GLOBAL_WORKUNIT);
  5322. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5323. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5324. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  5325. return &cw->lockRemote(false);
  5326. }
  5327. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  5328. {
  5329. StringBuffer path("*");
  5330. if (owner && *owner)
  5331. path.append("[@submitID=?~\"").append(owner).append("\"]");
  5332. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5333. }
  5334. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  5335. {
  5336. StringBuffer path("*");
  5337. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  5338. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5339. }
  5340. virtual void clientShutdown();
  5341. virtual unsigned numWorkUnits()
  5342. {
  5343. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5344. if (!conn)
  5345. return 0;
  5346. IPropertyTree *root = conn->queryRoot();
  5347. return root->numChildren();
  5348. }
  5349. /**
  5350. * Add a filter to an xpath query, with the appropriate filter flags
  5351. */
  5352. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  5353. {
  5354. query.append('[').append(name).append('=');
  5355. if (flags & WUSFnocase)
  5356. query.append('?');
  5357. if (flags & WUSFwild)
  5358. query.append('~');
  5359. query.append('"').append(value).append("\"]");
  5360. };
  5361. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  5362. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5363. const void *filterbuf, // (appended) string values for filters
  5364. unsigned startoffset,
  5365. unsigned maxnum,
  5366. __int64 *cachehint,
  5367. unsigned *total,
  5368. ISecManager *secmgr,
  5369. ISecUser *secuser)
  5370. {
  5371. class CQueryOrFilter : public CInterface
  5372. {
  5373. unsigned flags;
  5374. StringAttr name;
  5375. StringArray values;
  5376. public:
  5377. IMPLEMENT_IINTERFACE;
  5378. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5379. : flags(_flags), name(_name)
  5380. {
  5381. values.appendListUniq(_value, "|");
  5382. };
  5383. const char* queryName() { return name.get(); };
  5384. unsigned querySearchFlags() { return flags; };
  5385. const StringArray& queryValues() const { return values; };
  5386. };
  5387. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5388. {
  5389. public:
  5390. virtual bool first() override
  5391. {
  5392. curSource = 0;
  5393. while (sources.isItem(curSource))
  5394. {
  5395. if (sources.item(curSource).first())
  5396. return true;
  5397. curSource++;
  5398. }
  5399. return false;
  5400. }
  5401. virtual bool next() override
  5402. {
  5403. if (sources.isItem(curSource))
  5404. {
  5405. if (sources.item(curSource).next())
  5406. return true;
  5407. curSource++;
  5408. while (sources.isItem(curSource))
  5409. {
  5410. if (sources.item(curSource).first())
  5411. return true;
  5412. curSource++;
  5413. }
  5414. }
  5415. return false;
  5416. }
  5417. virtual bool isValid() override
  5418. {
  5419. return sources.isItem(curSource);
  5420. }
  5421. virtual IPropertyTree & query() override
  5422. {
  5423. return sources.item(curSource).query();
  5424. }
  5425. void addSource(IPropertyTreeIterator &source)
  5426. {
  5427. sources.append(source);
  5428. }
  5429. private:
  5430. IArrayOf<IPropertyTreeIterator> sources;
  5431. unsigned curSource = 0;
  5432. };
  5433. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5434. {
  5435. StringAttr xPath;
  5436. StringAttr sortOrder;
  5437. StringAttr nameFilterLo;
  5438. StringAttr nameFilterHi;
  5439. StringArray unknownAttributes;
  5440. Owned<CQueryOrFilter> orFilter;
  5441. public:
  5442. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5443. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5444. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5445. {
  5446. ForEachItemIn(x, _unknownAttributes)
  5447. unknownAttributes.append(_unknownAttributes.item(x));
  5448. }
  5449. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5450. {
  5451. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5452. if (!conn)
  5453. return NULL;
  5454. Owned<IPropertyTreeIterator> iter;
  5455. if (!orFilter)
  5456. {
  5457. iter.setown(conn->getElements(xPath.get()));
  5458. }
  5459. else
  5460. {
  5461. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5462. bool added = false;
  5463. const char* fieldName = orFilter->queryName();
  5464. unsigned flags = orFilter->querySearchFlags();
  5465. const StringArray& values = orFilter->queryValues();
  5466. ForEachItemIn(i, values)
  5467. {
  5468. StringBuffer path(xPath.get());
  5469. const char* value = values.item(i);
  5470. if (!isEmptyString(value))
  5471. {
  5472. appendFilterToQueryString(path, flags, fieldName, value);
  5473. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5474. if (itr)
  5475. {
  5476. multi->addSource(*itr);
  5477. added = true;
  5478. }
  5479. }
  5480. }
  5481. if (added)
  5482. iter.setown(multi.getClear());
  5483. }
  5484. if (!iter)
  5485. return NULL;
  5486. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5487. return conn.getClear();
  5488. }
  5489. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5490. };
  5491. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5492. {
  5493. UniqueScopes done;
  5494. ISecManager *secmgr;
  5495. ISecUser *secuser;
  5496. CriticalSection crit;
  5497. public:
  5498. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5499. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5500. {
  5501. secmgr = _secmgr;
  5502. secuser = _secuser;
  5503. }
  5504. bool isOK(IPropertyTree &tree)
  5505. {
  5506. const char *scopename = tree.queryProp("@scope");
  5507. if (!scopename||!*scopename)
  5508. return true;
  5509. {
  5510. CriticalBlock block(crit);
  5511. const bool *b = done.getValue(scopename);
  5512. if (b)
  5513. return *b;
  5514. }
  5515. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5516. {
  5517. // conceivably could have already been checked and added, but ok.
  5518. CriticalBlock block(crit);
  5519. done.setValue(scopename,ret);
  5520. }
  5521. return ret;
  5522. }
  5523. };
  5524. Owned<CQueryOrFilter> orFilter;
  5525. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5526. StringBuffer query;
  5527. StringBuffer so;
  5528. StringAttr namefilter("*");
  5529. StringAttr namefilterlo;
  5530. StringAttr namefilterhi;
  5531. StringArray unknownAttributes;
  5532. if (filters)
  5533. {
  5534. const char *fv = (const char *) filterbuf;
  5535. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5536. {
  5537. assertex(fv);
  5538. int fmt = filters[i];
  5539. int subfmt = (fmt&0xff);
  5540. if (subfmt==WUSFwuid)
  5541. namefilterlo.set(fv);
  5542. else if (subfmt==WUSFwuidhigh)
  5543. namefilterhi.set(fv);
  5544. else if (subfmt==WUSFwildwuid)
  5545. namefilter.set(fv);
  5546. else if (subfmt==WUSFappvalue)
  5547. {
  5548. const char *app = fv;
  5549. fv = fv + strlen(fv)+1;
  5550. query.append("[Application/").append(app);
  5551. if (*fv)
  5552. query.append("=?~\"").append(fv).append('\"');
  5553. query.append("]");
  5554. }
  5555. else if (subfmt==WUSFtotalthortime)
  5556. {
  5557. query.append("[@totalThorTime>=\"");
  5558. formatTimeCollatable(query, milliToNano(atoi(fv)), false);
  5559. query.append("\"]");
  5560. }
  5561. else if (!*fv)
  5562. {
  5563. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5564. if (subfmt==WUSFtotalthortime)
  5565. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5566. }
  5567. else
  5568. {
  5569. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5570. if (!strchr(fv, '|'))
  5571. appendFilterToQueryString(query, fmt, fieldName, fv);
  5572. else if (orFilter)
  5573. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5574. else
  5575. {
  5576. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5577. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5578. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5579. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5580. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5581. }
  5582. }
  5583. fv = fv + strlen(fv)+1;
  5584. }
  5585. }
  5586. if ((sortorder&0xff)==WUSFtotalthortime)
  5587. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5588. query.insert(0, namefilter.get());
  5589. if (sortorder)
  5590. {
  5591. if (so.length())
  5592. so.append(',');
  5593. if (sortorder & WUSFreverse)
  5594. so.append('-');
  5595. if (sortorder & WUSFnocase)
  5596. so.append('?');
  5597. if (sortorder & WUSFnumeric)
  5598. so.append('#');
  5599. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5600. }
  5601. IArrayOf<IPropertyTree> results;
  5602. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5603. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5604. return new CConstWUArrayIterator(results);
  5605. }
  5606. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5607. {
  5608. WUState ret = WUStateUnknown;
  5609. StringBuffer wuRoot;
  5610. getXPath(wuRoot, wuid);
  5611. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5612. if (timeout == 0) //no need to subscribe
  5613. {
  5614. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5615. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5616. if (it != expectedStates.end())
  5617. return ret;
  5618. switch (ret)
  5619. {
  5620. case WUStateCompiled:
  5621. case WUStateUploadingFiles:
  5622. if (!compiled)
  5623. break;
  5624. //fall through
  5625. case WUStateCompleted:
  5626. case WUStateFailed:
  5627. case WUStateAborted:
  5628. return ret;
  5629. default:
  5630. break;
  5631. }
  5632. return WUStateUnknown;
  5633. }
  5634. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5635. LocalIAbortHandler abortHandler(*waiter);
  5636. if (conn)
  5637. {
  5638. SessionId agent = -1;
  5639. bool agentSessionStopped = false;
  5640. unsigned start = msTick();
  5641. for (;;)
  5642. {
  5643. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5644. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5645. if (it != expectedStates.end())
  5646. return ret;
  5647. switch (ret)
  5648. {
  5649. case WUStateCompiled:
  5650. case WUStateUploadingFiles:
  5651. if (!compiled)
  5652. break;
  5653. // fall into
  5654. case WUStateCompleted:
  5655. case WUStateFailed:
  5656. case WUStateAborted:
  5657. return ret;
  5658. case WUStateWait:
  5659. break;
  5660. case WUStateCompiling:
  5661. case WUStateRunning:
  5662. case WUStateDebugPaused:
  5663. case WUStateDebugRunning:
  5664. case WUStateBlocked:
  5665. case WUStateAborting:
  5666. if (agentSessionStopped)
  5667. {
  5668. reportAbnormalTermination(wuid, ret, agent);
  5669. return ret;
  5670. }
  5671. if (queryDaliServerVersion().compare("2.1")>=0)
  5672. {
  5673. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5674. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5675. {
  5676. agentSessionStopped = true;
  5677. conn->reload();
  5678. continue;
  5679. }
  5680. }
  5681. break;
  5682. }
  5683. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5684. unsigned waited = msTick() - start;
  5685. if (timeout==-1 || waited + 20000 < timeout)
  5686. {
  5687. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5688. if (waiter->isAborted())
  5689. {
  5690. ret = WUStateUnknown; // MORE - throw an exception?
  5691. break;
  5692. }
  5693. }
  5694. else if (waited > timeout || !waiter->wait(timeout-waited))
  5695. {
  5696. ret = WUStateUnknown; // MORE - throw an exception?
  5697. break;
  5698. }
  5699. conn->reload();
  5700. }
  5701. }
  5702. return ret;
  5703. }
  5704. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5705. {
  5706. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5707. LocalIAbortHandler abortHandler(*waiter);
  5708. WUAction ret = WUActionUnknown;
  5709. StringBuffer wuRoot;
  5710. getXPath(wuRoot, wuid);
  5711. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5712. if (conn)
  5713. {
  5714. unsigned start = msTick();
  5715. for (;;)
  5716. {
  5717. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5718. if (ret != original)
  5719. break;
  5720. unsigned waited = msTick() - start;
  5721. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5722. if (waiter->isAborted())
  5723. {
  5724. ret = WUActionUnknown; // MORE - throw an exception?
  5725. break;
  5726. }
  5727. conn->reload();
  5728. }
  5729. }
  5730. waiter->unsubscribe();
  5731. return ret;
  5732. }
  5733. protected:
  5734. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5735. {
  5736. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5737. if (conn)
  5738. {
  5739. CDaliVersion serverVersionNeeded("3.2");
  5740. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5741. conn->queryRoot()->getElements(xpath) :
  5742. conn->getElements(xpath));
  5743. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5744. }
  5745. else
  5746. return NULL;
  5747. }
  5748. ISDSManager *sdsManager;
  5749. SessionId session;
  5750. };
  5751. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5752. {
  5753. if (secmgr)
  5754. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5755. else
  5756. return iter;
  5757. }
  5758. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5759. {
  5760. if (secmgr)
  5761. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5762. else
  5763. return new CConstWUIterator(iter);
  5764. }
  5765. static CriticalSection factoryCrit;
  5766. static Owned<IWorkUnitFactory> globalFactory;
  5767. void CDaliWorkUnitFactory::clientShutdown()
  5768. {
  5769. CriticalBlock b(factoryCrit);
  5770. globalFactory.clear();
  5771. }
  5772. void clientShutdownWorkUnit()
  5773. {
  5774. CriticalBlock b(factoryCrit);
  5775. globalFactory.clear();
  5776. }
  5777. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5778. {
  5779. CriticalBlock b(factoryCrit);
  5780. globalFactory.setown(_factory);
  5781. }
  5782. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5783. {
  5784. if (!globalFactory)
  5785. {
  5786. CriticalBlock b(factoryCrit);
  5787. if (!globalFactory) // NOTE - this "double test" paradigm is not guaranteed threadsafe on modern systems/compilers - I think in this instance that is harmless even in the (extremely) unlikely event that it resulted in the setown being called twice.
  5788. {
  5789. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5790. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5791. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5792. IPropertyTree *pluginInfo = NULL;
  5793. if (env)
  5794. {
  5795. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5796. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5797. if (daliInfo)
  5798. {
  5799. const char *daliName = daliInfo->queryProp("@name");
  5800. if (daliName)
  5801. {
  5802. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5803. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5804. }
  5805. if (!pluginInfo)
  5806. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5807. }
  5808. }
  5809. if (pluginInfo && !forceDali)
  5810. globalFactory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5811. else
  5812. globalFactory.setown(new CDaliWorkUnitFactory());
  5813. }
  5814. }
  5815. return globalFactory.getLink();
  5816. }
  5817. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5818. {
  5819. if (!globalFactory)
  5820. {
  5821. CriticalBlock b(factoryCrit);
  5822. if (!globalFactory) // NOTE - this "double test" paradigm is not guaranteed threadsafe on modern systems/compilers - I think in this instance that is harmless even in the (extremely) unlikely event that it resulted in the setown being called twice.
  5823. globalFactory.setown(new CDaliWorkUnitFactory());
  5824. }
  5825. return globalFactory.getLink();
  5826. }
  5827. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5828. // They can still be supplied if you want...
  5829. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5830. {
  5831. public:
  5832. IMPLEMENT_IINTERFACE;
  5833. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5834. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5835. {
  5836. }
  5837. virtual bool initializeStore()
  5838. {
  5839. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5840. }
  5841. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5842. {
  5843. return baseFactory->getWatcher(subscriber, options, wuid);
  5844. }
  5845. virtual unsigned validateRepository(bool fix)
  5846. {
  5847. return baseFactory->validateRepository(fix);
  5848. }
  5849. virtual void deleteRepository(bool recreate)
  5850. {
  5851. return baseFactory->deleteRepository(recreate);
  5852. }
  5853. virtual void createRepository()
  5854. {
  5855. return baseFactory->createRepository();
  5856. }
  5857. virtual const char *queryStoreType() const
  5858. {
  5859. return baseFactory->queryStoreType();
  5860. }
  5861. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5862. {
  5863. return baseFactory->getUniqueValues(field, prefix, result);
  5864. }
  5865. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5866. {
  5867. if (!secMgr) secMgr = defaultSecMgr.get();
  5868. if (!secUser) secUser = defaultSecUser.get();
  5869. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5870. }
  5871. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5872. {
  5873. if (!secMgr) secMgr = defaultSecMgr.get();
  5874. if (!secUser) secUser = defaultSecUser.get();
  5875. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5876. }
  5877. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5878. {
  5879. if (!secMgr) secMgr = defaultSecMgr.get();
  5880. if (!secUser) secUser = defaultSecUser.get();
  5881. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5882. }
  5883. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5884. {
  5885. if (!secMgr) secMgr = defaultSecMgr.get();
  5886. if (!secUser) secUser = defaultSecUser.get();
  5887. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5888. }
  5889. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5890. {
  5891. if (!secMgr) secMgr = defaultSecMgr.get();
  5892. if (!secUser) secUser = defaultSecUser.get();
  5893. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5894. }
  5895. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5896. {
  5897. if (!secMgr) secMgr = defaultSecMgr.get();
  5898. if (!secUser) secUser = defaultSecUser.get();
  5899. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5900. }
  5901. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5902. {
  5903. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5904. }
  5905. virtual void importWorkUnit(const char *zapReportFileName, const char *zapReportPassword,
  5906. const char *importDir, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5907. {
  5908. baseFactory->importWorkUnit(zapReportFileName, zapReportPassword, importDir, app, user, secMgr, secUser);
  5909. }
  5910. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5911. {
  5912. if (!secMgr) secMgr = defaultSecMgr.get();
  5913. if (!secUser) secUser = defaultSecUser.get();
  5914. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5915. }
  5916. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5917. {
  5918. if (!secMgr) secMgr = defaultSecMgr.get();
  5919. if (!secUser) secUser = defaultSecUser.get();
  5920. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5921. }
  5922. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5923. {
  5924. if (!secMgr) secMgr = defaultSecMgr.get();
  5925. if (!secUser) secUser = defaultSecUser.get();
  5926. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5927. }
  5928. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5929. {
  5930. if (!secMgr) secMgr = defaultSecMgr.get();
  5931. if (!secUser) secUser = defaultSecUser.get();
  5932. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5933. }
  5934. virtual int setTracingLevel(int newLevel)
  5935. {
  5936. return baseFactory->setTracingLevel(newLevel);
  5937. }
  5938. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5939. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5940. const void *filterbuf, // (appended) string values for filters
  5941. unsigned startoffset,
  5942. unsigned maxnum,
  5943. __int64 *cachehint,
  5944. unsigned *total,
  5945. ISecManager *secMgr, ISecUser *secUser)
  5946. {
  5947. if (!secMgr) secMgr = defaultSecMgr.get();
  5948. if (!secUser) secUser = defaultSecUser.get();
  5949. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5950. }
  5951. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5952. WUQuerySortField *filters,
  5953. const void *filterbuf,
  5954. unsigned startoffset,
  5955. unsigned maxnum,
  5956. __int64 *cachehint,
  5957. unsigned *total,
  5958. const MapStringTo<bool> *subset,
  5959. const MapStringTo<bool> *suspendedByCluster)
  5960. {
  5961. // MORE - why no security?
  5962. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset,suspendedByCluster);
  5963. }
  5964. virtual unsigned numWorkUnits()
  5965. {
  5966. return baseFactory->numWorkUnits();
  5967. }
  5968. virtual bool isAborting(const char *wuid) const
  5969. {
  5970. return baseFactory->isAborting(wuid);
  5971. }
  5972. virtual void clearAborting(const char *wuid)
  5973. {
  5974. baseFactory->clearAborting(wuid);
  5975. }
  5976. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5977. {
  5978. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, expectedStates);
  5979. }
  5980. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5981. {
  5982. return baseFactory->waitForWorkUnitAction(wuid, original);
  5983. }
  5984. private:
  5985. Owned<IWorkUnitFactory> baseFactory;
  5986. Linked<ISecManager> defaultSecMgr;
  5987. Linked<ISecUser> defaultSecUser;
  5988. };
  5989. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5990. {
  5991. if (secmgr && secuser)
  5992. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5993. else
  5994. return getWorkUnitFactory();
  5995. }
  5996. //==========================================================================================
  5997. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5998. {
  5999. Owned<IPropertyTreeIterator> it;
  6000. public:
  6001. IMPLEMENT_IINTERFACE;
  6002. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  6003. virtual bool first() { return it->first(); }
  6004. virtual bool next() { return it->next(); }
  6005. virtual bool isValid() { return it->isValid(); }
  6006. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  6007. };
  6008. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  6009. {
  6010. Owned<IPropertyTreeIterator> it;
  6011. public:
  6012. IMPLEMENT_IINTERFACE;
  6013. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  6014. virtual bool first() { return it->first(); }
  6015. virtual bool next() { return it->next(); }
  6016. virtual bool isValid() { return it->isValid(); }
  6017. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  6018. };
  6019. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  6020. {
  6021. Owned<IPropertyTreeIterator> it;
  6022. StringAttr name;
  6023. public:
  6024. IMPLEMENT_IINTERFACE;
  6025. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  6026. virtual bool first() { return it->first(); }
  6027. virtual bool next() { return it->next(); }
  6028. virtual bool isValid() { return it->isValid(); }
  6029. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  6030. };
  6031. //==========================================================================================
  6032. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  6033. {
  6034. clearCached(false);
  6035. secMgr.set(secmgr);
  6036. secUser.set(secuser);
  6037. workflowIteratorCached = false;
  6038. resultsCached = false;
  6039. graphsCached = false;
  6040. temporariesCached = false;
  6041. variablesCached = false;
  6042. exceptionsCached = false;
  6043. pluginsCached = false;
  6044. librariesCached = false;
  6045. activitiesCached = false;
  6046. webServicesInfoCached = false;
  6047. roxieQueryInfoCached = false;
  6048. }
  6049. void CLocalWorkUnit::clearCached(bool clearTree)
  6050. {
  6051. query.clear();
  6052. webServicesInfo.clear();
  6053. workflowIterator.clear();
  6054. graphs.kill();
  6055. results.kill();
  6056. variables.kill();
  6057. plugins.kill();
  6058. libraries.kill();
  6059. exceptions.kill();
  6060. temporaries.kill();
  6061. statistics.kill();
  6062. appvalues.kill();
  6063. if (clearTree)
  6064. p.clear();
  6065. workflowIteratorCached = false;
  6066. resultsCached = false;
  6067. graphsCached = false;
  6068. temporariesCached = false;
  6069. variablesCached = false;
  6070. exceptionsCached = false;
  6071. pluginsCached = false;
  6072. librariesCached = false;
  6073. activitiesCached = false;
  6074. webServicesInfoCached = false;
  6075. roxieQueryInfoCached = false;
  6076. }
  6077. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  6078. {
  6079. clearCached(false);
  6080. p.setown(ptree);
  6081. }
  6082. void CLocalWorkUnit::beforeDispose()
  6083. {
  6084. try
  6085. {
  6086. unsubscribe();
  6087. clearCached(true);
  6088. userDesc.clear();
  6089. secMgr.clear();
  6090. secUser.clear();
  6091. }
  6092. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  6093. }
  6094. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  6095. {
  6096. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  6097. // Delete any related things in SDS etc that might otherwise be forgotten
  6098. if (p->getPropBool("@protected", false))
  6099. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  6100. switch (getState())
  6101. {
  6102. case WUStateAborted:
  6103. case WUStateCompleted:
  6104. case WUStateFailed:
  6105. case WUStateArchived:
  6106. break;
  6107. case WUStateCompiled:
  6108. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  6109. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  6110. break;
  6111. case WUStateWait:
  6112. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  6113. default:
  6114. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  6115. break;
  6116. }
  6117. if (getIsQueryService())
  6118. {
  6119. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  6120. if (registry)
  6121. {
  6122. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  6123. if (registry->hasProp(xpath.str()))
  6124. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  6125. }
  6126. }
  6127. try
  6128. {
  6129. if (deldll && !p->getPropBool("@isClone", false))
  6130. {
  6131. Owned<IConstWUQuery> q = getQuery();
  6132. if (q)
  6133. {
  6134. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  6135. SCMStringBuffer name;
  6136. ForEach(*iter)
  6137. {
  6138. IConstWUAssociatedFile & cur = iter->query();
  6139. cur.getNameTail(name);
  6140. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  6141. {
  6142. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  6143. if (entry.get())
  6144. asyncRemoveDll(name.str());
  6145. else
  6146. {
  6147. SCMStringBuffer ip, localPath;
  6148. cur.getName(localPath);
  6149. cur.getIp(ip);
  6150. asyncRemoveFile(ip.str(), localPath.str());
  6151. }
  6152. }
  6153. }
  6154. }
  6155. }
  6156. globalFactory->clearAborting(queryWuid());
  6157. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  6158. }
  6159. catch(IException *E)
  6160. {
  6161. StringBuffer s;
  6162. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  6163. E->Release();
  6164. }
  6165. catch (...)
  6166. {
  6167. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  6168. }
  6169. }
  6170. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  6171. {
  6172. SCMStringBuffer strval;
  6173. val.getGmtString(strval);
  6174. p->setProp("@timescheduled",strval.str());
  6175. }
  6176. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  6177. {
  6178. StringBuffer str;
  6179. p->getProp("@timescheduled",str);
  6180. if(str.length())
  6181. val.setGmtString(str.str());
  6182. return val;
  6183. }
  6184. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  6185. {
  6186. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  6187. if (extra.length())
  6188. {
  6189. const char *bufStart = buf.str();
  6190. const char *bufPtr = bufStart+buf.length();
  6191. while (bufStart != bufPtr)
  6192. {
  6193. --bufPtr;
  6194. if (!isspace(*bufPtr))
  6195. break;
  6196. }
  6197. assertex('>' == *bufPtr);
  6198. size_t l = strlen(wuid);
  6199. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  6200. bufPtr -= l+2; // skip back over </wuid
  6201. assertex(0 == memcmp(bufPtr, "</", 2) );
  6202. assertex(0 == memcmp(bufPtr+2, wuid, l));
  6203. buf.insert(bufPtr-bufStart, extra);
  6204. }
  6205. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  6206. }
  6207. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  6208. {
  6209. CriticalBlock block(crit);
  6210. StringBuffer path(base);
  6211. if (!p)
  6212. return false;
  6213. const char *wuid = p->queryName();
  6214. if (!wuid||!*wuid)
  6215. return false;
  6216. addPathSepChar(path).append(wuid).append(".xml");
  6217. Owned<IFile> file = createIFile(path.str());
  6218. if (!file)
  6219. return false;
  6220. Owned<IFileIO> fileio = file->open(IFOcreate);
  6221. if (!fileio)
  6222. return false;
  6223. StringBuffer buf;
  6224. exportWorkUnitToXML(this, buf, false, false, true);
  6225. StringBuffer extraWorkUnitXML;
  6226. Owned<IPTree> graphProgress = getGraphProgressTree();
  6227. if (graphProgress)
  6228. {
  6229. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  6230. graphProgress.clear();
  6231. }
  6232. Owned<IConstWUQuery> q = getQuery();
  6233. if (!q)
  6234. {
  6235. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6236. return false;
  6237. if (del)
  6238. {
  6239. if (getState()==WUStateUnknown)
  6240. setState(WUStateArchived); // to allow delete
  6241. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  6242. }
  6243. return false;
  6244. }
  6245. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  6246. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  6247. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  6248. ForEach(*iter)
  6249. {
  6250. IConstWUAssociatedFile & cur = iter->query();
  6251. SCMStringBuffer name;
  6252. cur.getNameTail(name);
  6253. if (name.length())
  6254. {
  6255. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  6256. SCMStringBuffer curPath, curIp;
  6257. cur.getName(curPath);
  6258. cur.getIp(curIp);
  6259. SocketEndpoint curEp(curIp.str());
  6260. RemoteFilename curRfn;
  6261. curRfn.setPath(curEp, curPath.str());
  6262. StringBuffer dst(base);
  6263. addPathSepChar(dst);
  6264. curRfn.getTail(dst);
  6265. Owned<IFile> dstFile = createIFile(dst.str());
  6266. if (entry.get())
  6267. {
  6268. Owned<IException> exception;
  6269. Owned<IDllLocation> loc;
  6270. Owned<IPropertyTree> generatedDllBranch = createPTree();
  6271. generatedDllBranch->setProp("@name", entry->queryName());
  6272. generatedDllBranch->setProp("@kind", entry->queryKind());
  6273. if (exportAssociatedFiles)
  6274. {
  6275. try
  6276. {
  6277. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  6278. }
  6279. catch(IException * e)
  6280. {
  6281. exception.setown(e);
  6282. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  6283. }
  6284. RemoteFilename filename;
  6285. loc->getDllFilename(filename);
  6286. if (!exception)
  6287. {
  6288. Owned<IFile> srcfile = createIFile(filename);
  6289. try
  6290. {
  6291. if (dstFile->exists())
  6292. {
  6293. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  6294. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  6295. // still want to delete if already archived but there are source file copies
  6296. }
  6297. else
  6298. copyFile(dstFile, srcfile);
  6299. }
  6300. catch(IException * e)
  6301. {
  6302. exception.setown(e);
  6303. }
  6304. }
  6305. if (exception)
  6306. {
  6307. if (ignoredllerrors)
  6308. {
  6309. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  6310. //copy failed, so don't delete the registered dll files
  6311. deleteExclusions.append(name.str());
  6312. }
  6313. else
  6314. throw exception.getClear();
  6315. }
  6316. }
  6317. // Record Associated path to restore back to
  6318. StringBuffer restorePath;
  6319. curRfn.getRemotePath(restorePath);
  6320. generatedDllBranch->setProp("@location", restorePath.str());
  6321. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  6322. }
  6323. else if (exportAssociatedFiles) // no generated dll entry
  6324. {
  6325. Owned<IFile> srcFile = createIFile(curRfn);
  6326. try
  6327. {
  6328. copyFile(dstFile, srcFile);
  6329. }
  6330. catch (IException *e)
  6331. {
  6332. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  6333. EXCLOG(e, msg.str());
  6334. e->Release();
  6335. deleteExclusions.append(name.str());
  6336. }
  6337. }
  6338. }
  6339. }
  6340. iter.clear();
  6341. if (generatedDlls->numChildren())
  6342. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  6343. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6344. return false;
  6345. if (del)
  6346. {
  6347. //setState(WUStateArchived); // this isn't useful as about to delete it!
  6348. q.clear();
  6349. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  6350. }
  6351. return true;
  6352. }
  6353. void CLocalWorkUnit::loadXML(const char *xml)
  6354. {
  6355. CriticalBlock block(crit);
  6356. clearCached(true);
  6357. assertex(xml);
  6358. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  6359. }
  6360. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  6361. {
  6362. CriticalBlock block(crit);
  6363. StringBuffer x;
  6364. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  6365. }
  6366. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  6367. {
  6368. CriticalBlock block(crit);
  6369. StringAttr value;
  6370. src.read(value);
  6371. loadXML(value);
  6372. }
  6373. void CLocalWorkUnit::requestAbort()
  6374. {
  6375. CriticalBlock block(crit);
  6376. abortWorkUnit(p->queryName());
  6377. }
  6378. void CLocalWorkUnit::unlockRemote()
  6379. {
  6380. CriticalBlock block(crit);
  6381. locked.unlock();
  6382. _unlockRemote();
  6383. }
  6384. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6385. {
  6386. if (secMgr)
  6387. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6388. locked.lock();
  6389. CriticalBlock block(crit);
  6390. if (commit)
  6391. {
  6392. try
  6393. {
  6394. _lockRemote();
  6395. }
  6396. catch (IException *E)
  6397. {
  6398. StringBuffer s;
  6399. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6400. locked.unlock();
  6401. throw;
  6402. }
  6403. }
  6404. return *new CLockedWorkUnit(LINK(this));
  6405. }
  6406. void CLocalWorkUnit::commit()
  6407. {
  6408. // Nothing to do if not backed by a persistent store
  6409. }
  6410. IWorkUnit& CLocalWorkUnit::lock()
  6411. {
  6412. return lockRemote(true);
  6413. }
  6414. const char *CLocalWorkUnit::queryWuid() const
  6415. {
  6416. CriticalBlock block(crit);
  6417. return p->queryName();
  6418. }
  6419. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6420. {
  6421. CriticalBlock block(crit);
  6422. return p->getPropInt("@DebugListenerPort", 0);
  6423. }
  6424. unsigned CLocalWorkUnit::getTotalThorTime() const
  6425. {
  6426. CriticalBlock block(crit);
  6427. if (p->hasProp("@totalThorTime"))
  6428. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6429. const WuScopeFilter filter("stype[graph],nested[0],stat[TimeElapsed]");
  6430. StatsAggregation summary;
  6431. aggregateStatistic(summary, (IConstWorkUnit *)this, filter, StTimeElapsed);
  6432. return (unsigned)nanoToMilli(summary.getSum());
  6433. }
  6434. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6435. {
  6436. CriticalBlock block(crit);
  6437. p->setPropInt("@DebugListenerPort", port);
  6438. }
  6439. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6440. {
  6441. CriticalBlock block(crit);
  6442. ip.set(p->queryProp("@DebugListenerIP"));
  6443. return ip;
  6444. }
  6445. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6446. {
  6447. CriticalBlock block(crit);
  6448. p->setProp("@DebugListenerIP", ip);
  6449. }
  6450. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6451. {
  6452. CriticalBlock block(crit);
  6453. datoken.set(p->queryProp("@distributedAccessToken"));
  6454. return datoken;
  6455. }
  6456. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6457. {
  6458. CriticalBlock block(crit);
  6459. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6460. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6461. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6462. if (pDSM && pDSM->isDigiSignerConfigured())
  6463. {
  6464. datoken.append(pDSM->queryKeyName()).append(';');
  6465. StringBuffer b64Signature;
  6466. if (pDSM->digiSign(b64Signature, datoken))
  6467. {
  6468. datoken.append(b64Signature.str());
  6469. }
  6470. else
  6471. {
  6472. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6473. return false;
  6474. }
  6475. }
  6476. else
  6477. {
  6478. if (workUnitTraceLevel > 1)
  6479. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6480. datoken.append(";");
  6481. }
  6482. p->setProp("@distributedAccessToken", datoken);
  6483. return true;
  6484. }
  6485. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6486. {
  6487. // Only implemented in derived classes
  6488. return false;
  6489. }
  6490. void CLocalWorkUnit::setJobName(const char *value)
  6491. {
  6492. CriticalBlock block(crit);
  6493. p->setProp("@jobName", value);
  6494. }
  6495. const char *CLocalWorkUnit::queryJobName() const
  6496. {
  6497. CriticalBlock block(crit);
  6498. const char *ret = p->queryProp("@jobName");
  6499. if (!ret)
  6500. ret = "";
  6501. return ret;
  6502. }
  6503. void CLocalWorkUnit::setClusterName(const char *value)
  6504. {
  6505. CriticalBlock block(crit);
  6506. p->setProp("@clusterName", value);
  6507. }
  6508. const char *CLocalWorkUnit::queryClusterName() const
  6509. {
  6510. CriticalBlock block(crit);
  6511. const char *ret = p->queryProp("@clusterName");
  6512. if (!ret)
  6513. ret = "";
  6514. return ret;
  6515. }
  6516. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6517. {
  6518. setDebugValue("allowedclusters",value, true);
  6519. }
  6520. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6521. {
  6522. CriticalBlock block(crit);
  6523. getDebugValue("allowedclusters",str);
  6524. if (str.length()!=0)
  6525. return str;
  6526. str.set(p->queryProp("@clusterName"));
  6527. return str;
  6528. }
  6529. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6530. {
  6531. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6532. }
  6533. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6534. {
  6535. CriticalBlock block(crit);
  6536. return getDebugValueBool("allowautoqueueswitch",false);
  6537. }
  6538. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6539. {
  6540. StringBuffer suffix;
  6541. if (name && *name)
  6542. setApplicationValue("LibraryModule", "name", name, true);
  6543. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6544. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6545. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6546. }
  6547. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6548. {
  6549. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6550. if (writeaccess)
  6551. auditflags |= DALI_LDAP_WRITE_WANTED;
  6552. SecAccessFlags perm = SecAccess_Full;
  6553. const char *scopename = p->queryProp("@scope");
  6554. if (scopename&&*scopename) {
  6555. if (!user)
  6556. user = queryUserDescriptor();
  6557. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6558. if (perm<0) {
  6559. if (perm == SecAccess_Unavailable)
  6560. perm = SecAccess_Full;
  6561. else
  6562. perm = SecAccess_None;
  6563. }
  6564. }
  6565. if (!HASREADPERMISSION(perm))
  6566. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6567. if (writeaccess && !HASWRITEPERMISSION(perm))
  6568. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6569. }
  6570. void CLocalWorkUnit::setUser(const char * value)
  6571. {
  6572. CriticalBlock block(crit);
  6573. p->setProp("@submitID", value);
  6574. }
  6575. const char *CLocalWorkUnit::queryUser() const
  6576. {
  6577. CriticalBlock block(crit);
  6578. const char *ret = p->queryProp("@submitID");
  6579. if (!ret)
  6580. ret = "";
  6581. return ret;
  6582. }
  6583. void CLocalWorkUnit::setWuScope(const char * value)
  6584. {
  6585. if (value && *value)
  6586. {
  6587. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6588. {
  6589. CriticalBlock block(crit);
  6590. p->setProp("@scope", value);
  6591. }
  6592. }
  6593. }
  6594. const char *CLocalWorkUnit::queryWuScope() const
  6595. {
  6596. CriticalBlock block(crit);
  6597. const char *ret = p->queryProp("@scope");
  6598. if (!ret)
  6599. ret = "";
  6600. return ret;
  6601. }
  6602. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6603. {
  6604. CriticalBlock block(crit);
  6605. setEnum(p, "@priorityClass", cls, priorityClasses);
  6606. }
  6607. WUPriorityClass CLocalWorkUnit::getPriority() const
  6608. {
  6609. CriticalBlock block(crit);
  6610. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6611. }
  6612. const char *CLocalWorkUnit::queryPriorityDesc() const
  6613. {
  6614. return getEnumText(getPriority(), priorityClasses);
  6615. }
  6616. void CLocalWorkUnit::setState(WUState value)
  6617. {
  6618. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6619. {
  6620. if (globalFactory)
  6621. globalFactory->clearAborting(queryWuid());
  6622. }
  6623. CriticalBlock block(crit);
  6624. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6625. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6626. if (getDebugValueBool("monitorWorkunit", false))
  6627. {
  6628. switch(value)
  6629. {
  6630. case WUStateAborted:
  6631. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6632. break;
  6633. case WUStateCompleted:
  6634. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6635. break;
  6636. case WUStateFailed:
  6637. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6638. break;
  6639. }
  6640. }
  6641. p->removeProp("@stateEx");
  6642. }
  6643. void CLocalWorkUnit::setStateEx(const char * text)
  6644. {
  6645. CriticalBlock block(crit);
  6646. p->setProp("@stateEx", text);
  6647. }
  6648. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6649. {
  6650. CriticalBlock block(crit);
  6651. p->setPropInt64("@agentSession", sessionId);
  6652. }
  6653. bool CLocalWorkUnit::getIsQueryService() const
  6654. {
  6655. CriticalBlock block(crit);
  6656. return p->getPropBool("@isQueryService", false);
  6657. }
  6658. void CLocalWorkUnit::setIsQueryService(bool value)
  6659. {
  6660. CriticalBlock block(crit);
  6661. p->setPropBool("@isQueryService", value);
  6662. }
  6663. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6664. {
  6665. if (queryDaliServerVersion().compare("2.1")<0)
  6666. return;
  6667. switch(state)
  6668. {
  6669. case WUStateRunning:
  6670. case WUStateDebugPaused:
  6671. case WUStateDebugRunning:
  6672. case WUStateBlocked:
  6673. case WUStateAborting:
  6674. case WUStateCompiling:
  6675. case WUStatePaused:
  6676. {
  6677. SessionId agent = getAgentSession();
  6678. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6679. {
  6680. forceReload();
  6681. state = (WUState) getEnum(p, "@state", states);
  6682. bool isecl=state==WUStateCompiling;
  6683. if (aborting())
  6684. state = WUStateAborted;
  6685. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6686. state = WUStateFailed;
  6687. else
  6688. return;
  6689. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6690. Owned<IWorkUnit> w = &lock();
  6691. w->setState(state);
  6692. Owned<IWUException> e = w->createException();
  6693. WUAction action = w->getAction();
  6694. switch (action)
  6695. {
  6696. case WUActionPause:
  6697. case WUActionPauseNow:
  6698. case WUActionResume:
  6699. w->setAction(WUActionUnknown);
  6700. }
  6701. if(isecl)
  6702. {
  6703. e->setExceptionCode(1001);
  6704. e->setExceptionMessage("EclServer terminated unexpectedly");
  6705. }
  6706. else
  6707. {
  6708. e->setExceptionCode(1000);
  6709. e->setExceptionMessage("Workunit terminated unexpectedly");
  6710. }
  6711. }
  6712. }
  6713. }
  6714. }
  6715. WUState CLocalWorkUnit::getState() const
  6716. {
  6717. CriticalBlock block(crit);
  6718. WUState state = (WUState) getEnum(p, "@state", states);
  6719. switch (state)
  6720. {
  6721. case WUStateRunning:
  6722. case WUStateDebugPaused:
  6723. case WUStateDebugRunning:
  6724. case WUStateBlocked:
  6725. case WUStateCompiling:
  6726. if (aborting())
  6727. state = WUStateAborting;
  6728. break;
  6729. case WUStateSubmitted:
  6730. if (aborting())
  6731. state = WUStateAborted;
  6732. break;
  6733. }
  6734. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6735. return state;
  6736. }
  6737. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6738. {
  6739. CriticalBlock block(crit);
  6740. str.set(p->queryProp("@stateEx"));
  6741. return str;
  6742. }
  6743. __int64 CLocalWorkUnit::getAgentSession() const
  6744. {
  6745. CriticalBlock block(crit);
  6746. return p->getPropInt64("@agentSession", -1);
  6747. }
  6748. unsigned CLocalWorkUnit::getAgentPID() const
  6749. {
  6750. CriticalBlock block(crit);
  6751. return p->getPropInt("@agentPID", -1);
  6752. }
  6753. const char * CLocalWorkUnit::queryStateDesc() const
  6754. {
  6755. // MORE - not sure about this - may prefer a separate interface
  6756. CriticalBlock block(crit);
  6757. try
  6758. {
  6759. return getEnumText(getState(), states);
  6760. }
  6761. catch (...)
  6762. {
  6763. return "???";
  6764. }
  6765. }
  6766. void CLocalWorkUnit::setAction(WUAction value)
  6767. {
  6768. CriticalBlock block(crit);
  6769. setEnum(p, "Action", value, actions);
  6770. }
  6771. WUAction CLocalWorkUnit::getAction() const
  6772. {
  6773. CriticalBlock block(crit);
  6774. return (WUAction) getEnum(p, "Action", actions);
  6775. }
  6776. const char *CLocalWorkUnit::queryActionDesc() const
  6777. {
  6778. CriticalBlock block(crit);
  6779. return p->queryProp("Action");
  6780. }
  6781. bool CLocalWorkUnit::hasApplicationValue(const char *app, const char *propname) const
  6782. {
  6783. StringBuffer prop("Application/");
  6784. prop.append(app).append('/').append(propname);
  6785. CriticalBlock block(crit);
  6786. return p->hasProp(prop);
  6787. }
  6788. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6789. {
  6790. StringBuffer prop("Application/");
  6791. prop.append(app).append('/').append(propname);
  6792. CriticalBlock block(crit);
  6793. str.set(p->queryProp(prop.str()));
  6794. return str;
  6795. }
  6796. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6797. {
  6798. StringBuffer prop("Application/");
  6799. prop.append(app).append('/').append(propname);
  6800. CriticalBlock block(crit);
  6801. return p->getPropInt(prop.str(), defVal);
  6802. }
  6803. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6804. {
  6805. CriticalBlock block(crit);
  6806. appvalues.load(p,"Application/*");
  6807. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6808. }
  6809. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6810. {
  6811. CriticalBlock block(crit);
  6812. StringBuffer prop("Application/");
  6813. prop.append(app).append('/').append(propname);
  6814. if (overwrite || !p->hasProp(prop.str()))
  6815. {
  6816. StringBuffer sp;
  6817. p->setProp(sp.append("Application").str(), "");
  6818. p->setProp(sp.append('/').append(app).str(), "");
  6819. p->setProp(prop.str(), value);
  6820. }
  6821. }
  6822. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6823. {
  6824. VStringBuffer s("%d", value);
  6825. setApplicationValue(app, propname, s, overwrite);
  6826. }
  6827. void CLocalWorkUnit::setPriorityLevel(int level)
  6828. {
  6829. CriticalBlock block(crit);
  6830. p->setPropInt("PriorityFlag", level);
  6831. }
  6832. int CLocalWorkUnit::getPriorityLevel() const
  6833. {
  6834. CriticalBlock block(crit);
  6835. return p->getPropInt("PriorityFlag");
  6836. }
  6837. int calcPriorityValue(const IPropertyTree * p)
  6838. {
  6839. int priority = p->getPropInt("PriorityFlag");
  6840. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6841. {
  6842. case PriorityClassLow:
  6843. priority -= 100;
  6844. break;
  6845. case PriorityClassHigh:
  6846. priority += 100;
  6847. break;
  6848. }
  6849. return priority;
  6850. }
  6851. int CLocalWorkUnit::getPriorityValue() const
  6852. {
  6853. CriticalBlock block(crit);
  6854. return calcPriorityValue(p);
  6855. }
  6856. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6857. {
  6858. CriticalBlock block(crit);
  6859. p->setPropInt("RescheduleFlag", (int) value);
  6860. }
  6861. bool CLocalWorkUnit::getRescheduleFlag() const
  6862. {
  6863. CriticalBlock block(crit);
  6864. return p->getPropInt("RescheduleFlag") != 0;
  6865. }
  6866. class NullIStringIterator : implements IStringIterator, public CInterface
  6867. {
  6868. public:
  6869. IMPLEMENT_IINTERFACE;
  6870. bool first() { return false; }
  6871. bool next() { return false; }
  6872. bool isValid() { return false; }
  6873. IStringVal & str(IStringVal & str) { return str; }
  6874. };
  6875. ClusterType getClusterType(const char * platform, ClusterType dft)
  6876. {
  6877. if (stricmp(platform, "thor") == 0)
  6878. return ThorLCRCluster;
  6879. if (stricmp(platform, "thorlcr") == 0)
  6880. return ThorLCRCluster;
  6881. if (stricmp(platform, "hthor") == 0)
  6882. return HThorCluster;
  6883. if (stricmp(platform, "roxie") == 0)
  6884. return RoxieCluster;
  6885. return dft;
  6886. }
  6887. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6888. {
  6889. switch (clusterType)
  6890. {
  6891. case ThorLCRCluster:
  6892. if (lcrSensitive)
  6893. return "thorlcr";
  6894. return "thor";
  6895. case RoxieCluster:
  6896. return "roxie";
  6897. case HThorCluster:
  6898. return "hthor";
  6899. }
  6900. throwUnexpected();
  6901. }
  6902. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6903. {
  6904. if (!isWorkunitDAToken(distributedAccessToken))
  6905. {
  6906. DBGLOG("Not a valid workunit distributed access token");
  6907. return false;
  6908. }
  6909. //Extract the string between [ and ]
  6910. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6911. StringBuffer tokenValues;
  6912. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6913. StringArray nameValues;
  6914. nameValues.appendList(tokenValues.str(), ",",true);
  6915. if (user || wuid)
  6916. {
  6917. for (int x = 0; x < nameValues.ordinality(); x++)
  6918. {
  6919. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6920. user->append(nameValues[x] + 2);
  6921. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6922. wuid->append(nameValues[x] + 2);
  6923. }
  6924. }
  6925. if (privKey)
  6926. {
  6927. const char * finger = pEndBracket;
  6928. ++finger;
  6929. while (*finger && *finger != ';')
  6930. privKey->append(1, finger++);
  6931. }
  6932. return true;
  6933. }
  6934. //Verifies the given signed workunit distributed access token was created
  6935. //and signed by the given wuid and user, and that the workunit is still active
  6936. //Returns:
  6937. // 0 : Success, token is valid and workunit is active
  6938. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6939. // 2 : Workunit not active
  6940. // Throws if unable to open workunit
  6941. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6942. {
  6943. #ifdef _CONTAINERIZED
  6944. if (!getComponentConfigSP()->getPropBool("@wuTokens", false))
  6945. return wuTokenInvalid;
  6946. #endif
  6947. if (isEmptyString(daToken))
  6948. {
  6949. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6950. return wuTokenInvalid;
  6951. }
  6952. StringBuffer tokWuid;
  6953. StringBuffer tokUser;
  6954. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6955. {
  6956. //Not a valid workunit distributed access token
  6957. return wuTokenInvalid;
  6958. }
  6959. //Validate signature
  6960. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6961. if (pDSM && pDSM->isDigiVerifierConfigured())
  6962. {
  6963. const char * finger;
  6964. StringBuffer token;//receives copy of everything up until signature
  6965. for (finger = daToken; *finger && *finger != ';'; finger++)
  6966. token.append(1, finger);
  6967. token.append(1, finger);//append ;
  6968. StringBuffer sig(++finger);
  6969. if (!pDSM->digiVerify(sig, token))
  6970. {
  6971. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6972. return wuTokenInvalid;
  6973. }
  6974. }
  6975. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6976. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6977. if(!cw)
  6978. {
  6979. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6980. }
  6981. //Verify user matches
  6982. bool wuUserExist = !isEmptyString(cw->queryUser());
  6983. bool tokUserExist = !isEmptyString(tokUser.str());
  6984. bool ctxUserExist = !isEmptyString(ctxUser);
  6985. if (wuUserExist && tokUserExist)
  6986. {
  6987. //if both users are found, they must match
  6988. if (!streq(tokUser.str(), cw->queryUser()))
  6989. {
  6990. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6991. return wuTokenInvalid;//Possible Internal error
  6992. }
  6993. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6994. {
  6995. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6996. return wuTokenInvalid;
  6997. }
  6998. }
  6999. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  7000. {
  7001. if (ctxUserExist)
  7002. {
  7003. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  7004. return wuTokenInvalid;
  7005. }
  7006. //both users empty and no context user means if no security enabled
  7007. }
  7008. else
  7009. {
  7010. //one user found, but not the other, treat as an error
  7011. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  7012. return wuTokenInvalid;
  7013. }
  7014. // no need to compare tokWuid with workunit wuid, because it will always match
  7015. bool wuActive;
  7016. switch (cw->getState())
  7017. {
  7018. case WUStateRunning:
  7019. case WUStateDebugRunning:
  7020. case WUStateBlocked:
  7021. case WUStateAborting:
  7022. case WUStateUploadingFiles:
  7023. #ifdef _DEBUG
  7024. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  7025. #endif
  7026. wuActive = true;
  7027. break;
  7028. default:
  7029. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  7030. wuActive = false;
  7031. break;
  7032. }
  7033. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  7034. }
  7035. bool CLocalWorkUnit::resolveFilePrefix(StringBuffer & prefix, const char * queue) const
  7036. {
  7037. if (hasApplicationValue("prefix", queue))
  7038. {
  7039. getApplicationValue("prefix", queue, StringBufferAdaptor(prefix));
  7040. return true;
  7041. }
  7042. #ifndef _CONTAINERIZED
  7043. Owned<IConstWUClusterInfo> ci = getTargetClusterInfo(queue);
  7044. if (ci)
  7045. {
  7046. ci->getScope(StringBufferAdaptor(prefix));
  7047. return true;
  7048. }
  7049. #endif
  7050. return false;
  7051. }
  7052. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  7053. {
  7054. StringBuffer prefix;
  7055. CriticalBlock block(crit);
  7056. if (p->hasProp("Debug/ForceScope"))
  7057. {
  7058. prefix.append(p->queryProp("Debug/ForceScope")).toLowerCase();
  7059. }
  7060. else
  7061. {
  7062. resolveFilePrefix(prefix, p->queryProp("@clusterName"));
  7063. }
  7064. str.set(prefix.str());
  7065. return str;
  7066. }
  7067. //Queries
  7068. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  7069. {
  7070. CriticalBlock block(crit);
  7071. p->setPropInt("@codeVersion", codeVersion);
  7072. p->setProp("@buildVersion", buildVersion);
  7073. p->setProp("@eclVersion", eclVersion);
  7074. }
  7075. unsigned CLocalWorkUnit::getCodeVersion() const
  7076. {
  7077. CriticalBlock block(crit);
  7078. return p->getPropInt("@codeVersion");
  7079. }
  7080. unsigned CLocalWorkUnit::getWuidVersion() const
  7081. {
  7082. CriticalBlock block(crit);
  7083. return p->getPropInt("@wuidVersion");
  7084. }
  7085. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  7086. {
  7087. CriticalBlock block(crit);
  7088. buildVersion.set(p->queryProp("@buildVersion"));
  7089. eclVersion.set(p->queryProp("@eclVersion"));
  7090. }
  7091. void CLocalWorkUnit::setCloneable(bool value)
  7092. {
  7093. CriticalBlock block(crit);
  7094. p->setPropInt("@cloneable", value);
  7095. }
  7096. void CLocalWorkUnit::setIsClone(bool value)
  7097. {
  7098. CriticalBlock block(crit);
  7099. p->setPropInt("@isClone", value);
  7100. }
  7101. bool CLocalWorkUnit::getCloneable() const
  7102. {
  7103. CriticalBlock block(crit);
  7104. return p->getPropBool("@cloneable", false);
  7105. }
  7106. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  7107. {
  7108. CriticalBlock block(crit);
  7109. if (!userDesc)
  7110. {
  7111. userDesc.setown(createUserDescriptor());
  7112. SCMStringBuffer token;
  7113. getWorkunitDistributedAccessToken(token);
  7114. userDesc->set(queryUser(), token.str());//use token as password
  7115. }
  7116. return userDesc;
  7117. }
  7118. bool CLocalWorkUnit::isProtected() const
  7119. {
  7120. CriticalBlock block(crit);
  7121. return p->getPropBool("@protected", false);
  7122. }
  7123. bool CLocalWorkUnit::isPausing() const
  7124. {
  7125. CriticalBlock block(crit);
  7126. if (WUActionPause == getAction())
  7127. {
  7128. switch (getState())
  7129. {
  7130. case WUStateRunning:
  7131. case WUStateAborting:
  7132. return true;
  7133. }
  7134. }
  7135. return false;
  7136. }
  7137. void CLocalWorkUnit::protect(bool protectMode)
  7138. {
  7139. CriticalBlock block(crit);
  7140. p->setPropBool("@protected", protectMode);
  7141. }
  7142. void CLocalWorkUnit::setResultLimit(unsigned value)
  7143. {
  7144. CriticalBlock block(crit);
  7145. p->setPropInt("resultLimit", value);
  7146. }
  7147. unsigned CLocalWorkUnit::getResultLimit() const
  7148. {
  7149. CriticalBlock block(crit);
  7150. return p->getPropInt("resultLimit");
  7151. }
  7152. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  7153. {
  7154. CriticalBlock block(crit);
  7155. str.set(p->queryProp("SNAPSHOT"));
  7156. return str;
  7157. }
  7158. void CLocalWorkUnit::setSnapshot(const char * val)
  7159. {
  7160. CriticalBlock block(crit);
  7161. p->setProp("SNAPSHOT", val);
  7162. }
  7163. const static EnumMapping warningSeverityMap[] =
  7164. {
  7165. { SeverityInformation, "info" },
  7166. { SeverityWarning, "warning" },
  7167. { SeverityError, "error" },
  7168. { SeverityAlert, "alert" },
  7169. { SeverityIgnore, "ignore" },
  7170. { SeverityFatal, "fatal" },
  7171. { SeverityUnknown, NULL }
  7172. };
  7173. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  7174. {
  7175. StringBuffer xpath;
  7176. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7177. CriticalBlock block(crit);
  7178. IPropertyTree * mapping = p->queryPropTree(xpath);
  7179. if (mapping)
  7180. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  7181. return defaultSeverity;
  7182. }
  7183. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  7184. {
  7185. StringBuffer xpath;
  7186. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7187. CriticalBlock block(crit);
  7188. IPropertyTree * mapping = p->queryPropTree(xpath);
  7189. if (!mapping)
  7190. {
  7191. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  7192. mapping = onWarnings->addPropTree("OnWarning");
  7193. mapping->setPropInt("@code", code);
  7194. }
  7195. setEnum(mapping, "@severity", severity, warningSeverityMap);
  7196. }
  7197. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  7198. {
  7199. IPropertyTree *l = (IPropertyTree *) *ll;
  7200. IPropertyTree *r = (IPropertyTree *) *rr;
  7201. return stricmp(l->queryName(), r->queryName());
  7202. };
  7203. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  7204. {
  7205. // Any other values in the WU that could affect generated code should be crc'ed here
  7206. IPropertyTree *tree = p->queryBranch("Debug");
  7207. if (tree)
  7208. {
  7209. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  7210. ICopyArrayOf<IPropertyTree> subs;
  7211. for(sub->first(); sub->isValid(); sub->next())
  7212. subs.append(sub->query());
  7213. subs.sort(comparePropTrees);
  7214. ForEachItemIn(idx, subs)
  7215. {
  7216. const char *name = subs.item(idx).queryName();
  7217. const char *val = subs.item(idx).queryProp(NULL);
  7218. crc = crc32(name, (size32_t)strlen(name), crc);
  7219. if (val)
  7220. crc = crc32(val, (size32_t)strlen(val), crc);
  7221. }
  7222. }
  7223. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  7224. for (plugins->first();plugins->isValid();plugins->next())
  7225. {
  7226. IConstWUPlugin &thisplugin = plugins->query();
  7227. SCMStringBuffer version;
  7228. thisplugin.getPluginVersion(version);
  7229. crc = crc32(version.str(), version.length(), crc);
  7230. }
  7231. return crc;
  7232. }
  7233. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7234. {
  7235. if (!to->hasProp(xpath) && from->hasProp(xpath))
  7236. to->setProp(xpath, from->queryProp(xpath));
  7237. }
  7238. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7239. {
  7240. if (from->hasProp(xpath))
  7241. to->setProp(xpath, from->queryProp(xpath));
  7242. }
  7243. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7244. {
  7245. IPropertyTree * match = from->getBranch(xpath);
  7246. if (match)
  7247. to->setPropTree(xpath, match);
  7248. }
  7249. IPropertyTree *CLocalWorkUnit::queryPTree() const
  7250. {
  7251. return p;
  7252. }
  7253. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  7254. {
  7255. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  7256. if (!from)
  7257. {
  7258. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  7259. if (!fl)
  7260. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  7261. from = fl->c;
  7262. }
  7263. // Need to copy the query, the results, and the graphs from the cached query.
  7264. // The cache is made before the query is executed so there is no need to clear them.
  7265. if (!cached->getCloneable())
  7266. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  7267. const IPropertyTree * fromP = from->p;
  7268. IPropertyTree *pt;
  7269. CriticalBlock block(crit);
  7270. clearCached(false);
  7271. query.clear();
  7272. updateProp(p, fromP, "@jobName");
  7273. copyTree(p, fromP, "Query");
  7274. pt = fromP->getBranch("Application/LibraryModule");
  7275. if (pt)
  7276. {
  7277. ensurePTree(p, "Application");
  7278. p->setPropTree("Application/LibraryModule", pt);
  7279. }
  7280. pt = fromP->getBranch("Application/prefix");
  7281. if (pt)
  7282. {
  7283. ensurePTree(p, "Application");
  7284. p->setPropTree("Application/prefix", pt);
  7285. }
  7286. pt = fromP->queryBranch("Debug");
  7287. if (pt)
  7288. {
  7289. IPropertyTree *curDebug = p->queryPropTree("Debug");
  7290. if (curDebug)
  7291. {
  7292. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  7293. ForEach(*elems)
  7294. {
  7295. IPropertyTree *elem = &elems->query();
  7296. if (!curDebug->hasProp(elem->queryName()))
  7297. curDebug->setPropTree(elem->queryName(),LINK(elem));
  7298. }
  7299. }
  7300. else
  7301. p->setPropTree("Debug", LINK(pt));
  7302. }
  7303. copyTree(p, fromP, "OnWarnings");
  7304. copyTree(p, fromP, "Plugins");
  7305. copyTree(p, fromP, "Libraries");
  7306. copyTree(p, fromP, "Results");
  7307. copyTree(p, fromP, "Graphs");
  7308. copyTree(p, fromP, "Workflow");
  7309. copyTree(p, fromP, "WebServicesInfo");
  7310. if (copyStats)
  7311. {
  7312. // Merge timing info from both branches
  7313. pt = fromP->getBranch("Statistics");
  7314. if (pt)
  7315. {
  7316. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7317. mergePTree(tgtStatistics, pt);
  7318. pt->Release();
  7319. }
  7320. }
  7321. updateProp(p, fromP, "@clusterName");
  7322. updateProp(p, fromP, "allowedclusters");
  7323. updateProp(p, fromP, "@submitID");
  7324. updateProp(p, fromP, "SNAPSHOT");
  7325. setProp(p, fromP, "@eventScheduledCount");
  7326. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7327. if (all)
  7328. {
  7329. setProp(p, fromP, "PriorityFlag");
  7330. setProp(p, fromP, "@priorityClass");
  7331. setProp(p, fromP, "@protected");
  7332. setProp(p, fromP, "@clusterName");
  7333. updateProp(p, fromP, "@scope");
  7334. }
  7335. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7336. pt = fromP->getBranch("Variables");
  7337. if (pt)
  7338. {
  7339. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7340. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7341. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7342. {
  7343. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7344. const char *name = ptSrcVariable->queryProp("@name");
  7345. assertex(name);
  7346. StringBuffer xpath;
  7347. xpath.append("Variable[@name='").append(name).append("']");
  7348. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7349. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7350. merged->removeProp("Value"); // except value and status
  7351. merged->setProp("@status", "undefined");
  7352. if (!merged->getPropBool("@isScalar"))
  7353. merged->removeProp("totalRowCount");
  7354. merged->removeProp("rowCount");
  7355. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7356. if (ptTgtVariable)
  7357. {
  7358. // copy status and Value from what is already set in target
  7359. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7360. MemoryBuffer value;
  7361. if (ptTgtVariable->getPropBin("Value", value))
  7362. merged->setPropBin("Value", value.length(), value.toByteArray());
  7363. ptTgtVariable->removeProp(xpath.str());
  7364. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7365. }
  7366. ptTgtVariables->addPropTree("Variable", merged);
  7367. }
  7368. pt->Release();
  7369. }
  7370. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7371. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7372. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7373. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7374. p->setProp("@hash", fromP->queryProp("@hash"));
  7375. p->setPropBool("@cloneable", true);
  7376. p->setPropBool("@isClone", true);
  7377. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7378. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7379. ForEach(*results)
  7380. {
  7381. CLocalWUResult result(LINK(&results->query()));
  7382. result.setResultStatus(ResultStatusUndefined);
  7383. }
  7384. copyTree(p, fromP, "usedsources"); // field usage
  7385. }
  7386. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7387. {
  7388. StringBuffer lower;
  7389. lower.append(propname).toLowerCase();
  7390. CriticalBlock block(crit);
  7391. StringBuffer prop("Debug/");
  7392. return p->hasProp(prop.append(lower));
  7393. }
  7394. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7395. {
  7396. StringBuffer lower;
  7397. lower.append(propname).toLowerCase();
  7398. CriticalBlock block(crit);
  7399. StringBuffer prop("Debug/");
  7400. str.set(p->queryProp(prop.append(lower).str()));
  7401. return str;
  7402. }
  7403. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7404. {
  7405. return getDebugValues(NULL);
  7406. }
  7407. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7408. {
  7409. CriticalBlock block(crit);
  7410. StringBuffer path("Debug/");
  7411. if (prop)
  7412. {
  7413. StringBuffer lower;
  7414. lower.append(prop).toLowerCase();
  7415. path.append(lower);
  7416. }
  7417. else
  7418. path.append("*");
  7419. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7420. }
  7421. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7422. {
  7423. StringBuffer lower;
  7424. lower.append(propname).toLowerCase();
  7425. CriticalBlock block(crit);
  7426. StringBuffer prop("Debug/");
  7427. prop.append(lower);
  7428. return p->getPropInt(prop.str(), defVal);
  7429. }
  7430. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7431. {
  7432. StringBuffer lower;
  7433. lower.append(propname).toLowerCase();
  7434. CriticalBlock block(crit);
  7435. StringBuffer prop("Debug/");
  7436. prop.append(lower);
  7437. return p->getPropInt64(prop.str(), defVal);
  7438. }
  7439. double CLocalWorkUnit::getDebugValueReal(const char *propname, double defVal) const
  7440. {
  7441. StringBuffer lower;
  7442. lower.append(propname).toLowerCase();
  7443. CriticalBlock block(crit);
  7444. StringBuffer prop("Debug/");
  7445. prop.append(lower);
  7446. return p->getPropReal(prop.str(), defVal);
  7447. }
  7448. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7449. {
  7450. StringBuffer lower;
  7451. lower.append(propname).toLowerCase();
  7452. CriticalBlock block(crit);
  7453. StringBuffer prop("Debug/");
  7454. prop.append(lower);
  7455. return p->getPropBool(prop.str(), defVal);
  7456. }
  7457. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7458. {
  7459. VStringBuffer xpath("Process/%s/", type);
  7460. if (instance)
  7461. xpath.append(instance);
  7462. else
  7463. xpath.append("*");
  7464. CriticalBlock block(crit);
  7465. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7466. {
  7467. // NB: instance unused
  7468. if (streq("EclAgent", type))
  7469. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7470. else if (streq("Thor", type))
  7471. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7472. VStringBuffer xpath("Debug/%s", type);
  7473. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7474. }
  7475. else
  7476. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7477. }
  7478. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7479. {
  7480. VStringBuffer xpath("Process/%s/", type);
  7481. if (instance)
  7482. xpath.append(instance);
  7483. else
  7484. xpath.append("*");
  7485. CriticalBlock block(crit);
  7486. return p->getElements(xpath.str());
  7487. }
  7488. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7489. {
  7490. VStringBuffer xpath("Process/%s/*", type);
  7491. CriticalBlock block(crit);
  7492. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7493. }
  7494. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid,
  7495. unsigned max, const char *pattern, bool singleLog, const char *log)
  7496. {
  7497. VStringBuffer processType("Process/%s", type);
  7498. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7499. if (log)
  7500. xpath.appendf("[@log=\"%s\"]", log);
  7501. CriticalBlock block(crit);
  7502. if (!p->hasProp(xpath))
  7503. {
  7504. IPropertyTree *node = ensurePTree(p, processType.str());
  7505. node = node->addPropTree(instance);
  7506. node->setProp("@log", log);
  7507. node->setPropInt("@pid", pid);
  7508. if (max > 0)
  7509. node->setPropInt("@max", max);
  7510. if (!isEmptyString(pattern))
  7511. node->setProp("@pattern", pattern);
  7512. if (singleLog)
  7513. node->setPropBool("@singleLog", true);
  7514. }
  7515. }
  7516. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7517. {
  7518. StringBuffer lower;
  7519. lower.append(propname).toLowerCase();
  7520. CriticalBlock block(crit);
  7521. StringBuffer prop("Debug/");
  7522. prop.append(lower);
  7523. if (overwrite || !p->hasProp(prop.str()))
  7524. {
  7525. // MORE - not sure this line should be needed....
  7526. p->setProp("Debug", "");
  7527. p->setProp(prop.str(), value);
  7528. }
  7529. }
  7530. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7531. {
  7532. StringBuffer lower;
  7533. lower.append(propname).toLowerCase();
  7534. CriticalBlock block(crit);
  7535. StringBuffer prop("Debug/");
  7536. prop.append(lower);
  7537. if (overwrite || !p->hasProp(prop.str()))
  7538. {
  7539. // MORE - not sure this line should be needed....
  7540. p->setProp("Debug", "");
  7541. p->setPropInt(prop.str(), value);
  7542. }
  7543. }
  7544. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7545. {
  7546. CriticalBlock block(crit);
  7547. // MORE - not sure this line should be needed....
  7548. p->setProp("Tracing", "");
  7549. StringBuffer prop("Tracing/");
  7550. p->setProp(prop.append(propname).str(), value);
  7551. }
  7552. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7553. {
  7554. CriticalBlock block(crit);
  7555. StringBuffer prop("Tracing/");
  7556. p->setPropInt(prop.append(propname).str(), value);
  7557. }
  7558. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7559. {
  7560. CriticalBlock block(crit);
  7561. VStringBuffer prop("Tracing/%s", propname);
  7562. p->setPropInt64(prop.str(), value);
  7563. }
  7564. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7565. {
  7566. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7567. CriticalBlock block(crit);
  7568. if (!query)
  7569. {
  7570. IPropertyTree *s = p->getPropTree("Query");
  7571. if (s)
  7572. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7573. }
  7574. return query.getLink();
  7575. }
  7576. IWUQuery* CLocalWorkUnit::updateQuery()
  7577. {
  7578. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7579. CriticalBlock block(crit);
  7580. if (!query)
  7581. {
  7582. IPropertyTree *s = p->queryPropTree("Query");
  7583. if (!s)
  7584. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7585. s->Link();
  7586. query.setown(new CLocalWUQuery(s));
  7587. }
  7588. return query.getLink();
  7589. }
  7590. void CLocalWorkUnit::loadPlugins() const
  7591. {
  7592. CriticalBlock block(crit);
  7593. if (!pluginsCached)
  7594. {
  7595. assertex(plugins.length() == 0);
  7596. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7597. for (r->first(); r->isValid(); r->next())
  7598. {
  7599. IPropertyTree *rp = &r->query();
  7600. rp->Link();
  7601. plugins.append(*new CLocalWUPlugin(rp));
  7602. }
  7603. pluginsCached = true;
  7604. }
  7605. }
  7606. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7607. {
  7608. CriticalBlock block(crit);
  7609. loadPlugins();
  7610. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7611. }
  7612. void CLocalWorkUnit::loadLibraries() const
  7613. {
  7614. CriticalBlock block(crit);
  7615. if (!librariesCached)
  7616. {
  7617. assertex(libraries.length() == 0);
  7618. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7619. ForEach(*r)
  7620. {
  7621. IPropertyTree *rp = &r->query();
  7622. rp->Link();
  7623. libraries.append(*new CLocalWULibrary(rp));
  7624. }
  7625. librariesCached = true;
  7626. }
  7627. }
  7628. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7629. {
  7630. CriticalBlock block(crit);
  7631. loadLibraries();
  7632. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7633. }
  7634. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7635. {
  7636. CriticalBlock block(crit);
  7637. loadLibraries();
  7638. ForEachItemIn(idx, libraries)
  7639. {
  7640. SCMStringBuffer name;
  7641. IConstWULibrary &cur = libraries.item(idx);
  7642. cur.getName(name);
  7643. if (stricmp(name.str(), search)==0)
  7644. return &OLINK(cur);
  7645. }
  7646. return NULL;
  7647. }
  7648. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7649. {
  7650. str.append("Graph ").append(graphName);
  7651. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7652. else if (subId) str.append(" - id(").append(subId).append(")");
  7653. return str;
  7654. }
  7655. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7656. {
  7657. if (wfid)
  7658. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7659. str.append(graphName);
  7660. if (subId) str.append(":sg").append(subId);
  7661. return str;
  7662. }
  7663. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7664. {
  7665. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7666. unsigned len = (size32_t)strlen(label);
  7667. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7668. return false;
  7669. graphNum = 0;
  7670. subGraphNum = 0;
  7671. subId = 0;
  7672. const char *finger = label+6;
  7673. const char *finger2 = strchr(finger, '-');
  7674. if (NULL == finger2) // just graphName
  7675. graphName.set(finger);
  7676. else
  7677. {
  7678. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7679. finger = finger2+2; // skip '-' and space
  7680. finger2 = strchr(finger, ' ');
  7681. if (finger2)
  7682. {
  7683. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7684. finger = finger2+2; // skip space and '('
  7685. finger2 = strchr(finger, ')');
  7686. if (finger2)
  7687. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7688. }
  7689. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7690. {
  7691. finger += 3;
  7692. finger2 = strchr(finger, ')');
  7693. if (finger2)
  7694. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7695. }
  7696. }
  7697. if (graphName && !memicmp(graphName, "graph", 5))
  7698. graphNum = atoi(graphName + 5);
  7699. return true;
  7700. }
  7701. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7702. {
  7703. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7704. return false;
  7705. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7706. subGraphId = 0;
  7707. const char * colon = strchr(scope, ':');
  7708. if (!colon)
  7709. {
  7710. graphName.set(scope);
  7711. return true;
  7712. }
  7713. const char * subgraph = colon+1;
  7714. graphName.set(scope, (size32_t)(colon - scope));
  7715. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7716. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7717. return true;
  7718. }
  7719. void CLocalWorkUnit::setStatistic(StatisticCreatorType creatorType, const char * creator, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * optDescription, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction)
  7720. {
  7721. if (!scope) scope = GLOBAL_SCOPE;
  7722. const char * kindName = queryStatisticName(kind);
  7723. StatisticMeasure measure = queryMeasure(kind);
  7724. //creator. scope and name must all be present, and must not contain semi colons.
  7725. assertex(creator && scope);
  7726. CriticalBlock block(crit);
  7727. IPropertyTree * stats = p->queryPropTree("Statistics");
  7728. if (!stats)
  7729. stats = p->addPropTree("Statistics");
  7730. IPropertyTree * statTree = NULL;
  7731. if (mergeAction != StatsMergeAppend)
  7732. {
  7733. StringBuffer xpath;
  7734. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7735. statTree = stats->queryPropTree(xpath.str());
  7736. }
  7737. if (!statTree)
  7738. {
  7739. /* NB: Sasha archive uses this structure directly
  7740. * if it changes, the code in saarch.cpp needs updating
  7741. */
  7742. statTree = stats->addPropTree("Statistic");
  7743. statTree->setProp("@creator", creator);
  7744. statTree->setProp("@scope", scope);
  7745. statTree->setProp("@kind", kindName);
  7746. //These items are primarily here to facilitate filtering.
  7747. statTree->setProp("@unit", queryMeasureName(measure));
  7748. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7749. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7750. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7751. if (optDescription)
  7752. statTree->setProp("@desc", optDescription);
  7753. if (statistics.cached)
  7754. statistics.append(statTree); // links statTree
  7755. mergeAction = StatsMergeAppend;
  7756. }
  7757. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7758. {
  7759. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7760. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7761. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7762. if (oldMax < oldValue)
  7763. oldMax = oldValue;
  7764. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7765. statTree->setPropInt64("@count", count + oldCount);
  7766. if (maxValue > oldMax)
  7767. statTree->setPropInt64("@max", maxValue);
  7768. }
  7769. else
  7770. {
  7771. statTree->setPropInt64("@value", value);
  7772. statTree->setPropInt64("@count", count);
  7773. if (maxValue)
  7774. statTree->setPropInt64("@max", maxValue);
  7775. else
  7776. statTree->removeProp("@max");
  7777. }
  7778. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7779. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7780. {
  7781. _loadStatistics();
  7782. stat_type totalTime = 0;
  7783. ForEachItemIn(i, statistics)
  7784. {
  7785. IConstWUStatistic & cur = statistics.item(i);
  7786. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7787. totalTime += cur.getValue();
  7788. }
  7789. StringBuffer t;
  7790. formatTimeCollatable(t, totalTime, false);
  7791. p->setProp("@totalThorTime", t);
  7792. }
  7793. }
  7794. void CLocalWorkUnit::_loadStatistics() const
  7795. {
  7796. statistics.load(p,"Statistics/*");
  7797. }
  7798. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7799. {
  7800. //MORE: Optimize this....
  7801. WuScopeFilter filter;
  7802. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7803. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7804. if (stats->first())
  7805. return stats->getStat(kind, value);
  7806. return false;
  7807. }
  7808. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7809. {
  7810. assertex(filter.isOptimized());
  7811. WuScopeSourceFlags sources = filter.querySources();
  7812. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7813. if (sources & SSFsearchGlobalStats)
  7814. {
  7815. CriticalBlock block(crit);
  7816. statistics.loadBranch(p,"Statistics");
  7817. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7818. compoundIter->addIter(localStats);
  7819. }
  7820. if (sources & SSFsearchGraphStats)
  7821. {
  7822. const char * wuid = p->queryName();
  7823. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.queryMinVersion()));
  7824. compoundIter->addIter(scopeIter);
  7825. }
  7826. if (sources & SSFsearchGraph)
  7827. {
  7828. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7829. compoundIter->addIter(graphIter);
  7830. }
  7831. if (sources & SSFsearchWorkflow)
  7832. {
  7833. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7834. if (iter)
  7835. {
  7836. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7837. compoundIter->addIter(workflowIter);
  7838. }
  7839. }
  7840. if (sources & SSFsearchExceptions)
  7841. {
  7842. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7843. compoundIter->addIter(notesIter);
  7844. }
  7845. return *compoundIter.getClear();
  7846. }
  7847. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7848. {
  7849. CriticalBlock block(crit);
  7850. IConstWUPlugin *existing = getPluginByName(qname);
  7851. if (existing)
  7852. return (IWUPlugin *) existing;
  7853. if (!plugins.length())
  7854. p->addPropTree("Plugins");
  7855. IPropertyTree *pl = p->queryPropTree("Plugins");
  7856. IPropertyTree *s = pl->addPropTree("Plugin");
  7857. s->Link();
  7858. IWUPlugin* q = new CLocalWUPlugin(s);
  7859. q->Link();
  7860. plugins.append(*q);
  7861. q->setPluginName(qname);
  7862. return q;
  7863. }
  7864. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  7865. {
  7866. CriticalBlock block(crit);
  7867. loadPlugins();
  7868. ForEachItemIn(idx, plugins)
  7869. {
  7870. SCMStringBuffer name;
  7871. IConstWUPlugin &cur = plugins.item(idx);
  7872. cur.getPluginName(name);
  7873. if (stricmp(name.str(), qname)==0)
  7874. {
  7875. cur.Link();
  7876. return &cur;
  7877. }
  7878. }
  7879. return NULL;
  7880. }
  7881. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  7882. {
  7883. CriticalBlock block(crit);
  7884. IConstWULibrary *existing = getLibraryByName(qname);
  7885. if (existing)
  7886. return (IWULibrary *) existing;
  7887. if (!libraries.length())
  7888. p->addPropTree("Libraries");
  7889. IPropertyTree *pl = p->queryPropTree("Libraries");
  7890. IPropertyTree *s = pl->addPropTree("Library");
  7891. s->Link();
  7892. IWULibrary* q = new CLocalWULibrary(s);
  7893. q->Link();
  7894. libraries.append(*q);
  7895. q->setName(qname);
  7896. return q;
  7897. }
  7898. void CLocalWorkUnit::_loadExceptions() const
  7899. {
  7900. assertex(exceptions.length() == 0);
  7901. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  7902. for (r->first(); r->isValid(); r->next())
  7903. {
  7904. IPropertyTree *rp = &r->query();
  7905. rp->Link();
  7906. exceptions.append(*new CLocalWUException(rp));
  7907. }
  7908. }
  7909. void CLocalWorkUnit::loadExceptions() const
  7910. {
  7911. CriticalBlock block(crit);
  7912. if (!exceptionsCached)
  7913. {
  7914. _loadExceptions();
  7915. exceptionsCached = true;
  7916. }
  7917. }
  7918. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  7919. {
  7920. CriticalBlock block(crit);
  7921. loadExceptions();
  7922. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  7923. }
  7924. unsigned CLocalWorkUnit::getExceptionCount() const
  7925. {
  7926. CriticalBlock block(crit);
  7927. loadExceptions();
  7928. return exceptions.length();
  7929. }
  7930. void CLocalWorkUnit::clearExceptions(const char *source)
  7931. {
  7932. CriticalBlock block(crit);
  7933. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7934. loadExceptions();
  7935. ForEachItemInRev(idx, exceptions)
  7936. {
  7937. IWUException &e = exceptions.item(idx);
  7938. SCMStringBuffer s;
  7939. e.getExceptionSource(s);
  7940. if (source)
  7941. {
  7942. if (!strieq(s.s, source))
  7943. continue;
  7944. }
  7945. else
  7946. {
  7947. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  7948. break;
  7949. }
  7950. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  7951. p->removeProp(xpath);
  7952. exceptions.remove(idx);
  7953. }
  7954. if (exceptions.length() == 0)
  7955. p->removeProp("Exceptions");
  7956. }
  7957. IWUException* CLocalWorkUnit::createException()
  7958. {
  7959. CriticalBlock block(crit);
  7960. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7961. loadExceptions();
  7962. if (!exceptions.length())
  7963. p->addPropTree("Exceptions");
  7964. IPropertyTree *r = p->queryPropTree("Exceptions");
  7965. IPropertyTree *s = r->addPropTree("Exception");
  7966. s->setPropInt("@sequence", exceptions.ordinality());
  7967. IWUException* q = new CLocalWUException(LINK(s));
  7968. exceptions.append(*LINK(q));
  7969. Owned<IJlibDateTime> now = createDateTimeNow();
  7970. SCMStringBuffer temp;
  7971. now->getString(temp);
  7972. q->setTimeStamp(temp.str());
  7973. return q;
  7974. }
  7975. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  7976. {
  7977. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7978. CriticalBlock block(crit);
  7979. if (!webServicesInfoCached)
  7980. {
  7981. assertex(!webServicesInfo);
  7982. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  7983. if (s)
  7984. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  7985. webServicesInfoCached = true;
  7986. }
  7987. return webServicesInfo.getLink();
  7988. }
  7989. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  7990. {
  7991. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7992. CriticalBlock block(crit);
  7993. if (!webServicesInfoCached)
  7994. {
  7995. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  7996. if (!s)
  7997. {
  7998. if (create)
  7999. s = p->addPropTree("WebServicesInfo");
  8000. else
  8001. return NULL;
  8002. }
  8003. s->Link();
  8004. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  8005. webServicesInfoCached = true;
  8006. }
  8007. return webServicesInfo.getLink();
  8008. }
  8009. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  8010. {
  8011. CLocalWUResult *l = (CLocalWUResult *) *ll;
  8012. CLocalWUResult *r = (CLocalWUResult *) *rr;
  8013. return l->getResultSequence() - r->getResultSequence();
  8014. }
  8015. void CLocalWorkUnit::_loadResults() const
  8016. {
  8017. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  8018. for (r->first(); r->isValid(); r->next())
  8019. {
  8020. IPropertyTree *rp = &r->query();
  8021. rp->Link();
  8022. results.append(*new CLocalWUResult(rp));
  8023. }
  8024. }
  8025. void CLocalWorkUnit::loadResults() const
  8026. {
  8027. if (!resultsCached)
  8028. {
  8029. assertex(results.length() == 0);
  8030. _loadResults();
  8031. results.sort(compareResults);
  8032. resultsCached = true;
  8033. }
  8034. }
  8035. void CLocalWorkUnit::_loadVariables() const
  8036. {
  8037. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  8038. for (r->first(); r->isValid(); r->next())
  8039. {
  8040. IPropertyTree *rp = &r->query();
  8041. rp->Link();
  8042. variables.append(*new CLocalWUResult(rp));
  8043. }
  8044. }
  8045. void CLocalWorkUnit::loadVariables() const
  8046. {
  8047. if (!variablesCached)
  8048. {
  8049. assertex(variables.length() == 0);
  8050. _loadVariables();
  8051. variablesCached = true;
  8052. }
  8053. }
  8054. void CLocalWorkUnit::_loadTemporaries() const
  8055. {
  8056. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  8057. for (r->first(); r->isValid(); r->next())
  8058. {
  8059. IPropertyTree *rp = &r->query();
  8060. rp->Link();
  8061. temporaries.append(*new CLocalWUResult(rp));
  8062. }
  8063. }
  8064. void CLocalWorkUnit::loadTemporaries() const
  8065. {
  8066. if (!temporariesCached)
  8067. {
  8068. assertex(temporaries.length() == 0);
  8069. _loadTemporaries();
  8070. temporariesCached = true;
  8071. }
  8072. }
  8073. void CLocalWorkUnit::deleteTemporaries()
  8074. {
  8075. CriticalBlock block(crit);
  8076. if (temporariesCached)
  8077. {
  8078. temporaries.kill();
  8079. temporariesCached = false;
  8080. }
  8081. p->removeProp("Temporaries");
  8082. }
  8083. IWUResult* CLocalWorkUnit::createResult()
  8084. {
  8085. CriticalBlock block(crit);
  8086. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8087. loadResults();
  8088. if (!results.length())
  8089. p->addPropTree("Results");
  8090. IPropertyTree *r = p->queryPropTree("Results");
  8091. IPropertyTree *s = r->addPropTree("Result");
  8092. s->Link();
  8093. IWUResult* q = new CLocalWUResult(s);
  8094. q->Link();
  8095. results.append(*q);
  8096. return q;
  8097. }
  8098. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  8099. {
  8100. CriticalBlock block(crit);
  8101. IConstWUResult *existing = getResultByName(qname);
  8102. if (existing)
  8103. return (IWUResult *) existing;
  8104. IWUResult* q = createResult();
  8105. q->setResultName(qname);
  8106. return q;
  8107. }
  8108. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  8109. {
  8110. CriticalBlock block(crit);
  8111. IConstWUResult *existing = getResultBySequence(seq);
  8112. if (existing)
  8113. return (IWUResult *) existing;
  8114. IWUResult* q = createResult();
  8115. q->setResultSequence(seq);
  8116. return q;
  8117. }
  8118. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  8119. {
  8120. CriticalBlock block(crit);
  8121. loadResults();
  8122. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  8123. }
  8124. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  8125. {
  8126. CriticalBlock block(crit);
  8127. loadResults();
  8128. ForEachItemIn(idx, results)
  8129. {
  8130. SCMStringBuffer name;
  8131. IConstWUResult &cur = results.item(idx);
  8132. cur.getResultName(name);
  8133. if (stricmp(name.str(), qname)==0)
  8134. {
  8135. cur.Link();
  8136. return &cur;
  8137. }
  8138. }
  8139. return NULL;
  8140. }
  8141. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  8142. {
  8143. CriticalBlock block(crit);
  8144. loadResults();
  8145. ForEachItemIn(idx, results)
  8146. {
  8147. IConstWUResult &cur = results.item(idx);
  8148. if (!isSpecialResultSequence(cur.getResultSequence()))
  8149. {
  8150. SCMStringBuffer name;
  8151. cur.getResultName(name);
  8152. if (stricmp(name.str(), qname)==0)
  8153. {
  8154. cur.Link();
  8155. return &cur;
  8156. }
  8157. }
  8158. }
  8159. return NULL;
  8160. }
  8161. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  8162. {
  8163. CriticalBlock block(crit);
  8164. loadResults();
  8165. ForEachItemIn(idx, results)
  8166. {
  8167. IConstWUResult &cur = results.item(idx);
  8168. if (cur.getResultSequence() == seq)
  8169. {
  8170. cur.Link();
  8171. return &cur;
  8172. }
  8173. }
  8174. return NULL;
  8175. }
  8176. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  8177. {
  8178. CriticalBlock block(crit);
  8179. loadVariables();
  8180. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  8181. }
  8182. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  8183. {
  8184. CriticalBlock block(crit);
  8185. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8186. return getVariableByName(qname);
  8187. Owned <IWorkUnit> global = globalFactory->getGlobalWorkUnit(secMgr, secUser);
  8188. return global->getVariableByName(qname);
  8189. }
  8190. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  8191. {
  8192. CriticalBlock block(crit);
  8193. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8194. return updateVariableByName(qname);
  8195. Owned <IWorkUnit> global = globalFactory->getGlobalWorkUnit(secMgr, secUser);
  8196. return global->updateVariableByName(qname);
  8197. }
  8198. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  8199. {
  8200. CriticalBlock block(crit);
  8201. loadVariables();
  8202. ForEachItemIn(idx, variables)
  8203. {
  8204. SCMStringBuffer name;
  8205. IConstWUResult &cur = variables.item(idx);
  8206. cur.getResultName(name);
  8207. if (stricmp(name.str(), qname)==0)
  8208. {
  8209. cur.Link();
  8210. return &cur;
  8211. }
  8212. }
  8213. return NULL;
  8214. }
  8215. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  8216. {
  8217. CriticalBlock block(crit);
  8218. loadTemporaries();
  8219. ForEachItemIn(idx, temporaries)
  8220. {
  8221. SCMStringBuffer name;
  8222. IConstWUResult &cur = temporaries.item(idx);
  8223. cur.getResultName(name);
  8224. if (stricmp(name.str(), qname)==0)
  8225. {
  8226. cur.Link();
  8227. return &cur;
  8228. }
  8229. }
  8230. return NULL;
  8231. }
  8232. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  8233. {
  8234. CriticalBlock block(crit);
  8235. loadTemporaries();
  8236. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  8237. }
  8238. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  8239. {
  8240. CriticalBlock block(crit);
  8241. IConstWUResult *existing = getTemporaryByName(qname);
  8242. if (existing)
  8243. return (IWUResult *) existing;
  8244. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  8245. IPropertyTree *s = vars->addPropTree("Variable");
  8246. s->Link();
  8247. IWUResult* q = new CLocalWUResult(s);
  8248. q->Link();
  8249. temporaries.append(*q);
  8250. q->setResultName(qname);
  8251. q->setResultSequence(ResultSequenceInternal);
  8252. return q;
  8253. }
  8254. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  8255. {
  8256. CriticalBlock block(crit);
  8257. IConstWUResult *existing = getVariableByName(qname);
  8258. if (existing)
  8259. return (IWUResult *) existing;
  8260. if (!variables.length())
  8261. p->addPropTree("Variables");
  8262. IPropertyTree *vars = p->queryPropTree("Variables");
  8263. IPropertyTree *s = vars->addPropTree("Variable");
  8264. s->Link();
  8265. IWUResult* q = new CLocalWUResult(s);
  8266. q->Link();
  8267. variables.append(*q);
  8268. q->setResultName(qname);
  8269. q->setResultSequence(ResultSequenceStored);
  8270. return q;
  8271. }
  8272. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  8273. {
  8274. CriticalBlock block(crit);
  8275. IPropertyTree *files = p->queryPropTree("Files");
  8276. if (!files) return;
  8277. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  8278. ICopyArrayOf<IPropertyTree> toRemove;
  8279. ForEach (*iter)
  8280. {
  8281. IPropertyTree &file = iter->query();
  8282. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  8283. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  8284. bool needDelete;
  8285. switch(fileKind)
  8286. {
  8287. case WUFileTemporary:
  8288. if(graph==NULL)
  8289. needDelete = true;
  8290. else
  8291. {
  8292. const char *graphOwner = file.queryProp("@graph");
  8293. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  8294. }
  8295. break;
  8296. case WUFileJobOwned:
  8297. needDelete = ((graph==NULL) && deleteJobOwned);
  8298. break;
  8299. case WUFileOwned:
  8300. needDelete = ((graph==NULL) && deleteOwned);
  8301. break;
  8302. default:
  8303. needDelete = false;
  8304. }
  8305. if(needDelete)
  8306. {
  8307. const char *name = file.queryProp("@name");
  8308. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  8309. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  8310. toRemove.append(file);
  8311. }
  8312. }
  8313. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  8314. }
  8315. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  8316. {
  8317. IDistributedSuperFile *super = file->querySuperFile();
  8318. StringBuffer fname;
  8319. file->getLogicalName(fname);
  8320. if (fname.length())
  8321. {
  8322. StringBuffer path("File[@name=\"");
  8323. path.append(fname).append("\"]");
  8324. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8325. if (fileTree)
  8326. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8327. else
  8328. {
  8329. StringBuffer cluster;
  8330. file->getClusterName(0,cluster);
  8331. fileTree = createPTree();
  8332. fileTree->setProp("@name", fname.str());
  8333. fileTree->setProp("@cluster", cluster.str());
  8334. fileTree->setPropInt("@useCount", 1);
  8335. fileTree = filesRead->addPropTree("File", fileTree);
  8336. }
  8337. if (super)
  8338. {
  8339. fileTree->setPropBool("@super", true);
  8340. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8341. ForEach (*iter)
  8342. {
  8343. IDistributedFile &file = iter->query();
  8344. StringBuffer fname;
  8345. file.getLogicalName(fname);
  8346. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8347. _noteFileRead(&file, filesRead);
  8348. }
  8349. }
  8350. }
  8351. }
  8352. void CLocalWorkUnit::_loadFilesRead() const
  8353. {
  8354. // Nothing to do
  8355. }
  8356. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8357. {
  8358. if (file)
  8359. {
  8360. CriticalBlock block(crit);
  8361. IPropertyTree *files = p->queryPropTree("FilesRead");
  8362. if (!files)
  8363. files = p->addPropTree("FilesRead");
  8364. _noteFileRead(file, files);
  8365. }
  8366. }
  8367. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8368. {
  8369. if (fieldUsage)
  8370. {
  8371. CriticalBlock block(crit);
  8372. p->addPropTree("usedsources", fieldUsage);
  8373. }
  8374. }
  8375. void CLocalWorkUnit::_loadFilesWritten() const
  8376. {
  8377. // Nothing to do
  8378. }
  8379. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8380. {
  8381. StringBuffer path("File[@name=\"");
  8382. path.append(fileName).append("\"]");
  8383. if (cluster)
  8384. path.append("[@cluster=\"").append(cluster).append("\"]");
  8385. IPropertyTree *file = files->queryPropTree(path.str());
  8386. if (file) files->removeTree(file);
  8387. file = createPTree();
  8388. file->setProp("@name", fileName);
  8389. if (cluster)
  8390. file->setProp("@cluster", cluster);
  8391. if (graphOwner)
  8392. file->setProp("@graph", graphOwner);
  8393. file->setPropInt("@kind", (unsigned)fileKind);
  8394. if (WUFileTemporary == fileKind)
  8395. file->setPropInt("@usageCount", usageCount);
  8396. files->addPropTree("File", file);
  8397. }
  8398. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8399. {
  8400. CriticalBlock block(crit);
  8401. IPropertyTree *files = p->queryPropTree("Files");
  8402. if (!files)
  8403. files = p->addPropTree("Files");
  8404. if (!clusters)
  8405. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8406. else
  8407. {
  8408. ForEachItemIn(c, *clusters)
  8409. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8410. }
  8411. }
  8412. void CLocalWorkUnit::releaseFile(const char *fileName)
  8413. {
  8414. StringBuffer path("File[@name=\"");
  8415. path.append(fileName).append("\"]");
  8416. CriticalBlock block(crit);
  8417. IPropertyTree *files = p->queryPropTree("Files");
  8418. if (!files) return;
  8419. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8420. if (fiter->first())
  8421. {
  8422. while (true)
  8423. {
  8424. IPropertyTree *file = &fiter->query();
  8425. unsigned usageCount = file->getPropInt("@usageCount");
  8426. bool more = fiter->next();
  8427. if (usageCount > 1)
  8428. file->setPropInt("@usageCount", usageCount-1);
  8429. else
  8430. {
  8431. StringAttr name(file->queryProp("@name"));
  8432. files->removeTree(file);
  8433. if (!name.isEmpty()&&(1 == usageCount))
  8434. {
  8435. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8436. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8437. }
  8438. }
  8439. if (!more)
  8440. break;
  8441. }
  8442. }
  8443. }
  8444. void CLocalWorkUnit::clearGraphProgress() const
  8445. {
  8446. }
  8447. void CLocalWorkUnit::resetBeforeGeneration()
  8448. {
  8449. CriticalBlock block(crit);
  8450. //Remove all associated files
  8451. Owned<IWUQuery> q = updateQuery();
  8452. q->removeAssociatedFiles();
  8453. //Remove any pre-existing workflow information
  8454. workflowIterator.clear();
  8455. p->removeProp("Workflow");
  8456. }
  8457. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8458. {
  8459. StringBuffer path("Files/File[@name=\"");
  8460. path.append(fileName).append("\"]/@usageCount");
  8461. CriticalBlock block(crit);
  8462. return p->getPropInt(path.str());
  8463. }
  8464. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8465. {
  8466. CriticalBlock block(crit);
  8467. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8468. if (!fieldUsageTree)
  8469. return NULL;
  8470. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8471. return new CConstWUFileUsageIterator(iter);
  8472. }
  8473. bool isFilenameResolved(StringBuffer& filename)
  8474. {
  8475. size32_t length = filename.length();
  8476. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8477. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8478. return true;
  8479. else
  8480. return false;
  8481. }
  8482. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8483. {
  8484. bool scopeLoaded = false;
  8485. StringBuffer defaultScope;
  8486. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8487. if (!files)
  8488. return false; // this query was not compiled with recordFieldUsage option.
  8489. ForEach(*files)
  8490. {
  8491. Owned<IConstWUFileUsage> file = files->get();
  8492. StringBuffer filename(file->queryName());
  8493. size32_t length = filename.length();
  8494. if (length == 0)
  8495. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8496. StringBuffer normalizedFilename;
  8497. // Two cases to handle:
  8498. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8499. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8500. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8501. if (isFilenameResolved(filename))
  8502. {
  8503. // filename cannot be empty (i.e. empty single quotes '')
  8504. if (length == 2)
  8505. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8506. // Remove surrounding single quotes
  8507. StringAttr cleanFilename(filename.str()+1, length-2);
  8508. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8509. // We need to load a default scope from config and prefix the filename with it.
  8510. if (cleanFilename.str()[0] != '~')
  8511. {
  8512. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8513. if (!scopeLoaded)
  8514. {
  8515. //MORE: This should actually depend on the cluster that was active when the file was read!
  8516. if (!resolveFilePrefix(defaultScope, clusterName))
  8517. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8518. scopeLoaded = true;
  8519. }
  8520. normalizedFilename.append(defaultScope.str());
  8521. normalizedFilename.append(cleanFilename.str());
  8522. }
  8523. else
  8524. {
  8525. normalizedFilename.append(cleanFilename);
  8526. }
  8527. }
  8528. else
  8529. {
  8530. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8531. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8532. normalizedFilename.append(filename.str());
  8533. }
  8534. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8535. ForEach(*fields)
  8536. {
  8537. Owned<IConstWUFieldUsage> field = fields->get();
  8538. filenames.append(normalizedFilename.str());
  8539. columnnames.append(field->queryName());
  8540. }
  8541. }
  8542. return true;
  8543. }
  8544. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8545. {
  8546. return p->getPropTree("DiskUsageStats");
  8547. }
  8548. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8549. {
  8550. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8551. offset_t maxNodeUsage;
  8552. if (stats)
  8553. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8554. else
  8555. {
  8556. stats = p->addPropTree("DiskUsageStats");
  8557. maxNodeUsage = 0;
  8558. }
  8559. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8560. {
  8561. // record all details at time of max node usage.
  8562. stats->setPropInt("@minNode", _minNode);
  8563. stats->setPropInt("@maxNode", _maxNode);
  8564. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8565. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8566. stats->setPropInt64("@graphId", _graphId);
  8567. if (_avgNodeUsage)
  8568. {
  8569. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8570. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8571. stats->setPropInt("@skewHi", _skewHi);
  8572. stats->setPropInt("@skewLo", _skewLo);
  8573. }
  8574. }
  8575. }
  8576. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8577. {
  8578. CriticalBlock block(crit);
  8579. _loadFilesWritten();
  8580. return * p->getElements("Files/File");
  8581. }
  8582. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8583. {
  8584. CriticalBlock block(crit);
  8585. _loadFilesRead();
  8586. return * p->getElements("FilesRead/File");
  8587. }
  8588. //=================================================================================================
  8589. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8590. {
  8591. CriticalBlock block(crit);
  8592. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8593. return false;
  8594. const char * currentcluster = queryClusterName();
  8595. const char *wuid = p->queryName();
  8596. StringBuffer curqname;
  8597. getClusterThorQueueName(curqname, currentcluster);
  8598. void *qi = qs->getQ(curqname.str(),wuid);
  8599. if (!qi)
  8600. return false;
  8601. setClusterName(cluster);
  8602. StringBuffer newqname;
  8603. getClusterThorQueueName(newqname, cluster);
  8604. qs->putQ(newqname.str(),wuid,qi);
  8605. return true;
  8606. }
  8607. //=================================================================================================
  8608. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8609. {
  8610. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8611. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8612. ForEach(*graphIter)
  8613. {
  8614. IConstWUGraph &graph = graphIter->query();
  8615. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8616. SCMStringBuffer gName;
  8617. graph.getName(gName);
  8618. StringBuffer xpath("Graphs/Graph[@name=\"");
  8619. xpath.append(gName.s).append("\"]/xgmml");
  8620. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8621. if (xgmml) // don't know of any reason it shouldn't exist
  8622. {
  8623. xgmml->removeProp("graphBin");
  8624. xgmml->setPropTree("graph", graphTree.getClear());
  8625. }
  8626. }
  8627. return ret.getClear();
  8628. }
  8629. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8630. {
  8631. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8632. ForEach(*iter)
  8633. {
  8634. IPropertyTree &graph = iter->query();
  8635. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8636. }
  8637. }
  8638. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8639. {
  8640. if (graphsCached < (heavy ? 2 : 1))
  8641. {
  8642. graphs.kill();
  8643. _loadGraphs(heavy);
  8644. graphsCached = (heavy ? 2 : 1);
  8645. }
  8646. }
  8647. EnumMapping graphTypes[] = {
  8648. { GraphTypeAny, "unknown" },
  8649. { GraphTypeProgress, "progress" },
  8650. { GraphTypeEcl, "ECL" },
  8651. { GraphTypeActivities, "activities" },
  8652. { GraphTypeSubProgress, "subgraph" },
  8653. { GraphTypeSize, NULL },
  8654. };
  8655. WUGraphType getGraphTypeFromString(const char* type)
  8656. {
  8657. return (WUGraphType) getEnum(type, graphTypes);
  8658. }
  8659. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8660. {
  8661. wuidVersion = owner.getWuidVersion();
  8662. }
  8663. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8664. {
  8665. str.set(p->queryProp("@name"));
  8666. return str;
  8667. }
  8668. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8669. {
  8670. if (wuidVersion >= 2)
  8671. {
  8672. str.set(p->queryProp("@label"));
  8673. return str;
  8674. }
  8675. else
  8676. {
  8677. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8678. str.set(xgmml->queryProp("@label"));
  8679. return str;
  8680. }
  8681. }
  8682. WUGraphState CLocalWUGraph::getState() const
  8683. {
  8684. return owner.queryGraphState(p->queryProp("@name"));
  8685. }
  8686. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8687. {
  8688. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8689. if (xgmml)
  8690. {
  8691. StringBuffer x;
  8692. toXML(xgmml, x);
  8693. str.set(x.str());
  8694. }
  8695. return str;
  8696. }
  8697. unsigned CLocalWorkUnit::getGraphCount() const
  8698. {
  8699. CriticalBlock block(crit);
  8700. if (p->hasProp("Graphs"))
  8701. {
  8702. return p->queryPropTree("Graphs")->numChildren();
  8703. }
  8704. return 0;
  8705. }
  8706. unsigned CLocalWorkUnit::getSourceFileCount() const
  8707. {
  8708. CriticalBlock block(crit);
  8709. _loadFilesRead();
  8710. if (p->hasProp("FilesRead"))
  8711. {
  8712. return p->queryPropTree("FilesRead")->numChildren();
  8713. }
  8714. return 0;
  8715. }
  8716. unsigned CLocalWorkUnit::getResultCount() const
  8717. {
  8718. CriticalBlock block(crit);
  8719. if (p->hasProp("Results"))
  8720. {
  8721. return p->queryPropTree("Results")->numChildren();
  8722. }
  8723. return 0;
  8724. }
  8725. unsigned CLocalWorkUnit::getVariableCount() const
  8726. {
  8727. CriticalBlock block(crit);
  8728. if (p->hasProp("Variables"))
  8729. {
  8730. return p->queryPropTree("Variables")->numChildren();
  8731. }
  8732. return 0;
  8733. }
  8734. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8735. {
  8736. CriticalBlock block(crit);
  8737. if (p->hasProp("Application"))
  8738. {
  8739. return p->queryPropTree("Application")->numChildren();
  8740. }
  8741. return 0;
  8742. }
  8743. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8744. {
  8745. appendXMLOpenTag(s, name, NULL, false);
  8746. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8747. if (attrs->first())
  8748. {
  8749. unsigned attributeindent = indent + (size32_t) strlen(name);
  8750. unsigned count = attrs->count();
  8751. bool doindent = false;
  8752. ForEach(*attrs)
  8753. {
  8754. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8755. continue;
  8756. #ifndef _DEBUG
  8757. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8758. continue;
  8759. #endif
  8760. if (doindent)
  8761. s.append('\n').appendN(attributeindent, ' ');
  8762. else if (count > 3)
  8763. doindent = true;
  8764. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8765. }
  8766. }
  8767. s.append('>');
  8768. return s;
  8769. }
  8770. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8771. {
  8772. CriticalBlock block(crit);
  8773. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8774. if (!paramTree)
  8775. return str;
  8776. StringBuffer xml;
  8777. if (!hidePasswords)
  8778. toXML(paramTree, xml);
  8779. else
  8780. {
  8781. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8782. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8783. ForEach(*elems)
  8784. {
  8785. const char *paramname = elems->query().queryName();
  8786. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8787. if (p->getPropBool(xpath))
  8788. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8789. else
  8790. toXML(&elems->query(), xml, 2);
  8791. }
  8792. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8793. }
  8794. str.set(xml);
  8795. return str;
  8796. }
  8797. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8798. {
  8799. CriticalBlock block(crit);
  8800. return p->getPropTree("Parameters");
  8801. }
  8802. void CLocalWorkUnit::setXmlParams(const char *params)
  8803. {
  8804. CriticalBlock block(crit);
  8805. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8806. }
  8807. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8808. {
  8809. CriticalBlock block(crit);
  8810. p->setPropTree("Parameters", tree);
  8811. }
  8812. unsigned __int64 CLocalWorkUnit::getHash() const
  8813. {
  8814. CriticalBlock block(crit);
  8815. return p->getPropInt64("@hash");
  8816. }
  8817. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8818. {
  8819. CriticalBlock block(crit);
  8820. p->setPropInt64("@hash", hash);
  8821. }
  8822. // getGraphs / getGraphsMeta
  8823. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8824. // If a type other than any is requested, a postfilter is needed.
  8825. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8826. {
  8827. WUGraphType type;
  8828. Owned<T> base;
  8829. bool match()
  8830. {
  8831. return base->query().getType()==type;
  8832. }
  8833. public:
  8834. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8835. : base(_base), type(_type)
  8836. {
  8837. }
  8838. bool first()
  8839. {
  8840. if (!base->first())
  8841. return false;
  8842. if (match())
  8843. return true;
  8844. return next();
  8845. }
  8846. bool next()
  8847. {
  8848. while (base->next())
  8849. if (match())
  8850. return true;
  8851. return false;
  8852. }
  8853. virtual bool isValid()
  8854. {
  8855. return base->isValid();
  8856. }
  8857. U & query()
  8858. {
  8859. return base->query();
  8860. }
  8861. };
  8862. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  8863. {
  8864. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  8865. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  8866. */
  8867. CriticalBlock block(crit);
  8868. loadGraphs(false);
  8869. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  8870. if (type!=GraphTypeAny)
  8871. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  8872. return *giter;
  8873. }
  8874. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  8875. {
  8876. CriticalBlock block(crit);
  8877. loadGraphs(true);
  8878. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  8879. if (type!=GraphTypeAny)
  8880. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  8881. return *giter;
  8882. }
  8883. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  8884. {
  8885. CriticalBlock block(crit);
  8886. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  8887. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  8888. IPTree *graph = p->queryPropTree(xpath);
  8889. if (graph)
  8890. return new CLocalWUGraph(*this, LINK(graph));
  8891. return NULL;
  8892. }
  8893. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  8894. {
  8895. CriticalBlock block(crit);
  8896. if (!graphs.length())
  8897. p->addPropTree("Graphs");
  8898. IPropertyTree *r = p->queryPropTree("Graphs");
  8899. IPropertyTree *s = r->addPropTree("Graph");
  8900. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  8901. q->setName(name);
  8902. q->setLabel(label);
  8903. q->setType(type);
  8904. q->setWfid(wfid);
  8905. q->setXGMMLTree(xgmml);
  8906. graphs.append(*q);
  8907. }
  8908. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  8909. {
  8910. /* Owned<IRemoteConnection> conn = getProgressConnection();
  8911. if (conn)
  8912. {
  8913. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  8914. if (progress)
  8915. return new CConstGraphProgress(p->queryName(), graphName, progress);
  8916. }
  8917. */
  8918. return NULL;
  8919. }
  8920. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  8921. {
  8922. throwUnexpected(); // Should only be used for persisted workunits
  8923. }
  8924. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  8925. {
  8926. throwUnexpected(); // Should only be used for persisted workunits
  8927. }
  8928. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  8929. {
  8930. throwUnexpected(); // Should only be used for persisted workunits
  8931. }
  8932. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  8933. {
  8934. throwUnexpected(); // Should only be used for persisted workunits
  8935. }
  8936. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  8937. {
  8938. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  8939. }
  8940. void CLocalWUGraph::setName(const char *str)
  8941. {
  8942. p->setProp("@name", str);
  8943. }
  8944. void CLocalWUGraph::setLabel(const char *str)
  8945. {
  8946. p->setProp("@label", str);
  8947. }
  8948. void CLocalWUGraph::setWfid(unsigned wfid)
  8949. {
  8950. p->setPropInt("@wfid", wfid);
  8951. }
  8952. void CLocalWUGraph::setXGMML(const char *str)
  8953. {
  8954. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  8955. }
  8956. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  8957. {
  8958. assertex(strcmp(_graph->queryName(), "graph")==0);
  8959. IPropertyTree *xgmml = p->setPropTree("xgmml");
  8960. MemoryBuffer mb;
  8961. _graph->serialize(mb);
  8962. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  8963. // Cassandra workunit code actually lzw compresses the parent anyway
  8964. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  8965. graph.setown(_graph);
  8966. }
  8967. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  8968. {
  8969. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  8970. ForEach (*aIter)
  8971. {
  8972. const char *aName = aIter->queryName()+1;
  8973. if (0 != stricmp("id", aName)) // "id" reserved.
  8974. {
  8975. IPropertyTree *att = targetNode.addPropTree("att");
  8976. att->setProp("@name", aName);
  8977. att->setProp("@value", aIter->queryValue());
  8978. }
  8979. }
  8980. }
  8981. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  8982. {
  8983. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  8984. if (!graphNode) return;
  8985. unsigned nodeId = rootNode.getPropInt("@id");
  8986. StringBuffer progressNodePath("node[@id=\"");
  8987. progressNodePath.append(nodeId).append("\"]");
  8988. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  8989. if (progressNode)
  8990. {
  8991. expandAttributes(*graphNode, *progressNode);
  8992. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  8993. ForEach (*edges)
  8994. {
  8995. IPropertyTree &edge = edges->query();
  8996. StringBuffer edgePath("edge[@id=\"");
  8997. edgePath.append(edge.queryProp("@id")).append("\"]");
  8998. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  8999. if (graphEdge)
  9000. {
  9001. if (progressV < 1)
  9002. mergePTree(graphEdge, &edge);
  9003. else
  9004. { // must translate to XGMML format
  9005. expandAttributes(*graphEdge, edge);
  9006. // This is really only here, so that our progress format can use non-attribute values, which have different efficiency qualifies (e.g. can be external by dali)
  9007. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  9008. ForEach (*iter)
  9009. {
  9010. IPropertyTree &t = iter->query();
  9011. IPropertyTree *att = graphEdge->addPropTree("att");
  9012. att->setProp("@name", t.queryName());
  9013. att->setProp("@value", t.queryProp(NULL));
  9014. }
  9015. }
  9016. }
  9017. }
  9018. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  9019. ForEach (*nodes)
  9020. {
  9021. IPropertyTree &node = nodes->query();
  9022. StringBuffer nodePath("node[@id=\"");
  9023. nodePath.append(node.queryProp("@id")).append("\"]");
  9024. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  9025. if (_node)
  9026. {
  9027. if (progressV < 1)
  9028. mergePTree(_node, &node);
  9029. else
  9030. { // must translate to XGMML format
  9031. expandAttributes(*_node, node);
  9032. }
  9033. }
  9034. }
  9035. }
  9036. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  9037. ForEach (*iter)
  9038. mergeProgress(iter->query(), progressTree, progressV);
  9039. }
  9040. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  9041. {
  9042. return p->getPropTree("xgmml");
  9043. }
  9044. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  9045. {
  9046. if (!graph)
  9047. {
  9048. // NB: although graphBin introduced in wuidVersion==2,
  9049. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  9050. MemoryBuffer mb;
  9051. if (p->getPropBin("xgmml/graphBin", mb))
  9052. graph.setown(createPTree(mb, ipt_lowmem));
  9053. else
  9054. graph.setown(p->getBranch("xgmml/graph"));
  9055. if (!graph)
  9056. return NULL;
  9057. }
  9058. if (!doMergeProgress)
  9059. return graph.getLink();
  9060. else
  9061. {
  9062. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  9063. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  9064. if (progress)
  9065. {
  9066. //MORE: Eventually this should directly access the new stats structure
  9067. unsigned progressV = progress->queryFormatVersion();
  9068. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  9069. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  9070. ForEach (*nodeIterator)
  9071. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  9072. }
  9073. return copy.getClear();
  9074. }
  9075. }
  9076. WUGraphType CLocalWUGraph::getType() const
  9077. {
  9078. return (WUGraphType) getEnum(p, "@type", graphTypes);
  9079. }
  9080. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  9081. {
  9082. str.set(p->queryProp("@type"));
  9083. if (!str.length())
  9084. str.set("unknown");
  9085. return str;
  9086. }
  9087. unsigned CLocalWUGraph::getWfid() const
  9088. {
  9089. return p->getPropInt("@wfid", 0);
  9090. }
  9091. void CLocalWUGraph::setType(WUGraphType _type)
  9092. {
  9093. setEnum(p, "@type", _type, graphTypes);
  9094. }
  9095. //=================================================================================================
  9096. EnumMapping queryFileTypes[] = {
  9097. { FileTypeCpp, "cpp" },
  9098. { FileTypeDll, "dll" },
  9099. { FileTypeResText, "res" },
  9100. { FileTypeHintXml, "hint" },
  9101. { FileTypeXml, "xml" },
  9102. { FileTypeLog, "log" },
  9103. { FileTypeSize, NULL },
  9104. };
  9105. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  9106. {
  9107. }
  9108. WUFileType CLocalWUAssociated::getType() const
  9109. {
  9110. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  9111. }
  9112. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  9113. {
  9114. str.set(p->queryProp("@desc"));
  9115. return str;
  9116. }
  9117. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  9118. {
  9119. str.set(p->queryProp("@ip"));
  9120. return str;
  9121. }
  9122. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  9123. {
  9124. str.set(p->queryProp("@filename"));
  9125. return str;
  9126. }
  9127. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  9128. {
  9129. str.set(pathTail(p->queryProp("@filename")));
  9130. return str;
  9131. }
  9132. unsigned CLocalWUAssociated::getCrc() const
  9133. {
  9134. return p->getPropInt("@crc", 0);
  9135. }
  9136. unsigned CLocalWUAssociated::getMinActivityId() const
  9137. {
  9138. return p->getPropInt("@minActivity", 0);
  9139. }
  9140. unsigned CLocalWUAssociated::getMaxActivityId() const
  9141. {
  9142. return p->getPropInt("@maxActivity", 0);
  9143. }
  9144. //=================================================================================================
  9145. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  9146. {
  9147. associatedCached = false;
  9148. }
  9149. EnumMapping queryTypes[] = {
  9150. { QueryTypeUnknown, "unknown" },
  9151. { QueryTypeEcl, "ECL" },
  9152. { QueryTypeSql, "SQL" },
  9153. { QueryTypeXml, "XML" },
  9154. { QueryTypeAttribute, "Attribute" },
  9155. { QueryTypeSize, NULL },
  9156. };
  9157. WUQueryType CLocalWUQuery::getQueryType() const
  9158. {
  9159. return (WUQueryType) getEnum(p, "@type", queryTypes);
  9160. }
  9161. void CLocalWUQuery::setQueryType(WUQueryType qt)
  9162. {
  9163. setEnum(p, "@type", qt, queryTypes);
  9164. }
  9165. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  9166. {
  9167. const char *text = p->queryProp("Text");
  9168. if (!text)
  9169. text = p->queryProp("ShortText");
  9170. str.set(text);
  9171. return str;
  9172. }
  9173. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  9174. {
  9175. const char * text = p->queryProp("ShortText");
  9176. if (text)
  9177. str.set(text);
  9178. else
  9179. {
  9180. text = p->queryProp("Text");
  9181. if (isArchiveQuery(text))
  9182. {
  9183. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9184. const char * path = xml->queryProp("Query/@attributePath");
  9185. if (path)
  9186. {
  9187. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9188. if (resolved)
  9189. str.set(resolved->queryProp(NULL));
  9190. }
  9191. else
  9192. str.set(xml->queryProp("Query"));
  9193. }
  9194. else
  9195. str.set(text);
  9196. }
  9197. return str;
  9198. }
  9199. bool CLocalWUQuery::isArchive() const
  9200. {
  9201. if (p->hasProp("@isArchive"))
  9202. return p->getPropBool("@isArchive");
  9203. const char *text = p->queryProp("Text");
  9204. return isArchiveQuery(text);
  9205. }
  9206. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  9207. {
  9208. str.set(p->queryProp("@name"));
  9209. return str;
  9210. }
  9211. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  9212. {
  9213. str.set(p->queryProp("@main"));
  9214. return str;
  9215. }
  9216. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  9217. {
  9218. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9219. if (entry)
  9220. entry->getNameTail(str);
  9221. return str;
  9222. }
  9223. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  9224. {
  9225. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  9226. if (entry)
  9227. entry->getName(str);
  9228. return str;
  9229. }
  9230. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  9231. {
  9232. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  9233. if (entry)
  9234. entry->getName(str);
  9235. return str;
  9236. }
  9237. unsigned CLocalWUQuery::getQueryDllCrc() const
  9238. {
  9239. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9240. if (entry)
  9241. return entry->getCrc();
  9242. return 0;
  9243. }
  9244. void CLocalWUQuery::setQueryText(const char *text)
  9245. {
  9246. bool isArchive = isArchiveQuery(text);
  9247. if (isArchive)
  9248. {
  9249. p->setProp("Text", text);
  9250. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9251. const char * path = xml->queryProp("Query/@attributePath");
  9252. if (path)
  9253. {
  9254. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9255. if (resolved)
  9256. p->setProp("ShortText", resolved->queryProp(NULL));
  9257. }
  9258. else
  9259. p->setProp("ShortText", xml->queryProp("Query"));
  9260. }
  9261. else
  9262. {
  9263. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  9264. // but as long as there may be new workunits compiled by old systems, we can't
  9265. p->setProp("ShortText", text);
  9266. }
  9267. p->setPropBool("@isArchive", isArchive);
  9268. if (isArchive)
  9269. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  9270. }
  9271. void CLocalWUQuery::setQueryName(const char *qname)
  9272. {
  9273. p->setProp("@name", qname);
  9274. }
  9275. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  9276. {
  9277. p->setProp("@main", str);
  9278. }
  9279. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  9280. {
  9281. CriticalBlock block(crit);
  9282. loadAssociated();
  9283. StringBuffer xpath;
  9284. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  9285. if (p->hasProp(xpath))
  9286. return;
  9287. if (!associated.length())
  9288. p->addPropTree("Associated");
  9289. IPropertyTree *pl = p->queryPropTree("Associated");
  9290. IPropertyTree *s = pl->addPropTree("File");
  9291. setEnum(s, "@type", type, queryFileTypes);
  9292. s->setProp("@filename", name);
  9293. s->setProp("@ip", ip);
  9294. s->setProp("@desc", desc);
  9295. if (crc)
  9296. s->setPropInt("@crc", crc);
  9297. if (minActivity)
  9298. s->setPropInt("@minActivity", minActivity);
  9299. if (maxActivity)
  9300. s->setPropInt("@maxActivity", maxActivity);
  9301. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  9302. associated.append(*q);
  9303. }
  9304. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  9305. {
  9306. CriticalBlock block(crit);
  9307. associatedCached = false;
  9308. associated.kill();
  9309. StringBuffer xpath;
  9310. xpath.append("Associated/File");
  9311. if (type)
  9312. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  9313. if (name)
  9314. xpath.append("[@filename=\"").append(name).append("\"]");
  9315. if (desc)
  9316. xpath.append("[@desc=\"").append(desc).append("\"]");
  9317. p->removeProp(xpath.str());
  9318. }
  9319. void CLocalWUQuery::removeAssociatedFiles()
  9320. {
  9321. associatedCached = false;
  9322. associated.kill();
  9323. p->removeProp("Associated");
  9324. }
  9325. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9326. {
  9327. CriticalBlock block(crit);
  9328. loadAssociated();
  9329. ForEachItemIn(idx, associated)
  9330. {
  9331. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9332. if (cur.getType() == type)
  9333. {
  9334. if (index-- == 0)
  9335. return &OLINK(cur);
  9336. }
  9337. }
  9338. return NULL;
  9339. }
  9340. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9341. {
  9342. const char * name = p->queryProp(propname);
  9343. if (name)
  9344. {
  9345. IPropertyTree *s = createPTree("File");
  9346. setEnum(s, "@type", type, queryFileTypes);
  9347. s->setProp("@filename", name);
  9348. if (crc)
  9349. s->setPropInt("@crc", crc);
  9350. associated.append(*new CLocalWUAssociated(s));
  9351. }
  9352. }
  9353. void CLocalWUQuery::loadAssociated() const
  9354. {
  9355. CriticalBlock block(crit);
  9356. if (!associatedCached)
  9357. {
  9358. assertex(associated.length() == 0);
  9359. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9360. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9361. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9362. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9363. for (r->first(); r->isValid(); r->next())
  9364. {
  9365. IPropertyTree *rp = &r->query();
  9366. rp->Link();
  9367. associated.append(*new CLocalWUAssociated(rp));
  9368. }
  9369. associatedCached = true;
  9370. }
  9371. }
  9372. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9373. {
  9374. CriticalBlock block(crit);
  9375. loadAssociated();
  9376. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9377. }
  9378. //========================================================================================
  9379. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9380. {
  9381. }
  9382. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9383. {
  9384. str.set(p->queryProp("@module"));
  9385. return str;
  9386. }
  9387. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9388. {
  9389. str.set(p->queryProp("@attribute"));
  9390. return str;
  9391. }
  9392. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9393. {
  9394. str.set(p->queryProp("@defaultName"));
  9395. return str;
  9396. }
  9397. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9398. {
  9399. return (unsigned) p->getPropInt("@crc");
  9400. }
  9401. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9402. {
  9403. if (!name)
  9404. {
  9405. StringBuffer ws_info;
  9406. ws_info.appendf("<%s ", p->queryName());
  9407. Owned<IAttributeIterator> attrs = p->getAttributes();
  9408. for(attrs->first(); attrs->isValid(); attrs->next())
  9409. {
  9410. const char *name = attrs->queryName()+1;
  9411. const char *value = attrs->queryValue();
  9412. ws_info.appendf("%s='%s' ", name, value);
  9413. }
  9414. ws_info.append("> \n");
  9415. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9416. ForEach(*info)
  9417. {
  9418. IPropertyTree &item = info->query();
  9419. const char *name = item.queryName();
  9420. if (name)
  9421. {
  9422. MemoryBuffer mb;
  9423. bool isbin = p->isBinary(name);
  9424. if (isbin)
  9425. {
  9426. p->getPropBin(name,mb);
  9427. if (mb.length())
  9428. {
  9429. unsigned len = 0;
  9430. mb.read(len);
  9431. StringBuffer encodedString;
  9432. StringBuffer val(len, (const char *) mb.readDirect(len));
  9433. encodeXML(val, encodedString);
  9434. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9435. }
  9436. }
  9437. else
  9438. {
  9439. StringBuffer tmp;
  9440. toXML(&item, tmp);
  9441. ws_info.append(tmp.str());
  9442. }
  9443. }
  9444. }
  9445. ws_info.appendf("</%s>", p->queryName());
  9446. str.setLen(ws_info.str(), ws_info.length());
  9447. }
  9448. else
  9449. {
  9450. MemoryBuffer mb;
  9451. p->getPropBin(name,mb);
  9452. if (mb.length())
  9453. {
  9454. unsigned len;
  9455. mb.read(len);
  9456. str.setLen((const char *) mb.readDirect(len), len);
  9457. }
  9458. }
  9459. return str;
  9460. }
  9461. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9462. {
  9463. str.set(p->queryProp(name));
  9464. return str;
  9465. }
  9466. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9467. {
  9468. p->setProp("@module", mname);
  9469. }
  9470. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9471. {
  9472. p->setProp("@attribute", aname);
  9473. }
  9474. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9475. {
  9476. p->setProp("@defaultName", dname);
  9477. }
  9478. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9479. {
  9480. p->setPropInt("@crc", crc);
  9481. }
  9482. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9483. {
  9484. MemoryBuffer m;
  9485. unsigned len = (size32_t)strlen(info);
  9486. serializeLPString(len, info, m);
  9487. p->setPropBin(name, m.length(), m.toByteArray());
  9488. }
  9489. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9490. {
  9491. p->setProp(name, info);
  9492. }
  9493. //========================================================================================
  9494. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9495. {
  9496. }
  9497. EnumMapping resultStatuses[] = {
  9498. { ResultStatusUndefined, "undefined" },
  9499. { ResultStatusCalculated, "calculated" },
  9500. { ResultStatusSupplied, "supplied" },
  9501. { ResultStatusFailed, "failed" },
  9502. { ResultStatusPartial, "partial" },
  9503. { ResultStatusSize, NULL }
  9504. };
  9505. WUResultStatus CLocalWUResult::getResultStatus() const
  9506. {
  9507. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9508. }
  9509. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9510. {
  9511. str.set(p->queryProp("@name"));
  9512. return str;
  9513. }
  9514. int CLocalWUResult::getResultSequence() const
  9515. {
  9516. return p->getPropInt("@sequence", -1);
  9517. }
  9518. bool CLocalWUResult::isResultScalar() const
  9519. {
  9520. return p->getPropInt("@isScalar", 1) != 0;
  9521. }
  9522. bool findSize(int size, IntArray &sizes)
  9523. {
  9524. ForEachItemIn(idx, sizes)
  9525. {
  9526. if (sizes.item(idx)==size)
  9527. return true;
  9528. }
  9529. return false;
  9530. }
  9531. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9532. {
  9533. MemoryBuffer schema;
  9534. p->getPropBin("SchemaRaw", schema);
  9535. if (schema.length())
  9536. {
  9537. for (;;)
  9538. {
  9539. StringAttr name;
  9540. schema.read(name);
  9541. if (*schema.readDirect(0)==type_void)
  9542. break;
  9543. names.append(*new StringAttrItem(name));
  9544. types.append(*deserializeType(schema)); // MORE - nested records!
  9545. }
  9546. schema.skip(1);
  9547. if (schema.length() != schema.getPos())
  9548. {
  9549. unsigned eclLen;
  9550. schema.read(eclLen);
  9551. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9552. if (eclText)
  9553. {
  9554. eclText->setLen(schemaData, eclLen);
  9555. if ((eclLen == 0) && names.ordinality())
  9556. {
  9557. const char * firstName = names.item(0).text;
  9558. StringBuffer temp;
  9559. temp.append("RECORD ");
  9560. types.item(0).getECLType(temp);
  9561. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9562. eclText->set(temp.str());
  9563. }
  9564. }
  9565. }
  9566. }
  9567. }
  9568. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9569. {
  9570. ForEachItemIn(idx, types)
  9571. {
  9572. StringAttrItem &name = names.item(idx);
  9573. ITypeInfo &type = types.item(idx);
  9574. unsigned size = type.getSize();
  9575. switch(type.getTypeCode())
  9576. {
  9577. case type_data:
  9578. if (size==UNKNOWN_LENGTH)
  9579. {
  9580. if (in.remaining() < sizeof(int))
  9581. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9582. in.read(size);
  9583. }
  9584. outputXmlData(size, in.readDirect(size), name.text, out);
  9585. break;
  9586. case type_string:
  9587. if (size==UNKNOWN_LENGTH)
  9588. {
  9589. if (in.remaining() < sizeof(int))
  9590. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9591. in.read(size);
  9592. }
  9593. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9594. break;
  9595. case type_varstring:
  9596. {
  9597. if (size == UNKNOWN_LENGTH)
  9598. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9599. const char * text = (const char *) in.readDirect(size);
  9600. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9601. break;
  9602. }
  9603. case type_unicode:
  9604. {
  9605. unsigned len = type.getStringLen();
  9606. if (size==UNKNOWN_LENGTH)
  9607. in.read(len);
  9608. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9609. }
  9610. break;
  9611. case type_utf8:
  9612. {
  9613. unsigned len = type.getStringLen();
  9614. if (size==UNKNOWN_LENGTH)
  9615. {
  9616. in.read(len);
  9617. size = rtlUtf8Size(len, in.readDirect(0));
  9618. }
  9619. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9620. }
  9621. break;
  9622. case type_qstring:
  9623. {
  9624. unsigned len = type.getStringLen();
  9625. if (size==UNKNOWN_LENGTH)
  9626. in.read(len);
  9627. unsigned outlen;
  9628. char *outstr;
  9629. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9630. outputXmlString(outlen, outstr, name.text, out);
  9631. free(outstr);
  9632. break;
  9633. }
  9634. case type_int:
  9635. case type_swapint:
  9636. if (type.isSigned())
  9637. {
  9638. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9639. unsigned __int64 cval8 = 0;
  9640. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9641. if (type.isSwappedEndian())
  9642. {
  9643. unsigned idx = 0;
  9644. if (raw[idx] & 0x80)
  9645. cval8 = (__int64)-1;
  9646. while (size--)
  9647. cval8 = (cval8 << 8) | raw[idx++];
  9648. }
  9649. else
  9650. {
  9651. if (raw[size-1] & 0x80)
  9652. cval8 = (__int64)-1;
  9653. while (size--)
  9654. cval8 = (cval8 << 8) | raw[size];
  9655. }
  9656. outputXmlInt((__int64) cval8, name.text, out);
  9657. }
  9658. else
  9659. {
  9660. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9661. unsigned __int64 cval8 = 0;
  9662. if (type.isSwappedEndian())
  9663. {
  9664. unsigned idx = 0;
  9665. while (size--)
  9666. cval8 = (cval8 << 8) | raw[idx++];
  9667. }
  9668. else
  9669. {
  9670. while (size--)
  9671. cval8 = (cval8 << 8) | raw[size];
  9672. }
  9673. outputXmlUInt(cval8, name.text, out);
  9674. }
  9675. break;
  9676. case type_boolean:
  9677. bool cvalb;
  9678. in.read(cvalb);
  9679. outputXmlBool(cvalb, name.text, out);
  9680. break;
  9681. case type_decimal:
  9682. if (type.isSigned())
  9683. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9684. else
  9685. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9686. break;
  9687. case type_real:
  9688. double cvald;
  9689. switch(size)
  9690. {
  9691. case 4:
  9692. float cvalf;
  9693. in.read(cvalf);
  9694. cvald = cvalf;
  9695. break;
  9696. case 8:
  9697. in.read(cvald);
  9698. break;
  9699. default:
  9700. throwUnexpected();
  9701. }
  9702. outputXmlReal(cvald, name.text, out);
  9703. break;
  9704. default:
  9705. assertex(!"unexpected type in raw record");
  9706. break;
  9707. }
  9708. }
  9709. }
  9710. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9711. {
  9712. TypeInfoArray types;
  9713. StringAttrArray names;
  9714. getSchema(types, names);
  9715. StringBuffer xml;
  9716. const char * name = p->queryProp("@name");
  9717. if (name)
  9718. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9719. else
  9720. xml.append("<Dataset>\n");
  9721. if (hidePassword && p->getPropBool("Format/@password"))
  9722. {
  9723. xml.append(" <Row>");
  9724. appendXMLTag(xml, name, "****");
  9725. xml.append("</Row>\n");
  9726. }
  9727. else if (p->hasProp("Value"))
  9728. {
  9729. MemoryBuffer raw;
  9730. p->getPropBin("Value", raw);
  9731. unsigned __int64 numrows = getResultRowCount();
  9732. while (numrows--)
  9733. {
  9734. xml.append(" <Row>");
  9735. readRow(xml, raw, types, names);
  9736. xml.append("</Row>\n");
  9737. }
  9738. }
  9739. else if (p->hasProp("xmlValue"))
  9740. {
  9741. xml.append(" <Row>");
  9742. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9743. xml.append("</Row>\n");
  9744. }
  9745. xml.append("</Dataset>\n");
  9746. str.set(xml.str());
  9747. return str;
  9748. }
  9749. IProperties *CLocalWUResult::queryResultXmlns()
  9750. {
  9751. CriticalBlock block(crit);
  9752. if (xmlns)
  9753. return xmlns;
  9754. xmlns.setown(createProperties());
  9755. Owned<IAttributeIterator> it = p->getAttributes();
  9756. unsigned prefixLen = strlen("@xmlns");
  9757. ForEach(*it)
  9758. {
  9759. const char *name = it->queryName();
  9760. if (!strncmp("@xmlns", name, prefixLen))
  9761. {
  9762. if (name[prefixLen]==':') //normal case
  9763. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9764. else if (!name[prefixLen]) //special case, unprefixed namespace
  9765. xmlns->setProp("xmlns", it->queryValue());
  9766. }
  9767. }
  9768. return xmlns;
  9769. }
  9770. unsigned CLocalWUResult::getResultFetchSize() const
  9771. {
  9772. return p->getPropInt("fetchSize", 100);
  9773. }
  9774. __int64 CLocalWUResult::getResultTotalRowCount() const
  9775. {
  9776. return p->getPropInt64("totalRowCount", -1);
  9777. }
  9778. __int64 CLocalWUResult::getResultRowCount() const
  9779. {
  9780. return p->getPropInt64("rowCount", 0);
  9781. }
  9782. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9783. {
  9784. ecl.set(p->queryProp("datasetEcl"));
  9785. defs.set(p->queryProp("datasetEclDefs"));
  9786. }
  9787. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9788. {
  9789. val.set(p->queryProp("logicalName"));
  9790. return val;
  9791. }
  9792. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9793. {
  9794. ecl.set(p->queryProp("keyField"));
  9795. return ecl;
  9796. }
  9797. unsigned CLocalWUResult::getResultRequestedRows() const
  9798. {
  9799. return p->getPropInt("requestedRows", 1);
  9800. }
  9801. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9802. {
  9803. TypeInfoArray types;
  9804. StringAttrArray names;
  9805. getSchema(types, names, &str);
  9806. return str;
  9807. }
  9808. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9809. {
  9810. str.set(p->queryProp("@recordSizeEntry"));
  9811. return str;
  9812. }
  9813. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9814. {
  9815. str.set(p->queryProp("@transformerEntry"));
  9816. return str;
  9817. }
  9818. __int64 CLocalWUResult::getResultRowLimit() const
  9819. {
  9820. return p->getPropInt64("@rowLimit");
  9821. }
  9822. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9823. {
  9824. str.set(p->queryProp("@tempFilename"));
  9825. return str;
  9826. }
  9827. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9828. {
  9829. str.clear();
  9830. if (!name || !*name)
  9831. return str;
  9832. IPropertyTree *format = p->queryPropTree("Format");
  9833. if (!format)
  9834. return str;
  9835. VStringBuffer xpath("@%s", name);
  9836. str.set(format->queryProp(xpath));
  9837. return str;
  9838. }
  9839. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9840. {
  9841. _graph.set(p->queryProp("@graph"));
  9842. _activityId = p->getPropInt("@activity", 0);
  9843. }
  9844. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9845. {
  9846. setEnum(p, "@status", status, resultStatuses);
  9847. if (status==ResultStatusUndefined)
  9848. {
  9849. p->removeProp("Value");
  9850. p->removeProp("totalRowCount");
  9851. p->removeProp("rowCount");
  9852. p->removeProp("@format");
  9853. p->removeProp("@tempFileNmae");
  9854. p->removeProp("logicalName");
  9855. }
  9856. }
  9857. void CLocalWUResult::setResultName(const char *s)
  9858. {
  9859. p->setProp("@name", s);
  9860. }
  9861. void CLocalWUResult::setResultSequence(unsigned seq)
  9862. {
  9863. p->setPropInt("@sequence", seq);
  9864. }
  9865. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  9866. {
  9867. p->setPropBin("SchemaRaw", size, schema);
  9868. }
  9869. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  9870. {
  9871. StringBuffer xpath("@xmlns");
  9872. if (prefix && *prefix)
  9873. xpath.append(':').append(prefix);
  9874. p->setProp(xpath, uri);
  9875. }
  9876. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  9877. {
  9878. if (!name || !*name)
  9879. return;
  9880. IPropertyTree *format = ensurePTree(p, "Format");
  9881. VStringBuffer xpath("@%s", name);
  9882. format->setProp(xpath, value);
  9883. }
  9884. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  9885. {
  9886. p->setProp("@graph", _graph);
  9887. p->setPropInt("@activity", _activityId);
  9888. }
  9889. void CLocalWUResult::setResultScalar(bool isScalar)
  9890. {
  9891. p->setPropInt("@isScalar", (int) isScalar);
  9892. if (isScalar)
  9893. setResultTotalRowCount(1);
  9894. }
  9895. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  9896. {
  9897. p->setPropBin("Value", len, data);
  9898. setResultStatus(ResultStatusSupplied);
  9899. setResultFormat(format);
  9900. }
  9901. void CLocalWUResult::setResultFormat(WUResultFormat format)
  9902. {
  9903. switch (format)
  9904. {
  9905. case ResultFormatXml:
  9906. p->setProp("@format","xml");
  9907. break;
  9908. case ResultFormatXmlSet:
  9909. p->setProp("@format","xmlSet");
  9910. break;
  9911. case ResultFormatCsv:
  9912. p->setProp("@format","csv");
  9913. break;
  9914. default:
  9915. p->removeProp("@format");
  9916. break;
  9917. }
  9918. }
  9919. void CLocalWUResult::setResultXML(const char *val)
  9920. {
  9921. p->setProp("xmlValue", val);
  9922. }
  9923. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  9924. {
  9925. p->appendPropBin("Value", len, data);
  9926. setResultStatus(ResultStatusPartial);
  9927. const char *existingFormat = p->queryProp("@format");
  9928. const char *formatStr = NULL;
  9929. switch (format)
  9930. {
  9931. case ResultFormatXml:
  9932. formatStr = "xml";
  9933. break;
  9934. case ResultFormatXmlSet:
  9935. formatStr = "xmlSet";
  9936. break;
  9937. case ResultFormatCsv:
  9938. formatStr = "csv";
  9939. break;
  9940. default:
  9941. existingFormat = nullptr;
  9942. p->removeProp("@format");
  9943. break;
  9944. }
  9945. if (format)
  9946. {
  9947. if (existingFormat)
  9948. {
  9949. if (0 != stricmp(formatStr, existingFormat))
  9950. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  9951. }
  9952. else
  9953. p->setProp("@format", formatStr);
  9954. }
  9955. }
  9956. void CLocalWUResult::setResultFetchSize(unsigned rows)
  9957. {
  9958. p->setPropInt("fetchSize", rows);
  9959. }
  9960. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  9961. {
  9962. p->setPropInt64("totalRowCount", rows);
  9963. }
  9964. void CLocalWUResult::setResultRowCount(__int64 rows)
  9965. {
  9966. p->setPropInt64("rowCount", rows);
  9967. }
  9968. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  9969. {
  9970. p->setProp("datasetEcl", ecl);
  9971. p->setProp("datasetEclDefs", defs);
  9972. }
  9973. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  9974. {
  9975. p->setProp("logicalName", logicalName);
  9976. }
  9977. void CLocalWUResult::setResultKeyField(const char *ecl)
  9978. {
  9979. p->setProp("keyField", ecl);
  9980. }
  9981. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  9982. {
  9983. p->setPropInt("requestedRows", rows);
  9984. }
  9985. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  9986. {
  9987. p->setProp("@recordSizeEntry", entry);
  9988. }
  9989. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  9990. {
  9991. p->setProp("@transformerEntry", entry);
  9992. }
  9993. void CLocalWUResult::setResultRowLimit(__int64 value)
  9994. {
  9995. p->setPropInt64("@rowLimit", value);
  9996. }
  9997. void CLocalWUResult::setResultFilename(const char * name)
  9998. {
  9999. p->setProp("@tempFilename", name);
  10000. }
  10001. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  10002. __int64 CLocalWUResult::getResultInt() const
  10003. {
  10004. __int64 result = 0;
  10005. MemoryBuffer s;
  10006. p->getPropBin("Value", s);
  10007. if (s.length())
  10008. s.read(result);
  10009. else
  10010. {
  10011. // NOTE - we use this rather than getPropInt64 since it handles uint64 values up to MAX_UINT better (for our purposes)
  10012. const char *val = p->queryProp("xmlValue");
  10013. if (val)
  10014. result = rtlStrToInt8(strlen(val), val);
  10015. }
  10016. return result;
  10017. }
  10018. bool CLocalWUResult::getResultBool() const
  10019. {
  10020. bool result = false;
  10021. MemoryBuffer s;
  10022. p->getPropBin("Value", s);
  10023. if (s.length())
  10024. s.read(result);
  10025. else
  10026. result = p->getPropBool("xmlValue");
  10027. return result;
  10028. }
  10029. double CLocalWUResult::getResultReal() const
  10030. {
  10031. double result = 0;
  10032. MemoryBuffer s;
  10033. p->getPropBin("Value", s);
  10034. if (s.length())
  10035. s.read(result);
  10036. else
  10037. {
  10038. const char *xmlVal = p->queryProp("xmlValue");
  10039. if (xmlVal)
  10040. result = atof(xmlVal);
  10041. }
  10042. return result;
  10043. }
  10044. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  10045. {
  10046. MemoryBuffer s;
  10047. p->getPropBin("Value", s);
  10048. if (s.length())
  10049. {
  10050. assertex(s.length() == len);
  10051. s.read(len, val);
  10052. }
  10053. else
  10054. {
  10055. const char *xmlVal = p->queryProp("xmlValue");
  10056. if (xmlVal)
  10057. {
  10058. Decimal d;
  10059. d.setString(strlen(xmlVal), xmlVal);
  10060. if (isSigned)
  10061. d.getDecimal(len, precision, val);
  10062. else
  10063. d.getUDecimal(len, precision, val);
  10064. }
  10065. else
  10066. memset(val, 0, len);
  10067. }
  10068. }
  10069. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  10070. {
  10071. if (hidePassword && p->getPropBool("@password"))
  10072. {
  10073. str.set("****");
  10074. return str;
  10075. }
  10076. MemoryBuffer s;
  10077. p->getPropBin("Value", s);
  10078. if (s.length())
  10079. {
  10080. unsigned len;
  10081. s.read(len);
  10082. str.setLen((const char *) s.readDirect(len), len);
  10083. }
  10084. else
  10085. {
  10086. p->getPropBin("xmlValue", s);
  10087. if (p->isBinary("xmlValue"))
  10088. str.setLen(s.toByteArray(), s.length());
  10089. else
  10090. {
  10091. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  10092. str.set(ascii);
  10093. rtlFree(ascii);
  10094. }
  10095. }
  10096. return str;
  10097. }
  10098. WUResultFormat CLocalWUResult::getResultFormat() const
  10099. {
  10100. const char * format = p->queryProp("@format");
  10101. if (!format)
  10102. return ResultFormatRaw;
  10103. else if (strcmp(format, "xml") == 0)
  10104. return ResultFormatXml;
  10105. else if (strcmp(format, "xmlSet") == 0)
  10106. return ResultFormatXmlSet;
  10107. else if (strcmp(format, "csv") == 0)
  10108. return ResultFormatCsv;
  10109. else
  10110. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  10111. }
  10112. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10113. {
  10114. MemoryBuffer s;
  10115. p->getPropBin("Value", s);
  10116. unsigned len = s.length();
  10117. if (len)
  10118. {
  10119. WUResultFormat format = getResultFormat();
  10120. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  10121. {
  10122. if (!xmlTransformer)
  10123. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  10124. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  10125. }
  10126. else if (format == ResultFormatCsv)
  10127. {
  10128. if (!csvTransformer)
  10129. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  10130. csvTransformer->transform(data, len, s.readDirect(len), true);
  10131. }
  10132. else
  10133. data.setLen(s.readDirect(len), len);
  10134. }
  10135. else
  10136. data.clear();
  10137. return data;
  10138. }
  10139. unsigned CLocalWUResult::getResultHash() const
  10140. {
  10141. MemoryBuffer s;
  10142. p->getPropBin("Value", s);
  10143. unsigned len = s.length();
  10144. const byte * data = (const byte *)s.toByteArray();
  10145. return ~hashc(data, len, ~0);
  10146. }
  10147. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  10148. {
  10149. MemoryBuffer s;
  10150. p->getPropBin("Value", s);
  10151. if (s.length())
  10152. {
  10153. unsigned len;
  10154. s.read(len);
  10155. data.setLen(s.readDirect(len*2), len*2);
  10156. }
  10157. else
  10158. {
  10159. StringBuffer utf8;
  10160. if (p->getProp("xmlValue", utf8))
  10161. {
  10162. unsigned outlen;
  10163. UChar *out;
  10164. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  10165. data.setLen(out, outlen*2);
  10166. rtlFree(out);
  10167. }
  10168. else
  10169. data.clear();
  10170. }
  10171. return data;
  10172. }
  10173. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10174. {
  10175. WUResultFormat format = getResultFormat();
  10176. if (format == ResultFormatRaw)
  10177. {
  10178. //MORE: This should not load the whole property...
  10179. MemoryBuffer s;
  10180. p->getPropBin("Value", s);
  10181. return s.length();
  10182. }
  10183. else
  10184. {
  10185. MemoryBuffer temp;
  10186. MemoryBuffer2IDataVal adaptor(temp);
  10187. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10188. return temp.length();
  10189. }
  10190. }
  10191. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10192. {
  10193. WUResultFormat format = getResultFormat();
  10194. if (format != ResultFormatRaw)
  10195. {
  10196. MemoryBuffer temp;
  10197. MemoryBuffer2IDataVal adaptor(temp);
  10198. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10199. unsigned len = temp.length();
  10200. if (from > len) from = len;
  10201. if (from + length > len) length = len - from;
  10202. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  10203. return data;
  10204. }
  10205. else
  10206. {
  10207. //MORE: This should not load the whole property, and should be different from the code above...
  10208. MemoryBuffer s;
  10209. p->getPropBin("Value", s);
  10210. unsigned len = s.length();
  10211. if (from > len) from = len;
  10212. if (from + length > len) length = len - from;
  10213. data.setLen(s.readDirect(len) + from, (size32_t)length);
  10214. return data;
  10215. }
  10216. }
  10217. bool CLocalWUResult::getResultIsAll() const
  10218. {
  10219. return p->getPropBool("@isAll", false);
  10220. }
  10221. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  10222. void CLocalWUResult::setResultInt(__int64 val)
  10223. {
  10224. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  10225. MemoryBuffer m;
  10226. serializeInt8(val, m);
  10227. p->setPropBin("Value", m.length(), m.toByteArray());
  10228. setResultRowCount(1);
  10229. setResultTotalRowCount(1);
  10230. }
  10231. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  10232. {
  10233. setResultInt((__int64) val);
  10234. }
  10235. void CLocalWUResult::setResultReal(double val)
  10236. {
  10237. // Note: we always serialize scalar real results as real8, and schema must reflect this
  10238. MemoryBuffer m;
  10239. serializeReal8(val, m);
  10240. p->setPropBin("Value", m.length(), m.toByteArray());
  10241. setResultRowCount(1);
  10242. setResultTotalRowCount(1);
  10243. }
  10244. void CLocalWUResult::setResultBool(bool val)
  10245. {
  10246. MemoryBuffer m;
  10247. serializeBool(val, m);
  10248. p->setPropBin("Value", m.length(), m.toByteArray());
  10249. setResultRowCount(1);
  10250. setResultTotalRowCount(1);
  10251. }
  10252. void CLocalWUResult::setResultString(const char *val, unsigned len)
  10253. {
  10254. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10255. MemoryBuffer m;
  10256. serializeLPString(len, val, m);
  10257. p->setPropBin("Value", m.length(), m.toByteArray());
  10258. setResultRowCount(1);
  10259. setResultTotalRowCount(1);
  10260. }
  10261. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  10262. {
  10263. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10264. MemoryBuffer m;
  10265. m.append(len).append(len*2, val);
  10266. p->setPropBin("Value", m.length(), m.toByteArray());
  10267. setResultRowCount(1);
  10268. setResultTotalRowCount(1);
  10269. }
  10270. void CLocalWUResult::setResultData(const void *val, unsigned len)
  10271. {
  10272. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  10273. MemoryBuffer m;
  10274. serializeLPString(len, (const char *)val, m);
  10275. p->setPropBin("Value", m.length(), m.toByteArray());
  10276. setResultRowCount(1);
  10277. setResultTotalRowCount(1);
  10278. }
  10279. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  10280. {
  10281. // Note: serialized as data but with length known from schema
  10282. MemoryBuffer m;
  10283. serializeFixedData(len, val, m);
  10284. p->setPropBin("Value", m.length(), m.toByteArray());
  10285. setResultRowCount(1);
  10286. setResultTotalRowCount(1);
  10287. }
  10288. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  10289. {
  10290. p->setPropBin("Value", len, data);
  10291. setResultRowCount(1);
  10292. setResultTotalRowCount(1);
  10293. setResultFormat(ResultFormatRaw);
  10294. }
  10295. void CLocalWUResult::setResultIsAll(bool value)
  10296. {
  10297. p->setPropBool("@isAll", value);
  10298. }
  10299. //==========================================================================================
  10300. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  10301. {
  10302. }
  10303. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  10304. {
  10305. str.set(p->queryProp("@dllname"));
  10306. return str;
  10307. }
  10308. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  10309. {
  10310. str.set(p->queryProp("@version"));
  10311. return str;
  10312. }
  10313. void CLocalWUPlugin::setPluginName(const char *str)
  10314. {
  10315. p->setProp("@dllname", str);
  10316. }
  10317. void CLocalWUPlugin::setPluginVersion(const char *str)
  10318. {
  10319. p->setProp("@version", str);
  10320. }
  10321. //==========================================================================================
  10322. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  10323. {
  10324. }
  10325. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10326. {
  10327. str.set(p->queryProp("@name"));
  10328. return str;
  10329. }
  10330. void CLocalWULibrary::setName(const char *str)
  10331. {
  10332. p->setProp("@name", str);
  10333. }
  10334. //==========================================================================================
  10335. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10336. {
  10337. }
  10338. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10339. {
  10340. str.set(p->queryProp("@source"));
  10341. return str;
  10342. }
  10343. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10344. {
  10345. str.set(p->queryProp(NULL));
  10346. return str;
  10347. }
  10348. unsigned CLocalWUException::getExceptionCode() const
  10349. {
  10350. return p->getPropInt("@code", 0);
  10351. }
  10352. ErrorSeverity CLocalWUException::getSeverity() const
  10353. {
  10354. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10355. }
  10356. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10357. {
  10358. dt.set(p->queryProp("@time"));
  10359. return dt;
  10360. }
  10361. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10362. {
  10363. str.set(p->queryProp("@filename"));
  10364. return str;
  10365. }
  10366. unsigned CLocalWUException::getExceptionLineNo() const
  10367. {
  10368. return p->getPropInt("@row", 0);
  10369. }
  10370. unsigned CLocalWUException::getExceptionColumn() const
  10371. {
  10372. return p->getPropInt("@col", 0);
  10373. }
  10374. unsigned CLocalWUException::getActivityId() const
  10375. {
  10376. const char * scope = queryScope();
  10377. if (scope)
  10378. {
  10379. const char * colon = strrchr(scope, ':');
  10380. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10381. return atoi(colon+1+strlen(ActivityScopePrefix));
  10382. }
  10383. return p->getPropInt("@activity", 0);
  10384. }
  10385. unsigned CLocalWUException::getSequence() const
  10386. {
  10387. return p->getPropInt("@sequence", 0);
  10388. }
  10389. const char * CLocalWUException::queryScope() const
  10390. {
  10391. return p->queryProp("@scope");
  10392. }
  10393. unsigned CLocalWUException::getPriority() const
  10394. {
  10395. return p->getPropInt("@prio", 0);
  10396. }
  10397. void CLocalWUException::setExceptionSource(const char *str)
  10398. {
  10399. p->setProp("@source", str);
  10400. }
  10401. void CLocalWUException::setExceptionMessage(const char *str)
  10402. {
  10403. p->setProp(NULL, str);
  10404. }
  10405. void CLocalWUException::setExceptionCode(unsigned code)
  10406. {
  10407. p->setPropInt("@code", code);
  10408. }
  10409. void CLocalWUException::setSeverity(ErrorSeverity level)
  10410. {
  10411. p->setPropInt("@severity", level);
  10412. }
  10413. void CLocalWUException::setTimeStamp(const char *str)
  10414. {
  10415. p->setProp("@time", str);
  10416. }
  10417. void CLocalWUException::setExceptionFileName(const char *str)
  10418. {
  10419. p->setProp("@filename", str);
  10420. }
  10421. void CLocalWUException::setExceptionLineNo(unsigned r)
  10422. {
  10423. p->setPropInt("@row", r);
  10424. }
  10425. void CLocalWUException::setExceptionColumn(unsigned c)
  10426. {
  10427. p->setPropInt("@col", c);
  10428. }
  10429. void CLocalWUException::setActivityId(unsigned _id)
  10430. {
  10431. p->setPropInt("@activity", _id);
  10432. }
  10433. void CLocalWUException::setScope(const char * _scope)
  10434. {
  10435. p->setProp("@scope", _scope);
  10436. }
  10437. void CLocalWUException::setPriority(unsigned _priority)
  10438. {
  10439. p->setPropInt("@prio", _priority);
  10440. }
  10441. //==========================================================================================
  10442. CLocalWUAppValue::CLocalWUAppValue(const IPropertyTree *_owner, const IPropertyTree *_props) : owner(_owner), props(_props)
  10443. {
  10444. }
  10445. const char * CLocalWUAppValue::queryApplication() const
  10446. {
  10447. return owner->queryName();
  10448. }
  10449. const char * CLocalWUAppValue::queryName() const
  10450. {
  10451. return props->queryName();
  10452. }
  10453. const char * CLocalWUAppValue::queryValue() const
  10454. {
  10455. return props->queryProp(nullptr);
  10456. }
  10457. //==========================================================================================
  10458. CLocalWUStatistic::CLocalWUStatistic(const IPropertyTree *props) : p(props)
  10459. {
  10460. }
  10461. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10462. {
  10463. const char * creator = p->queryProp("@creator");
  10464. str.set(creator);
  10465. return str;
  10466. }
  10467. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10468. {
  10469. const char * desc = p->queryProp("@desc");
  10470. if (desc)
  10471. {
  10472. str.set(desc); // legacy and in case it is overridden
  10473. }
  10474. else if (createDefault)
  10475. {
  10476. StatisticKind kind = getKind();
  10477. assertex(kind != StKindNone);
  10478. const char * scope = p->queryProp("@scope");
  10479. assertex(scope);
  10480. //Clean up the format of the scope when converting it to a description
  10481. StringBuffer descriptionText;
  10482. if (isGlobalScope(scope))
  10483. {
  10484. const char * creator = p->queryProp("@creator");
  10485. descriptionText.append(creator).append(":");
  10486. queryLongStatisticName(descriptionText, kind);
  10487. }
  10488. else
  10489. {
  10490. for (;;)
  10491. {
  10492. char c = *scope++;
  10493. if (!c)
  10494. break;
  10495. if (c == ':')
  10496. descriptionText.append(": ");
  10497. else
  10498. descriptionText.append(c);
  10499. }
  10500. if (kind != StTimeElapsed)
  10501. queryLongStatisticName(descriptionText.append(": "), kind);
  10502. }
  10503. str.set(descriptionText);
  10504. }
  10505. else
  10506. str.clear();
  10507. return str;
  10508. }
  10509. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10510. {
  10511. StringBuffer formatted;
  10512. formatStatistic(formatted, getValue(), getMeasure());
  10513. str.set(formatted);
  10514. return str;
  10515. }
  10516. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10517. {
  10518. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10519. }
  10520. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10521. {
  10522. return queryScopeType(p->queryProp("@s"), SSTnone);
  10523. }
  10524. StatisticKind CLocalWUStatistic::getKind() const
  10525. {
  10526. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10527. }
  10528. const char * CLocalWUStatistic::queryScope() const
  10529. {
  10530. const char * scope = p->queryProp("@scope");
  10531. if (!scope || streq(scope, LEGACY_GLOBAL_SCOPE))
  10532. scope = GLOBAL_SCOPE;
  10533. return scope;
  10534. }
  10535. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10536. {
  10537. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10538. }
  10539. unsigned __int64 CLocalWUStatistic::getValue() const
  10540. {
  10541. return p->getPropInt64("@value", 0);
  10542. }
  10543. unsigned __int64 CLocalWUStatistic::getCount() const
  10544. {
  10545. return p->getPropInt64("@count", 0);
  10546. }
  10547. unsigned __int64 CLocalWUStatistic::getMax() const
  10548. {
  10549. return p->getPropInt64("@max", 0);
  10550. }
  10551. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10552. {
  10553. return p->getPropInt64("@ts", 0);
  10554. }
  10555. //==========================================================================================
  10556. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10557. {
  10558. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10559. if (xml)
  10560. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10561. else
  10562. {
  10563. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10564. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10565. cw->loadPTree(p.getClear());
  10566. }
  10567. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10568. return ret;
  10569. }
  10570. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10571. {
  10572. const char *name = p->queryName();
  10573. if (!name)
  10574. name = "__unnamed__";
  10575. StringBuffer temp;
  10576. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10577. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10578. ForEach(*elems)
  10579. {
  10580. IPropertyTree &elem = elems->query();
  10581. if (streq(elem.queryName(), "Parameters"))
  10582. {
  10583. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10584. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10585. ForEach(*params)
  10586. {
  10587. IPropertyTree &param = params->query();
  10588. const char *paramname = param.queryName();
  10589. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10590. if (p->getPropBool(xpath))
  10591. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10592. else
  10593. {
  10594. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10595. }
  10596. }
  10597. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10598. }
  10599. else if (streq(elem.queryName(), "Variables"))
  10600. {
  10601. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10602. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10603. ForEach(*vars)
  10604. {
  10605. Owned<IPropertyTree> var = LINK(&vars->query());
  10606. if (var->getPropBool("Format/@password"))
  10607. {
  10608. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10609. var->removeProp("Value");
  10610. var->removeProp("xmlValue");
  10611. }
  10612. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10613. }
  10614. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10615. }
  10616. else
  10617. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10618. }
  10619. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10620. }
  10621. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10622. {
  10623. class CAdapter : public CInterface, implements IIOStream
  10624. {
  10625. StringBuffer &out;
  10626. public:
  10627. IMPLEMENT_IINTERFACE;
  10628. CAdapter(StringBuffer &_out) : out(_out) { }
  10629. virtual void flush() { }
  10630. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10631. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10632. } adapter(str);
  10633. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10634. return str;
  10635. }
  10636. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10637. {
  10638. OwnedIFile ifile = createIFile(filename);
  10639. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10640. Owned<IIOStream> stream = createIOStream(ifileio);
  10641. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10642. }
  10643. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10644. {
  10645. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10646. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10647. if (ewu)
  10648. {
  10649. Linked<IPropertyTree> p;
  10650. if (unpack||includeProgress)
  10651. p.setown(ewu->getUnpackedTree(includeProgress));
  10652. else
  10653. p.set(ewu->queryPTree());
  10654. if (hidePasswords)
  10655. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10656. else
  10657. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10658. }
  10659. else
  10660. return str.append("Unrecognized workunit format");
  10661. }
  10662. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10663. {
  10664. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10665. if (ewu)
  10666. {
  10667. Linked<IPropertyTree> p;
  10668. if (unpack||includeProgress)
  10669. p.setown(ewu->getUnpackedTree(includeProgress));
  10670. else if (regressionTest)
  10671. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10672. else
  10673. p.set(ewu->queryPTree());
  10674. if (hidePasswords)
  10675. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10676. if (regressionTest)
  10677. {
  10678. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10679. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10680. p->removeProp("@buildVersion");
  10681. p->removeProp("@eclVersion");
  10682. p->removeProp("@hash");
  10683. //Remove statistics, and extract them to a separate file
  10684. IPropertyTree * stats = p->queryPropTree("Statistics");
  10685. if (stats)
  10686. {
  10687. StringBuffer statsFilename;
  10688. statsFilename.append(filename).append(".stats");
  10689. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10690. p->removeProp("Statistics");
  10691. }
  10692. //Now remove timestamps from exceptions
  10693. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10694. ForEach(*elems)
  10695. {
  10696. IPropertyTree &elem = elems->query();
  10697. elem.removeProp("@time");
  10698. }
  10699. }
  10700. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10701. }
  10702. else
  10703. throw makeStringException(0, "Unrecognized workunit format");
  10704. }
  10705. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10706. {
  10707. MemoryBuffer buffer;
  10708. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10709. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10710. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10711. assertex(cw);
  10712. StringAttr clusterName(cw->queryClusterName());
  10713. cw.clear();
  10714. if (!clusterName.length())
  10715. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10716. StringBuffer serverQueue;
  10717. getClusterEclCCServerQueueName(serverQueue, clusterName);
  10718. assertex(serverQueue.length());
  10719. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10720. if (!queue.get())
  10721. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10722. IJobQueueItem *item = createJobQueueItem(wuid);
  10723. queue->enqueue(item);
  10724. }
  10725. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10726. {
  10727. StringBuffer xpath("/WorkUnitAborts/");
  10728. xpath.append(wuid);
  10729. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10730. acon->queryRoot()->setPropInt(NULL, 1);
  10731. }
  10732. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10733. {
  10734. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10735. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10736. }
  10737. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10738. {
  10739. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10740. return;
  10741. abortWorkUnit(wuid);
  10742. Owned<IConstWorkUnit> cw = globalFactory->openWorkUnit(wuid);
  10743. if(!cw)
  10744. return;
  10745. WorkunitUpdate wu(&cw->lock());
  10746. const char *abortBy = secuser.getName();
  10747. if (abortBy && *abortBy)
  10748. wu->setTracingValue("AbortBy", abortBy);
  10749. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10750. }
  10751. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10752. {
  10753. if (secmgr && secuser)
  10754. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10755. if (secuser)
  10756. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10757. submitWorkUnit(wuid, "", "");
  10758. }
  10759. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10760. {
  10761. if (secmgr && secuser)
  10762. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10763. abortWorkUnit(wuid);
  10764. }
  10765. bool CLocalWorkUnit::hasWorkflow() const
  10766. {
  10767. return p->hasProp("Workflow");
  10768. }
  10769. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10770. {
  10771. CriticalBlock block(crit);
  10772. if (p->hasProp("@eventScheduledCount"))
  10773. return p->getPropInt("@eventScheduledCount", 0);
  10774. else
  10775. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10776. }
  10777. void CLocalWorkUnit::incEventScheduledCount()
  10778. {
  10779. CriticalBlock block(crit);
  10780. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10781. }
  10782. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10783. {
  10784. CriticalBlock block(crit);
  10785. return p->queryPropTree("Workflow");
  10786. }
  10787. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10788. {
  10789. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10790. CriticalBlock block(crit);
  10791. if(!workflowIteratorCached)
  10792. {
  10793. assertex(!workflowIterator);
  10794. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10795. if(s)
  10796. workflowIterator.setown(createWorkflowItemIterator(s));
  10797. workflowIteratorCached = true;
  10798. }
  10799. return workflowIterator.getLink();
  10800. }
  10801. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10802. {
  10803. unsigned count = 0;
  10804. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10805. for(iter->first(); iter->isValid(); iter->next())
  10806. count++;
  10807. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10808. for(iter->first(); iter->isValid(); iter->next())
  10809. array->addClone(iter->query());
  10810. return array.getLink();
  10811. }
  10812. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10813. {
  10814. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10815. CriticalBlock block(crit);
  10816. workflowIterator.clear();
  10817. workflowIteratorCached = false;
  10818. IPropertyTree * s = p->queryPropTree("Workflow");
  10819. if(!s)
  10820. s = p->addPropTree("Workflow");
  10821. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10822. }
  10823. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10824. {
  10825. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10826. CriticalBlock block(crit);
  10827. if(!workflowIterator)
  10828. {
  10829. IPropertyTree * s = p->queryPropTree("Workflow");
  10830. if(!s)
  10831. s = p->addPropTree("Workflow");
  10832. workflowIterator.setown(createWorkflowItemIterator(s));
  10833. workflowIteratorCached = true;
  10834. }
  10835. return workflowIterator.getLink();
  10836. }
  10837. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10838. {
  10839. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10840. Owned<IWorkflowItem> item;
  10841. for(iter->first(); iter->isValid(); iter->next())
  10842. {
  10843. item.setown(iter->get());
  10844. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10845. }
  10846. workflowIterator.clear();
  10847. workflowIteratorCached = false;
  10848. }
  10849. void CLocalWorkUnit::resetWorkflow()
  10850. {
  10851. if (hasWorkflow())
  10852. {
  10853. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10854. Owned<IWorkflowItem> wf;
  10855. for(iter->first(); iter->isValid(); iter->next())
  10856. {
  10857. wf.setown(iter->get());
  10858. wf->reset();
  10859. }
  10860. workflowIterator.clear();
  10861. workflowIteratorCached = false;
  10862. }
  10863. }
  10864. void CLocalWorkUnit::schedule()
  10865. {
  10866. CriticalBlock block(crit);
  10867. if(queryEventScheduledCount() == 0) return;
  10868. switch(getState())
  10869. {
  10870. case WUStateCompleted:
  10871. setState(WUStateWait);
  10872. break;
  10873. case WUStateFailed:
  10874. case WUStateArchived:
  10875. case WUStateAborting:
  10876. case WUStateAborted:
  10877. case WUStateScheduled:
  10878. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  10879. }
  10880. StringBuffer rootPath;
  10881. rootPath.append("/Schedule/").append(queryClusterName());
  10882. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10883. Owned<IPropertyTree> root = conn->getRoot();
  10884. if(!root->hasChildren())
  10885. {
  10886. StringBuffer addPath;
  10887. addPath.append("/Schedulers/").append(queryClusterName());
  10888. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10889. }
  10890. char const * wuid = p->queryName();
  10891. StringBuffer xpath("*/*/");
  10892. ncnameEscape(wuid, xpath);
  10893. bool more;
  10894. do more = root->removeProp(xpath.str()); while(more);
  10895. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10896. Owned<IWorkflowEvent> event;
  10897. Owned<IPropertyTree> branch1, branch2;
  10898. for(iter->first(); iter->isValid(); iter->next())
  10899. {
  10900. event.setown(iter->query()->getScheduleEvent());
  10901. if(!event) continue;
  10902. ncnameEscape(event->queryName(), xpath.clear());
  10903. ensurePTree(root, xpath.str());
  10904. branch1.setown(root->getPropTree(xpath.str()));
  10905. ncnameEscape(event->queryText(), xpath.clear());
  10906. ensurePTree(branch1, xpath.str());
  10907. branch2.setown(branch1->getPropTree(xpath.str()));
  10908. ncnameEscape(wuid, xpath.clear());
  10909. ensurePTree(branch2, xpath.str());
  10910. }
  10911. }
  10912. void CLocalWorkUnit::deschedule()
  10913. {
  10914. if(queryEventScheduledCount() == 0) return;
  10915. if(getState() == WUStateWait)
  10916. setState(WUStateCompleted);
  10917. doDescheduleWorkkunit(p->queryName());
  10918. }
  10919. EnumMapping localFileUploadTypes[] = {
  10920. { UploadTypeFileSpray, "FileSpray" },
  10921. { UploadTypeWUResult, "WUResult" },
  10922. { UploadTypeWUResultCsv, "WUResultCsv" },
  10923. { UploadTypeWUResultXml, "WUResultXml" },
  10924. { UploadTypeSize, NULL }
  10925. };
  10926. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  10927. {
  10928. public:
  10929. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  10930. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10931. {
  10932. tree.setown(createPTree());
  10933. tree->setPropInt("@id", id);
  10934. setEnum(tree, "@type", type, localFileUploadTypes);
  10935. tree->setProp("@source", source);
  10936. tree->setProp("@destination", destination);
  10937. if (eventTag)
  10938. tree->setProp("@eventTag", eventTag);
  10939. }
  10940. IMPLEMENT_IINTERFACE;
  10941. IPropertyTree * getTree() { return tree.getLink(); }
  10942. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  10943. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  10944. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  10945. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  10946. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  10947. private:
  10948. Owned<IPropertyTree> tree;
  10949. };
  10950. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  10951. {
  10952. public:
  10953. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  10954. IMPLEMENT_IINTERFACE;
  10955. bool first() { return iter->first(); }
  10956. bool isValid() { return iter->isValid(); }
  10957. bool next() { return iter->next(); }
  10958. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  10959. private:
  10960. Owned<IPropertyTree> tree;
  10961. Owned<IPropertyTreeIterator> iter;
  10962. };
  10963. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  10964. {
  10965. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10966. CriticalBlock block(crit);
  10967. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  10968. if(s)
  10969. return new CLocalFileUploadIterator(s.getClear());
  10970. else
  10971. return NULL;
  10972. }
  10973. bool CLocalWorkUnit::requiresLocalFileUpload() const
  10974. {
  10975. SCMStringBuffer dest;
  10976. Owned<IConstWUResult> result;
  10977. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  10978. if(!iter)
  10979. return false;
  10980. for(iter->first(); iter->isValid(); iter->next())
  10981. {
  10982. Owned<IConstLocalFileUpload> upload(iter->get());
  10983. switch(upload->queryType())
  10984. {
  10985. case UploadTypeWUResult:
  10986. case UploadTypeWUResultCsv:
  10987. case UploadTypeWUResultXml:
  10988. upload->getDestination(dest);
  10989. result.setown(getResultByName(dest.str()));
  10990. if(!result)
  10991. return true;
  10992. break;
  10993. default:
  10994. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  10995. }
  10996. }
  10997. return false;
  10998. }
  10999. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  11000. {
  11001. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  11002. CriticalBlock block(crit);
  11003. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  11004. if(!s)
  11005. s = p->addPropTree("LocalFileUploads");
  11006. unsigned id = s->numChildren();
  11007. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  11008. s->addPropTree("LocalFileUpload", upload->getTree());
  11009. return id;
  11010. }
  11011. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  11012. {
  11013. CriticalBlock block(crit);
  11014. str.set(p->queryProp("Tracing/AbortBy"));
  11015. return str;
  11016. }
  11017. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  11018. {
  11019. CriticalBlock block(crit);
  11020. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  11021. }
  11022. #if 0
  11023. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  11024. {
  11025. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  11026. unsigned deps = 0;
  11027. Owned<IWorkflowDependencyIterator> diter;
  11028. switch(cwf->queryWfid())
  11029. {
  11030. case 1:
  11031. assertex(!cwf->isScheduled());
  11032. assertex(cwf->queryType() == WFTypeNormal);
  11033. assertex(cwf->queryState() == WFStateNull);
  11034. diter.setown(cwf->getDependencies());
  11035. for(diter->first(); diter->isValid(); diter->next())
  11036. deps++;
  11037. assertex(deps==0);
  11038. okay[0] = true;
  11039. break;
  11040. case 2:
  11041. assertex(!cwf->isScheduled());
  11042. assertex(cwf->queryType() == WFTypeRecovery);
  11043. assertex(cwf->queryState() == WFStateSkip);
  11044. okay[1] = true;
  11045. break;
  11046. case 3:
  11047. assertex(cwf->queryContingencyFor() == 4);
  11048. okay[2] = true;
  11049. break;
  11050. case 4:
  11051. assertex(cwf->isScheduled());
  11052. assertex(cwf->queryType() == WFTypeNormal);
  11053. assertex(cwf->queryState() == WFStateReqd);
  11054. assertex(cwf->querySuccess() == 0);
  11055. assertex(cwf->queryFailure() == 3);
  11056. assertex(cwf->queryRecovery() == 2);
  11057. assertex(cwf->queryRetriesAllowed() == 10);
  11058. assertex(cwf->queryRetriesRemaining() == 10);
  11059. diter.setown(cwf->getDependencies());
  11060. for(diter->first(); diter->isValid(); diter->next())
  11061. {
  11062. dep[diter->query()-1] = true;
  11063. deps++;
  11064. }
  11065. assertex(deps==2);
  11066. assertex(dep[0]);
  11067. assertex(dep[1]);
  11068. okay[3] = true;
  11069. break;
  11070. case 5:
  11071. assertex(cwf->isScheduled());
  11072. assertex(!cwf->isScheduledNow());
  11073. assertex(cwf->querySchedulePriority() == 75);
  11074. assertex(cwf->queryScheduleCount() == 5);
  11075. assertex(cwf->queryScheduleCountRemaining() == 5);
  11076. okay[4] = true;
  11077. break;
  11078. case 6:
  11079. assertex(cwf->isScheduled());
  11080. assertex(!cwf->isScheduledNow());
  11081. assertex(cwf->querySchedulePriority() == 25);
  11082. assertex(!cwf->hasScheduleCount());
  11083. okay[5] = true;
  11084. break;
  11085. default:
  11086. assertex(!"unknown wfid in test");
  11087. }
  11088. }
  11089. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  11090. {
  11091. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  11092. switch(rwf->queryWfid())
  11093. {
  11094. case 1:
  11095. case 2:
  11096. case 3:
  11097. okay[rwf->queryWfid()-1] = true;
  11098. break;
  11099. case 4:
  11100. {
  11101. unsigned tries = 0;
  11102. while(rwf->testAndDecRetries())
  11103. tries++;
  11104. assertex(tries == 10);
  11105. assertex(rwf->queryRetriesRemaining() == 0);
  11106. rwf->setState(WFStateFail);
  11107. assertex(rwf->queryState() == WFStateFail);
  11108. rwf->reset();
  11109. assertex(rwf->queryRetriesRemaining() == 10);
  11110. assertex(rwf->queryState() == WFStateReqd);
  11111. }
  11112. okay[3] = true;
  11113. break;
  11114. case 5:
  11115. {
  11116. assertex(rwf->queryScheduleCountRemaining() == 5);
  11117. unsigned count = 0;
  11118. do count++; while(rwf->decAndTestScheduleCountRemaining());
  11119. assertex(count == 5);
  11120. assertex(rwf->queryScheduleCountRemaining() == 0);
  11121. rwf->reset();
  11122. assertex(rwf->queryScheduleCountRemaining() == 5);
  11123. }
  11124. okay[4] = true;
  11125. break;
  11126. case 6:
  11127. {
  11128. assertex(!rwf->hasScheduleCount());
  11129. unsigned count;
  11130. for(count=0; count<20; count++)
  11131. assertex(rwf->decAndTestScheduleCountRemaining());
  11132. }
  11133. okay[5] = true;
  11134. break;
  11135. default:
  11136. assertex(!"unknown wfid in test");
  11137. }
  11138. }
  11139. void testWorkflow()
  11140. {
  11141. DBGLOG("workunit.cpp : testWorkflow");
  11142. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  11143. Owned<IWorkflowItem> wf;
  11144. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  11145. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  11146. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  11147. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  11148. wf->setScheduledNow();
  11149. wf->addDependency(1);
  11150. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  11151. wf->setScheduledOn("test", "foo*");
  11152. wf->setSchedulePriority(75);
  11153. wf->setScheduleCount(5);
  11154. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  11155. wf->setScheduledOn("test", "bar*");
  11156. wf->setSchedulePriority(25);
  11157. unsigned const n = 6;
  11158. bool okay[n];
  11159. bool dep[n];
  11160. unsigned i;
  11161. for(i=0; i<n; i++)
  11162. okay[i] = dep[i] = 0;
  11163. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  11164. for(citer->first(); citer->isValid(); citer->next())
  11165. testConstWorkflow(citer->query(), okay, dep);
  11166. for(i=0; i<n; i++)
  11167. {
  11168. assertex(okay[i]);
  11169. okay[i] = false;
  11170. }
  11171. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  11172. for(miter->first(); miter->isValid(); miter->next())
  11173. {
  11174. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  11175. testRuntimeWorkflow(rwf, okay);
  11176. }
  11177. for(i=0; i<n; i++)
  11178. {
  11179. assertex(okay[i]);
  11180. okay[i] = dep[i] = false;
  11181. }
  11182. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  11183. unsigned wfid;
  11184. for(wfid = 1; array->isValid(wfid); wfid++)
  11185. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  11186. for(i=0; i<n; i++)
  11187. {
  11188. assertex(okay[i]);
  11189. okay[i] = false;
  11190. }
  11191. for(wfid = 1; array->isValid(wfid); wfid++)
  11192. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  11193. for(i=0; i<n; i++)
  11194. {
  11195. assertex(okay[i]);
  11196. okay[i] = false;
  11197. }
  11198. }
  11199. #endif
  11200. //------------------------------------------------------------------------------------------
  11201. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, std::list<WUState> expectedStates)
  11202. {
  11203. return globalFactory->waitForWorkUnit(wuid, (unsigned) timeout, false, expectedStates);
  11204. }
  11205. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, std::list<WUState> expectedStates)
  11206. {
  11207. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  11208. return waitForWorkUnitToComplete(wuid, timeout, expectedStates);
  11209. return WUStateUnknown;
  11210. }
  11211. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  11212. {
  11213. switch(globalFactory->waitForWorkUnit(wuid, (unsigned) timeout, true, { WUStateWait }))
  11214. {
  11215. case WUStateCompiled:
  11216. case WUStateCompleted:
  11217. case WUStateWait:
  11218. case WUStateUploadingFiles:
  11219. return true;
  11220. default:
  11221. return false;
  11222. }
  11223. }
  11224. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  11225. {
  11226. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  11227. return waitForWorkUnitToCompile(wuid, timeout);
  11228. return false;
  11229. }
  11230. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  11231. {
  11232. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  11233. {
  11234. Owned<IConstWorkUnit> wu = globalFactory->openWorkUnit(wuid, &secmgr, &secuser);
  11235. SCMStringBuffer ip;
  11236. unsigned port = 0;
  11237. try
  11238. {
  11239. port = wu->getDebugAgentListenerPort();
  11240. wu->getDebugAgentListenerIP(ip);
  11241. SocketEndpoint debugEP(ip.str(), port);
  11242. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  11243. unsigned len = (size32_t)strlen(command);
  11244. unsigned revlen = len;
  11245. _WINREV(revlen);
  11246. socket->write(&revlen, sizeof(revlen));
  11247. socket->write(command, len);
  11248. for (;;)
  11249. {
  11250. socket->read(&len, sizeof(len));
  11251. _WINREV(len);
  11252. if (len == 0)
  11253. break;
  11254. if (len & 0x80000000)
  11255. {
  11256. throwUnexpected();
  11257. }
  11258. char * mem = (char*) response.reserve(len);
  11259. socket->read(mem, len);
  11260. }
  11261. return true;
  11262. }
  11263. catch (IException *E)
  11264. {
  11265. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  11266. EXCLOG(E, msg.str());
  11267. throw;
  11268. }
  11269. }
  11270. return false;
  11271. }
  11272. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  11273. {
  11274. TypeInfoArray types;
  11275. StringAttrArray names;
  11276. r->getSchema(types, names, NULL);
  11277. if (types.ordinality()==1)
  11278. type.set(&types.item(0));
  11279. }
  11280. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  11281. {
  11282. if (!r->isResultScalar())
  11283. return false;
  11284. if (!curVal.hasChildren())
  11285. return true;
  11286. getSimpleResultType(r, type);
  11287. return type && type->isScalar();
  11288. }
  11289. void updateSuppliedXmlParams(IWorkUnit * w)
  11290. {
  11291. Owned<const IPropertyTree> params = w->getXmlParams();
  11292. if (!params)
  11293. return;
  11294. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  11295. ForEach(*elems)
  11296. {
  11297. IPropertyTree & curVal = elems->query();
  11298. const char *name = curVal.queryName();
  11299. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  11300. if (r)
  11301. {
  11302. Owned<ITypeInfo> type;
  11303. StringBuffer s;
  11304. if (isSuppliedParamScalar(r, curVal, type))
  11305. {
  11306. curVal.getProp(".", s);
  11307. r->setResultXML(s);
  11308. r->setResultStatus(ResultStatusSupplied);
  11309. }
  11310. else
  11311. {
  11312. toXML(&curVal, s);
  11313. if (!type)
  11314. getSimpleResultType(r, type);
  11315. bool isSet = (type && type->getTypeCode()==type_set);
  11316. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  11317. }
  11318. }
  11319. else
  11320. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11321. }
  11322. }
  11323. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11324. {
  11325. switch ((int)sequence)
  11326. {
  11327. case ResultSequenceStored:
  11328. return w->updateVariableByName(name);
  11329. case ResultSequencePersist:
  11330. return w->updateGlobalByName(name);
  11331. case ResultSequenceInternal:
  11332. case ResultSequenceOnce:
  11333. return w->updateTemporaryByName(name);
  11334. default:
  11335. return w->updateResultBySequence(sequence);
  11336. }
  11337. }
  11338. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11339. {
  11340. switch ((int)sequence)
  11341. {
  11342. case ResultSequenceStored:
  11343. return w->getVariableByName(name);
  11344. case ResultSequencePersist:
  11345. return w->getGlobalByName(name);
  11346. case ResultSequenceInternal:
  11347. case ResultSequenceOnce:
  11348. return w->getTemporaryByName(name);
  11349. default:
  11350. if (name && name[0])
  11351. return w->getResultByName(name);//name takes precedence over sequence
  11352. else
  11353. return w->getResultBySequence(sequence);
  11354. }
  11355. }
  11356. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11357. {
  11358. if (wuid) {
  11359. char prefchar;
  11360. unsigned year,month,day,hour,min,sec;
  11361. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11362. time.set(year, month, day, hour, min, sec, 0, true);
  11363. // time.setDate(year, month, day);
  11364. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11365. return true;
  11366. }
  11367. }
  11368. return false;
  11369. }
  11370. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11371. {
  11372. return (WUState) getEnum(state, states);
  11373. }
  11374. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11375. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11376. {
  11377. public:
  11378. CWorkflowScheduleConnection(char const * wuid)
  11379. {
  11380. basexpath.append("/WorkflowSchedule/").append(wuid);
  11381. flagxpath.append(basexpath.str()).append("/Active");
  11382. }
  11383. IMPLEMENT_IINTERFACE;
  11384. virtual void lock()
  11385. {
  11386. LOG(MCschedconn, "Locking base schedule connection");
  11387. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11388. if(!baseconn)
  11389. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11390. }
  11391. virtual void unlock()
  11392. {
  11393. LOG(MCschedconn, "Unlocking base schedule connection");
  11394. baseconn.clear();
  11395. }
  11396. virtual void setActive()
  11397. {
  11398. LOG(MCschedconn, "Setting active flag in schedule connection");
  11399. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11400. if(!flagconn)
  11401. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11402. }
  11403. virtual void resetActive()
  11404. {
  11405. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11406. flagconn.clear();
  11407. }
  11408. virtual bool queryActive()
  11409. {
  11410. return baseconn->queryRoot()->hasProp("Active");
  11411. }
  11412. virtual bool pull(IWorkflowItemArray * workflow)
  11413. {
  11414. assertex(baseconn);
  11415. Owned<IPropertyTree> root = baseconn->getRoot();
  11416. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11417. if(!eventQueue) return false;
  11418. if(!eventQueue->hasProp("Item")) return false;
  11419. {
  11420. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11421. Owned<IPropertyTree> eventItem;
  11422. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11423. Owned<IRuntimeWorkflowItem> wfItem;
  11424. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11425. {
  11426. eventItem.setown(&eventItems->get());
  11427. const char * eventName = eventItem->queryProp("@name");
  11428. const char * eventText = eventItem->queryProp("@text");
  11429. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11430. {
  11431. wfItem.setown(wfItems->get());
  11432. if(wfItem->queryState() != WFStateWait)
  11433. continue;
  11434. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11435. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11436. continue;
  11437. wfItem->setEvent(eventName, eventText);
  11438. wfItem->setState(WFStateReqd);
  11439. resetDependentsState(workflow, *wfItem);
  11440. }
  11441. }
  11442. }
  11443. bool more;
  11444. do
  11445. more = eventQueue->removeProp("Item");
  11446. while(more);
  11447. return true;
  11448. }
  11449. virtual void push(char const * name, char const * text)
  11450. {
  11451. assertex(baseconn);
  11452. Owned<IPropertyTree> root = baseconn->getRoot();
  11453. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11454. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11455. eventItem->setProp("@name", name);
  11456. eventItem->setProp("@text", text);
  11457. }
  11458. virtual void remove()
  11459. {
  11460. if (baseconn)
  11461. {
  11462. baseconn->close(true);
  11463. baseconn.clear();
  11464. }
  11465. }
  11466. private:
  11467. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11468. {
  11469. if (wfid)
  11470. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11471. }
  11472. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11473. {
  11474. switch(item.queryState())
  11475. {
  11476. case WFStateDone:
  11477. case WFStateFail:
  11478. {
  11479. item.setState(WFStateNull);
  11480. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11481. resetDependentsState(workflow, item);
  11482. break;
  11483. }
  11484. }
  11485. }
  11486. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11487. {
  11488. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11489. for(iter->first(); iter->isValid(); iter->next())
  11490. {
  11491. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11492. resetItemStateAndDependents(workflow, dep);
  11493. }
  11494. }
  11495. private:
  11496. StringBuffer basexpath;
  11497. StringBuffer flagxpath;
  11498. Owned<IRemoteConnection> baseconn;
  11499. Owned<IRemoteConnection> flagconn;
  11500. };
  11501. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11502. {
  11503. return new CWorkflowScheduleConnection(wuid);
  11504. }
  11505. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11506. {
  11507. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11508. }
  11509. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11510. {
  11511. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11512. }
  11513. extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, ErrorSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, unsigned activity)
  11514. {
  11515. Owned<IWUException> we = wu->createException();
  11516. we->setSeverity(severity);
  11517. we->setExceptionMessage(text);
  11518. if (source)
  11519. we->setExceptionSource(source);
  11520. if (code)
  11521. we->setExceptionCode(code);
  11522. if (filename)
  11523. we->setExceptionFileName(filename);
  11524. if (lineno)
  11525. {
  11526. we->setExceptionLineNo(lineno);
  11527. if (column)
  11528. we->setExceptionColumn(lineno);
  11529. }
  11530. if (activity)
  11531. we->setActivityId(activity);
  11532. }
  11533. const char * skipLeadingXml(const char * text)
  11534. {
  11535. if (!text)
  11536. return NULL;
  11537. //skip utf8 BOM, probably excessive
  11538. if (memcmp(text, UTF8_BOM, 3) == 0)
  11539. text += 3;
  11540. for (;;)
  11541. {
  11542. if (isspace(*text))
  11543. text++;
  11544. else if (text[0] == '<' && text[1] == '?')
  11545. {
  11546. text += 2;
  11547. for (;;)
  11548. {
  11549. if (!*text) break;
  11550. if (text[0] == '?' && text[1] == '>')
  11551. {
  11552. text += 2;
  11553. break;
  11554. }
  11555. text++;
  11556. }
  11557. }
  11558. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11559. {
  11560. text += 4;
  11561. for (;;)
  11562. {
  11563. if (!*text) break;
  11564. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11565. {
  11566. text += 3;
  11567. break;
  11568. }
  11569. text++;
  11570. }
  11571. }
  11572. else
  11573. break;
  11574. }
  11575. return text;
  11576. }
  11577. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11578. {
  11579. text = skipLeadingXml(text);
  11580. if (!text)
  11581. return false;
  11582. const char * archivePrefix = "<Archive";
  11583. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11584. }
  11585. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11586. {
  11587. text = skipLeadingXml(text);
  11588. if (!text)
  11589. return false;
  11590. const char * manifestPrefix = "<Manifest";
  11591. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11592. }
  11593. //------------------------------------------------------------------------------
  11594. // Named Alias helper function
  11595. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11596. {
  11597. StringBuffer xpath;
  11598. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11599. return queryRegistry->getPropTree(xpath);
  11600. }
  11601. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11602. {
  11603. StringBuffer xpath;
  11604. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11605. return queryRegistry->getPropTree(xpath);
  11606. }
  11607. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11608. {
  11609. StringBuffer lcId(id);
  11610. lcId.toLowerCase();
  11611. StringBuffer xpath;
  11612. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11613. while (queryRegistry->removeProp(xpath));
  11614. }
  11615. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11616. {
  11617. StringBuffer lcName(name);
  11618. lcName.toLowerCase();
  11619. StringBuffer xpath;
  11620. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11621. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11622. unsigned seq = 1;
  11623. ForEach(*iter)
  11624. {
  11625. IPropertyTree &item = iter->query();
  11626. const char *thisWuid = item.queryProp("@wuid");
  11627. if (strieq(wuid, thisWuid))
  11628. return &item;
  11629. unsigned thisSeq = item.getPropInt("@seq");
  11630. if (thisSeq >= seq)
  11631. seq = thisSeq + 1;
  11632. }
  11633. StringBuffer id;
  11634. id.append(lcName).append(".").append(seq);
  11635. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11636. newEntry->setProp("@name", lcName);
  11637. newEntry->setProp("@wuid", wuid);
  11638. newEntry->setProp("@dll", dll);
  11639. newEntry->setProp("@id", id);
  11640. newEntry->setPropInt("@seq", seq);
  11641. if (library)
  11642. newEntry->setPropBool("@isLibrary", true);
  11643. if (userid && *userid)
  11644. newEntry->setProp("@publishedBy", userid);
  11645. if (snapshot && *snapshot)
  11646. newEntry->setProp("@snapshot", snapshot);
  11647. return queryRegistry->addPropTree("Query", newEntry);
  11648. }
  11649. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11650. {
  11651. StringBuffer lcId(id);
  11652. lcId.toLowerCase();
  11653. clearAliases(queryRegistry, lcId);
  11654. StringBuffer xpath;
  11655. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11656. queryRegistry->removeProp(xpath);
  11657. }
  11658. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11659. {
  11660. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11661. if (!match)
  11662. return;
  11663. clearAliases(queryRegistry, match->queryProp("@id"));
  11664. queryRegistry->removeTree(match);
  11665. }
  11666. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11667. {
  11668. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11669. if (!match)
  11670. return;
  11671. clearAliases(queryRegistry, match->queryProp("@id"));
  11672. queryRegistry->removeTree(match);
  11673. }
  11674. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11675. {
  11676. clearAliases(queryRegistry, id);
  11677. }
  11678. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11679. {
  11680. StringBuffer lcName(name);
  11681. lcName.toLowerCase();
  11682. StringBuffer xpath;
  11683. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11684. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11685. if (!match)
  11686. {
  11687. match = queryRegistry->addPropTree("Alias");
  11688. match->setProp("@name", lcName);
  11689. }
  11690. match->setProp("@id", value);
  11691. }
  11692. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11693. {
  11694. if (!queryRegistry || !queryid)
  11695. return NULL;
  11696. StringBuffer xpath;
  11697. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11698. return queryRegistry->getPropTree(xpath);
  11699. }
  11700. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11701. {
  11702. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11703. return getQueryById(queryRegistry, queryid);
  11704. }
  11705. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11706. {
  11707. if (!queryRegistry || !alias)
  11708. return NULL;
  11709. StringBuffer xpath;
  11710. unsigned cnt = 0;
  11711. StringBuffer lc(alias);
  11712. const char * search = lc.toLowerCase().str();
  11713. for (;;)
  11714. {
  11715. xpath.set("Alias[@name='").append(search).append("']/@id");
  11716. const char * queryId = queryRegistry->queryProp(xpath);
  11717. if (!queryId)
  11718. break;
  11719. //Check for too many alias indirections.
  11720. if (cnt++ > 10)
  11721. return NULL;
  11722. search = lc.set(queryId).toLowerCase().str();
  11723. }
  11724. return getQueryById(queryRegistry, search);
  11725. }
  11726. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11727. {
  11728. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11729. return resolveQueryAlias(queryRegistry, alias);
  11730. }
  11731. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11732. {
  11733. StringBuffer lcId(id);
  11734. lcId.toLowerCase();
  11735. StringBuffer xpath;
  11736. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11737. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11738. if (tree)
  11739. {
  11740. if (tree->getPropBool("@suspended", false) == suspend)
  11741. return;
  11742. if (suspend)
  11743. {
  11744. tree->addPropBool("@suspended", true);
  11745. if (userid && *userid)
  11746. tree->addProp("@suspendedBy", userid);
  11747. }
  11748. else
  11749. {
  11750. tree->removeProp("@suspended");
  11751. tree->removeProp("@suspendedBy");
  11752. }
  11753. }
  11754. else
  11755. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11756. }
  11757. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11758. {
  11759. if (queryComment)
  11760. {
  11761. StringBuffer lcId(id);
  11762. lcId.toLowerCase();
  11763. StringBuffer xpath;
  11764. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11765. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11766. if (tree)
  11767. tree->setProp("@queryComment", queryComment);
  11768. else
  11769. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11770. }
  11771. }
  11772. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11773. {
  11774. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11775. if (conn)
  11776. return conn->getRoot();
  11777. else
  11778. return NULL;
  11779. }
  11780. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11781. {
  11782. if (!queryTree || !libraries)
  11783. return;
  11784. if (queryTree->hasProp("@libCount")) //already added
  11785. return;
  11786. unsigned libCount=0;
  11787. ForEach(*libraries)
  11788. {
  11789. IConstWULibrary &library = libraries->query();
  11790. SCMStringBuffer libname;
  11791. if (!library.getName(libname).length())
  11792. continue;
  11793. queryTree->addProp("Library", libname.str());
  11794. libCount++;
  11795. }
  11796. queryTree->setPropInt("@libCount", libCount);
  11797. }
  11798. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11799. {
  11800. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11801. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11802. }
  11803. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11804. {
  11805. //Only lock the branch for the target we're interested in.
  11806. StringBuffer xpath;
  11807. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11808. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11809. if (conn)
  11810. return conn->getRoot();
  11811. if (readonly)
  11812. return NULL;
  11813. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11814. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11815. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11816. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11817. if (conn)
  11818. return conn->getRoot();
  11819. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11820. if (!conn)
  11821. throwUnexpected();
  11822. IPropertyTree * root = conn->queryRoot();
  11823. root->setProp("@id",wsEclId);
  11824. conn->commit();
  11825. return LINK(root);
  11826. }
  11827. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11828. {
  11829. StringBuffer xpath;
  11830. StringBuffer lcName(name);
  11831. lcName.toLowerCase();
  11832. // see if "name" already exists
  11833. xpath.append("Package[@id='").append(name).append("']");
  11834. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11835. if (pkgTree)
  11836. {
  11837. if (overWrite)
  11838. packageRegistry->removeTree(pkgTree);
  11839. else
  11840. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11841. }
  11842. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11843. tree->setProp("@id", lcName);
  11844. return tree;
  11845. }
  11846. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11847. {
  11848. StringBuffer lcId(id);
  11849. lcId.toLowerCase();
  11850. StringBuffer xpath;
  11851. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  11852. packageRegistry->removeProp(xpath);
  11853. }
  11854. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  11855. {
  11856. //Only lock the branch for the target we're interested in.
  11857. StringBuffer xpath;
  11858. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  11859. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11860. if (conn)
  11861. return conn->getRoot();
  11862. if (readonly)
  11863. return NULL;
  11864. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  11865. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11866. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  11867. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11868. if (conn)
  11869. return conn->getRoot();
  11870. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11871. if (!conn)
  11872. throwUnexpected();
  11873. IPropertyTree* root = conn->queryRoot();
  11874. root->setProp("@id",wsEclId);
  11875. conn->commit();
  11876. return LINK(root);
  11877. }
  11878. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11879. {
  11880. StringBuffer cleanQueryName;
  11881. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11882. SCMStringBuffer dllName;
  11883. Owned<IConstWUQuery> q = workunit->getQuery();
  11884. q->getQueryDllName(dllName);
  11885. if (!dllName.length())
  11886. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  11887. StringBuffer currentTargetClusterType;
  11888. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  11889. SCMStringBuffer targetClusterType;
  11890. workunit->getDebugValue("targetclustertype", targetClusterType);
  11891. SCMStringBuffer snapshot;
  11892. workunit->getSnapshot(snapshot);
  11893. if (currentTargetClusterType.length() < 1)
  11894. {
  11895. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  11896. }
  11897. else
  11898. {
  11899. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  11900. {
  11901. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  11902. }
  11903. }
  11904. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  11905. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  11906. checkAddLibrariesToQueryEntry(newEntry, libraries);
  11907. newQueryId.append(newEntry->queryProp("@id"));
  11908. workunit->setIsQueryService(true); //will check querysets before delete
  11909. workunit->commit();
  11910. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  11911. }
  11912. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  11913. {
  11914. StringBuffer cleanQueryName;
  11915. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11916. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  11917. {
  11918. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  11919. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11920. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  11921. {
  11922. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  11923. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  11924. else
  11925. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  11926. }
  11927. }
  11928. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  11929. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11930. }
  11931. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11932. {
  11933. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11934. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  11935. }
  11936. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  11937. {
  11938. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11939. StringBuffer xpath;
  11940. xpath.appendf("Alias[@name='%s']", alias);
  11941. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  11942. return queryRegistry->removeTree(t);
  11943. }
  11944. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  11945. {
  11946. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11947. setQueryAlias(queryRegistry, alias, id);
  11948. }
  11949. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  11950. {
  11951. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11952. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  11953. }
  11954. void deleteQuerySetQuery(const char *querySetName, const char *id)
  11955. {
  11956. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11957. removeNamedQuery(queryRegistry, id);
  11958. }
  11959. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  11960. {
  11961. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11962. clearAliases(queryRegistry, id);
  11963. }
  11964. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  11965. {
  11966. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11967. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  11968. }
  11969. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  11970. {
  11971. if (!queryRegistry)
  11972. return NULL;
  11973. StringBuffer xpath;
  11974. xpath.appendf("Query[@wuid='%s']", wuid);
  11975. if (queryName && *queryName)
  11976. xpath.appendf("[@name='%s']", queryName);
  11977. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  11978. if (q)
  11979. {
  11980. id.set(q->queryProp("@id"));
  11981. }
  11982. return id.str();
  11983. }
  11984. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  11985. {
  11986. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11987. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  11988. }
  11989. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  11990. {
  11991. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  11992. ForEach(*wulibraries)
  11993. {
  11994. SCMStringBuffer libname;
  11995. IConstWULibrary &wulibrary = wulibraries->query();
  11996. wulibrary.getName(libname);
  11997. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  11998. continue;
  11999. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  12000. if (query && query->getPropBool("@isLibrary"))
  12001. {
  12002. const char *wuid = query->queryProp("@wuid");
  12003. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  12004. if (libcw)
  12005. {
  12006. names.appendUniq(libname.str());
  12007. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  12008. continue;
  12009. }
  12010. }
  12011. unresolved.appendUniq(libname.str());
  12012. }
  12013. }
  12014. bool looksLikeAWuid(const char * wuid, const char firstChar)
  12015. {
  12016. if (!wuid)
  12017. return false;
  12018. if (wuid[0] != firstChar)
  12019. return false;
  12020. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  12021. return false;
  12022. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  12023. return false;
  12024. return (wuid[9]=='-');
  12025. }
  12026. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  12027. {
  12028. IPropertyTree * module = archive;
  12029. const char * dot = strrchr(path, '.');
  12030. StringBuffer xpath;
  12031. if (dot)
  12032. {
  12033. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  12034. module = archive->queryPropTree(xpath);
  12035. path = dot+1;
  12036. }
  12037. else
  12038. module = archive->queryPropTree("Module[@key='']");
  12039. if (!module)
  12040. return NULL;
  12041. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  12042. return module->queryPropTree(xpath);
  12043. }
  12044. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  12045. {
  12046. StringBuffer fullPathName;
  12047. makeAbsolutePath(name, fullPathName);
  12048. if (isContainerized())
  12049. {
  12050. const char *dllserver_root = getenv("HPCC_DLLSERVER_PATH");
  12051. assertex(dllserver_root != nullptr);
  12052. StringBuffer destPathName(dllserver_root);
  12053. addNonEmptyPathSepChar(destPathName);
  12054. splitFilename(fullPathName.str(), nullptr, nullptr, &destPathName, &destPathName);
  12055. OwnedIFile source = createIFile(fullPathName);
  12056. OwnedIFile target = createIFile(destPathName);
  12057. if (!target->exists())
  12058. {
  12059. source->copyTo(target, 0, NULL, true);
  12060. }
  12061. query->addAssociatedFile(type, destPathName, "localhost", description, crc, minActivity, maxActivity);
  12062. // Should we delete the local files? No - they may not be finished with
  12063. }
  12064. else
  12065. {
  12066. StringBuffer hostname;
  12067. queryHostIP().getIpText(hostname);
  12068. query->addAssociatedFile(type, fullPathName, hostname, description, crc, minActivity, maxActivity);
  12069. }
  12070. }
  12071. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  12072. {
  12073. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12074. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  12075. if(workunit)
  12076. workunit->deschedule();
  12077. else
  12078. doDescheduleWorkkunit(wuid);
  12079. }
  12080. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  12081. {
  12082. StringBuffer scopestr;
  12083. if (wfid && scope && *scope)
  12084. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12085. else
  12086. scopestr.set(scope);
  12087. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  12088. }
  12089. class WuTimingUpdater : implements ITimeReportInfo
  12090. {
  12091. public:
  12092. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  12093. : wu(_wu), scopeType(_scopeType), kind(_kind)
  12094. { }
  12095. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  12096. {
  12097. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  12098. }
  12099. protected:
  12100. IWorkUnit * wu;
  12101. StatisticScopeType scopeType;
  12102. StatisticKind kind;
  12103. };
  12104. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  12105. {
  12106. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  12107. timer->report(target);
  12108. }
  12109. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  12110. {
  12111. WuTimingUpdater target(wu, scopeType, kind);
  12112. timer->report(target);
  12113. }
  12114. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  12115. {
  12116. StringBuffer scopestr;
  12117. if (wfid && scope && *scope)
  12118. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12119. else
  12120. scopestr.set(scope);
  12121. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  12122. }
  12123. static double getCpuSize(const char *resourceName)
  12124. {
  12125. Owned<IPropertyTree> compConfig = getComponentConfig();
  12126. const char * cpuRequestedStr = compConfig->queryProp(resourceName);
  12127. if (!cpuRequestedStr)
  12128. return 0.0;
  12129. char * endptr;
  12130. double cpuRequested = strtod(cpuRequestedStr, &endptr);
  12131. if (cpuRequested < 0.0)
  12132. return 0.0;
  12133. if (*endptr == 'm')
  12134. cpuRequested /= 1000;
  12135. return cpuRequested;
  12136. }
  12137. static double getCostCpuHour()
  12138. {
  12139. double costCpuHour = getGlobalConfigSP()->getPropReal("cost/@perCpu");
  12140. if (costCpuHour < 0.0)
  12141. return 0.0;
  12142. return costCpuHour;
  12143. }
  12144. extern WORKUNIT_API double getMachineCostRate()
  12145. {
  12146. return getCostCpuHour() * getCpuSize("resources/@cpu") ;
  12147. };
  12148. extern WORKUNIT_API double getThorManagerRate()
  12149. {
  12150. return getCostCpuHour() * getCpuSize("managerResources/@cpu");
  12151. }
  12152. extern WORKUNIT_API double getThorWorkerRate()
  12153. {
  12154. return getCostCpuHour() * getCpuSize("workerResources/@cpu");
  12155. }
  12156. extern WORKUNIT_API double calculateThorCost(unsigned __int64 ms, unsigned clusterWidth)
  12157. {
  12158. return calcCost(getThorManagerRate(), ms) + calcCost(getThorWorkerRate(), ms) * clusterWidth;
  12159. }
  12160. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  12161. {
  12162. SimpleReferenceAggregator aggregator(search, result);
  12163. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  12164. ForEach(*it)
  12165. it->playProperties(aggregator);
  12166. }
  12167. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  12168. {
  12169. public:
  12170. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  12171. virtual void beginScope(const StatsScopeId & id)
  12172. {
  12173. prevLenStack.append(scope.length());
  12174. if (scope.length())
  12175. scope.append(":");
  12176. id.getScopeText(scope);
  12177. scopeTypeStack.append(id.queryScopeType());
  12178. }
  12179. virtual void beginSubGraphScope(unsigned id)
  12180. {
  12181. StatsScopeId scopeId(SSTsubgraph, id);
  12182. beginScope(scopeId);
  12183. }
  12184. virtual void beginActivityScope(unsigned id)
  12185. {
  12186. StatsScopeId scopeId(SSTactivity, id);
  12187. beginScope(scopeId);
  12188. }
  12189. virtual void beginEdgeScope(unsigned id, unsigned oid)
  12190. {
  12191. StatsScopeId scopeId(SSTedge, id, oid);
  12192. beginScope(scopeId);
  12193. }
  12194. virtual void beginChildGraphScope(unsigned id)
  12195. {
  12196. StatsScopeId scopeId(SSTchildgraph, id);
  12197. beginScope(scopeId);
  12198. }
  12199. virtual void endScope()
  12200. {
  12201. scope.setLength(prevLenStack.popGet());
  12202. scopeTypeStack.pop();
  12203. }
  12204. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  12205. {
  12206. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12207. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  12208. }
  12209. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  12210. {
  12211. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12212. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  12213. }
  12214. virtual IStatisticCollection * getResult()
  12215. {
  12216. return NULL;
  12217. }
  12218. protected:
  12219. Linked<IWorkUnit> wu;
  12220. StringBuffer scope;
  12221. UnsignedArray prevLenStack;
  12222. UnsignedArray scopeTypeStack;
  12223. };
  12224. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  12225. {
  12226. return new GlobalStatisticGatherer(wu);
  12227. }
  12228. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  12229. {
  12230. if (!wuid || !*wuid)
  12231. return NULL;
  12232. VStringBuffer path("/GraphProgress/%s", wuid);
  12233. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12234. if (conn)
  12235. return conn->getRoot();
  12236. else
  12237. return NULL;
  12238. }
  12239. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  12240. {
  12241. ErrorSeverity wuSeverity = SeverityInformation;
  12242. ErrorSeverity severity = error->getSeverity();
  12243. switch (severity)
  12244. {
  12245. case SeverityIgnore:
  12246. return;
  12247. case SeverityInformation:
  12248. break;
  12249. case SeverityWarning:
  12250. wuSeverity = SeverityWarning;
  12251. break;
  12252. case SeverityError:
  12253. case SeverityFatal:
  12254. wuSeverity = SeverityError;
  12255. break;
  12256. }
  12257. Owned<IWUException> exception = wu->createException();
  12258. exception->setSeverity(wuSeverity);
  12259. StringBuffer msg;
  12260. exception->setExceptionCode(error->errorCode());
  12261. exception->setExceptionMessage(error->errorMessage(msg).str());
  12262. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  12263. exception->setExceptionSource(source);
  12264. exception->setExceptionFileName(error->getFilename());
  12265. exception->setExceptionLineNo(error->getLine());
  12266. exception->setExceptionColumn(error->getColumn());
  12267. if (removeTimeStamp)
  12268. exception->setTimeStamp(nullptr);
  12269. if (error->getActivity())
  12270. exception->setActivityId(error->getActivity());
  12271. if (error->queryScope())
  12272. exception->setScope(error->queryScope());
  12273. }
  12274. IError * WorkUnitErrorReceiver::mapError(IError * error)
  12275. {
  12276. return LINK(error);
  12277. }
  12278. void WorkUnitErrorReceiver::report(IError* eclError)
  12279. {
  12280. addWorkunitException(wu, eclError, removeTimeStamp);
  12281. }
  12282. size32_t WorkUnitErrorReceiver::errCount()
  12283. {
  12284. unsigned count = 0;
  12285. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12286. ForEach(*exceptions)
  12287. if (exceptions->query().getSeverity() == SeverityError)
  12288. count++;
  12289. return count;
  12290. }
  12291. size32_t WorkUnitErrorReceiver::warnCount()
  12292. {
  12293. unsigned count = 0;
  12294. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12295. ForEach(*exceptions)
  12296. if (exceptions->query().getSeverity() == SeverityWarning)
  12297. count++;
  12298. return count;
  12299. }
  12300. bool isValidPriorityValue(const char *priority)
  12301. {
  12302. if (isEmptyString(priority))
  12303. return false;
  12304. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  12305. return true;
  12306. return false;
  12307. }
  12308. bool isValidMemoryValue(const char *memoryUnit)
  12309. {
  12310. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  12311. return false;
  12312. while (isdigit(*++memoryUnit));
  12313. if (!*memoryUnit)
  12314. return true;
  12315. switch (toupper(*memoryUnit++))
  12316. {
  12317. case 'E':
  12318. case 'P':
  12319. case 'T':
  12320. case 'G':
  12321. case 'M':
  12322. case 'K':
  12323. if (!*memoryUnit || strieq("B", memoryUnit))
  12324. return true;
  12325. break;
  12326. case 'B':
  12327. if (!*memoryUnit)
  12328. return true;
  12329. break;
  12330. }
  12331. return false;
  12332. }
  12333. // used by eclagent and roxie
  12334. #define ABORT_POLL_PERIOD (5*1000)
  12335. void executeThorGraph(const char * graphName, IConstWorkUnit &workunit, const IPropertyTree &config)
  12336. {
  12337. unsigned timelimit = workunit.getDebugValueInt("thorConnectTimeout", config.getPropInt("@thorConnectTimeout", 60));
  12338. StringAttr wuid(workunit.queryWuid());
  12339. IConstWUGraph *graph = workunit.getGraph(graphName);
  12340. if (!graph)
  12341. throw makeStringExceptionV(0, "getGraph() returns nullptr for %s", graphName);
  12342. unsigned wfid = graph->getWfid();
  12343. #ifdef _CONTAINERIZED
  12344. // NB: If a single agent were to want to launch >1 Thor, then the threading could be in the workflow above this call.
  12345. {
  12346. Owned<IWorkUnit> w = &workunit.lock();
  12347. w->setState(WUStateBlocked);
  12348. }
  12349. WUState state = WUStateUnknown;
  12350. if (config.hasProp("@queue"))
  12351. {
  12352. CCycleTimer elapsedTimer;
  12353. bool multiJobLinger = config.getPropBool("@multiJobLinger");
  12354. if (executeGraphOnLingeringThor(workunit, graphName, multiJobLinger ? config.queryProp("@queue") : nullptr))
  12355. PROGLOG("Existing lingering Thor handled graph: %s", graphName);
  12356. else
  12357. {
  12358. VStringBuffer queueName("%s.thor", config.queryProp("@queue"));
  12359. DBGLOG("Queueing wuid=%s, graph=%s, on queue=%s, timelimit=%u seconds", wuid.str(), graphName, queueName.str(), timelimit);
  12360. Owned<IJobQueue> queue = createJobQueue(queueName);
  12361. VStringBuffer jobName("%s/%s", wuid.get(), graphName);
  12362. IJobQueueItem *item = createJobQueueItem(jobName);
  12363. queue->enqueue(item);
  12364. }
  12365. // NB: overall max runtime if guillotine set handled by abortmonitor
  12366. unsigned runningTimeLimit = workunit.getDebugValueInt("maxRunTime", 0);
  12367. runningTimeLimit = runningTimeLimit ? runningTimeLimit : INFINITE;
  12368. std::list<WUState> expectedStates = { WUStateRunning, WUStateWait };
  12369. unsigned __int64 blockedTime = 0;
  12370. for (unsigned i=0; i<2; i++)
  12371. {
  12372. WUState state = waitForWorkUnitToComplete(wuid, timelimit*1000, expectedStates);
  12373. DBGLOG("Got state: %s", getWorkunitStateStr(state));
  12374. if (WUStateWait == state) // already finished
  12375. {
  12376. // workunit may have spent time in blocked state, but then transitioned to
  12377. // wait state quickly such that this code did not see its running state.
  12378. if (!blockedTime)
  12379. blockedTime = elapsedTimer.elapsedNs();
  12380. break;
  12381. }
  12382. else if ((INFINITE != timelimit) && (WUStateUnknown == state))
  12383. throw makeStringExceptionV(0, "Query %s failed to start within specified timelimit (%u) seconds", wuid.str(), timelimit);
  12384. else
  12385. {
  12386. auto it = std::find(expectedStates.begin(), expectedStates.end(), state);
  12387. if (it == expectedStates.end())
  12388. throw makeStringExceptionV(0, "Query %s failed, state: %s", wuid.str(), getWorkunitStateStr(state));
  12389. }
  12390. blockedTime = elapsedTimer.elapsedNs();
  12391. timelimit = runningTimeLimit;
  12392. expectedStates = { WUStateWait };
  12393. }
  12394. Owned<IWorkUnit> w = &workunit.lock();
  12395. updateWorkunitStat(w, SSTgraph, graphName, StTimeBlocked, nullptr, blockedTime, wfid);
  12396. }
  12397. else
  12398. {
  12399. VStringBuffer job("%s-%s", wuid.str(), graphName);
  12400. runK8sJob("thormanager", wuid, job, { { "graphName", graphName} });
  12401. }
  12402. /* In k8s, Thor feeds back the terminating exception via the workunit.
  12403. * (in bare-metal it is returned via a socket the agent connect to Thor with)
  12404. */
  12405. workunit.forceReload();
  12406. if (workunit.getExceptionCount())
  12407. {
  12408. Owned<IConstWUExceptionIterator> iter = &workunit.getExceptions();
  12409. ForEach(*iter)
  12410. {
  12411. IConstWUException &e = iter->query();
  12412. SCMStringBuffer str;
  12413. e.getExceptionSource(str);
  12414. if (streq("thormasterexception", str.s))
  12415. {
  12416. str.clear();
  12417. e.getExceptionMessage(str);
  12418. unsigned errCode = e.getExceptionCode();
  12419. {
  12420. /* Clear the feedback exception (consume it),
  12421. * so that any future re-submissions of this workunit (e.g. due to workflow)
  12422. * don't see it again.
  12423. */
  12424. Owned<IWorkUnit> w = &workunit.lock();
  12425. w->clearExceptions("thormasterexception");
  12426. }
  12427. throw makeStringException(errCode, str.str());
  12428. }
  12429. }
  12430. }
  12431. else
  12432. {
  12433. Owned<IWorkUnit> w = &workunit.lock();
  12434. WUState state = w->getState();
  12435. if (WUStateFailed == state)
  12436. throw makeStringException(0, "Workunit failed");
  12437. }
  12438. {
  12439. Owned<IWorkUnit> w = &workunit.lock();
  12440. w->setState(WUStateRunning);
  12441. }
  12442. #else
  12443. StringAttr owner(workunit.queryUser());
  12444. StringAttr cluster(workunit.queryClusterName());
  12445. int priority = workunit.getPriorityValue();
  12446. Owned<IConstWUClusterInfo> c = getTargetClusterInfo(cluster);
  12447. if (!c)
  12448. throw MakeStringException(0, "Invalid thor cluster %s", cluster.str());
  12449. SCMStringBuffer queueName;
  12450. c->getThorQueue(queueName);
  12451. Owned<IJobQueue> jq = createJobQueue(queueName.str());
  12452. bool resubmit;
  12453. Owned<IWorkUnitFactory> wuFactory = getWorkUnitFactory();
  12454. do // loop if pause interrupted graph and needs resubmitting on resume
  12455. {
  12456. resubmit = false; // set if job interrupted in thor
  12457. if (WUStatePaused == workunit.getState()) // check initial state - and wait if paused
  12458. {
  12459. for (;;)
  12460. {
  12461. WUAction action = wuFactory->waitForWorkUnitAction(wuid, workunit.getAction());
  12462. if (action == WUActionUnknown)
  12463. throw new WorkflowException(0, "Workunit aborting", 0, WorkflowException::ABORT, MSGAUD_user);
  12464. if (action != WUActionPause && action != WUActionPauseNow)
  12465. break;
  12466. }
  12467. }
  12468. {
  12469. Owned<IWorkUnit> w = &workunit.lock();
  12470. w->setState(WUStateBlocked);
  12471. }
  12472. class cPollThread: public Thread // MORE - why do we ned a thread here?
  12473. {
  12474. Semaphore sem;
  12475. bool stopped;
  12476. IJobQueue *jq;
  12477. IConstWorkUnit *wu;
  12478. public:
  12479. bool timedout;
  12480. CTimeMon tm;
  12481. cPollThread(IJobQueue *_jq, IConstWorkUnit *_wu, unsigned timelimit)
  12482. : tm(timelimit)
  12483. {
  12484. stopped = false;
  12485. jq = _jq;
  12486. wu = _wu;
  12487. timedout = false;
  12488. }
  12489. ~cPollThread()
  12490. {
  12491. stop();
  12492. }
  12493. int run()
  12494. {
  12495. while (!stopped) {
  12496. sem.wait(ABORT_POLL_PERIOD);
  12497. if (stopped)
  12498. break;
  12499. if (tm.timedout()) {
  12500. timedout = true;
  12501. stopped = true;
  12502. jq->cancelInitiateConversation();
  12503. }
  12504. else if (wu->aborting()) {
  12505. stopped = true;
  12506. jq->cancelInitiateConversation();
  12507. }
  12508. }
  12509. return 0;
  12510. }
  12511. void stop()
  12512. {
  12513. stopped = true;
  12514. sem.signal();
  12515. }
  12516. } pollthread(jq, &workunit, timelimit*1000);
  12517. pollthread.start();
  12518. CCycleTimer elapsedTimer;
  12519. PROGLOG("Enqueuing on %s to run wuid=%s, graph=%s, timelimit=%d seconds, priority=%d", queueName.str(), wuid.str(), graphName, timelimit, priority);
  12520. VStringBuffer wuidGraph("%s/%s", wuid.str(), graphName);
  12521. IJobQueueItem* item = createJobQueueItem(wuidGraph.str());
  12522. item->setOwner(owner.str());
  12523. item->setPriority(priority);
  12524. Owned<IConversation> conversation = jq->initiateConversation(item);
  12525. bool got = conversation.get()!=NULL;
  12526. pollthread.stop();
  12527. pollthread.join();
  12528. if (!got)
  12529. {
  12530. if (pollthread.timedout)
  12531. throw MakeStringException(0, "Query %s failed to start within specified timelimit (%u) seconds", wuidGraph.str(), timelimit);
  12532. throw MakeStringException(0, "Query %s cancelled (1)", wuidGraph.str());
  12533. }
  12534. // get the thor ep from whoever picked up
  12535. SocketEndpoint thorMaster;
  12536. MemoryBuffer msg;
  12537. if (!conversation->recv(msg,1000*60))
  12538. throw MakeStringException(0, "Query %s cancelled (2)", wuidGraph.str());
  12539. thorMaster.deserialize(msg);
  12540. msg.clear();
  12541. SocketEndpoint myep;
  12542. myep.setLocalHost(0);
  12543. myep.serialize(msg); // only used for tracing
  12544. if (!conversation->send(msg)) {
  12545. StringBuffer s("Failed to send query to Thor on ");
  12546. thorMaster.getUrlStr(s);
  12547. throw MakeStringExceptionDirect(-1, s.str()); // maybe retry?
  12548. }
  12549. unsigned __int64 blockedTime = elapsedTimer.elapsedNs();
  12550. {
  12551. Owned<IWorkUnit> w = &workunit.lock();
  12552. updateWorkunitStat(w, SSTgraph, graphName, StTimeBlocked, nullptr, blockedTime, wfid);
  12553. }
  12554. StringBuffer eps;
  12555. PROGLOG("Thor on %s running %s", thorMaster.getUrlStr(eps).str(), wuidGraph.str());
  12556. MemoryBuffer reply;
  12557. try
  12558. {
  12559. if (!conversation->recv(reply,INFINITE))
  12560. {
  12561. StringBuffer s("Failed to receive reply from thor ");
  12562. thorMaster.getUrlStr(s);
  12563. throw MakeStringExceptionDirect(-1, s.str());
  12564. }
  12565. }
  12566. catch (IException *e)
  12567. {
  12568. StringBuffer s("Failed to receive reply from thor ");
  12569. thorMaster.getUrlStr(s);
  12570. s.append("; (").append(e->errorCode()).append(", ");
  12571. e->errorMessage(s).append(")");
  12572. e->Release();
  12573. throw MakeStringExceptionDirect(-1, s.str());
  12574. }
  12575. unsigned replyCode;
  12576. reply.read(replyCode);
  12577. switch ((ThorReplyCodes) replyCode)
  12578. {
  12579. case DAMP_THOR_REPLY_PAUSED:
  12580. {
  12581. bool isException;
  12582. reply.read(isException);
  12583. if (isException)
  12584. {
  12585. Owned<IException> e = deserializeException(reply);
  12586. VStringBuffer str("Pausing job %s caused exception", wuidGraph.str());
  12587. EXCLOG(e, str.str());
  12588. }
  12589. Owned<IWorkUnit> w = &workunit.lock();
  12590. w->setState(WUStatePaused); // will trigger executeThorGraph to pause next time around.
  12591. WUAction action = w->getAction();
  12592. switch (action)
  12593. {
  12594. case WUActionPause:
  12595. case WUActionPauseNow:
  12596. w->setAction(WUActionUnknown);
  12597. }
  12598. resubmit = true; // JCSMORE - all subgraph _could_ be done, thor will check though and not rerun
  12599. break;
  12600. }
  12601. case DAMP_THOR_REPLY_GOOD:
  12602. break;
  12603. case DAMP_THOR_REPLY_ERROR:
  12604. {
  12605. throw deserializeException(reply);
  12606. }
  12607. case DAMP_THOR_REPLY_ABORT:
  12608. {
  12609. Owned<IException> e = deserializeException(reply);
  12610. StringBuffer msg;
  12611. e->errorMessage(msg);
  12612. throw new WorkflowException(e->errorCode(), msg.str(), 0, WorkflowException::ABORT, MSGAUD_user);
  12613. }
  12614. default:
  12615. throwUnexpected();
  12616. }
  12617. workunit.forceReload();
  12618. }
  12619. while (resubmit); // if pause interrupted job (i.e. with pausenow action), resubmit graph
  12620. #endif
  12621. }
  12622. #ifdef _CONTAINERIZED
  12623. bool executeGraphOnLingeringThor(IConstWorkUnit &workunit, const char *graphName, const char *multiJobLingerQueueName)
  12624. {
  12625. // check if lingering thor instance is up.
  12626. // Returns true if successfully submitted graph to a lingering Thor.
  12627. /* If code was dependent on reading a workunit in parallel, the whole area of
  12628. * workunit locking and reading will need revisiting, because at the moment the
  12629. * workunit reading code does not lock at all.
  12630. *
  12631. * Either,
  12632. * 1) multiJobThorLinger is set, meaning Thor instances will wait for any job's graph.
  12633. * OR
  12634. * 2) if not set, the Thor will wait for graphs from same job only, and will be
  12635. * notified to quit by the agent, when the last graph is complete.
  12636. *
  12637. * This code is called from the client (agent) when it wants to execute a Thor graph.
  12638. * This function checks to see if there any registered lingering Thor instances available.
  12639. *
  12640. * Lingering Thor's register when they are idle either with the workunit itself in
  12641. * the case of [2], or with a Dali psuedo queue (a branch under /Status/ThorLinger),
  12642. * in the case of [1]
  12643. * If they have not been contacted within the 'lingerPeriod' they shutdown and remove
  12644. * their registered instance from the queue.
  12645. *
  12646. * The client will attempt to find a lingering Thor in either the workunit or a global
  12647. * named dali queue (depending on the configuration), it will then remove that entry,
  12648. * and attempt to post the graph to that lingering Thor. If the Thor acknowledges the
  12649. * request, this function exits with success. If it it fails, or there are no more
  12650. * lingering Thor instances, it returns with false to indicate that the graph was not
  12651. * submitted to a lingering Thor.
  12652. * The client should then queue the wuid/graph normally, which will invoke a new Thor
  12653. * instance.
  12654. */
  12655. try
  12656. {
  12657. if (multiJobLingerQueueName && graphName)
  12658. {
  12659. // check a Dali queue for idle spare Thor's
  12660. DBGLOG("Checking multi job lingering queue: %s", multiJobLingerQueueName);
  12661. VStringBuffer xpath("/Status/ThorLinger/%s", multiJobLingerQueueName);
  12662. while (true)
  12663. {
  12664. Owned<IRemoteConnection> conn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE, 5*60*1000);
  12665. if (!conn)
  12666. break;
  12667. IPropertyTree *root = conn->queryRoot();
  12668. if (0 == root->numChildren())
  12669. break;
  12670. IPropertyTree *entry = root->queryPropTree("Thor*[1]");
  12671. const char *entryName = entry->queryName();
  12672. // get available instance and remove it
  12673. VStringBuffer entryXPath("%s/%s", xpath.str(), entryName);
  12674. Owned<IRemoteConnection> lingerInstanceConn = querySDS().connect(entryXPath, myProcessSession(), RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, 5*1000);
  12675. if (lingerInstanceConn)
  12676. {
  12677. StringBuffer instanceName;
  12678. lingerInstanceConn->queryRoot()->getProp(nullptr, instanceName);
  12679. lingerInstanceConn->close(true);
  12680. lingerInstanceConn.clear();
  12681. conn.clear();
  12682. Owned<INode> masterNode = createINode(instanceName);
  12683. CMessageBuffer msg;
  12684. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName);
  12685. msg.append(jobStr);
  12686. bool success = queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000);
  12687. DBGLOG("Found lingering Thor: %s, submitted: %s, success: %s", instanceName.str(), jobStr.str(), boolToStr(success));
  12688. if (success)
  12689. {
  12690. bool ok;
  12691. msg.read(ok);
  12692. return true;
  12693. }
  12694. }
  12695. }
  12696. }
  12697. else
  12698. {
  12699. /* NB: forcing a reload here to ensure Debug values are recent.
  12700. * Could be improved by refreshing only the specific area of interest (i.e. Debug/ in this case).
  12701. * The area of persisting a non-locked connection to workunits should be resivisted..
  12702. */
  12703. workunit.forceReload();
  12704. Owned<IStringIterator> iter = &workunit.getDebugValues("thorinstance_*");
  12705. ForEach(*iter)
  12706. {
  12707. /* NB: Thor's set their running endpoint into Debug values of workunit
  12708. * Check to see if workunit has any Thor's available lingering instances.
  12709. */
  12710. SCMStringBuffer thorInstance;
  12711. iter->str(thorInstance);
  12712. SCMStringBuffer thorInstanceValue;
  12713. if (workunit.getDebugValueBool(thorInstance.s, false))
  12714. {
  12715. {
  12716. Owned<IWorkUnit> w = &workunit.lock();
  12717. w->setDebugValue(thorInstance.s, "0", true);
  12718. }
  12719. /* NB: there's a window where Thor could shutdown here.
  12720. * In that case, the sendRecv will fail and it will fall through to queueing.
  12721. */
  12722. const char *instanceName = strchr(thorInstance.str(), '_') + 1;
  12723. Owned<INode> masterNode = createINode(instanceName);
  12724. CMessageBuffer msg;
  12725. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName?graphName:"");
  12726. msg.append(jobStr);
  12727. if (queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000))
  12728. {
  12729. bool ok;
  12730. msg.read(ok);
  12731. if (graphName) // if graphName==nullptr, then continue around to look at others
  12732. {
  12733. if (ok)
  12734. return true;
  12735. }
  12736. }
  12737. }
  12738. }
  12739. }
  12740. }
  12741. catch (IException *e)
  12742. {
  12743. EXCLOG(e, "executeGraphOnLingeringThor");
  12744. e->Release();
  12745. }
  12746. return false;
  12747. }
  12748. static void setResources(IPropertyTree *workerConfig, const IConstWorkUnit *workunit, const char *process)
  12749. {
  12750. auto setResourcesItem = [&workerConfig](const char *category, const char *resourceName, unsigned value, const char *units)
  12751. {
  12752. if (!value) return;
  12753. VStringBuffer xpath("spec/template/spec/containers/resources/%s@%s", category, resourceName);
  12754. ensurePTree(workerConfig, xpath.str());
  12755. VStringBuffer v("%u%s", value, units);
  12756. workerConfig->setProp(xpath.str(), v.str());
  12757. };
  12758. StringBuffer s;
  12759. unsigned memRequest = workunit->getDebugValueInt(s.clear().appendf("resource-%s-memory", process), 0);
  12760. setResourcesItem("requests", "memory", memRequest, "Mi");
  12761. setResourcesItem("limits", "memory", memRequest, "Mi");
  12762. unsigned cpuRequest = workunit->getDebugValueInt(s.clear().appendf("resource-%s-cpu", process), 0);
  12763. setResourcesItem("requests", "cpu", cpuRequest, "m");
  12764. setResourcesItem("limits", "cpu", cpuRequest, "m");
  12765. }
  12766. KeepK8sJobs translateKeepJobs(const char *keepJob)
  12767. {
  12768. if (!isEmptyString(keepJob)) // common case
  12769. {
  12770. if (streq("podfailures", keepJob))
  12771. return KeepK8sJobs::podfailures;
  12772. else if (streq("all", keepJob))
  12773. return KeepK8sJobs::all;
  12774. }
  12775. return KeepK8sJobs::none;
  12776. }
  12777. void deleteK8sResource(const char *componentName, const char *job, const char *resource)
  12778. {
  12779. VStringBuffer jobname("%s-%s", componentName, job);
  12780. jobname.toLowerCase();
  12781. VStringBuffer deleteResource("kubectl delete %s/%s", resource, jobname.str());
  12782. StringBuffer output, error;
  12783. bool ret = runExternalCommand(componentName, output, error, deleteResource.str(), nullptr);
  12784. DBGLOG("kubectl delete output: %s", output.trimRight().str());
  12785. if (error.length())
  12786. DBGLOG("kubectl delete error: %s", error.trimRight().str());
  12787. if (ret)
  12788. throw makeStringException(0, "Failed to run kubectl delete");
  12789. }
  12790. void waitK8sJob(const char *componentName, const char *job, unsigned pendingTimeoutSecs, KeepK8sJobs keepJob)
  12791. {
  12792. VStringBuffer jobname("%s-%s", componentName, job);
  12793. jobname.toLowerCase();
  12794. VStringBuffer waitJob("kubectl get jobs %s -o jsonpath={.status.active}", jobname.str());
  12795. VStringBuffer getScheduleStatus("kubectl get pods --selector=job-name=%s --output=jsonpath={.items[*].status.conditions[?(@.type=='PodScheduled')].status}", jobname.str());
  12796. VStringBuffer checkJobExitCode("kubectl get pods --selector=job-name=%s --output=jsonpath={.items[*].status.containerStatuses[?(@.name==\"%s\")].state.terminated.exitCode}", jobname.str(), jobname.str());
  12797. unsigned delay = 100;
  12798. unsigned start = msTick();
  12799. bool schedulingTimeout = false;
  12800. Owned<IException> exception;
  12801. try
  12802. {
  12803. for (;;)
  12804. {
  12805. StringBuffer output, error;
  12806. unsigned ret = runExternalCommand(nullptr, output, error, waitJob.str(), nullptr);
  12807. if (ret || error.length())
  12808. throw makeStringExceptionV(0, "Failed to run %s: error %u: %s", waitJob.str(), ret, error.str());
  12809. if (!streq(output, "1")) // status.active value
  12810. {
  12811. // Job is no longer active - we can terminate
  12812. DBGLOG("kubectl jobs output: %s", output.str());
  12813. unsigned ret = runExternalCommand(nullptr, output.clear(), error.clear(), checkJobExitCode.str(), nullptr);
  12814. if (ret || error.length())
  12815. throw makeStringExceptionV(0, "Failed to run %s: error %u: %s", checkJobExitCode.str(), ret, error.str());
  12816. if (output.length() && !streq(output, "0")) // state.terminated.exitCode
  12817. throw makeStringExceptionV(0, "Failed to run %s: pod exited with error: %s", jobname.str(), output.str());
  12818. break;
  12819. }
  12820. ret = runExternalCommand(nullptr, output.clear(), error.clear(), getScheduleStatus.str(), nullptr);
  12821. if (error.length())
  12822. {
  12823. DBGLOG("kubectl get schedule status error: %s", error.str());
  12824. break;
  12825. }
  12826. // Check whether pod has been scheduled yet - if resources are not available pods may block indefinitely waiting to be scheduled, and
  12827. // we would prefer them to fail instead.
  12828. bool pending = streq(output, "False");
  12829. if (pendingTimeoutSecs && pending && msTick()-start > pendingTimeoutSecs*1000)
  12830. {
  12831. schedulingTimeout = true;
  12832. VStringBuffer getReason("kubectl get pods --selector=job-name=%s \"--output=jsonpath={range .items[*].status.conditions[?(@.type=='PodScheduled')]}{.reason}{': '}{.message}{end}\"", jobname.str());
  12833. runExternalCommand(componentName, output.clear(), error.clear(), getReason.str(), nullptr);
  12834. throw makeStringExceptionV(0, "Failed to run %s - pod not scheduled after %u seconds: %s ", jobname.str(), pendingTimeoutSecs, output.str());
  12835. }
  12836. MilliSleep(delay);
  12837. if (delay < 10000)
  12838. delay = delay * 2;
  12839. }
  12840. }
  12841. catch (IException *e)
  12842. {
  12843. EXCLOG(e, nullptr);
  12844. exception.setown(e);
  12845. }
  12846. if (keepJob != KeepK8sJobs::all)
  12847. {
  12848. // Delete jobs unless the pod failed and keepJob==podfailures
  12849. if ((nullptr == exception) || (KeepK8sJobs::podfailures != keepJob) || schedulingTimeout)
  12850. deleteK8sResource(componentName, job, "job");
  12851. }
  12852. if (exception)
  12853. throw exception.getClear();
  12854. }
  12855. bool applyK8sYaml(const char *componentName, const char *wuid, const char *job, const char *suffix, const std::list<std::pair<std::string, std::string>> &extraParams, bool optional)
  12856. {
  12857. StringBuffer jobname(job);
  12858. jobname.toLowerCase();
  12859. VStringBuffer jobSpecFilename("/etc/config/%s-%s.yaml", componentName, suffix);
  12860. StringBuffer jobYaml;
  12861. try
  12862. {
  12863. jobYaml.loadFile(jobSpecFilename, false);
  12864. }
  12865. catch (IException *E)
  12866. {
  12867. if (!optional)
  12868. throw;
  12869. E->Release();
  12870. return false;
  12871. }
  12872. jobYaml.replaceString("_HPCC_JOBNAME_", jobname.str());
  12873. VStringBuffer args("\"--workunit=%s\"", wuid);
  12874. for (const auto &p: extraParams)
  12875. {
  12876. if (hasPrefix(p.first.c_str(), "_HPCC_", false)) // jobspec substituion
  12877. jobYaml.replaceString(p.first.c_str(), p.second.c_str());
  12878. else
  12879. args.append(" \"--").append(p.first.c_str()).append('=').append(p.second.c_str()).append("\"");
  12880. }
  12881. jobYaml.replaceString("_HPCC_ARGS_", args.str());
  12882. // Disable ability change resources from within workunit
  12883. // - all values are unquoted by toYAML. This caused problems when previous string values are
  12884. // outputted unquoted and then treated as a non string type -e.g. labels in metadata.
  12885. // - Also, ability to control if and how much users may change resources should be provided.
  12886. #if 0
  12887. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12888. if (factory)
  12889. {
  12890. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(wuid);
  12891. if (workunit)
  12892. {
  12893. Owned<IPropertyTree> workerConfig = createPTreeFromYAMLString(jobYaml.length(), jobYaml.str(), 0, ptr_none, nullptr);
  12894. setResources(workerConfig, workunit, componentName);
  12895. toYAML(workerConfig, jobYaml.clear(), 2, 0);
  12896. }
  12897. }
  12898. #endif
  12899. StringBuffer output, error;
  12900. unsigned ret = runExternalCommand(componentName, output, error, "kubectl replace --force -f -", jobYaml.str());
  12901. DBGLOG("kubectl output: %s", output.trimRight().str());
  12902. if (error.length())
  12903. DBGLOG("kubectl error: %s", error.trimRight().str());
  12904. if (ret)
  12905. {
  12906. DBGLOG("Using yaml %s", jobYaml.str());
  12907. throw makeStringException(0, "Failed to replace k8s resource");
  12908. }
  12909. return true;
  12910. }
  12911. static constexpr unsigned defaultPendingTimeSecs = 600;
  12912. void runK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams)
  12913. {
  12914. Owned<IPropertyTree> compConfig = getComponentConfig();
  12915. KeepK8sJobs keepJob = translateKeepJobs(compConfig->queryProp("@keepJobs"));
  12916. unsigned pendingTimeoutSecs = compConfig->getPropInt("@pendingTimeoutSecs", defaultPendingTimeSecs);
  12917. bool removeNetwork = applyK8sYaml(componentName, wuid, job, "networkspec", extraParams, true);
  12918. applyK8sYaml(componentName, wuid, job, "jobspec", extraParams, false);
  12919. Owned<IException> exception;
  12920. try
  12921. {
  12922. waitK8sJob(componentName, job, pendingTimeoutSecs, keepJob);
  12923. }
  12924. catch (IException *e)
  12925. {
  12926. EXCLOG(e, nullptr);
  12927. exception.setown(e);
  12928. }
  12929. if (removeNetwork)
  12930. deleteK8sResource(componentName, job, "networkpolicy");
  12931. if (exception)
  12932. throw exception.getClear();
  12933. }
  12934. #endif