workunit.cpp 448 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807
  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. unsigned numIters = treeIters.ordinality();
  1397. //This should really be implemented by a filter on the node - but it would require _kind/_parentActivity to move to the node tag
  1398. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1399. {
  1400. state = SChildGraphNext;
  1401. break;
  1402. }
  1403. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1404. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1405. if (parentId != parentActivityId)
  1406. {
  1407. state = SChildGraphNext;
  1408. break;
  1409. }
  1410. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1411. pushScope(scopeId);
  1412. scopeType = SSTchildgraph;
  1413. return true;
  1414. }
  1415. //Graph iteration
  1416. case SGraphFirst:
  1417. if (!graphIter->first())
  1418. state = SDone;
  1419. else
  1420. state = SGraph;
  1421. break;
  1422. case SGraphEnd:
  1423. state = SGraphNext;
  1424. break;
  1425. case SGraphNext:
  1426. if (!graphIter->next())
  1427. state = SDone;
  1428. else
  1429. state = SGraph;
  1430. break;
  1431. //Edge iteration
  1432. case SGraphFirstEdge:
  1433. {
  1434. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1435. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1436. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1437. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1438. if (treeIter && treeIter->first())
  1439. {
  1440. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1441. treeIter->first();
  1442. pushIterator(treeIter, SGraphFirstSubGraph);
  1443. state = SEdge;
  1444. }
  1445. else
  1446. state = SGraphFirstSubGraph;
  1447. break;
  1448. }
  1449. case SChildGraphFirstEdge:
  1450. {
  1451. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1452. if (treeIter && treeIter->first())
  1453. {
  1454. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1455. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1456. state = SEdge;
  1457. }
  1458. else
  1459. state = SChildGraphFirstSubGraph;
  1460. break;
  1461. }
  1462. case SEdgeEnd:
  1463. popScope();
  1464. state = SEdgeNext;
  1465. break;
  1466. case SEdgeNext:
  1467. if (treeIters.tos().next())
  1468. state = SEdge;
  1469. else
  1470. state = popIterator();
  1471. break;
  1472. //Subgraph iteration
  1473. case SGraphFirstSubGraph:
  1474. {
  1475. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1476. if (treeIter && treeIter->first())
  1477. {
  1478. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1479. treeIter->first();
  1480. pushIterator(treeIter, SGraphNext);
  1481. state = SSubGraph;
  1482. }
  1483. else
  1484. state = SGraphNext;
  1485. break;
  1486. }
  1487. case SChildGraphFirstSubGraph:
  1488. {
  1489. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1490. if (treeIter && treeIter->first())
  1491. {
  1492. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1493. pushIterator(treeIter, SChildGraphEnd);
  1494. state = SSubGraph;
  1495. }
  1496. else
  1497. state = SChildGraphEnd;
  1498. break;
  1499. }
  1500. case SSubGraphFirstEdge:
  1501. {
  1502. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1503. if (treeIter && treeIter->first())
  1504. {
  1505. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1506. pushIterator(treeIter, SSubGraphFirstActivity);
  1507. state = SEdge;
  1508. }
  1509. else
  1510. state = SSubGraphFirstActivity;
  1511. break;
  1512. }
  1513. case SSubGraphFirstActivity:
  1514. {
  1515. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1516. if (treeIter && treeIter->first())
  1517. {
  1518. treeIter.setown(createSortedIterator(*treeIter, compareActivityNode));
  1519. pushIterator(treeIter, SSubGraphEnd);
  1520. state = SActivity;
  1521. }
  1522. else
  1523. state = SSubGraphEnd;
  1524. break;
  1525. }
  1526. case SSubGraphEnd:
  1527. popScope();
  1528. state = SSubGraphNext;
  1529. break;
  1530. case SChildGraphEnd:
  1531. popScope();
  1532. state = SChildGraphNext;
  1533. break;
  1534. case SSubGraphNext:
  1535. if (treeIters.tos().next())
  1536. state = SSubGraph;
  1537. else
  1538. state = popIterator();
  1539. break;
  1540. case SActivityEnd:
  1541. popScope();
  1542. state = SActivityNext;
  1543. break;
  1544. case SActivityNext:
  1545. if (treeIters.tos().next())
  1546. state = SActivity;
  1547. else
  1548. state = popIterator();
  1549. break;
  1550. case SChildGraphNext:
  1551. if (treeIters.tos().next())
  1552. state = SChildGraph;
  1553. else
  1554. state = popIterator();
  1555. break;
  1556. case SChildGraphFirst:
  1557. {
  1558. unsigned numIters = treeIters.ordinality();
  1559. IPropertyTreeIterator & graphIter = treeIters.item(numIters-2);
  1560. Owned<IPropertyTreeIterator> treeIter = graphIter.query().getElements("att/graph/node");
  1561. //Really want to filter by <att name="_parentActivity" value="<parentid>">
  1562. if (treeIter && treeIter->first())
  1563. {
  1564. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1565. pushIterator(treeIter, SActivityEnd);
  1566. state = SChildGraph;
  1567. }
  1568. else
  1569. state = SActivityEnd;
  1570. break;
  1571. }
  1572. case SDone:
  1573. return false;
  1574. default:
  1575. throwUnexpected();
  1576. }
  1577. }
  1578. }
  1579. bool nextScope()
  1580. {
  1581. for(;;)
  1582. {
  1583. if (!doNextScope())
  1584. return false;
  1585. ScopeCompare cmp = filter.compare(curScopeName);
  1586. if (cmp & SCequal)
  1587. return true;
  1588. //MORE: Optimize next based on result of compare
  1589. if (!selectNext())
  1590. return false;
  1591. }
  1592. }
  1593. bool selectNext()
  1594. {
  1595. switch (state)
  1596. {
  1597. case SGraph:
  1598. state = SGraphFirstEdge;
  1599. break;
  1600. case SChildGraph:
  1601. state = SChildGraphFirstEdge;
  1602. break;
  1603. case SSubGraph:
  1604. state = SSubGraphFirstEdge;
  1605. break;
  1606. case SEdge:
  1607. state = SEdgeEnd;
  1608. break;
  1609. case SActivity:
  1610. state = SChildGraphFirst;
  1611. break;
  1612. case SDone:
  1613. return false;
  1614. default:
  1615. throwUnexpected();
  1616. }
  1617. return true;
  1618. }
  1619. bool selectNextSibling()
  1620. {
  1621. switch (state)
  1622. {
  1623. case SGraph:
  1624. state = SGraphEnd;
  1625. break;
  1626. case SChildGraph:
  1627. state = SChildGraphEnd;
  1628. break;
  1629. case SSubGraph:
  1630. state = SSubGraphEnd;
  1631. break;
  1632. case SEdge:
  1633. state = SEdgeEnd;
  1634. break;
  1635. case SActivity:
  1636. state = SActivityEnd;
  1637. break;
  1638. case SDone:
  1639. return false;
  1640. default:
  1641. throwUnexpected();
  1642. }
  1643. return true;
  1644. }
  1645. bool selectNextParent()
  1646. {
  1647. switch (state)
  1648. {
  1649. case SGraph:
  1650. state = SDone;
  1651. break;
  1652. case SChildGraph:
  1653. case SSubGraph:
  1654. case SEdge:
  1655. case SActivity:
  1656. popScope();
  1657. state = popIterator();
  1658. break;
  1659. case SDone:
  1660. return false;
  1661. default:
  1662. throwUnexpected();
  1663. }
  1664. return true;
  1665. }
  1666. protected:
  1667. const ScopeFilter & filter;
  1668. Owned<IConstWUGraphIterator> graphIter;
  1669. Owned<IPropertyTree> curGraph;
  1670. IArrayOf<IPropertyTreeIterator> treeIters;
  1671. UnsignedArray scopeLengths;
  1672. UnsignedArray stateStack;
  1673. StringBuffer curScopeName;
  1674. StringBuffer scopeId;
  1675. StatisticScopeType scopeType = SSTnone;
  1676. };
  1677. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1678. {
  1679. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1680. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1681. return left->queryWfid() - right->queryWfid();
  1682. }
  1683. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1684. /*
  1685. * An implementation of IConstWUScopeIterator for the workflow information.
  1686. */
  1687. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1688. {
  1689. public:
  1690. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1691. {
  1692. ForEach(*wfIter)
  1693. workflow.append(*LINK(wfIter->query()));
  1694. workflow.sort(compareWorkflow);
  1695. }
  1696. virtual bool first() override
  1697. {
  1698. if (workflow.empty())
  1699. return false;
  1700. curWorkflow = 0;
  1701. return initWorkflowItem();
  1702. }
  1703. virtual bool next() override
  1704. {
  1705. if (!workflow.isItem(++curWorkflow))
  1706. return false;
  1707. return initWorkflowItem();
  1708. }
  1709. virtual bool nextSibling() override
  1710. {
  1711. return next();
  1712. }
  1713. virtual bool nextParent() override
  1714. {
  1715. curWorkflow = NotFound;
  1716. return false;
  1717. }
  1718. virtual bool isValid() override
  1719. {
  1720. return workflow.isItem(curWorkflow);
  1721. }
  1722. virtual const char * queryScope() const override
  1723. {
  1724. return curScope.str();
  1725. }
  1726. virtual StatisticScopeType getScopeType() const override
  1727. {
  1728. return SSTworkflow;
  1729. }
  1730. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1731. {
  1732. if (whichProperties & PTattributes)
  1733. {
  1734. {
  1735. StringBuffer scratchpad;
  1736. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1737. ForEach(*depends)
  1738. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1739. }
  1740. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1741. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1742. }
  1743. }
  1744. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1745. {
  1746. return false;
  1747. }
  1748. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1749. {
  1750. auto wf = &workflow.item(curWorkflow);
  1751. StringBufferAdaptor adaptor(scratchpad);
  1752. switch (attr)
  1753. {
  1754. case WaIdDependencyList:
  1755. {
  1756. bool first = true;
  1757. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1758. ForEach(*depends)
  1759. {
  1760. if (first)
  1761. scratchpad.append("[");
  1762. else
  1763. scratchpad.append(",");
  1764. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1765. first = false;
  1766. }
  1767. if (first)
  1768. return nullptr;
  1769. scratchpad.append("]");
  1770. return scratchpad.str();
  1771. }
  1772. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1773. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1774. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1775. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1776. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1777. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1778. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1779. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1780. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1781. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1782. case WaState: return queryWorkflowStateText(wf->queryState());
  1783. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1784. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1785. /*
  1786. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1787. virtual bool isScheduledNow() const = 0;
  1788. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1789. virtual unsigned querySchedulePriority() const = 0;
  1790. virtual bool hasScheduleCount() const = 0;
  1791. virtual unsigned queryScheduleCount() const = 0;
  1792. virtual unsigned queryRetriesAllowed() const = 0;
  1793. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1794. virtual bool queryPersistRefresh() const = 0;
  1795. virtual unsigned queryScheduleCountRemaining() const = 0;
  1796. virtual unsigned queryRetriesRemaining() const = 0;
  1797. virtual int queryFailCode() const = 0;
  1798. virtual const char * queryFailMessage() const = 0;
  1799. virtual const char * queryEventName() const = 0;
  1800. virtual const char * queryEventExtra() const = 0;
  1801. */
  1802. }
  1803. return nullptr;
  1804. }
  1805. virtual const char * queryHint(const char * kind) const
  1806. {
  1807. return nullptr;
  1808. }
  1809. protected:
  1810. bool initWorkflowItem()
  1811. {
  1812. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1813. return true;
  1814. }
  1815. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1816. {
  1817. return scratchpad.clear().append(prefix).append(value).str();
  1818. }
  1819. const char * queryOptString(IStringVal & value) const
  1820. {
  1821. const char * text = value.str();
  1822. if (!text || !*text)
  1823. return nullptr;
  1824. return text;
  1825. }
  1826. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1827. {
  1828. if (!value)
  1829. return nullptr;
  1830. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1831. }
  1832. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1833. {
  1834. StringBuffer scratchpad;
  1835. for (auto attr : attrs)
  1836. {
  1837. const char * value = queryAttribute(attr, scratchpad.clear());
  1838. if (value)
  1839. visitor.noteAttribute(attr, value);
  1840. }
  1841. }
  1842. protected:
  1843. IArrayOf<IConstWorkflowItem> workflow;
  1844. unsigned curWorkflow = 0;
  1845. StringBuffer curScope;
  1846. };
  1847. /*
  1848. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1849. */
  1850. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1851. {
  1852. class VisitorMapper : implements IWuScopeVisitor
  1853. {
  1854. public:
  1855. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1856. filter(_filter), visitor(_visitor)
  1857. {}
  1858. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1859. {
  1860. if (filter.includeStatistic(kind))
  1861. visitor.noteStatistic(kind, value, extra);
  1862. }
  1863. virtual void noteAttribute(WuAttr attr, const char * value) override
  1864. {
  1865. if (filter.includeAttribute(attr))
  1866. visitor.noteAttribute(attr, value);
  1867. }
  1868. virtual void noteHint(const char * kind, const char * value) override
  1869. {
  1870. if (filter.includeHint(kind))
  1871. visitor.noteHint(kind, value);
  1872. }
  1873. virtual void noteException(IConstWUException & exception) override
  1874. {
  1875. visitor.noteException(exception);
  1876. }
  1877. protected:
  1878. const WuScopeFilter & filter;
  1879. IWuScopeVisitor & visitor;
  1880. };
  1881. public:
  1882. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1883. {
  1884. }
  1885. void addIter(IConstWUScopeIterator * iter)
  1886. {
  1887. if (iter)
  1888. {
  1889. iters.append(OLINK(*iter));
  1890. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1891. }
  1892. }
  1893. virtual bool first() override
  1894. {
  1895. activeIterMask = 0;
  1896. ForEachItemIn(i, iters)
  1897. {
  1898. if (iters.item(i).first())
  1899. activeIterMask |= (1U << i);
  1900. }
  1901. return findNextScope();
  1902. }
  1903. virtual bool next() override
  1904. {
  1905. selectNext();
  1906. return findNextScope();
  1907. }
  1908. virtual bool nextSibling() override
  1909. {
  1910. selectNextSibling();
  1911. return findNextScope();
  1912. }
  1913. virtual bool nextParent() override
  1914. {
  1915. selectNextParent();
  1916. return findNextScope();
  1917. }
  1918. virtual bool isValid() override
  1919. {
  1920. return (activeIterMask != 0);
  1921. }
  1922. virtual const char * queryScope() const override
  1923. {
  1924. return iters.item(firstMatchIter).queryScope();
  1925. }
  1926. virtual StatisticScopeType getScopeType() const override
  1927. {
  1928. return iters.item(firstMatchIter).getScopeType();
  1929. }
  1930. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1931. {
  1932. VisitorMapper mappedVisitor(filter, visitor);
  1933. whichProperties &= filter.properties;
  1934. ForEachItemIn(i, iters)
  1935. {
  1936. if (iterMatchesCurrentScope(i))
  1937. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1938. }
  1939. }
  1940. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1941. {
  1942. ForEachItemIn(i, iters)
  1943. {
  1944. if (iterMatchesCurrentScope(i))
  1945. {
  1946. if (iters.item(i).getStat(kind, value))
  1947. return true;
  1948. }
  1949. }
  1950. return false;
  1951. }
  1952. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1953. {
  1954. ForEachItemIn(i, iters)
  1955. {
  1956. if (iterMatchesCurrentScope(i))
  1957. {
  1958. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1959. if (value)
  1960. return value;
  1961. }
  1962. }
  1963. return nullptr;
  1964. }
  1965. virtual const char * queryHint(const char * kind) const override
  1966. {
  1967. ForEachItemIn(i, iters)
  1968. {
  1969. if (iterMatchesCurrentScope(i))
  1970. {
  1971. const char * value = iters.item(i).queryHint(kind);
  1972. if (value)
  1973. return value;
  1974. }
  1975. }
  1976. return nullptr;
  1977. }
  1978. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  1979. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  1980. protected:
  1981. //Calculate which iterators contain the scope that should come next
  1982. bool findNextScope()
  1983. {
  1984. for(;;)
  1985. {
  1986. if (activeIterMask == 0)
  1987. return false;
  1988. unsigned mask = 0;
  1989. const char * scope = nullptr;
  1990. ForEachItemIn(i, iters)
  1991. {
  1992. if (isAlive(i))
  1993. {
  1994. const char * iterScope = iters.item(i).queryScope();
  1995. if (mask)
  1996. {
  1997. int compare = compareScopeName(scope, iterScope);
  1998. if (compare == 0)
  1999. {
  2000. mask |= (1U << i);
  2001. }
  2002. else if (compare > 0)
  2003. {
  2004. scope = iterScope;
  2005. mask = (1U << i);
  2006. firstMatchIter = i;
  2007. }
  2008. }
  2009. else
  2010. {
  2011. scope = iterScope;
  2012. mask = (1U << i);
  2013. firstMatchIter = i;
  2014. }
  2015. }
  2016. }
  2017. matchIterMask = mask;
  2018. while (activeScopes)
  2019. {
  2020. const char * activeScope = activeScopes.tos();
  2021. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2022. if (compareScopes(scope, activeScope) & SCchild)
  2023. break;
  2024. activeScopes.pop();
  2025. }
  2026. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2027. bool include = false;
  2028. if (activeScopes)
  2029. {
  2030. const char * activeScope = activeScopes.tos();
  2031. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2032. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2033. if (nesting <= filter.include.nestedDepth)
  2034. include = true;
  2035. }
  2036. //Check to see if this is a new match
  2037. if (filter.compareMatchScopes(scope) & SCequal)
  2038. {
  2039. if (!include)
  2040. include = filter.include.matchedScope;
  2041. //Only add it to the list of active scopes if it can match child elements
  2042. if (filter.include.nestedDepth != 0)
  2043. activeScopes.append(scope);
  2044. }
  2045. if (include)
  2046. {
  2047. if (!filter.includeScope(scope))
  2048. include = false;
  2049. else if (filter.requiredStats.size())
  2050. {
  2051. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2052. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2053. {
  2054. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2055. unsigned __int64 value;
  2056. if (getStat(cur.queryKind(), value))
  2057. {
  2058. if (!cur.matches(value))
  2059. include = false;
  2060. }
  2061. else
  2062. include = false;
  2063. }
  2064. }
  2065. }
  2066. if (include)
  2067. return true;
  2068. //MORE: Optimize based on filter.compareScope()
  2069. selectNext();
  2070. }
  2071. }
  2072. void checkScopeOrder(unsigned input, const char * prevScope)
  2073. {
  2074. if (isAlive(input))
  2075. {
  2076. const char * curScope = iters.item(input).queryScope();
  2077. int compare = compareScopeName(prevScope, curScope);
  2078. if (compare >= 0)
  2079. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2080. }
  2081. }
  2082. void selectNext()
  2083. {
  2084. ForEachItemIn(i, iters)
  2085. {
  2086. if (iterMatchesCurrentScope(i))
  2087. {
  2088. #ifdef _DEBUG
  2089. StringBuffer prevScope(iters.item(i).queryScope());
  2090. #endif
  2091. if (!iters.item(i).next())
  2092. activeIterMask &= ~(1U << i);
  2093. #ifdef _DEBUG
  2094. checkScopeOrder(i, prevScope);
  2095. #endif
  2096. }
  2097. }
  2098. }
  2099. void selectNextSibling()
  2100. {
  2101. ForEachItemIn(i, iters)
  2102. {
  2103. if (iterMatchesCurrentScope(i))
  2104. {
  2105. #ifdef _DEBUG
  2106. StringBuffer prevScope(iters.item(i).queryScope());
  2107. #endif
  2108. if (!iters.item(i).nextSibling())
  2109. activeIterMask &= ~(1U << i);
  2110. #ifdef _DEBUG
  2111. checkScopeOrder(i, prevScope);
  2112. #endif
  2113. }
  2114. }
  2115. }
  2116. void selectNextParent()
  2117. {
  2118. ForEachItemIn(i, iters)
  2119. {
  2120. if (iterMatchesCurrentScope(i))
  2121. {
  2122. #ifdef _DEBUG
  2123. StringBuffer prevScope(iters.item(i).queryScope());
  2124. #endif
  2125. if (!iters.item(i).nextParent())
  2126. activeIterMask &= ~(1U << i);
  2127. #ifdef _DEBUG
  2128. checkScopeOrder(i, prevScope);
  2129. #endif
  2130. }
  2131. }
  2132. }
  2133. protected:
  2134. const WuScopeFilter & filter;
  2135. IArrayOf<IConstWUScopeIterator> iters;
  2136. unsigned curIter = 0;
  2137. unsigned firstMatchIter = 0;
  2138. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2139. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2140. StringArray activeScopes;
  2141. };
  2142. //---------------------------------------------------------------------------------------------------------------------
  2143. class AggregateFilter
  2144. {
  2145. public:
  2146. AggregateFilter(StatisticKind _search) : search(_search) {}
  2147. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2148. {
  2149. return (kind == search);
  2150. }
  2151. protected:
  2152. StatisticKind search;
  2153. //MORE: Allow filtering by scope?
  2154. };
  2155. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2156. {
  2157. public:
  2158. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2159. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2160. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2161. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2162. protected:
  2163. AggregateFilter filter;
  2164. };
  2165. class SimpleAggregator : public StatisticAggregator
  2166. {
  2167. public:
  2168. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2169. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2170. {
  2171. if (filter.matches(kind, value, extra))
  2172. summary.noteValue(value);
  2173. }
  2174. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2175. //with a noteAggregate(value, variant, value, grouping)?
  2176. protected:
  2177. StatsAggregation summary;
  2178. };
  2179. class SimpleReferenceAggregator : public StatisticAggregator
  2180. {
  2181. public:
  2182. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2183. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2184. {
  2185. if (filter.matches(kind, value, extra))
  2186. summary.noteValue(value);
  2187. }
  2188. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2189. //with a noteAggregate(value, variant, value, grouping)?
  2190. protected:
  2191. StatsAggregation & summary;
  2192. };
  2193. class GroupedAggregator : public StatisticAggregator
  2194. {
  2195. public:
  2196. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2197. {
  2198. if (filter.matches(kind, value, extra))
  2199. {
  2200. StatsAggregation & match = summary; // look up in hash table.
  2201. match.noteValue(value);
  2202. }
  2203. }
  2204. protected:
  2205. //HashTable of (possible groupings->summary)
  2206. StatsAggregation summary;
  2207. };
  2208. class CompoundAggregator : implements StatisticAggregator
  2209. {
  2210. public:
  2211. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2212. {
  2213. ForEachItemIn(i, aggregators)
  2214. aggregators.item(i).noteStatistic(kind, value, extra);
  2215. }
  2216. protected:
  2217. IArrayOf<StatisticAggregator> aggregators;
  2218. };
  2219. // Aggregate costs excluding all hThor costs
  2220. // Note: the only reason that this class is required is that it is not possible to determine the creator
  2221. // of a scope when iterating with IConstWUScopeIterator. (When this functionlity becomes available,
  2222. // consider filtering within aggregateCost and eliminating this class.)
  2223. class CostAggregatorExcludeHThor : public CInterfaceOf<IWuScopeVisitor>
  2224. {
  2225. public:
  2226. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2227. {
  2228. if (extra.getCreatorType() != SCThthor)
  2229. totalCost += value;
  2230. }
  2231. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2232. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2233. virtual void noteException(IConstWUException & exception) { throwUnexpected(); }
  2234. virtual cost_type getTotalCost() const { return totalCost; }
  2235. protected:
  2236. cost_type totalCost = 0;
  2237. };
  2238. // Aggregrate Thor or hThor costs
  2239. cost_type aggregateCost(const IConstWorkUnit * wu, const char *scope, bool excludeHThor)
  2240. {
  2241. // depth 1: workflow, depth 2: graph, depth 3: subgraph
  2242. WuScopeFilter filter;
  2243. if (scope && *scope) // All costs under specified scope (used to calculate all costs for a workflow)
  2244. {
  2245. filter.addScope(scope);
  2246. filter.setIncludeNesting(3);
  2247. filter.addOutputStatistic(StCostExecute);
  2248. filter.addRequiredStat(StCostExecute);
  2249. }
  2250. else
  2251. filter.addFilter("stat[CostExecute],depth[1..3],nested[0],where[CostExecute]");
  2252. filter.addSource("global");
  2253. filter.finishedFilter();
  2254. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  2255. // Note: use of CostAggregatorExcludeHThor will be a slower, so use only when necessary
  2256. if (excludeHThor)
  2257. {
  2258. CostAggregatorExcludeHThor aggregator;
  2259. for (it->first(); it->isValid(); )
  2260. {
  2261. it->playProperties(aggregator);
  2262. stat_type value;
  2263. if (it->getStat(StCostExecute, value))
  2264. it->nextSibling();
  2265. else
  2266. it->next();
  2267. }
  2268. return aggregator.getTotalCost();
  2269. }
  2270. else
  2271. {
  2272. cost_type totalCost = 0;
  2273. for (it->first(); it->isValid(); )
  2274. {
  2275. stat_type value = 0.0;
  2276. if (it->getStat(StCostExecute, value))
  2277. {
  2278. totalCost += value;
  2279. it->nextSibling();
  2280. }
  2281. else
  2282. it->next();
  2283. }
  2284. return totalCost;
  2285. }
  2286. }
  2287. //---------------------------------------------------------------------------------------------------------------------
  2288. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2289. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2290. {
  2291. const char * start = finger;
  2292. if (!*start)
  2293. return false;
  2294. const char * cur = start;
  2295. const char * bra = nullptr;
  2296. const char * end = nullptr;
  2297. unsigned braDepth = 0;
  2298. char next;
  2299. arg.clear();
  2300. for (;;)
  2301. {
  2302. next = *cur;
  2303. if (!next || ((next == ',') && (braDepth == 0)))
  2304. break;
  2305. switch (next)
  2306. {
  2307. case '[':
  2308. if (braDepth == 0)
  2309. {
  2310. if (bra)
  2311. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2312. bra = cur;
  2313. }
  2314. braDepth++;
  2315. break;
  2316. case ']':
  2317. if (braDepth > 0)
  2318. {
  2319. if (--braDepth == 0)
  2320. {
  2321. end = cur;
  2322. arg.append(cur - (bra+1), bra+1);
  2323. }
  2324. }
  2325. break;
  2326. }
  2327. cur++;
  2328. }
  2329. if (braDepth != 0)
  2330. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2331. option.clear();
  2332. if (bra)
  2333. {
  2334. if (cur != end+1)
  2335. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2336. option.append(bra-start, start);
  2337. }
  2338. else
  2339. option.append(cur-start, start);
  2340. if (next)
  2341. finger = cur+1;
  2342. else
  2343. finger = cur;
  2344. return true;
  2345. }
  2346. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2347. {
  2348. if (start == end)
  2349. return dft;
  2350. char * next;
  2351. unsigned value = (unsigned)strtoll(start, &next, 10);
  2352. if (next != end)
  2353. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2354. return value;
  2355. }
  2356. static unsigned readValue(const char * start, const char * type)
  2357. {
  2358. if (*start == '\0')
  2359. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2360. char * next;
  2361. unsigned value = (unsigned)strtoll(start, &next, 10);
  2362. if (*next != '\0')
  2363. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2364. return value;
  2365. }
  2366. /*
  2367. Scope service matching Syntax: * indicates
  2368. Which items are matched:
  2369. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2370. depth[n | low..high] - range of depths to search for a match
  2371. source[global|stats|graph|all]* - which sources to search within the workunit
  2372. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2373. Which items are include in the results:
  2374. matched[true|false] - are the matched scopes returned?
  2375. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2376. includetype[<scope-type>] - which scope types should be included?
  2377. Which properties of the items are returned:
  2378. properties[statistics|hints|attributes|scope|all]
  2379. statistic[<statistic-kind>|none|all] - include statistic
  2380. attribute[<attribute-name>|none|all] - include attribute
  2381. hint[<hint-name>] - include hint
  2382. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2383. measure[<measure>] - all statistics with a particular measure
  2384. version[<version>] - minimum version to return
  2385. */
  2386. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2387. //Some of the following contains aliases for the same option e.g. stat and statistic
  2388. static constexpr EnumMapping filterOptions[] = {
  2389. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2390. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2391. { FOmatched, "matched" }, { FOnested, "nested" },
  2392. { FOinclude, "include" }, { FOinclude, "includetype" },
  2393. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2394. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2395. { FOproperty, "prop" }, { FOproperty, "property" },
  2396. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2397. static constexpr EnumMapping sourceMappings[] = {
  2398. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2399. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2400. static constexpr EnumMapping propertyMappings[] = {
  2401. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2402. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2403. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2404. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2405. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2406. WuScopeFilter::WuScopeFilter(const char * filter)
  2407. {
  2408. addFilter(filter);
  2409. finishedFilter();
  2410. }
  2411. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2412. {
  2413. if (!filter)
  2414. return *this;
  2415. StringBuffer option;
  2416. StringBuffer arg;
  2417. while (extractOption(filter, option, arg))
  2418. {
  2419. switch (getEnum(option, filterOptions, FOunknown))
  2420. {
  2421. case FOscope:
  2422. addScope(arg);
  2423. break;
  2424. case FOstype:
  2425. addScopeType(arg);
  2426. break;
  2427. case FOid:
  2428. addId(arg);
  2429. break;
  2430. case FOdepth:
  2431. {
  2432. //Allow depth[n], depth[a,b] or depth[a..b]
  2433. const char * comma = strchr(arg, ',');
  2434. const char * dotdot = strstr(arg, "..");
  2435. if (comma)
  2436. {
  2437. unsigned low = readOptValue(arg, comma, 0, "depth");
  2438. if (comma[1])
  2439. {
  2440. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2441. }
  2442. else
  2443. scopeFilter.setDepth(low, UINT_MAX);
  2444. }
  2445. else if (dotdot)
  2446. {
  2447. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2448. if (dotdot[2])
  2449. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2450. else
  2451. scopeFilter.setDepth(low, UINT_MAX);
  2452. }
  2453. else
  2454. {
  2455. scopeFilter.setDepth(readValue(arg, "depth"));
  2456. }
  2457. break;
  2458. }
  2459. case FOsource:
  2460. addSource(arg);
  2461. break;
  2462. case FOwhere: // where[stat<op>value]
  2463. addRequiredStat(arg);
  2464. break;
  2465. case FOmatched:
  2466. setIncludeMatch(strToBool(arg));
  2467. break;
  2468. case FOnested:
  2469. if (strieq(arg, "all"))
  2470. setIncludeNesting(UINT_MAX);
  2471. else if (isdigit(*arg))
  2472. setIncludeNesting(atoi(arg));
  2473. else
  2474. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2475. break;
  2476. case FOinclude:
  2477. setIncludeScopeType(arg);
  2478. break;
  2479. case FOproperties:
  2480. {
  2481. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2482. if (prop == PTunknown)
  2483. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2484. addOutputProperties(prop);
  2485. break;
  2486. }
  2487. case FOstatistic:
  2488. addOutputStatistic(arg);
  2489. break;
  2490. case FOattribute:
  2491. addOutputAttribute(arg);
  2492. break;
  2493. case FOhint:
  2494. addOutputHint(arg);
  2495. break;
  2496. case FOproperty:
  2497. addOutput(arg);
  2498. break;
  2499. case FOmeasure:
  2500. setMeasure(arg);
  2501. break;
  2502. case FOversion:
  2503. if (isdigit(*arg))
  2504. minVersion = atoi64(arg);
  2505. else
  2506. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2507. break;
  2508. default:
  2509. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2510. }
  2511. }
  2512. return *this;
  2513. }
  2514. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2515. {
  2516. if (scope)
  2517. {
  2518. validateScope(scope);
  2519. scopeFilter.addScope(scope);
  2520. }
  2521. return *this;
  2522. }
  2523. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2524. {
  2525. if (scopeType)
  2526. {
  2527. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2528. if (sst == SSTmax)
  2529. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2530. scopeFilter.addScopeType(sst);
  2531. }
  2532. return *this;
  2533. }
  2534. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2535. {
  2536. validateScopeId(id);
  2537. scopeFilter.addId(id);
  2538. return *this;
  2539. }
  2540. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2541. {
  2542. WuAttr attr = queryWuAttribute(prop, WaNone);
  2543. if (attr != WaNone)
  2544. {
  2545. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2546. if (singleKindAttr != WaNone)
  2547. addOutputAttribute(singleKindAttr);
  2548. else
  2549. addOutputAttribute(attr);
  2550. } else if (queryStatisticKind(prop, StMax) != StMax)
  2551. addOutputStatistic(prop);
  2552. else
  2553. addOutputHint(prop);
  2554. return *this;
  2555. }
  2556. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2557. {
  2558. if (!prop)
  2559. return *this;
  2560. StatisticKind kind = queryStatisticKind(prop, StMax);
  2561. if (kind == StMax)
  2562. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2563. return addOutputStatistic(kind);
  2564. }
  2565. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2566. {
  2567. if (stat != StKindNone)
  2568. {
  2569. if (stat != StKindAll)
  2570. desiredStats.append(stat);
  2571. else
  2572. desiredStats.kill();
  2573. properties |= PTstatistics;
  2574. }
  2575. else
  2576. properties &= ~PTstatistics;
  2577. return *this;
  2578. }
  2579. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2580. {
  2581. if (!prop)
  2582. return *this;
  2583. WuAttr attr = queryWuAttribute(prop, WaMax);
  2584. if (attr == WaMax)
  2585. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2586. return addOutputAttribute(attr);
  2587. }
  2588. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2589. {
  2590. if (attr != WaNone)
  2591. {
  2592. if (attr != WaAll)
  2593. desiredAttrs.append(attr);
  2594. else
  2595. desiredAttrs.kill();
  2596. properties |= PTattributes;
  2597. }
  2598. else
  2599. properties &= ~PTattributes;
  2600. return *this;
  2601. }
  2602. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2603. {
  2604. if (strieq(prop, "none"))
  2605. {
  2606. desiredHints.kill();
  2607. properties &= ~PThints;
  2608. }
  2609. else
  2610. {
  2611. if (!strieq(prop, "all"))
  2612. desiredHints.append(prop);
  2613. else
  2614. desiredHints.kill();
  2615. properties |= PThints;
  2616. }
  2617. return *this;
  2618. }
  2619. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2620. {
  2621. include.matchedScope = value;
  2622. return *this;
  2623. }
  2624. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2625. {
  2626. include.nestedDepth = depth;
  2627. return *this;
  2628. }
  2629. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2630. {
  2631. if (scopeType)
  2632. {
  2633. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2634. if (sst == SSTmax)
  2635. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2636. include.scopeTypes.append(sst);
  2637. }
  2638. return *this;
  2639. }
  2640. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2641. {
  2642. if (measure)
  2643. {
  2644. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2645. if (desiredMeasure == SMeasureNone)
  2646. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2647. properties |= PTstatistics;
  2648. }
  2649. return *this;
  2650. }
  2651. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2652. {
  2653. if (properties == PTnone)
  2654. properties = mask;
  2655. else
  2656. properties |= mask;
  2657. return *this;
  2658. }
  2659. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2660. {
  2661. requiredStats.emplace_back(statKind, lowValue, highValue);
  2662. return *this;
  2663. }
  2664. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2665. {
  2666. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2667. return *this;
  2668. }
  2669. //process a filter in one of the following forms:
  2670. // <statistic-name>
  2671. // <statistic-name> (=|<|<=|>|>=) <value>
  2672. // <statistic-name>=[<low>]..[<high>]
  2673. void WuScopeFilter::addRequiredStat(const char * filter)
  2674. {
  2675. const char * stat = filter;
  2676. const char * cur = stat;
  2677. while (isalpha(*cur))
  2678. cur++;
  2679. StringBuffer statisticName(cur-stat, stat);
  2680. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2681. if (statKind == StKindNone)
  2682. throw makeStringExceptionV(0, "Unknown statistic name '%s'", statisticName.str());
  2683. //Skip any spaces before a comparison operator.
  2684. while (*cur && isspace(*cur))
  2685. cur++;
  2686. //Save the operator, and skip over any non digits.
  2687. const char * op = cur;
  2688. switch (*op)
  2689. {
  2690. case '=':
  2691. cur++;
  2692. break;
  2693. case '<':
  2694. case '>':
  2695. if (op[1] == '=')
  2696. cur += 2;
  2697. else
  2698. cur++;
  2699. break;
  2700. case '\0':
  2701. break;
  2702. default:
  2703. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2704. }
  2705. const char * next;
  2706. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2707. stat_type lowValue = 0;
  2708. stat_type highValue = MaxStatisticValue;
  2709. switch (op[0])
  2710. {
  2711. case '=':
  2712. {
  2713. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2714. if (next[0] == ',')
  2715. {
  2716. lowValue = value;
  2717. next++;
  2718. if (*next != '\0')
  2719. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2720. }
  2721. else if (strncmp(next, "..", 2) == 0)
  2722. {
  2723. lowValue = value;
  2724. next += 2;
  2725. if (*next != '\0')
  2726. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2727. }
  2728. else
  2729. {
  2730. lowValue = value;
  2731. highValue = value;
  2732. }
  2733. break;
  2734. }
  2735. case '<':
  2736. if (op[1] == '=')
  2737. highValue = value;
  2738. else
  2739. highValue = value-1;
  2740. break;
  2741. case '>':
  2742. if (op[1] == '=')
  2743. lowValue = value;
  2744. else
  2745. lowValue = value+1;
  2746. break;
  2747. }
  2748. if (*next)
  2749. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2750. requiredStats.emplace_back(statKind, lowValue, highValue);
  2751. }
  2752. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2753. {
  2754. WuScopeSourceFlags mask = querySource(source);
  2755. if (mask == SSFunknown)
  2756. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2757. if (!mask)
  2758. sourceFlags = mask;
  2759. else
  2760. sourceFlags |= mask;
  2761. return *this;
  2762. }
  2763. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2764. {
  2765. scopeFilter.setDepth(low, high);
  2766. return *this;
  2767. }
  2768. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2769. {
  2770. //If there is a post filter on the scopeType, then check if it matches
  2771. if (include.scopeTypes.ordinality() == 1)
  2772. return (include.scopeTypes.item(0) == scopeType);
  2773. //If filter doesn't match nested items, then check if the scope filter matches.
  2774. if (include.nestedDepth == 0)
  2775. {
  2776. if (scopeFilter.matchOnly(scopeType))
  2777. return true;
  2778. }
  2779. return false;
  2780. }
  2781. //Called once the filter has been updated to optimize the filter
  2782. void WuScopeFilter::finishedFilter()
  2783. {
  2784. scopeFilter.finishedFilter();
  2785. assertex(!optimized);
  2786. optimized = true;
  2787. if ((include.nestedDepth == 0) && !include.matchedScope)
  2788. include.nestedDepth = UINT_MAX;
  2789. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2790. if (scopeFilter.canAlwaysPreFilter())
  2791. preFilterScope = true;
  2792. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2793. if (!sourceFlags)
  2794. {
  2795. sourceFlags = SSFsearchAll;
  2796. //Use the other options to reduce the number of elements that are searched.
  2797. //If not interested in scopes on their own then...
  2798. if (!(properties & PTscope))
  2799. {
  2800. //Global stats and graph stats only contain stats => remove if not interested in them
  2801. if (!(properties & PTstatistics))
  2802. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2803. //graph, workflow only contains attributes and hints => remove if not interested
  2804. if (!(properties & (PTattributes|PThints)))
  2805. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2806. }
  2807. if (!(properties & PTnotes))
  2808. sourceFlags &= ~SSFsearchExceptions;
  2809. }
  2810. //Optimize sources if they haven't been explicitly specified
  2811. //Most of the following are dependent on internal knowledge of the way that information is represented
  2812. if (matchOnly(SSTworkflow))
  2813. {
  2814. //Workflow is not nested within a graph
  2815. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2816. setDepth(1, 1);
  2817. }
  2818. else if (matchOnly(SSTgraph))
  2819. {
  2820. //Graph starts are stored globally, not in the graph stats.
  2821. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2822. if (!(properties & (PTattributes|PThints)))
  2823. sourceFlags &= ~(SSFsearchGraph);
  2824. //This should really be setDepth(2,2) but workunits prior to 7.4 did not have graph ids prefixed by the wfid
  2825. //Remove once 7.2 is a distant memory (see HPCC-22887)
  2826. setDepth(1, 2);
  2827. }
  2828. else if (matchOnly(SSTsubgraph))
  2829. {
  2830. sourceFlags &= ~(SSFsearchWorkflow);
  2831. }
  2832. else if (matchOnly(SSTcompilestage))
  2833. {
  2834. //compile stages are not stored in the graph
  2835. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2836. }
  2837. else if (matchOnly(SSTactivity))
  2838. {
  2839. //information about activities is not stored globally
  2840. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2841. }
  2842. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2843. if (include.nestedDepth == 0)
  2844. {
  2845. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2846. sourceFlags &= ~(SSFsearchGraphStats);
  2847. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2848. {
  2849. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2850. //then do not include the subgraph timings
  2851. if (desiredStats.ordinality())
  2852. {
  2853. bool needGraphStats = false;
  2854. ForEachItemIn(i, desiredStats)
  2855. {
  2856. unsigned stat = desiredStats.item(i);
  2857. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2858. needGraphStats = true;
  2859. }
  2860. if (!needGraphStats)
  2861. {
  2862. sourceFlags &= ~(SSFsearchGraphStats);
  2863. if (matchOnly(SSTsubgraph))
  2864. sourceFlags &= SSFsearchGlobalStats;
  2865. }
  2866. }
  2867. }
  2868. }
  2869. if (scopeFilter.compareDepth(1) < 0)
  2870. {
  2871. //If minimum match depth is > 1 then it will never match workflow
  2872. sourceFlags &= ~(SSFsearchWorkflow);
  2873. }
  2874. //The xml graph is never updated, so do not check it if minVersion != 0
  2875. if (minVersion != 0)
  2876. {
  2877. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2878. }
  2879. }
  2880. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2881. {
  2882. if (!(properties & PTstatistics))
  2883. return false;
  2884. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2885. return false;
  2886. if (desiredStats.empty())
  2887. return true;
  2888. return desiredStats.contains(kind);
  2889. }
  2890. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2891. {
  2892. if (!(properties & PTattributes))
  2893. return false;
  2894. if (desiredAttrs.empty())
  2895. return true;
  2896. return desiredAttrs.contains(attr);
  2897. }
  2898. bool WuScopeFilter::includeHint(const char * kind) const
  2899. {
  2900. if (!(properties & PThints))
  2901. return false;
  2902. if (desiredHints.empty())
  2903. return true;
  2904. return desiredHints.contains(kind);
  2905. }
  2906. bool WuScopeFilter::includeScope(const char * scope) const
  2907. {
  2908. if (include.scopeTypes)
  2909. {
  2910. const char * tail = queryScopeTail(scope);
  2911. StatsScopeId id(tail);
  2912. if (!include.scopeTypes.contains(id.queryScopeType()))
  2913. return false;
  2914. }
  2915. return true;
  2916. }
  2917. const static ScopeFilter nullScopeFilter {};
  2918. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2919. {
  2920. if (preFilterScope)
  2921. return scopeFilter;
  2922. else
  2923. return nullScopeFilter;
  2924. }
  2925. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2926. {
  2927. return scopeFilter.compare(scope);
  2928. }
  2929. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2930. {
  2931. scopeFilter.describe(out);
  2932. if (requiredStats.size())
  2933. {
  2934. out.append(",where[");
  2935. bool first = false;
  2936. for (const auto & stat : requiredStats)
  2937. {
  2938. if (!first)
  2939. out.append(",");
  2940. stat.describe(out);
  2941. first = false;
  2942. }
  2943. out.append("]");
  2944. }
  2945. {
  2946. StringBuffer sources;
  2947. for (unsigned mask=1; mask; mask *= 2)
  2948. {
  2949. if (sourceFlags & mask)
  2950. {
  2951. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2952. if (source)
  2953. sources.append(",").append(source);
  2954. }
  2955. }
  2956. if (sources)
  2957. out.append(",source[").append(sources.str()+1).append("]");
  2958. }
  2959. if (include.nestedDepth != UINT_MAX)
  2960. out.appendf(",nested[%u]", include.nestedDepth);
  2961. if (include.scopeTypes)
  2962. {
  2963. out.append(",include[");
  2964. ForEachItemIn(i, include.scopeTypes)
  2965. {
  2966. if (i)
  2967. out.append(",");
  2968. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  2969. }
  2970. out.append("]");
  2971. }
  2972. {
  2973. StringBuffer props;
  2974. if (properties == PTnone)
  2975. props.append(",none");
  2976. else if (properties == PTall)
  2977. props.append(",all");
  2978. else
  2979. {
  2980. if (properties & PTstatistics)
  2981. props.append(",stat");
  2982. if (properties & PTattributes)
  2983. props.append(",attr");
  2984. if (properties & PThints)
  2985. props.append(",hint");
  2986. if (properties & PTscope)
  2987. props.append(",scope");
  2988. if (properties & PTnotes)
  2989. props.append(",note");
  2990. }
  2991. out.append(",properties[").append(props.str()+1).append("]");
  2992. }
  2993. if (desiredStats)
  2994. {
  2995. out.append(",stat[");
  2996. ForEachItemIn(i, desiredStats)
  2997. {
  2998. if (i)
  2999. out.append(",");
  3000. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  3001. }
  3002. out.append("]");
  3003. }
  3004. if (desiredAttrs)
  3005. {
  3006. out.append(",attr[");
  3007. ForEachItemIn(i, desiredAttrs)
  3008. {
  3009. if (i)
  3010. out.append(",");
  3011. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  3012. }
  3013. out.append("]");
  3014. }
  3015. if (desiredHints)
  3016. {
  3017. out.append(",hint[");
  3018. ForEachItemIn(i, desiredHints)
  3019. {
  3020. if (i)
  3021. out.append(",");
  3022. out.append(desiredHints.item(i));
  3023. }
  3024. out.append("]");
  3025. }
  3026. if (desiredMeasure != SMeasureAll)
  3027. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  3028. if (minVersion != 0)
  3029. out.appendf(",version(%" I64F "u)", minVersion);
  3030. return out;
  3031. }
  3032. //--------------------------------------------------------------------------------------------------------------------
  3033. EnumMapping states[] = {
  3034. { WUStateUnknown, "unknown" },
  3035. { WUStateCompiled, "compiled" },
  3036. { WUStateRunning, "running" },
  3037. { WUStateCompleted, "completed" },
  3038. { WUStateFailed, "failed" },
  3039. { WUStateArchived, "archived" },
  3040. { WUStateAborting, "aborting" },
  3041. { WUStateAborted, "aborted" },
  3042. { WUStateBlocked, "blocked" },
  3043. { WUStateSubmitted, "submitted" },
  3044. { WUStateScheduled, "scheduled" },
  3045. { WUStateCompiling, "compiling" },
  3046. { WUStateWait, "wait" },
  3047. { WUStateUploadingFiles, "uploading_files" },
  3048. { WUStateDebugPaused, "debugging" },
  3049. { WUStateDebugRunning, "debug_running" },
  3050. { WUStatePaused, "paused" },
  3051. { WUStateSize, NULL }
  3052. };
  3053. EnumMapping actions[] = {
  3054. { WUActionUnknown, "unknown" },
  3055. { WUActionCompile, "compile" },
  3056. { WUActionCheck, "check" },
  3057. { WUActionRun, "run" },
  3058. { WUActionExecuteExisting, "execute" },
  3059. { WUActionPause, "pause" },
  3060. { WUActionPauseNow, "pausenow" },
  3061. { WUActionResume, "resume" },
  3062. { WUActionSize, NULL },
  3063. };
  3064. EnumMapping priorityClasses[] = {
  3065. { PriorityClassUnknown, "unknown" },
  3066. { PriorityClassLow, "low" },
  3067. { PriorityClassNormal, "normal" },
  3068. { PriorityClassHigh, "high" },
  3069. { PriorityClassSize, NULL },
  3070. };
  3071. const char * getWorkunitStateStr(WUState state)
  3072. {
  3073. dbgassertex(state < WUStateSize);
  3074. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3075. }
  3076. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3077. {
  3078. const char *defval = map->str;
  3079. while (map->str)
  3080. {
  3081. if (value==map->val)
  3082. {
  3083. p->setProp(propname, map->str);
  3084. return;
  3085. }
  3086. map++;
  3087. }
  3088. assertex(!"Unexpected value in setEnum");
  3089. p->setProp(propname, defval);
  3090. }
  3091. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3092. {
  3093. return getEnum(p->queryProp(propname),map);
  3094. }
  3095. const char * getWorkunitActionStr(WUAction action)
  3096. {
  3097. return getEnumText(action, actions);
  3098. }
  3099. WUAction getWorkunitAction(const char *actionStr)
  3100. {
  3101. return (WUAction) getEnum(actionStr, actions);
  3102. }
  3103. //==========================================================================================
  3104. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3105. {
  3106. public:
  3107. CLightweightWorkunitInfo(IPropertyTree &p)
  3108. {
  3109. wuid.set(p.queryName());
  3110. user.set(p.queryProp("@submitID"));
  3111. jobName.set(p.queryProp("@jobName"));
  3112. clusterName.set(p.queryProp("@clusterName"));
  3113. timeScheduled.set(p.queryProp("@timeScheduled"));
  3114. state = (WUState) getEnum(&p, "@state", states);
  3115. action = (WUAction) getEnum(&p, "Action", actions);
  3116. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3117. priorityLevel = calcPriorityValue(&p);
  3118. wuscope.set(p.queryProp("@scope"));
  3119. appvalues.loadBranch(&p,"Application");
  3120. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3121. _isProtected = p.getPropBool("@protected", false);
  3122. }
  3123. virtual const char *queryWuid() const { return wuid.str(); }
  3124. virtual const char *queryUser() const { return user.str(); }
  3125. virtual const char *queryJobName() const { return jobName.str(); }
  3126. virtual const char *queryClusterName() const { return clusterName.str(); }
  3127. virtual const char *queryWuScope() const { return wuscope.str(); }
  3128. virtual WUState getState() const { return state; }
  3129. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3130. virtual WUAction getAction() const { return action; }
  3131. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3132. virtual WUPriorityClass getPriority() const { return priority; }
  3133. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3134. virtual int getPriorityLevel() const { return priorityLevel; }
  3135. virtual bool isProtected() const { return _isProtected; }
  3136. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3137. {
  3138. if (timeScheduled.length())
  3139. val.setGmtString(timeScheduled.str());
  3140. return val;
  3141. }
  3142. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3143. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3144. protected:
  3145. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3146. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3147. unsigned totalThorTime;
  3148. WUState state;
  3149. WUAction action;
  3150. WUPriorityClass priority;
  3151. int priorityLevel;
  3152. bool _isProtected;
  3153. };
  3154. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3155. {
  3156. return new CLightweightWorkunitInfo(p);
  3157. }
  3158. class CDaliWuGraphStats : public CWuGraphStats
  3159. {
  3160. public:
  3161. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3162. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3163. {
  3164. }
  3165. protected:
  3166. Owned<IRemoteConnection> conn;
  3167. };
  3168. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3169. {
  3170. abortId = 0;
  3171. stateId = 0;
  3172. actionId = 0;
  3173. assertex((flags & ~SubscribeOptionAbort) == 0);
  3174. if (flags & SubscribeOptionAbort)
  3175. {
  3176. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3177. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3178. }
  3179. }
  3180. CWorkUnitWatcher::~CWorkUnitWatcher()
  3181. {
  3182. assertex(abortId==0 && stateId==0 && actionId==0);
  3183. }
  3184. void CWorkUnitWatcher::unsubscribe()
  3185. {
  3186. CriticalBlock b(crit);
  3187. if (abortId)
  3188. querySDS().unsubscribe(abortId);
  3189. if (stateId)
  3190. querySDS().unsubscribe(stateId);
  3191. if (actionId)
  3192. querySDS().unsubscribe(actionId);
  3193. abortId = 0;
  3194. stateId = 0;
  3195. actionId = 0;
  3196. }
  3197. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3198. {
  3199. CriticalBlock b(crit);
  3200. if (id==stateId)
  3201. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3202. else if (id==actionId)
  3203. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3204. else if (id==abortId)
  3205. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3206. }
  3207. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3208. {
  3209. public:
  3210. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3211. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3212. {
  3213. if (flags & SubscribeOptionState)
  3214. {
  3215. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3216. stateId = querySDS().subscribe(xpath.str(), *this);
  3217. }
  3218. if (flags & SubscribeOptionAction)
  3219. {
  3220. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3221. actionId = querySDS().subscribe(xpath.str(), *this);
  3222. }
  3223. }
  3224. };
  3225. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3226. {
  3227. CriticalBlock block(crit);
  3228. assertex(options==SubscribeOptionAbort);
  3229. if (!abortWatcher)
  3230. {
  3231. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3232. abortDirty = true;
  3233. }
  3234. }
  3235. void CPersistedWorkUnit::unsubscribe()
  3236. {
  3237. CriticalBlock block(crit);
  3238. if (abortWatcher)
  3239. {
  3240. abortWatcher->unsubscribe();
  3241. abortWatcher.clear();
  3242. }
  3243. }
  3244. bool CPersistedWorkUnit::aborting() const
  3245. {
  3246. CriticalBlock block(crit);
  3247. if (abortDirty)
  3248. {
  3249. StringBuffer apath;
  3250. apath.append("/WorkUnitAborts/").append(p->queryName());
  3251. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3252. if (acon)
  3253. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3254. else
  3255. abortState = false;
  3256. abortDirty = false;
  3257. }
  3258. return abortState;
  3259. }
  3260. class CDaliWorkUnit : public CPersistedWorkUnit
  3261. {
  3262. public:
  3263. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3264. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3265. {
  3266. loadPTree(connection->getRoot());
  3267. }
  3268. ~CDaliWorkUnit()
  3269. {
  3270. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3271. // We use the beforeDispose() in base class to help ensure this
  3272. p.clear();
  3273. }
  3274. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3275. {
  3276. Owned<IRemoteConnection> conn = getProgressConnection();
  3277. if (conn)
  3278. {
  3279. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3280. if (progress)
  3281. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3282. }
  3283. return NULL;
  3284. }
  3285. virtual WUGraphState queryGraphState(const char *graphName) const
  3286. {
  3287. Owned<IRemoteConnection> conn = getProgressConnection();
  3288. if (conn)
  3289. {
  3290. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3291. if (progress)
  3292. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3293. }
  3294. return WUGraphUnknown;
  3295. }
  3296. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3297. {
  3298. Owned<IRemoteConnection> conn = getProgressConnection();
  3299. if (conn)
  3300. {
  3301. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3302. if (progress)
  3303. {
  3304. StringBuffer path;
  3305. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3306. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3307. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3308. }
  3309. }
  3310. return WUGraphUnknown;
  3311. }
  3312. virtual void clearGraphProgress() const
  3313. {
  3314. CriticalBlock block(crit);
  3315. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3316. StringBuffer path("/GraphProgress/");
  3317. path.append(p->queryName());
  3318. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3319. if (delconn)
  3320. delconn->close(true);
  3321. }
  3322. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3323. {
  3324. Owned<IRemoteConnection> conn = getProgressConnection();
  3325. if (!conn)
  3326. return false;
  3327. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3328. if (name)
  3329. {
  3330. graphName.set(name);
  3331. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3332. return true;
  3333. }
  3334. else
  3335. return false;
  3336. }
  3337. virtual void forceReload()
  3338. {
  3339. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3340. CriticalBlock block(crit);
  3341. clearCached(true);
  3342. connection->reload();
  3343. progressConnection.clear();
  3344. abortDirty = true;
  3345. p.setown(connection->getRoot());
  3346. }
  3347. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3348. {
  3349. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3350. clearGraphProgress();
  3351. connection->close(true);
  3352. connection.clear();
  3353. }
  3354. virtual void commit()
  3355. {
  3356. CPersistedWorkUnit::commit();
  3357. if (connection)
  3358. connection->commit();
  3359. }
  3360. virtual void _lockRemote()
  3361. {
  3362. StringBuffer wuRoot;
  3363. getXPath(wuRoot, p->queryName());
  3364. if (connection)
  3365. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3366. else
  3367. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3368. if (!connection)
  3369. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3370. clearCached(true);
  3371. p.setown(connection->getRoot());
  3372. }
  3373. virtual void _unlockRemote()
  3374. {
  3375. if (connection)
  3376. {
  3377. try
  3378. {
  3379. try
  3380. {
  3381. connection->commit();
  3382. }
  3383. catch (IException *e)
  3384. {
  3385. EXCLOG(e, "Error during workunit commit");
  3386. connection->rollback();
  3387. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3388. throw;
  3389. }
  3390. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3391. }
  3392. catch (IException *E)
  3393. {
  3394. StringBuffer s;
  3395. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3396. throw;
  3397. }
  3398. }
  3399. }
  3400. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3401. {
  3402. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3403. conn->queryRoot()->setPropInt("@_state", state);
  3404. }
  3405. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3406. {
  3407. CriticalBlock block(crit);
  3408. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3409. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3410. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3411. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3412. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3413. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3414. IPropertyTree *node = progress->queryPropTree(path.str());
  3415. if (!node)
  3416. {
  3417. node = progress->addPropTree("node");
  3418. node->setPropInt64("@id", nodeId);
  3419. }
  3420. node->setPropInt("@_state", (unsigned)state);
  3421. switch (state)
  3422. {
  3423. case WUGraphRunning:
  3424. {
  3425. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3426. running->setProp("@graph", graphName);
  3427. running->setPropInt64("@subId", nodeId);
  3428. break;
  3429. }
  3430. case WUGraphComplete:
  3431. {
  3432. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3433. break;
  3434. }
  3435. }
  3436. }
  3437. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3438. {
  3439. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3440. }
  3441. protected:
  3442. IRemoteConnection *getProgressConnection() const
  3443. {
  3444. CriticalBlock block(crit);
  3445. if (!progressConnection)
  3446. {
  3447. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3448. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3449. }
  3450. return progressConnection.getLink();
  3451. }
  3452. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3453. {
  3454. CriticalBlock block(crit);
  3455. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3456. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3457. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3458. IPropertyTree * root = conn->queryRoot();
  3459. assertex(wfid);
  3460. if (!root->hasProp("@wfid"))
  3461. {
  3462. root->setPropInt("@wfid", wfid);
  3463. }
  3464. else
  3465. {
  3466. //Ideally the following code would check that the wfids are passed consistently.
  3467. //However there is an obscure problem with out of line functions being called from multiple workflow
  3468. //ids, and possibly library graphs.
  3469. //Stats for library graphs should be nested below the library call activity
  3470. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3471. }
  3472. return conn.getClear();
  3473. }
  3474. IPropertyTree *getGraphProgressTree() const
  3475. {
  3476. Owned<IRemoteConnection> conn = getProgressConnection();
  3477. if (conn)
  3478. {
  3479. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3480. mergePTree(tmp,conn->queryRoot());
  3481. return tmp.getClear();
  3482. }
  3483. return NULL;
  3484. }
  3485. Owned<IRemoteConnection> connection;
  3486. mutable Owned<IRemoteConnection> progressConnection;
  3487. };
  3488. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3489. {
  3490. public:
  3491. Owned<CLocalWorkUnit> c;
  3492. IMPLEMENT_IINTERFACE;
  3493. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3494. ~CLockedWorkUnit()
  3495. {
  3496. if (workUnitTraceLevel > 1)
  3497. DBGLOG("Releasing locked workunit %s", queryWuid());
  3498. if (c)
  3499. c->unlockRemote();
  3500. }
  3501. virtual IConstWorkUnit * unlock()
  3502. {
  3503. c->unlockRemote();
  3504. return c.getClear();
  3505. }
  3506. virtual bool aborting() const
  3507. { return c->aborting(); }
  3508. virtual void forceReload()
  3509. { }
  3510. virtual WUAction getAction() const
  3511. { return c->getAction(); }
  3512. virtual const char *queryActionDesc() const
  3513. { return c->queryActionDesc(); }
  3514. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3515. { return c->getApplicationValue(application, propname, str); }
  3516. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3517. { return c->getApplicationValueInt(application, propname, defVal); }
  3518. virtual IConstWUAppValueIterator & getApplicationValues() const
  3519. { return c->getApplicationValues(); }
  3520. virtual bool hasWorkflow() const
  3521. { return c->hasWorkflow(); }
  3522. virtual unsigned queryEventScheduledCount() const
  3523. { return c->queryEventScheduledCount(); }
  3524. virtual IPropertyTree * queryWorkflowTree() const
  3525. { return c->queryWorkflowTree(); }
  3526. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3527. { return c->getWorkflowItems(); }
  3528. virtual IWorkflowItemArray * getWorkflowClone() const
  3529. { return c->getWorkflowClone(); }
  3530. virtual bool requiresLocalFileUpload() const
  3531. { return c->requiresLocalFileUpload(); }
  3532. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3533. { return c->getLocalFileUploads(); }
  3534. virtual bool getIsQueryService() const
  3535. { return c->getIsQueryService(); }
  3536. virtual bool getCloneable() const
  3537. { return c->getCloneable(); }
  3538. virtual IUserDescriptor * queryUserDescriptor() const
  3539. { return c->queryUserDescriptor(); }
  3540. virtual const char *queryClusterName() const
  3541. { return c->queryClusterName(); }
  3542. virtual unsigned getCodeVersion() const
  3543. { return c->getCodeVersion(); }
  3544. virtual unsigned getWuidVersion() const
  3545. { return c->getWuidVersion(); }
  3546. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3547. { c->getBuildVersion(buildVersion, eclVersion); }
  3548. virtual bool hasDebugValue(const char * propname) const
  3549. { return c->hasDebugValue(propname); }
  3550. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3551. { return c->getDebugValue(propname, str); }
  3552. virtual int getDebugValueInt(const char * propname, int defVal) const
  3553. { return c->getDebugValueInt(propname, defVal); }
  3554. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3555. { return c->getDebugValueInt64(propname, defVal); }
  3556. virtual double getDebugValueReal(const char * propname, double defVal) const
  3557. { return c->getDebugValueReal(propname, defVal); }
  3558. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3559. { return c->getDebugValueBool(propname, defVal); }
  3560. virtual IStringIterator & getDebugValues() const
  3561. { return c->getDebugValues(NULL); }
  3562. virtual IStringIterator & getDebugValues(const char *prop) const
  3563. { return c->getDebugValues(prop); }
  3564. virtual unsigned getExceptionCount() const
  3565. { return c->getExceptionCount(); }
  3566. virtual IConstWUExceptionIterator & getExceptions() const
  3567. { return c->getExceptions(); }
  3568. virtual unsigned getGraphCount() const
  3569. { return c->getGraphCount(); }
  3570. virtual unsigned getSourceFileCount() const
  3571. { return c->getSourceFileCount(); }
  3572. virtual unsigned getResultCount() const
  3573. { return c->getResultCount(); }
  3574. virtual unsigned getVariableCount() const
  3575. { return c->getVariableCount(); }
  3576. virtual unsigned getApplicationValueCount() const
  3577. { return c->getApplicationValueCount(); }
  3578. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3579. { return c->getGraphs(type); }
  3580. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3581. { return c->getGraphsMeta(type); }
  3582. virtual IConstWUGraph * getGraph(const char *name) const
  3583. { return c->getGraph(name); }
  3584. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3585. { return c->getGraphProgress(name); }
  3586. virtual const char *queryJobName() const
  3587. { return c->queryJobName(); }
  3588. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3589. { return c->getPluginByName(name); }
  3590. virtual IConstWUPluginIterator & getPlugins() const
  3591. { return c->getPlugins(); }
  3592. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3593. { return c->getLibraryByName(name); }
  3594. virtual IConstWULibraryIterator & getLibraries() const
  3595. { return c->getLibraries(); }
  3596. virtual WUPriorityClass getPriority() const
  3597. { return c->getPriority(); }
  3598. virtual const char *queryPriorityDesc() const
  3599. { return c->queryPriorityDesc(); }
  3600. virtual int getPriorityLevel() const
  3601. { return c->getPriorityLevel(); }
  3602. virtual int getPriorityValue() const
  3603. { return c->getPriorityValue(); }
  3604. virtual IConstWUQuery * getQuery() const
  3605. { return c->getQuery(); }
  3606. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3607. { return c->getWebServicesInfo(); }
  3608. virtual bool getRescheduleFlag() const
  3609. { return c->getRescheduleFlag(); }
  3610. virtual IConstWUResult * getResultByName(const char * name) const
  3611. { return c->getResultByName(name); }
  3612. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3613. { return c->getResultBySequence(seq); }
  3614. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3615. { return c->getQueryResultByName(name); }
  3616. virtual unsigned getResultLimit() const
  3617. { return c->getResultLimit(); }
  3618. virtual IConstWUResultIterator & getResults() const
  3619. { return c->getResults(); }
  3620. virtual IStringVal & getScope(IStringVal & str) const
  3621. { return c->getScope(str); }
  3622. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3623. { return c->getWorkunitDistributedAccessToken(str); }
  3624. virtual WUState getState() const
  3625. { return c->getState(); }
  3626. virtual IStringVal & getStateEx(IStringVal & str) const
  3627. { return c->getStateEx(str); }
  3628. virtual __int64 getAgentSession() const
  3629. { return c->getAgentSession(); }
  3630. virtual unsigned getAgentPID() const
  3631. { return c->getAgentPID(); }
  3632. virtual const char *queryStateDesc() const
  3633. { return c->queryStateDesc(); }
  3634. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3635. { return c->getRunningGraph(graphName, subId); }
  3636. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3637. { return c->getScopeIterator(filter); }
  3638. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3639. { return c->getStatistic(value, scope, kind); }
  3640. virtual IStringVal & getSnapshot(IStringVal & str) const
  3641. { return c->getSnapshot(str); }
  3642. virtual const char *queryUser() const
  3643. { return c->queryUser(); }
  3644. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3645. { return c->getWarningSeverity(code, defaultSeverity); }
  3646. virtual const char *queryWuScope() const
  3647. { return c->queryWuScope(); }
  3648. virtual const char *queryWuid() const
  3649. { return c->queryWuid(); }
  3650. virtual IConstWUResult * getGlobalByName(const char * name) const
  3651. { return c->getGlobalByName(name); }
  3652. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3653. { return c->getTemporaryByName(name); }
  3654. virtual IConstWUResultIterator & getTemporaries() const
  3655. { return c->getTemporaries(); }
  3656. virtual IConstWUResult * getVariableByName(const char * name) const
  3657. { return c->getVariableByName(name); }
  3658. virtual IConstWUResultIterator & getVariables() const
  3659. { return c->getVariables(); }
  3660. virtual bool isProtected() const
  3661. { return c->isProtected(); }
  3662. virtual bool isPausing() const
  3663. { return c->isPausing(); }
  3664. virtual IWorkUnit & lock()
  3665. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3666. virtual bool reload()
  3667. { UNIMPLEMENTED; }
  3668. virtual void subscribe(WUSubscribeOptions options)
  3669. { c->subscribe(options); }
  3670. virtual void requestAbort()
  3671. { c->requestAbort(); }
  3672. virtual unsigned calculateHash(unsigned prevHash)
  3673. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3674. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3675. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3676. virtual IPropertyTree *queryPTree() const
  3677. { return queryExtendedWU(c)->queryPTree(); }
  3678. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3679. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3680. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3681. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3682. virtual unsigned queryFileUsage(const char *filename) const
  3683. { return c->queryFileUsage(filename); }
  3684. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3685. { return c->getFieldUsage(); }
  3686. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3687. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3688. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3689. { return c->getTimeScheduled(val); }
  3690. virtual unsigned getDebugAgentListenerPort() const
  3691. { return c->getDebugAgentListenerPort(); }
  3692. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3693. { return c->getDebugAgentListenerIP(ip); }
  3694. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3695. { return c->getXmlParams(params, hidePasswords); }
  3696. virtual const IPropertyTree *getXmlParams() const
  3697. { return c->getXmlParams(); }
  3698. virtual unsigned __int64 getHash() const
  3699. { return c->getHash(); }
  3700. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3701. { return c->getLogs(type, instance); }
  3702. virtual IStringIterator *getProcesses(const char *type) const
  3703. { return c->getProcesses(type); }
  3704. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3705. { return c->getProcesses(type, instance); }
  3706. virtual unsigned getTotalThorTime() const
  3707. { return c->getTotalThorTime(); }
  3708. virtual WUGraphState queryGraphState(const char *graphName) const
  3709. { return c->queryGraphState(graphName); }
  3710. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3711. { return c->queryNodeState(graphName, nodeId); }
  3712. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3713. { c->setGraphState(graphName, wfid, state); }
  3714. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3715. { c->setNodeState(graphName, nodeId, state); }
  3716. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3717. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3718. virtual void clearGraphProgress() const
  3719. { c->clearGraphProgress(); }
  3720. virtual IStringVal & getAbortBy(IStringVal & str) const
  3721. { return c->getAbortBy(str); }
  3722. virtual unsigned __int64 getAbortTimeStamp() const
  3723. { return c->getAbortTimeStamp(); }
  3724. virtual void clearExceptions(const char *source=nullptr)
  3725. { c->clearExceptions(source); }
  3726. virtual void commit()
  3727. { c->commit(); }
  3728. virtual IWUException * createException()
  3729. { return c->createException(); }
  3730. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3731. { c->addProcess(type, instance, pid, log); }
  3732. virtual void protect(bool protectMode)
  3733. { c->protect(protectMode); }
  3734. virtual void setAction(WUAction action)
  3735. { c->setAction(action); }
  3736. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3737. { c->setApplicationValue(application, propname, value, overwrite); }
  3738. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3739. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3740. virtual void incEventScheduledCount()
  3741. { c->incEventScheduledCount(); }
  3742. virtual void setIsQueryService(bool value)
  3743. { c->setIsQueryService(value); }
  3744. virtual void setCloneable(bool value)
  3745. { c->setCloneable(value); }
  3746. virtual void setIsClone(bool value)
  3747. { c->setIsClone(value); }
  3748. virtual void setClusterName(const char * value)
  3749. { c->setClusterName(value); }
  3750. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3751. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3752. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3753. { c->setDebugValue(propname, value, overwrite); }
  3754. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3755. { c->setDebugValueInt(propname, value, overwrite); }
  3756. virtual void setJobName(const char * value)
  3757. { c->setJobName(value); }
  3758. virtual void setPriority(WUPriorityClass cls)
  3759. { c->setPriority(cls); }
  3760. virtual void setPriorityLevel(int level)
  3761. { c->setPriorityLevel(level); }
  3762. virtual void setRescheduleFlag(bool value)
  3763. { c->setRescheduleFlag(value); }
  3764. virtual void setResultLimit(unsigned value)
  3765. { c->setResultLimit(value); }
  3766. virtual void setState(WUState state)
  3767. { c->setState(state); }
  3768. virtual void setStateEx(const char * text)
  3769. { c->setStateEx(text); }
  3770. virtual void setAgentSession(__int64 sessionId)
  3771. { c->setAgentSession(sessionId); }
  3772. 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)
  3773. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3774. virtual void setTracingValue(const char * propname, const char * value)
  3775. { c->setTracingValue(propname, value); }
  3776. virtual void setTracingValueInt(const char * propname, int value)
  3777. { c->setTracingValueInt(propname, value); }
  3778. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3779. { c->setTracingValueInt64(propname, value); }
  3780. virtual void setUser(const char * value)
  3781. { c->setUser(value); }
  3782. virtual void setWuScope(const char * value)
  3783. { c->setWuScope(value); }
  3784. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3785. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3786. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3787. { c->syncRuntimeWorkflow(array); }
  3788. virtual IWorkflowItemIterator * updateWorkflowItems()
  3789. { return c->updateWorkflowItems(); }
  3790. virtual void resetWorkflow()
  3791. { c->resetWorkflow(); }
  3792. virtual void schedule()
  3793. { c->schedule(); }
  3794. virtual void deschedule()
  3795. { c->deschedule(); }
  3796. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3797. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3798. virtual IWUResult * updateGlobalByName(const char * name)
  3799. { return c->updateGlobalByName(name); }
  3800. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3801. { c->createGraph(name, label, type, xgmml, wfid); }
  3802. virtual IWUQuery * updateQuery()
  3803. { return c->updateQuery(); }
  3804. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3805. { return c->updateWebServicesInfo(create); }
  3806. virtual IWUPlugin * updatePluginByName(const char * name)
  3807. { return c->updatePluginByName(name); }
  3808. virtual IWULibrary * updateLibraryByName(const char * name)
  3809. { return c->updateLibraryByName(name); }
  3810. virtual IWUResult * updateResultByName(const char * name)
  3811. { return c->updateResultByName(name); }
  3812. virtual IWUResult * updateResultBySequence(unsigned seq)
  3813. { return c->updateResultBySequence(seq); }
  3814. virtual IWUResult * updateTemporaryByName(const char * name)
  3815. { return c->updateTemporaryByName(name); }
  3816. virtual IWUResult * updateVariableByName(const char * name)
  3817. { return c->updateVariableByName(name); }
  3818. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3819. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3820. virtual void noteFileRead(IDistributedFile *file)
  3821. { c->noteFileRead(file); }
  3822. virtual void noteFieldUsage(IPropertyTree * usage)
  3823. { c->noteFieldUsage(usage); }
  3824. virtual void releaseFile(const char *fileName)
  3825. { c->releaseFile(fileName); }
  3826. virtual void resetBeforeGeneration()
  3827. { c->resetBeforeGeneration(); }
  3828. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3829. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3830. virtual void deleteTemporaries()
  3831. { c->deleteTemporaries(); }
  3832. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3833. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3834. virtual IPropertyTree * getDiskUsageStats()
  3835. { return c->getDiskUsageStats(); }
  3836. virtual IPropertyTreeIterator & getFileIterator() const
  3837. { return c->getFileIterator(); }
  3838. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3839. { return c->getFilesReadIterator(); }
  3840. virtual void setSnapshot(const char * value)
  3841. { c->setSnapshot(value); }
  3842. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3843. { c->setWarningSeverity(code, severity); }
  3844. virtual void setTimeScheduled(const IJlibDateTime &val)
  3845. { c->setTimeScheduled(val); }
  3846. virtual void setDebugAgentListenerPort(unsigned port)
  3847. { c->setDebugAgentListenerPort(port); }
  3848. virtual void setDebugAgentListenerIP(const char * ip)
  3849. { c->setDebugAgentListenerIP(ip); }
  3850. virtual void setXmlParams(const char *params)
  3851. { c->setXmlParams(params); }
  3852. virtual void setXmlParams(IPropertyTree *tree)
  3853. { c->setXmlParams(tree); }
  3854. virtual void setHash(unsigned __int64 hash)
  3855. { c->setHash(hash); }
  3856. // ILocalWorkUnit - used for debugging etc
  3857. virtual void serialize(MemoryBuffer &tgt)
  3858. { c->serialize(tgt); }
  3859. virtual void deserialize(MemoryBuffer &src)
  3860. { c->deserialize(src); }
  3861. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3862. { return c->switchThorQueue(cluster,qs); }
  3863. virtual void setAllowedClusters(const char *value)
  3864. { c->setAllowedClusters(value); }
  3865. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3866. { return c->getAllowedClusters(str); }
  3867. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3868. { c->remoteCheckAccess(user,writeaccess); }
  3869. virtual void setAllowAutoQueueSwitch(bool val)
  3870. { c->setAllowAutoQueueSwitch(val); }
  3871. virtual bool getAllowAutoQueueSwitch() const
  3872. { return c->getAllowAutoQueueSwitch(); }
  3873. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3874. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3875. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3876. { c->setResultInt(name, sequence, val); }
  3877. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3878. { c->setResultUInt(name, sequence, val); }
  3879. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3880. { c->setResultReal(name, sequence, val); }
  3881. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3882. { c->setResultVarString(stepname, sequence, val); }
  3883. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3884. { c->setResultVarUnicode(stepname, sequence, val); }
  3885. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3886. { c->setResultString(stepname, sequence, len, val); }
  3887. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3888. { c->setResultData(stepname, sequence, len, val); }
  3889. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3890. { c->setResultRaw(name, sequence, len, val); }
  3891. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3892. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3893. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3894. { c->setResultUnicode(name, sequence, len, val); }
  3895. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3896. { c->setResultBool(name, sequence, val); }
  3897. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3898. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3899. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3900. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3901. };
  3902. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3903. {
  3904. Owned<IPropertyTree> p;
  3905. public:
  3906. IMPLEMENT_IINTERFACE;
  3907. CLocalWUAssociated(IPropertyTree *p);
  3908. virtual WUFileType getType() const;
  3909. virtual IStringVal & getDescription(IStringVal & ret) const;
  3910. virtual IStringVal & getIp(IStringVal & ret) const;
  3911. virtual IStringVal & getName(IStringVal & ret) const;
  3912. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3913. virtual unsigned getCrc() const;
  3914. virtual unsigned getMinActivityId() const;
  3915. virtual unsigned getMaxActivityId() const;
  3916. };
  3917. class CLocalWUQuery : implements IWUQuery, public CInterface
  3918. {
  3919. Owned<IPropertyTree> p;
  3920. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3921. mutable CriticalSection crit;
  3922. mutable bool associatedCached;
  3923. private:
  3924. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3925. void loadAssociated() const;
  3926. public:
  3927. IMPLEMENT_IINTERFACE;
  3928. CLocalWUQuery(IPropertyTree *p);
  3929. virtual WUQueryType getQueryType() const;
  3930. virtual IStringVal& getQueryText(IStringVal &str) const;
  3931. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3932. virtual IStringVal& getQueryName(IStringVal &str) const;
  3933. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3934. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3935. virtual unsigned getQueryDllCrc() const;
  3936. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3937. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3938. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3939. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3940. virtual bool isArchive() const;
  3941. virtual bool hasArchive() const
  3942. {
  3943. return p->getPropBool("@hasArchive");
  3944. }
  3945. virtual void setQueryType(WUQueryType qt);
  3946. virtual void setQueryText(const char *pstr);
  3947. virtual void setQueryName(const char *);
  3948. virtual void setQueryMainDefinition(const char * str);
  3949. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  3950. virtual void removeAssociatedFiles();
  3951. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  3952. };
  3953. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  3954. {
  3955. Owned<IPropertyTree> p;
  3956. mutable CriticalSection crit;
  3957. private:
  3958. public:
  3959. IMPLEMENT_IINTERFACE;
  3960. CLocalWUWebServicesInfo(IPropertyTree *p);
  3961. virtual IStringVal& getModuleName(IStringVal &str) const;
  3962. virtual IStringVal& getAttributeName(IStringVal &str) const;
  3963. virtual IStringVal& getDefaultName(IStringVal &str) const;
  3964. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  3965. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  3966. virtual unsigned getWebServicesCRC() const;
  3967. virtual void setModuleName(const char *);
  3968. virtual void setAttributeName(const char *);
  3969. virtual void setDefaultName(const char *);
  3970. virtual void setInfo(const char *name, const char *info);
  3971. virtual void setText(const char *name, const char *info);
  3972. virtual void setWebServicesCRC(unsigned);
  3973. };
  3974. class CLocalWUResult : implements IWUResult, public CInterface
  3975. {
  3976. friend class CLocalWorkUnit;
  3977. mutable CriticalSection crit;
  3978. Owned<IPropertyTree> p;
  3979. Owned<IProperties> xmlns;
  3980. public:
  3981. IMPLEMENT_IINTERFACE;
  3982. CLocalWUResult(IPropertyTree *props);
  3983. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  3984. virtual WUResultStatus getResultStatus() const;
  3985. virtual IStringVal& getResultName(IStringVal &str) const;
  3986. virtual int getResultSequence() const;
  3987. virtual bool isResultScalar() const;
  3988. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  3989. virtual unsigned getResultFetchSize() const;
  3990. virtual __int64 getResultTotalRowCount() const;
  3991. virtual __int64 getResultRowCount() const;
  3992. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  3993. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  3994. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  3995. virtual unsigned getResultRequestedRows() const;
  3996. virtual __int64 getResultInt() const;
  3997. virtual bool getResultBool() const;
  3998. virtual double getResultReal() const;
  3999. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  4000. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4001. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  4002. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  4003. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  4004. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4005. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  4006. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  4007. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  4008. virtual __int64 getResultRowLimit() const;
  4009. virtual IStringVal& getResultFilename(IStringVal & str) const;
  4010. virtual WUResultFormat getResultFormat() const;
  4011. virtual unsigned getResultHash() const;
  4012. virtual bool getResultIsAll() const;
  4013. virtual IProperties *queryResultXmlns();
  4014. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  4015. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  4016. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  4017. // interface IWUResult
  4018. virtual void setResultStatus(WUResultStatus status);
  4019. virtual void setResultName(const char *name);
  4020. virtual void setResultSequence(unsigned seq);
  4021. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  4022. virtual void setResultScalar(bool isScalar);
  4023. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  4024. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  4025. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  4026. virtual void setResultRowCount(__int64 rows);
  4027. virtual void setResultDataset(const char *ecl, const char *defs);
  4028. virtual void setResultLogicalName(const char *logicalName);
  4029. virtual void setResultKeyField(const char * name);
  4030. virtual void setResultRequestedRows(unsigned req);
  4031. virtual void setResultRecordSizeEntry(const char * val);
  4032. virtual void setResultTransformerEntry(const char * val);
  4033. virtual void setResultInt(__int64 val);
  4034. virtual void setResultReal(double val);
  4035. virtual void setResultBool(bool val);
  4036. virtual void setResultString(const char * val, unsigned length);
  4037. virtual void setResultUnicode(const void * val, unsigned length);
  4038. virtual void setResultData(const void * val, unsigned length);
  4039. virtual void setResultDecimal(const void * val, unsigned length);
  4040. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  4041. virtual void setResultRowLimit(__int64 value);
  4042. virtual void setResultFilename(const char * name);
  4043. virtual void setResultUInt(unsigned __int64 val);
  4044. virtual void setResultIsAll(bool value);
  4045. virtual void setResultFormat(WUResultFormat format);
  4046. virtual void setResultXML(const char *val);
  4047. virtual void setResultRow(unsigned len, const void * data);
  4048. virtual void setResultXmlns(const char *prefix, const char *uri);
  4049. virtual void setResultFieldOpt(const char *name, const char *value);
  4050. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  4051. virtual IPropertyTree *queryPTree() { return p; }
  4052. };
  4053. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  4054. {
  4055. Owned<IPropertyTree> p;
  4056. public:
  4057. IMPLEMENT_IINTERFACE;
  4058. CLocalWUPlugin(IPropertyTree *p);
  4059. virtual IStringVal& getPluginName(IStringVal &str) const;
  4060. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  4061. virtual void setPluginName(const char *str);
  4062. virtual void setPluginVersion(const char *str);
  4063. };
  4064. class CLocalWULibrary : implements IWULibrary, public CInterface
  4065. {
  4066. Owned<IPropertyTree> p;
  4067. public:
  4068. IMPLEMENT_IINTERFACE;
  4069. CLocalWULibrary(IPropertyTree *p);
  4070. virtual IStringVal & getName(IStringVal & str) const;
  4071. virtual void setName(const char * str);
  4072. };
  4073. class CLocalWUException : implements IWUException, public CInterface
  4074. {
  4075. Owned<IPropertyTree> p;
  4076. public:
  4077. IMPLEMENT_IINTERFACE;
  4078. CLocalWUException(IPropertyTree *p);
  4079. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4080. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4081. virtual unsigned getExceptionCode() const override;
  4082. virtual ErrorSeverity getSeverity() const override;
  4083. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4084. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4085. virtual unsigned getExceptionLineNo() const override;
  4086. virtual unsigned getExceptionColumn() const override;
  4087. virtual unsigned getActivityId() const override;
  4088. virtual unsigned getSequence() const override;
  4089. virtual const char * queryScope() const override;
  4090. virtual unsigned getPriority() const override;
  4091. virtual void setExceptionSource(const char *str) override;
  4092. virtual void setExceptionMessage(const char *str) override;
  4093. virtual void setExceptionCode(unsigned code) override;
  4094. virtual void setSeverity(ErrorSeverity level) override;
  4095. virtual void setTimeStamp(const char * dt) override;
  4096. virtual void setExceptionFileName(const char *str) override;
  4097. virtual void setExceptionLineNo(unsigned r) override;
  4098. virtual void setExceptionColumn(unsigned c) override;
  4099. virtual void setActivityId(unsigned _id) override;
  4100. virtual void setScope(const char * _scope) override;
  4101. virtual void setPriority(unsigned _priority) override;
  4102. };
  4103. //==========================================================================================
  4104. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4105. {
  4106. switch ((int) sequence)
  4107. {
  4108. case ResultSequenceInternal:
  4109. case ResultSequenceOnce:
  4110. case ResultSequencePersist:
  4111. case ResultSequenceStored:
  4112. return true;
  4113. default:
  4114. assertex(sequence <= INT_MAX);
  4115. if ((int) sequence >= LibraryBaseSequence)
  4116. return true;
  4117. return false;
  4118. }
  4119. }
  4120. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4121. {
  4122. unsigned curTreeNum;
  4123. IArrayOf<IPropertyTree> trees;
  4124. Owned<IConstWorkUnitInfo> cur;
  4125. void setCurrent()
  4126. {
  4127. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4128. }
  4129. public:
  4130. IMPLEMENT_IINTERFACE;
  4131. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4132. {
  4133. ForEachItemIn(t, _trees)
  4134. trees.append(*LINK(&_trees.item(t)));
  4135. curTreeNum = 0;
  4136. }
  4137. bool first()
  4138. {
  4139. curTreeNum = 0;
  4140. return next();
  4141. }
  4142. bool isValid()
  4143. {
  4144. return (NULL != cur.get());
  4145. }
  4146. bool next()
  4147. {
  4148. if (curTreeNum >= trees.ordinality())
  4149. {
  4150. cur.clear();
  4151. return false;
  4152. }
  4153. setCurrent();
  4154. ++curTreeNum;
  4155. return true;
  4156. }
  4157. IConstWorkUnitInfo & query() { return *cur; }
  4158. };
  4159. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4160. {
  4161. Owned<IPropertyTree> p;
  4162. public:
  4163. IMPLEMENT_IINTERFACE;
  4164. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4165. virtual const char * queryName() const { return p->queryProp("@name"); }
  4166. };
  4167. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4168. {
  4169. public:
  4170. IMPLEMENT_IINTERFACE;
  4171. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4172. bool first() override { return iter->first(); }
  4173. bool isValid() override { return iter->isValid(); }
  4174. bool next() override { return iter->next(); }
  4175. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4176. private:
  4177. Owned<IPropertyTreeIterator> iter;
  4178. };
  4179. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4180. {
  4181. Owned<IPropertyTree> p;
  4182. public:
  4183. IMPLEMENT_IINTERFACE;
  4184. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4185. virtual const char * queryName() const { return p->queryProp("@name"); }
  4186. virtual const char * queryType() const { return p->queryProp("@type"); }
  4187. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4188. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4189. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4190. };
  4191. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4192. {
  4193. public:
  4194. IMPLEMENT_IINTERFACE;
  4195. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4196. bool first() override { return iter->first(); }
  4197. bool isValid() override { return iter->isValid(); }
  4198. bool next() override { return iter->next(); }
  4199. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4200. private:
  4201. Owned<IPropertyTreeIterator> iter;
  4202. };
  4203. //==========================================================================================
  4204. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4205. {
  4206. Owned<IPropertyTreeIterator> it;
  4207. public:
  4208. IMPLEMENT_IINTERFACE;
  4209. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4210. virtual bool first() { return it->first(); }
  4211. virtual bool next() { return it->next(); }
  4212. virtual bool isValid() { return it->isValid(); }
  4213. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4214. };
  4215. EnumMapping workunitSortFields[] =
  4216. {
  4217. { WUSFuser, "@submitID" },
  4218. { WUSFcluster, "@clusterName" },
  4219. { WUSFjob, "@jobName" },
  4220. { WUSFstate, "@state" },
  4221. { WUSFpriority, "@priorityClass" },
  4222. { WUSFprotected, "@protected" },
  4223. { WUSFwuid, "@" },
  4224. { WUSFecl, "Query/ShortText" },
  4225. { WUSFfileread, "FilesRead/File/@name" },
  4226. { WUSFtotalthortime, "@totalThorTime|"
  4227. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4228. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4229. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4230. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4231. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4232. },
  4233. { WUSFwuidhigh, "@" },
  4234. { WUSFwildwuid, "@" },
  4235. { WUSFappvalue, "Application" },
  4236. { WUSFfilewritten, "Files/File/@name" },
  4237. { WUSFterm, NULL }
  4238. };
  4239. extern const char *queryFilterXPath(WUSortField field)
  4240. {
  4241. return getEnumText(field, workunitSortFields);
  4242. }
  4243. EnumMapping querySortFields[] =
  4244. {
  4245. { WUQSFId, "@id" },
  4246. { WUQSFwuid, "@wuid" },
  4247. { WUQSFname, "@name" },
  4248. { WUQSFdll, "@dll" },
  4249. { WUQSFmemoryLimit, "@memoryLimit" },
  4250. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4251. { WUQSFtimeLimit, "@timeLimit" },
  4252. { WUQSFtimeLimitHi, "@timeLimit" },
  4253. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4254. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4255. { WUQSFpriority, "@priority" },
  4256. { WUQSFpriorityHi, "@priority" },
  4257. { WUQSFQuerySet, "@querySetId" },
  4258. { WUQSFActivited, "@activated" },
  4259. { WUQSFSuspendedByUser, "@suspended" },
  4260. { WUQSFLibrary, "Library"},
  4261. { WUQSFPublishedBy, "@publishedBy" },
  4262. { WUQSFterm, NULL }
  4263. };
  4264. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4265. {
  4266. StringAttr name;
  4267. public:
  4268. IMPLEMENT_IINTERFACE;
  4269. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4270. {
  4271. }
  4272. void execute()
  4273. {
  4274. PROGLOG("WU removeDll %s", name.get());
  4275. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4276. }
  4277. };
  4278. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4279. {
  4280. RemoteFilename name;
  4281. public:
  4282. IMPLEMENT_IINTERFACE;
  4283. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4284. {
  4285. SocketEndpoint ep(_ip);
  4286. name.setPath(ep, _name);
  4287. }
  4288. void execute()
  4289. {
  4290. Owned<IFile> file = createIFile(name);
  4291. PROGLOG("WU removeDll %s",file->queryFilename());
  4292. file->remove();
  4293. }
  4294. };
  4295. //==========================================================================================
  4296. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4297. {
  4298. unsigned index;
  4299. IArrayOf<IPropertyTree> trees;
  4300. public:
  4301. IMPLEMENT_IINTERFACE;
  4302. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4303. {
  4304. ForEachItemIn(t, _trees)
  4305. trees.append(*LINK(&_trees.item(t)));
  4306. index = 0;
  4307. }
  4308. ~CConstQuerySetQueryIterator()
  4309. {
  4310. trees.kill();
  4311. }
  4312. bool first()
  4313. {
  4314. index = 0;
  4315. return (trees.ordinality()!=0);
  4316. }
  4317. bool next()
  4318. {
  4319. index++;
  4320. return (index<trees.ordinality());
  4321. }
  4322. bool isValid()
  4323. {
  4324. return (index<trees.ordinality());
  4325. }
  4326. IPropertyTree &query()
  4327. {
  4328. return trees.item(index);
  4329. }
  4330. };
  4331. class CSecurityCache
  4332. {
  4333. };
  4334. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4335. {
  4336. public:
  4337. IMPLEMENT_IINTERFACE;
  4338. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4339. : ptreeIter(_ptreeIter)
  4340. {
  4341. }
  4342. bool first()
  4343. {
  4344. if (!ptreeIter->first())
  4345. {
  4346. cur.clear();
  4347. return false;
  4348. }
  4349. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4350. return true;
  4351. }
  4352. bool isValid()
  4353. {
  4354. return (NULL != cur.get());
  4355. }
  4356. bool next()
  4357. {
  4358. if (!ptreeIter->next())
  4359. {
  4360. cur.clear();
  4361. return false;
  4362. }
  4363. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4364. return true;
  4365. }
  4366. IConstWorkUnitInfo & query() { return *cur; }
  4367. private:
  4368. Owned<IConstWorkUnitInfo> cur;
  4369. Owned<IPropertyTreeIterator> ptreeIter;
  4370. };
  4371. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4372. {
  4373. public:
  4374. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4375. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4376. {
  4377. assertex(_secuser && _secmgr);
  4378. }
  4379. bool first()
  4380. {
  4381. if (!parent->first())
  4382. return false;
  4383. return getNext();
  4384. }
  4385. bool next()
  4386. {
  4387. if (!parent->next())
  4388. return false;
  4389. return getNext();
  4390. }
  4391. virtual bool isValid()
  4392. {
  4393. return parent->isValid();
  4394. }
  4395. virtual IConstWorkUnitInfo &query()
  4396. {
  4397. return parent->query();
  4398. }
  4399. private:
  4400. Owned<IConstWorkUnitIterator> parent;
  4401. MapStringTo<int> scopePermissions;
  4402. Linked<ISecManager> secmgr;
  4403. Linked<ISecUser> secuser;
  4404. bool getNext() // scan for a workunit with permissions
  4405. {
  4406. do
  4407. {
  4408. const char *scopeName = parent->query().queryWuScope();
  4409. if (!scopeName || !*scopeName || checkScope(scopeName))
  4410. return true;
  4411. } while (parent->next());
  4412. return false;
  4413. }
  4414. bool checkScope(const char *scopeName)
  4415. {
  4416. int *perms = scopePermissions.getValue(scopeName);
  4417. SecAccessFlags perm;
  4418. if (!perms)
  4419. {
  4420. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4421. scopePermissions.setValue(scopeName, perm);
  4422. }
  4423. else
  4424. perm = (SecAccessFlags)*perms;
  4425. return perm >= SecAccess_Read;
  4426. }
  4427. };
  4428. CWorkUnitFactory::CWorkUnitFactory()
  4429. {
  4430. }
  4431. CWorkUnitFactory::~CWorkUnitFactory()
  4432. {
  4433. }
  4434. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4435. {
  4436. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4437. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4438. if (scope)
  4439. 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...
  4440. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4441. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4442. ret->setDebugValue("CREATED_BY", app, true);
  4443. ret->setDebugValue("CREATED_FOR", scope, true);
  4444. return ret;
  4445. }
  4446. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4447. {
  4448. StringBuffer wuid("W");
  4449. char result[32];
  4450. time_t ltime;
  4451. time( &ltime );
  4452. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4453. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4454. wuid.append(result);
  4455. if (workUnitTraceLevel > 1)
  4456. DBGLOG("createWorkUnit created %s", wuid.str());
  4457. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4458. if (workUnitTraceLevel > 1)
  4459. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4460. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4461. return ret;
  4462. }
  4463. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4464. {
  4465. if (workUnitTraceLevel > 1)
  4466. DBGLOG("deleteWorkUnit %s", wuid);
  4467. StringBuffer wuRoot;
  4468. getXPath(wuRoot, wuid);
  4469. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4470. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4471. return false;
  4472. if (throwException)
  4473. cw->cleanupAndDelete(true, true);
  4474. else
  4475. {
  4476. try
  4477. {
  4478. cw->cleanupAndDelete(true, true);
  4479. }
  4480. catch (IException *E)
  4481. {
  4482. StringBuffer s;
  4483. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4484. E->Release();
  4485. return false;
  4486. }
  4487. }
  4488. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4489. return true;
  4490. }
  4491. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4492. {
  4493. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4494. }
  4495. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4496. {
  4497. StringBuffer wuidStr(wuid);
  4498. wuidStr.trim();
  4499. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4500. wuidStr.setCharAt(0, 'W');
  4501. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4502. {
  4503. if (workUnitTraceLevel > 1)
  4504. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4505. return NULL;
  4506. }
  4507. if (workUnitTraceLevel > 1)
  4508. DBGLOG("openWorkUnit %s", wuidStr.str());
  4509. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4510. if (wu)
  4511. {
  4512. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4513. return NULL; // Actually throws exception on failure, so won't reach here
  4514. return wu.getClear();
  4515. }
  4516. else
  4517. {
  4518. if (workUnitTraceLevel > 0)
  4519. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4520. return NULL;
  4521. }
  4522. }
  4523. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4524. {
  4525. if (workUnitTraceLevel > 1)
  4526. DBGLOG("updateWorkUnit %s", wuid);
  4527. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4528. if (wu)
  4529. {
  4530. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4531. return NULL;
  4532. return &wu->lockRemote(false);
  4533. }
  4534. else
  4535. {
  4536. if (workUnitTraceLevel > 0)
  4537. IERRLOG("updateWorkUnit %s not found", wuid);
  4538. return NULL;
  4539. }
  4540. }
  4541. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4542. {
  4543. Owned<IPropertyTree> ret;
  4544. IPropertyTree * branch = from->queryPropTree(xpath);
  4545. if(branch)
  4546. {
  4547. ret.setown(createPTreeFromIPT(branch));
  4548. from->removeTree(branch);
  4549. }
  4550. return ret.getClear();
  4551. }
  4552. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4553. {
  4554. StringBuffer path(base);
  4555. addPathSepChar(path).append(wuid).append(".xml");
  4556. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4557. if (!pt)
  4558. return false;
  4559. CDateTime dt;
  4560. dt.setNow();
  4561. StringBuffer dts;
  4562. dt.getString(dts);
  4563. pt->setProp("@restoredDate", dts.str());
  4564. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4565. Owned<IPropertyTree> associatedFiles;
  4566. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4567. if (srcAssociated)
  4568. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4569. // The updating of the repo is implementation specific...
  4570. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4571. return false;
  4572. // now kludge back GeneratedDlls
  4573. if (generatedDlls)
  4574. {
  4575. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4576. for(dlls->first(); dlls->isValid(); dlls->next())
  4577. {
  4578. IPropertyTree & dll = dlls->query();
  4579. char const * name = dll.queryProp("@name");
  4580. char const * kind = dll.queryProp("@kind");
  4581. char const * location = dll.queryProp("@location");
  4582. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4583. if (!got)
  4584. {
  4585. RemoteFilename dstRfn;
  4586. dstRfn.setRemotePath(location);
  4587. StringBuffer srcPath(base);
  4588. addPathSepChar(srcPath);
  4589. dstRfn.getTail(srcPath);
  4590. OwnedIFile srcFile = createIFile(srcPath);
  4591. OwnedIFile dstFile = createIFile(dstRfn);
  4592. copyFile(dstFile, srcFile);
  4593. queryDllServer().registerDll(name, kind, location);
  4594. }
  4595. }
  4596. }
  4597. if (associatedFiles)
  4598. {
  4599. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4600. ForEach(*associated)
  4601. {
  4602. IPropertyTree &file = associated->query();
  4603. const char *filename = file.queryProp("@filename");
  4604. SocketEndpoint ep(file.queryProp("@ip"));
  4605. RemoteFilename rfn;
  4606. rfn.setPath(ep, filename);
  4607. OwnedIFile dstFile = createIFile(rfn);
  4608. StringBuffer srcPath(base), name;
  4609. addPathSepChar(srcPath);
  4610. rfn.getTail(name);
  4611. srcPath.append(name);
  4612. if (generatedDlls)
  4613. {
  4614. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4615. if (generatedDlls->hasProp(gDllPath))
  4616. continue; // generated dlls handled separately - see above
  4617. }
  4618. OwnedIFile srcFile = createIFile(srcPath);
  4619. if (srcFile->exists())
  4620. {
  4621. try
  4622. {
  4623. copyFile(dstFile, srcFile);
  4624. }
  4625. catch (IException *e)
  4626. {
  4627. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4628. EXCLOG(e, msg.str());
  4629. e->Release();
  4630. }
  4631. }
  4632. }
  4633. }
  4634. return true;
  4635. }
  4636. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4637. {
  4638. if (newLevel)
  4639. DBGLOG("Setting workunit trace level to %d", newLevel);
  4640. int level = workUnitTraceLevel;
  4641. workUnitTraceLevel = newLevel;
  4642. return level;
  4643. }
  4644. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4645. {
  4646. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4647. if(!conn) return;
  4648. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4649. KeptAtomTable entries;
  4650. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4651. StringBuffer wuid;
  4652. for(iter->first(); iter->isValid(); iter->next())
  4653. {
  4654. char const * entry = iter->query().queryName();
  4655. if(!entries.find(entry))
  4656. {
  4657. entries.addAtom(entry);
  4658. ncnameUnescape(entry, wuid.clear());
  4659. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4660. if(wu && (wu->getState() == WUStateWait))
  4661. wu->setState(WUStateCompleted);
  4662. }
  4663. }
  4664. bool more;
  4665. do more = root->removeProp("*"); while(more);
  4666. }
  4667. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4668. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4669. const void *filterbuf, // (appended) string values for filters
  4670. unsigned startoffset,
  4671. unsigned maxnum,
  4672. __int64 *cachehint,
  4673. unsigned *total,
  4674. const MapStringTo<bool> *_subset)
  4675. {
  4676. struct PostFilters
  4677. {
  4678. WUQueryFilterBoolean activatedFilter;
  4679. WUQueryFilterBoolean suspendedByUserFilter;
  4680. PostFilters()
  4681. {
  4682. activatedFilter = WUQFSAll;
  4683. suspendedByUserFilter = WUQFSAll;
  4684. };
  4685. } postFilters;
  4686. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4687. {
  4688. StringAttr querySet;
  4689. StringAttr xPath;
  4690. StringAttr sortOrder;
  4691. PostFilters postFilters;
  4692. StringArray unknownAttributes;
  4693. const MapStringTo<bool> *subset;
  4694. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4695. {
  4696. const char* querySetId = querySetTree->queryProp("@id");
  4697. std::unordered_set<std::string> aliasSet;
  4698. Owned<IPropertyTreeIterator> aliasIter = querySetTree->getElements("Alias");
  4699. ForEach(*aliasIter)
  4700. {
  4701. const char *id = aliasIter->query().queryProp("@id");
  4702. if (!isEmptyString(id))
  4703. aliasSet.insert(id);
  4704. }
  4705. VStringBuffer path("Query%s", xPath.get());
  4706. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4707. ForEach(*iter)
  4708. {
  4709. IPropertyTree &query = iter->query();
  4710. bool activated = false;
  4711. const char* queryId = query.queryProp("@id");
  4712. if (queryId && *queryId)
  4713. {
  4714. if (subset)
  4715. {
  4716. VStringBuffer match("%s/%s", querySetId, queryId);
  4717. if (!subset->getValue(match))
  4718. continue;
  4719. }
  4720. if (aliasSet.find(queryId) != aliasSet.end())
  4721. activated = true;
  4722. }
  4723. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4724. continue;
  4725. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4726. continue;
  4727. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4728. continue;
  4729. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4730. continue;
  4731. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4732. queryWithSetId->setProp("@querySetId", querySetId);
  4733. queryWithSetId->setPropBool("@activated", activated);
  4734. }
  4735. }
  4736. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4737. {
  4738. StringBuffer querySetXPath("QuerySets");
  4739. if (!querySet.isEmpty())
  4740. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4741. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4742. if (!conn)
  4743. return NULL;
  4744. IPropertyTree *root = conn->queryRoot()->queryBranch(nullptr);
  4745. if (querySet.isEmpty())
  4746. {
  4747. Owned<IPropertyTreeIterator> querySetIter = root->getElements("*");
  4748. ForEach(*querySetIter)
  4749. populateQueryTree(&querySetIter->query(), queryTree);
  4750. }
  4751. else
  4752. populateQueryTree(root, queryTree);
  4753. return conn.getClear();
  4754. }
  4755. public:
  4756. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4757. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  4758. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  4759. {
  4760. postFilters.activatedFilter = _postFilters.activatedFilter;
  4761. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  4762. ForEachItemIn(x, _unknownAttributes)
  4763. unknownAttributes.append(_unknownAttributes.item(x));
  4764. }
  4765. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4766. {
  4767. Owned<IPropertyTree> elementTree = createPTree("Queries");
  4768. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  4769. if (!conn)
  4770. return NULL;
  4771. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  4772. if (!iter)
  4773. return NULL;
  4774. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  4775. return conn.getClear();
  4776. }
  4777. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  4778. };
  4779. StringAttr querySet;
  4780. StringBuffer xPath;
  4781. StringBuffer so;
  4782. StringArray unknownAttributes;
  4783. if (filters)
  4784. {
  4785. const char *fv = (const char *)filterbuf;
  4786. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  4787. int fmt = filters[i];
  4788. int subfmt = (fmt&0xff);
  4789. if (subfmt==WUQSFQuerySet)
  4790. querySet.set(fv);
  4791. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  4792. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  4793. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  4794. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  4795. else if (subfmt==WUQSFActivited)
  4796. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  4797. else if (subfmt==WUQSFSuspendedByUser)
  4798. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  4799. else if (!fv || !*fv)
  4800. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  4801. else {
  4802. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  4803. if (fmt&WUQSFnocase)
  4804. xPath.append('?');
  4805. if (fmt&WUQSFnumeric)
  4806. xPath.append('#');
  4807. if (fmt&WUQSFwild)
  4808. xPath.append('~');
  4809. xPath.append('"').append(fv).append("\"]");
  4810. }
  4811. fv = fv + strlen(fv)+1;
  4812. }
  4813. }
  4814. if (sortorder) {
  4815. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  4816. if (so.length())
  4817. so.append(',');
  4818. int fmt = sortorder[i];
  4819. if (fmt&WUQSFreverse)
  4820. so.append('-');
  4821. if (fmt&WUQSFnocase)
  4822. so.append('?');
  4823. if (fmt&WUQSFnumeric)
  4824. so.append('#');
  4825. so.append(getEnumText(fmt&0xff,querySortFields));
  4826. }
  4827. }
  4828. IArrayOf<IPropertyTree> results;
  4829. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  4830. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  4831. return new CConstQuerySetQueryIterator(results);
  4832. }
  4833. bool CWorkUnitFactory::isAborting(const char *wuid) const
  4834. {
  4835. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4836. try
  4837. {
  4838. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4839. if (acon)
  4840. return acon->queryRoot()->getPropInt(NULL) != 0;
  4841. }
  4842. catch (IException *E)
  4843. {
  4844. EXCLOG(E);
  4845. E->Release();
  4846. }
  4847. return false;
  4848. }
  4849. void CWorkUnitFactory::clearAborting(const char *wuid)
  4850. {
  4851. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4852. try
  4853. {
  4854. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4855. if (acon)
  4856. acon->close(true);
  4857. }
  4858. catch (IException *E)
  4859. {
  4860. EXCLOG(E);
  4861. E->Release();
  4862. }
  4863. }
  4864. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  4865. {
  4866. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  4867. bool isEcl = false;
  4868. switch (state)
  4869. {
  4870. case WUStateAborting:
  4871. state = WUStateAborted;
  4872. break;
  4873. case WUStateCompiling:
  4874. isEcl = true;
  4875. // drop into
  4876. default:
  4877. state = WUStateFailed;
  4878. }
  4879. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  4880. wu->setState(state);
  4881. Owned<IWUException> e = wu->createException();
  4882. e->setExceptionCode(isEcl ? 1001 : 1000);
  4883. e->setExceptionMessage(isEcl ? "EclCC terminated unexpectedly" : "Workunit terminated unexpectedly");
  4884. }
  4885. static CriticalSection deleteDllLock;
  4886. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  4887. MODULE_INIT(INIT_PRIORITY_STANDARD)
  4888. {
  4889. return true;
  4890. }
  4891. MODULE_EXIT()
  4892. {
  4893. CriticalBlock b(deleteDllLock);
  4894. if (deleteDllWorkQ)
  4895. ::Release(deleteDllWorkQ);
  4896. deleteDllWorkQ = nullptr;
  4897. }
  4898. static void asyncRemoveDll(const char * name)
  4899. {
  4900. CriticalBlock b(deleteDllLock);
  4901. if (!deleteDllWorkQ)
  4902. deleteDllWorkQ = createWorkQueueThread();
  4903. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  4904. }
  4905. static void asyncRemoveFile(const char * ip, const char * name)
  4906. {
  4907. CriticalBlock b(deleteDllLock);
  4908. if (!deleteDllWorkQ)
  4909. deleteDllWorkQ = createWorkQueueThread();
  4910. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  4911. }
  4912. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  4913. {
  4914. public:
  4915. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  4916. CDaliWorkUnitFactory()
  4917. {
  4918. // Assumes dali client configuration has already been done
  4919. sdsManager = &querySDS();
  4920. session = myProcessSession();
  4921. addShutdownHook(*this);
  4922. }
  4923. ~CDaliWorkUnitFactory()
  4924. {
  4925. removeShutdownHook(*this);
  4926. }
  4927. virtual bool initializeStore()
  4928. {
  4929. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  4930. }
  4931. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  4932. {
  4933. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  4934. }
  4935. virtual unsigned validateRepository(bool fixErrors)
  4936. {
  4937. return 0;
  4938. }
  4939. virtual void deleteRepository(bool recreate)
  4940. {
  4941. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4942. if (conn)
  4943. conn->close(true);
  4944. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  4945. if (conn)
  4946. conn->close(true);
  4947. }
  4948. virtual void createRepository()
  4949. {
  4950. // Nothing to do
  4951. }
  4952. virtual const char *queryStoreType() const
  4953. {
  4954. return "Dali";
  4955. }
  4956. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4957. {
  4958. StringBuffer wuRoot;
  4959. getXPath(wuRoot, wuid);
  4960. IRemoteConnection *conn;
  4961. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  4962. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4963. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  4964. conn->queryRoot()->setProp("@totalThorTime", "");
  4965. return new CDaliWorkUnit(conn, secmgr, secuser);
  4966. }
  4967. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4968. {
  4969. StringBuffer wuRoot;
  4970. getXPath(wuRoot, wuid);
  4971. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  4972. if (conn)
  4973. return new CDaliWorkUnit(conn, secmgr, secuser);
  4974. else
  4975. return NULL;
  4976. }
  4977. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  4978. {
  4979. Owned<IPTree> pt(_pt);
  4980. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  4981. StringBuffer wuRoot;
  4982. getXPath(wuRoot, wuid);
  4983. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4984. if (!conn)
  4985. {
  4986. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  4987. return false;
  4988. }
  4989. IPropertyTree *root = conn->queryRoot();
  4990. if (root->hasChildren())
  4991. {
  4992. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  4993. return false;
  4994. }
  4995. root->setPropTree(NULL, pt.getClear());
  4996. conn.clear();
  4997. // now kludge back GraphProgress
  4998. if (gprogress)
  4999. {
  5000. VStringBuffer xpath("/GraphProgress/%s", wuid);
  5001. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  5002. if (conn)
  5003. {
  5004. IPropertyTree *groot = conn->queryRoot();
  5005. if (groot->hasChildren())
  5006. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  5007. groot->setPropTree(NULL, gprogress.getClear());
  5008. }
  5009. }
  5010. return true;
  5011. }
  5012. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  5013. {
  5014. StringBuffer wuRoot;
  5015. getXPath(wuRoot, wuid);
  5016. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  5017. if (conn)
  5018. return new CDaliWorkUnit(conn, secmgr, secuser);
  5019. else
  5020. return NULL;
  5021. }
  5022. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5023. {
  5024. // MORE - should it check security?
  5025. StringBuffer wuRoot;
  5026. getXPath(wuRoot, GLOBAL_WORKUNIT);
  5027. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  5028. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  5029. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  5030. return &cw->lockRemote(false);
  5031. }
  5032. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  5033. {
  5034. StringBuffer path("*");
  5035. if (owner && *owner)
  5036. path.append("[@submitID=?~\"").append(owner).append("\"]");
  5037. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5038. }
  5039. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  5040. {
  5041. StringBuffer path("*");
  5042. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  5043. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  5044. }
  5045. virtual void clientShutdown();
  5046. virtual unsigned numWorkUnits()
  5047. {
  5048. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5049. if (!conn)
  5050. return 0;
  5051. IPropertyTree *root = conn->queryRoot();
  5052. return root->numChildren();
  5053. }
  5054. /**
  5055. * Add a filter to an xpath query, with the appropriate filter flags
  5056. */
  5057. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  5058. {
  5059. query.append('[').append(name).append('=');
  5060. if (flags & WUSFnocase)
  5061. query.append('?');
  5062. if (flags & WUSFwild)
  5063. query.append('~');
  5064. query.append('"').append(value).append("\"]");
  5065. };
  5066. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  5067. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5068. const void *filterbuf, // (appended) string values for filters
  5069. unsigned startoffset,
  5070. unsigned maxnum,
  5071. __int64 *cachehint,
  5072. unsigned *total,
  5073. ISecManager *secmgr,
  5074. ISecUser *secuser)
  5075. {
  5076. class CQueryOrFilter : public CInterface
  5077. {
  5078. unsigned flags;
  5079. StringAttr name;
  5080. StringArray values;
  5081. public:
  5082. IMPLEMENT_IINTERFACE;
  5083. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5084. : flags(_flags), name(_name)
  5085. {
  5086. values.appendListUniq(_value, "|");
  5087. };
  5088. const char* queryName() { return name.get(); };
  5089. unsigned querySearchFlags() { return flags; };
  5090. const StringArray& queryValues() const { return values; };
  5091. };
  5092. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5093. {
  5094. public:
  5095. virtual bool first() override
  5096. {
  5097. curSource = 0;
  5098. while (sources.isItem(curSource))
  5099. {
  5100. if (sources.item(curSource).first())
  5101. return true;
  5102. curSource++;
  5103. }
  5104. return false;
  5105. }
  5106. virtual bool next() override
  5107. {
  5108. if (sources.isItem(curSource))
  5109. {
  5110. if (sources.item(curSource).next())
  5111. return true;
  5112. curSource++;
  5113. while (sources.isItem(curSource))
  5114. {
  5115. if (sources.item(curSource).first())
  5116. return true;
  5117. curSource++;
  5118. }
  5119. }
  5120. return false;
  5121. }
  5122. virtual bool isValid() override
  5123. {
  5124. return sources.isItem(curSource);
  5125. }
  5126. virtual IPropertyTree & query() override
  5127. {
  5128. return sources.item(curSource).query();
  5129. }
  5130. void addSource(IPropertyTreeIterator &source)
  5131. {
  5132. sources.append(source);
  5133. }
  5134. private:
  5135. IArrayOf<IPropertyTreeIterator> sources;
  5136. unsigned curSource = 0;
  5137. };
  5138. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5139. {
  5140. StringAttr xPath;
  5141. StringAttr sortOrder;
  5142. StringAttr nameFilterLo;
  5143. StringAttr nameFilterHi;
  5144. StringArray unknownAttributes;
  5145. Owned<CQueryOrFilter> orFilter;
  5146. public:
  5147. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5148. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5149. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5150. {
  5151. ForEachItemIn(x, _unknownAttributes)
  5152. unknownAttributes.append(_unknownAttributes.item(x));
  5153. }
  5154. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5155. {
  5156. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5157. if (!conn)
  5158. return NULL;
  5159. Owned<IPropertyTreeIterator> iter;
  5160. if (!orFilter)
  5161. {
  5162. iter.setown(conn->getElements(xPath.get()));
  5163. }
  5164. else
  5165. {
  5166. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5167. bool added = false;
  5168. const char* fieldName = orFilter->queryName();
  5169. unsigned flags = orFilter->querySearchFlags();
  5170. const StringArray& values = orFilter->queryValues();
  5171. ForEachItemIn(i, values)
  5172. {
  5173. StringBuffer path(xPath.get());
  5174. const char* value = values.item(i);
  5175. if (!isEmptyString(value))
  5176. {
  5177. appendFilterToQueryString(path, flags, fieldName, value);
  5178. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5179. if (itr)
  5180. {
  5181. multi->addSource(*itr);
  5182. added = true;
  5183. }
  5184. }
  5185. }
  5186. if (added)
  5187. iter.setown(multi.getClear());
  5188. }
  5189. if (!iter)
  5190. return NULL;
  5191. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5192. return conn.getClear();
  5193. }
  5194. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5195. };
  5196. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5197. {
  5198. UniqueScopes done;
  5199. ISecManager *secmgr;
  5200. ISecUser *secuser;
  5201. CriticalSection crit;
  5202. public:
  5203. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5204. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5205. {
  5206. secmgr = _secmgr;
  5207. secuser = _secuser;
  5208. }
  5209. bool isOK(IPropertyTree &tree)
  5210. {
  5211. const char *scopename = tree.queryProp("@scope");
  5212. if (!scopename||!*scopename)
  5213. return true;
  5214. {
  5215. CriticalBlock block(crit);
  5216. const bool *b = done.getValue(scopename);
  5217. if (b)
  5218. return *b;
  5219. }
  5220. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5221. {
  5222. // conceivably could have already been checked and added, but ok.
  5223. CriticalBlock block(crit);
  5224. done.setValue(scopename,ret);
  5225. }
  5226. return ret;
  5227. }
  5228. };
  5229. Owned<CQueryOrFilter> orFilter;
  5230. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5231. StringBuffer query;
  5232. StringBuffer so;
  5233. StringAttr namefilter("*");
  5234. StringAttr namefilterlo;
  5235. StringAttr namefilterhi;
  5236. StringArray unknownAttributes;
  5237. if (filters)
  5238. {
  5239. const char *fv = (const char *) filterbuf;
  5240. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5241. {
  5242. assertex(fv);
  5243. int fmt = filters[i];
  5244. int subfmt = (fmt&0xff);
  5245. if (subfmt==WUSFwuid)
  5246. namefilterlo.set(fv);
  5247. else if (subfmt==WUSFwuidhigh)
  5248. namefilterhi.set(fv);
  5249. else if (subfmt==WUSFwildwuid)
  5250. namefilter.set(fv);
  5251. else if (subfmt==WUSFappvalue)
  5252. {
  5253. const char *app = fv;
  5254. fv = fv + strlen(fv)+1;
  5255. query.append("[Application/").append(app);
  5256. if (*fv)
  5257. query.append("=?~\"").append(fv).append('\"');
  5258. query.append("]");
  5259. }
  5260. else if (subfmt==WUSFtotalthortime)
  5261. {
  5262. query.append("[@totalThorTime>=\"");
  5263. formatTimeCollatable(query, milliToNano(atoi(fv)), false);
  5264. query.append("\"]");
  5265. }
  5266. else if (!*fv)
  5267. {
  5268. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5269. if (subfmt==WUSFtotalthortime)
  5270. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5271. }
  5272. else
  5273. {
  5274. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5275. if (!strchr(fv, '|'))
  5276. appendFilterToQueryString(query, fmt, fieldName, fv);
  5277. else if (orFilter)
  5278. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5279. else
  5280. {
  5281. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5282. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5283. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5284. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5285. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5286. }
  5287. }
  5288. fv = fv + strlen(fv)+1;
  5289. }
  5290. }
  5291. if ((sortorder&0xff)==WUSFtotalthortime)
  5292. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5293. query.insert(0, namefilter.get());
  5294. if (sortorder)
  5295. {
  5296. if (so.length())
  5297. so.append(',');
  5298. if (sortorder & WUSFreverse)
  5299. so.append('-');
  5300. if (sortorder & WUSFnocase)
  5301. so.append('?');
  5302. if (sortorder & WUSFnumeric)
  5303. so.append('#');
  5304. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5305. }
  5306. IArrayOf<IPropertyTree> results;
  5307. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5308. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5309. return new CConstWUArrayIterator(results);
  5310. }
  5311. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5312. {
  5313. WUState ret = WUStateUnknown;
  5314. StringBuffer wuRoot;
  5315. getXPath(wuRoot, wuid);
  5316. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5317. if (timeout == 0) //no need to subscribe
  5318. {
  5319. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5320. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5321. if (it != expectedStates.end())
  5322. return ret;
  5323. switch (ret)
  5324. {
  5325. case WUStateCompiled:
  5326. case WUStateUploadingFiles:
  5327. if (!compiled)
  5328. break;
  5329. //fall through
  5330. case WUStateCompleted:
  5331. case WUStateFailed:
  5332. case WUStateAborted:
  5333. return ret;
  5334. default:
  5335. break;
  5336. }
  5337. return WUStateUnknown;
  5338. }
  5339. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5340. LocalIAbortHandler abortHandler(*waiter);
  5341. if (conn)
  5342. {
  5343. SessionId agent = -1;
  5344. bool agentSessionStopped = false;
  5345. unsigned start = msTick();
  5346. for (;;)
  5347. {
  5348. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5349. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5350. if (it != expectedStates.end())
  5351. return ret;
  5352. switch (ret)
  5353. {
  5354. case WUStateCompiled:
  5355. case WUStateUploadingFiles:
  5356. if (!compiled)
  5357. break;
  5358. // fall into
  5359. case WUStateCompleted:
  5360. case WUStateFailed:
  5361. case WUStateAborted:
  5362. return ret;
  5363. case WUStateWait:
  5364. break;
  5365. case WUStateCompiling:
  5366. case WUStateRunning:
  5367. case WUStateDebugPaused:
  5368. case WUStateDebugRunning:
  5369. case WUStateBlocked:
  5370. case WUStateAborting:
  5371. if (agentSessionStopped)
  5372. {
  5373. reportAbnormalTermination(wuid, ret, agent);
  5374. return ret;
  5375. }
  5376. if (queryDaliServerVersion().compare("2.1")>=0)
  5377. {
  5378. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5379. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5380. {
  5381. agentSessionStopped = true;
  5382. conn->reload();
  5383. continue;
  5384. }
  5385. }
  5386. break;
  5387. }
  5388. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5389. unsigned waited = msTick() - start;
  5390. if (timeout==-1 || waited + 20000 < timeout)
  5391. {
  5392. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5393. if (waiter->isAborted())
  5394. {
  5395. ret = WUStateUnknown; // MORE - throw an exception?
  5396. break;
  5397. }
  5398. }
  5399. else if (waited > timeout || !waiter->wait(timeout-waited))
  5400. {
  5401. ret = WUStateUnknown; // MORE - throw an exception?
  5402. break;
  5403. }
  5404. conn->reload();
  5405. }
  5406. }
  5407. return ret;
  5408. }
  5409. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5410. {
  5411. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5412. LocalIAbortHandler abortHandler(*waiter);
  5413. WUAction ret = WUActionUnknown;
  5414. StringBuffer wuRoot;
  5415. getXPath(wuRoot, wuid);
  5416. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5417. if (conn)
  5418. {
  5419. unsigned start = msTick();
  5420. for (;;)
  5421. {
  5422. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5423. if (ret != original)
  5424. break;
  5425. unsigned waited = msTick() - start;
  5426. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5427. if (waiter->isAborted())
  5428. {
  5429. ret = WUActionUnknown; // MORE - throw an exception?
  5430. break;
  5431. }
  5432. conn->reload();
  5433. }
  5434. }
  5435. waiter->unsubscribe();
  5436. return ret;
  5437. }
  5438. protected:
  5439. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5440. {
  5441. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5442. if (conn)
  5443. {
  5444. CDaliVersion serverVersionNeeded("3.2");
  5445. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5446. conn->queryRoot()->getElements(xpath) :
  5447. conn->getElements(xpath));
  5448. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5449. }
  5450. else
  5451. return NULL;
  5452. }
  5453. ISDSManager *sdsManager;
  5454. SessionId session;
  5455. };
  5456. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5457. {
  5458. if (secmgr)
  5459. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5460. else
  5461. return iter;
  5462. }
  5463. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5464. {
  5465. if (secmgr)
  5466. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5467. else
  5468. return new CConstWUIterator(iter);
  5469. }
  5470. static CriticalSection factoryCrit;
  5471. static Owned<IWorkUnitFactory> factory;
  5472. void CDaliWorkUnitFactory::clientShutdown()
  5473. {
  5474. CriticalBlock b(factoryCrit);
  5475. factory.clear();
  5476. }
  5477. void clientShutdownWorkUnit()
  5478. {
  5479. CriticalBlock b(factoryCrit);
  5480. factory.clear();
  5481. }
  5482. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5483. {
  5484. CriticalBlock b(factoryCrit);
  5485. factory.setown(_factory);
  5486. }
  5487. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5488. {
  5489. if (!factory)
  5490. {
  5491. CriticalBlock b(factoryCrit);
  5492. if (!factory) // 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.
  5493. {
  5494. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5495. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5496. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5497. IPropertyTree *pluginInfo = NULL;
  5498. if (env)
  5499. {
  5500. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5501. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5502. if (daliInfo)
  5503. {
  5504. const char *daliName = daliInfo->queryProp("@name");
  5505. if (daliName)
  5506. {
  5507. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5508. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5509. }
  5510. if (!pluginInfo)
  5511. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5512. }
  5513. }
  5514. if (pluginInfo && !forceDali)
  5515. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5516. else
  5517. factory.setown(new CDaliWorkUnitFactory());
  5518. }
  5519. }
  5520. return factory.getLink();
  5521. }
  5522. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5523. {
  5524. if (!factory)
  5525. {
  5526. CriticalBlock b(factoryCrit);
  5527. if (!factory) // 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.
  5528. factory.setown(new CDaliWorkUnitFactory());
  5529. }
  5530. return factory.getLink();
  5531. }
  5532. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5533. // They can still be supplied if you want...
  5534. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5535. {
  5536. public:
  5537. IMPLEMENT_IINTERFACE;
  5538. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5539. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5540. {
  5541. }
  5542. virtual bool initializeStore()
  5543. {
  5544. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5545. }
  5546. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5547. {
  5548. return baseFactory->getWatcher(subscriber, options, wuid);
  5549. }
  5550. virtual unsigned validateRepository(bool fix)
  5551. {
  5552. return baseFactory->validateRepository(fix);
  5553. }
  5554. virtual void deleteRepository(bool recreate)
  5555. {
  5556. return baseFactory->deleteRepository(recreate);
  5557. }
  5558. virtual void createRepository()
  5559. {
  5560. return baseFactory->createRepository();
  5561. }
  5562. virtual const char *queryStoreType() const
  5563. {
  5564. return baseFactory->queryStoreType();
  5565. }
  5566. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5567. {
  5568. return baseFactory->getUniqueValues(field, prefix, result);
  5569. }
  5570. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5571. {
  5572. if (!secMgr) secMgr = defaultSecMgr.get();
  5573. if (!secUser) secUser = defaultSecUser.get();
  5574. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5575. }
  5576. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5577. {
  5578. if (!secMgr) secMgr = defaultSecMgr.get();
  5579. if (!secUser) secUser = defaultSecUser.get();
  5580. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5581. }
  5582. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5583. {
  5584. if (!secMgr) secMgr = defaultSecMgr.get();
  5585. if (!secUser) secUser = defaultSecUser.get();
  5586. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5587. }
  5588. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5589. {
  5590. if (!secMgr) secMgr = defaultSecMgr.get();
  5591. if (!secUser) secUser = defaultSecUser.get();
  5592. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5593. }
  5594. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5595. {
  5596. if (!secMgr) secMgr = defaultSecMgr.get();
  5597. if (!secUser) secUser = defaultSecUser.get();
  5598. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5599. }
  5600. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5601. {
  5602. if (!secMgr) secMgr = defaultSecMgr.get();
  5603. if (!secUser) secUser = defaultSecUser.get();
  5604. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5605. }
  5606. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5607. {
  5608. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5609. }
  5610. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5611. {
  5612. if (!secMgr) secMgr = defaultSecMgr.get();
  5613. if (!secUser) secUser = defaultSecUser.get();
  5614. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5615. }
  5616. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5617. {
  5618. if (!secMgr) secMgr = defaultSecMgr.get();
  5619. if (!secUser) secUser = defaultSecUser.get();
  5620. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5621. }
  5622. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5623. {
  5624. if (!secMgr) secMgr = defaultSecMgr.get();
  5625. if (!secUser) secUser = defaultSecUser.get();
  5626. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5627. }
  5628. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5629. {
  5630. if (!secMgr) secMgr = defaultSecMgr.get();
  5631. if (!secUser) secUser = defaultSecUser.get();
  5632. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5633. }
  5634. virtual int setTracingLevel(int newLevel)
  5635. {
  5636. return baseFactory->setTracingLevel(newLevel);
  5637. }
  5638. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5639. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5640. const void *filterbuf, // (appended) string values for filters
  5641. unsigned startoffset,
  5642. unsigned maxnum,
  5643. __int64 *cachehint,
  5644. unsigned *total,
  5645. ISecManager *secMgr, ISecUser *secUser)
  5646. {
  5647. if (!secMgr) secMgr = defaultSecMgr.get();
  5648. if (!secUser) secUser = defaultSecUser.get();
  5649. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5650. }
  5651. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5652. WUQuerySortField *filters,
  5653. const void *filterbuf,
  5654. unsigned startoffset,
  5655. unsigned maxnum,
  5656. __int64 *cachehint,
  5657. unsigned *total,
  5658. const MapStringTo<bool> *subset)
  5659. {
  5660. // MORE - why no security?
  5661. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  5662. }
  5663. virtual unsigned numWorkUnits()
  5664. {
  5665. return baseFactory->numWorkUnits();
  5666. }
  5667. virtual bool isAborting(const char *wuid) const
  5668. {
  5669. return baseFactory->isAborting(wuid);
  5670. }
  5671. virtual void clearAborting(const char *wuid)
  5672. {
  5673. baseFactory->clearAborting(wuid);
  5674. }
  5675. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5676. {
  5677. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, expectedStates);
  5678. }
  5679. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5680. {
  5681. return baseFactory->waitForWorkUnitAction(wuid, original);
  5682. }
  5683. private:
  5684. Owned<IWorkUnitFactory> baseFactory;
  5685. Linked<ISecManager> defaultSecMgr;
  5686. Linked<ISecUser> defaultSecUser;
  5687. };
  5688. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5689. {
  5690. if (secmgr && secuser)
  5691. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5692. else
  5693. return getWorkUnitFactory();
  5694. }
  5695. //==========================================================================================
  5696. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5697. {
  5698. Owned<IPropertyTreeIterator> it;
  5699. public:
  5700. IMPLEMENT_IINTERFACE;
  5701. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5702. virtual bool first() { return it->first(); }
  5703. virtual bool next() { return it->next(); }
  5704. virtual bool isValid() { return it->isValid(); }
  5705. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5706. };
  5707. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5708. {
  5709. Owned<IPropertyTreeIterator> it;
  5710. public:
  5711. IMPLEMENT_IINTERFACE;
  5712. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5713. virtual bool first() { return it->first(); }
  5714. virtual bool next() { return it->next(); }
  5715. virtual bool isValid() { return it->isValid(); }
  5716. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5717. };
  5718. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5719. {
  5720. Owned<IPropertyTreeIterator> it;
  5721. StringAttr name;
  5722. public:
  5723. IMPLEMENT_IINTERFACE;
  5724. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  5725. virtual bool first() { return it->first(); }
  5726. virtual bool next() { return it->next(); }
  5727. virtual bool isValid() { return it->isValid(); }
  5728. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  5729. };
  5730. //==========================================================================================
  5731. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5732. {
  5733. clearCached(false);
  5734. secMgr.set(secmgr);
  5735. secUser.set(secuser);
  5736. workflowIteratorCached = false;
  5737. resultsCached = false;
  5738. graphsCached = false;
  5739. temporariesCached = false;
  5740. variablesCached = false;
  5741. exceptionsCached = false;
  5742. pluginsCached = false;
  5743. librariesCached = false;
  5744. activitiesCached = false;
  5745. webServicesInfoCached = false;
  5746. roxieQueryInfoCached = false;
  5747. }
  5748. void CLocalWorkUnit::clearCached(bool clearTree)
  5749. {
  5750. query.clear();
  5751. webServicesInfo.clear();
  5752. workflowIterator.clear();
  5753. graphs.kill();
  5754. results.kill();
  5755. variables.kill();
  5756. plugins.kill();
  5757. libraries.kill();
  5758. exceptions.kill();
  5759. temporaries.kill();
  5760. statistics.kill();
  5761. appvalues.kill();
  5762. if (clearTree)
  5763. p.clear();
  5764. workflowIteratorCached = false;
  5765. resultsCached = false;
  5766. graphsCached = false;
  5767. temporariesCached = false;
  5768. variablesCached = false;
  5769. exceptionsCached = false;
  5770. pluginsCached = false;
  5771. librariesCached = false;
  5772. activitiesCached = false;
  5773. webServicesInfoCached = false;
  5774. roxieQueryInfoCached = false;
  5775. }
  5776. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  5777. {
  5778. clearCached(false);
  5779. p.setown(ptree);
  5780. }
  5781. void CLocalWorkUnit::beforeDispose()
  5782. {
  5783. try
  5784. {
  5785. unsubscribe();
  5786. clearCached(true);
  5787. userDesc.clear();
  5788. secMgr.clear();
  5789. secUser.clear();
  5790. }
  5791. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  5792. }
  5793. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  5794. {
  5795. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  5796. // Delete any related things in SDS etc that might otherwise be forgotten
  5797. if (p->getPropBool("@protected", false))
  5798. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  5799. switch (getState())
  5800. {
  5801. case WUStateAborted:
  5802. case WUStateCompleted:
  5803. case WUStateFailed:
  5804. case WUStateArchived:
  5805. break;
  5806. case WUStateCompiled:
  5807. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  5808. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5809. break;
  5810. case WUStateWait:
  5811. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  5812. default:
  5813. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5814. break;
  5815. }
  5816. if (getIsQueryService())
  5817. {
  5818. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  5819. if (registry)
  5820. {
  5821. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  5822. if (registry->hasProp(xpath.str()))
  5823. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  5824. }
  5825. }
  5826. try
  5827. {
  5828. if (deldll && !p->getPropBool("@isClone", false))
  5829. {
  5830. Owned<IConstWUQuery> q = getQuery();
  5831. if (q)
  5832. {
  5833. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5834. SCMStringBuffer name;
  5835. ForEach(*iter)
  5836. {
  5837. IConstWUAssociatedFile & cur = iter->query();
  5838. cur.getNameTail(name);
  5839. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  5840. {
  5841. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5842. if (entry.get())
  5843. asyncRemoveDll(name.str());
  5844. else
  5845. {
  5846. SCMStringBuffer ip, localPath;
  5847. cur.getName(localPath);
  5848. cur.getIp(ip);
  5849. asyncRemoveFile(ip.str(), localPath.str());
  5850. }
  5851. }
  5852. }
  5853. }
  5854. }
  5855. factory->clearAborting(queryWuid());
  5856. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  5857. }
  5858. catch(IException *E)
  5859. {
  5860. StringBuffer s;
  5861. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  5862. E->Release();
  5863. }
  5864. catch (...)
  5865. {
  5866. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  5867. }
  5868. }
  5869. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  5870. {
  5871. SCMStringBuffer strval;
  5872. val.getGmtString(strval);
  5873. p->setProp("@timescheduled",strval.str());
  5874. }
  5875. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  5876. {
  5877. StringBuffer str;
  5878. p->getProp("@timescheduled",str);
  5879. if(str.length())
  5880. val.setGmtString(str.str());
  5881. return val;
  5882. }
  5883. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  5884. {
  5885. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  5886. if (extra.length())
  5887. {
  5888. const char *bufStart = buf.str();
  5889. const char *bufPtr = bufStart+buf.length();
  5890. while (bufStart != bufPtr)
  5891. {
  5892. --bufPtr;
  5893. if (!isspace(*bufPtr))
  5894. break;
  5895. }
  5896. assertex('>' == *bufPtr);
  5897. size_t l = strlen(wuid);
  5898. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  5899. bufPtr -= l+2; // skip back over </wuid
  5900. assertex(0 == memcmp(bufPtr, "</", 2) );
  5901. assertex(0 == memcmp(bufPtr+2, wuid, l));
  5902. buf.insert(bufPtr-bufStart, extra);
  5903. }
  5904. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  5905. }
  5906. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  5907. {
  5908. CriticalBlock block(crit);
  5909. StringBuffer path(base);
  5910. if (!p)
  5911. return false;
  5912. const char *wuid = p->queryName();
  5913. if (!wuid||!*wuid)
  5914. return false;
  5915. addPathSepChar(path).append(wuid).append(".xml");
  5916. Owned<IFile> file = createIFile(path.str());
  5917. if (!file)
  5918. return false;
  5919. Owned<IFileIO> fileio = file->open(IFOcreate);
  5920. if (!fileio)
  5921. return false;
  5922. StringBuffer buf;
  5923. exportWorkUnitToXML(this, buf, false, false, true);
  5924. StringBuffer extraWorkUnitXML;
  5925. Owned<IPTree> graphProgress = getGraphProgressTree();
  5926. if (graphProgress)
  5927. {
  5928. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  5929. graphProgress.clear();
  5930. }
  5931. Owned<IConstWUQuery> q = getQuery();
  5932. if (!q)
  5933. {
  5934. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5935. return false;
  5936. if (del)
  5937. {
  5938. if (getState()==WUStateUnknown)
  5939. setState(WUStateArchived); // to allow delete
  5940. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  5941. }
  5942. return false;
  5943. }
  5944. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  5945. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5946. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  5947. ForEach(*iter)
  5948. {
  5949. IConstWUAssociatedFile & cur = iter->query();
  5950. SCMStringBuffer name;
  5951. cur.getNameTail(name);
  5952. if (name.length())
  5953. {
  5954. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5955. SCMStringBuffer curPath, curIp;
  5956. cur.getName(curPath);
  5957. cur.getIp(curIp);
  5958. SocketEndpoint curEp(curIp.str());
  5959. RemoteFilename curRfn;
  5960. curRfn.setPath(curEp, curPath.str());
  5961. StringBuffer dst(base);
  5962. addPathSepChar(dst);
  5963. curRfn.getTail(dst);
  5964. Owned<IFile> dstFile = createIFile(dst.str());
  5965. if (entry.get())
  5966. {
  5967. Owned<IException> exception;
  5968. Owned<IDllLocation> loc;
  5969. Owned<IPropertyTree> generatedDllBranch = createPTree();
  5970. generatedDllBranch->setProp("@name", entry->queryName());
  5971. generatedDllBranch->setProp("@kind", entry->queryKind());
  5972. if (exportAssociatedFiles)
  5973. {
  5974. try
  5975. {
  5976. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  5977. }
  5978. catch(IException * e)
  5979. {
  5980. exception.setown(e);
  5981. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  5982. }
  5983. RemoteFilename filename;
  5984. loc->getDllFilename(filename);
  5985. if (!exception)
  5986. {
  5987. Owned<IFile> srcfile = createIFile(filename);
  5988. try
  5989. {
  5990. if (dstFile->exists())
  5991. {
  5992. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  5993. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  5994. // still want to delete if already archived but there are source file copies
  5995. }
  5996. else
  5997. copyFile(dstFile, srcfile);
  5998. }
  5999. catch(IException * e)
  6000. {
  6001. exception.setown(e);
  6002. }
  6003. }
  6004. if (exception)
  6005. {
  6006. if (ignoredllerrors)
  6007. {
  6008. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  6009. //copy failed, so don't delete the registered dll files
  6010. deleteExclusions.append(name.str());
  6011. }
  6012. else
  6013. throw exception.getClear();
  6014. }
  6015. }
  6016. // Record Associated path to restore back to
  6017. StringBuffer restorePath;
  6018. curRfn.getRemotePath(restorePath);
  6019. generatedDllBranch->setProp("@location", restorePath.str());
  6020. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  6021. }
  6022. else if (exportAssociatedFiles) // no generated dll entry
  6023. {
  6024. Owned<IFile> srcFile = createIFile(curRfn);
  6025. try
  6026. {
  6027. copyFile(dstFile, srcFile);
  6028. }
  6029. catch (IException *e)
  6030. {
  6031. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  6032. EXCLOG(e, msg.str());
  6033. e->Release();
  6034. deleteExclusions.append(name.str());
  6035. }
  6036. }
  6037. }
  6038. }
  6039. iter.clear();
  6040. if (generatedDlls->numChildren())
  6041. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  6042. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  6043. return false;
  6044. if (del)
  6045. {
  6046. //setState(WUStateArchived); // this isn't useful as about to delete it!
  6047. q.clear();
  6048. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  6049. }
  6050. return true;
  6051. }
  6052. void CLocalWorkUnit::loadXML(const char *xml)
  6053. {
  6054. CriticalBlock block(crit);
  6055. clearCached(true);
  6056. assertex(xml);
  6057. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  6058. }
  6059. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  6060. {
  6061. CriticalBlock block(crit);
  6062. StringBuffer x;
  6063. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  6064. }
  6065. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  6066. {
  6067. CriticalBlock block(crit);
  6068. StringAttr value;
  6069. src.read(value);
  6070. loadXML(value);
  6071. }
  6072. void CLocalWorkUnit::requestAbort()
  6073. {
  6074. CriticalBlock block(crit);
  6075. abortWorkUnit(p->queryName());
  6076. }
  6077. void CLocalWorkUnit::unlockRemote()
  6078. {
  6079. CriticalBlock block(crit);
  6080. locked.unlock();
  6081. _unlockRemote();
  6082. }
  6083. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6084. {
  6085. if (secMgr)
  6086. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6087. locked.lock();
  6088. CriticalBlock block(crit);
  6089. if (commit)
  6090. {
  6091. try
  6092. {
  6093. _lockRemote();
  6094. }
  6095. catch (IException *E)
  6096. {
  6097. StringBuffer s;
  6098. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6099. locked.unlock();
  6100. throw;
  6101. }
  6102. }
  6103. return *new CLockedWorkUnit(LINK(this));
  6104. }
  6105. void CLocalWorkUnit::commit()
  6106. {
  6107. // Nothing to do if not backed by a persistent store
  6108. }
  6109. IWorkUnit& CLocalWorkUnit::lock()
  6110. {
  6111. return lockRemote(true);
  6112. }
  6113. const char *CLocalWorkUnit::queryWuid() const
  6114. {
  6115. CriticalBlock block(crit);
  6116. return p->queryName();
  6117. }
  6118. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6119. {
  6120. CriticalBlock block(crit);
  6121. return p->getPropInt("@DebugListenerPort", 0);
  6122. }
  6123. unsigned CLocalWorkUnit::getTotalThorTime() const
  6124. {
  6125. CriticalBlock block(crit);
  6126. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6127. }
  6128. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6129. {
  6130. CriticalBlock block(crit);
  6131. p->setPropInt("@DebugListenerPort", port);
  6132. }
  6133. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6134. {
  6135. CriticalBlock block(crit);
  6136. ip.set(p->queryProp("@DebugListenerIP"));
  6137. return ip;
  6138. }
  6139. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6140. {
  6141. CriticalBlock block(crit);
  6142. p->setProp("@DebugListenerIP", ip);
  6143. }
  6144. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6145. {
  6146. CriticalBlock block(crit);
  6147. datoken.set(p->queryProp("@distributedAccessToken"));
  6148. return datoken;
  6149. }
  6150. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6151. {
  6152. CriticalBlock block(crit);
  6153. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6154. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6155. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6156. if (pDSM && pDSM->isDigiSignerConfigured())
  6157. {
  6158. datoken.append(pDSM->queryKeyName()).append(';');
  6159. StringBuffer b64Signature;
  6160. if (pDSM->digiSign(b64Signature, datoken))
  6161. {
  6162. datoken.append(b64Signature.str());
  6163. }
  6164. else
  6165. {
  6166. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6167. return false;
  6168. }
  6169. }
  6170. else
  6171. {
  6172. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6173. datoken.append(";");
  6174. }
  6175. p->setProp("@distributedAccessToken", datoken);
  6176. return true;
  6177. }
  6178. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6179. {
  6180. // Only implemented in derived classes
  6181. return false;
  6182. }
  6183. void CLocalWorkUnit::setJobName(const char *value)
  6184. {
  6185. CriticalBlock block(crit);
  6186. p->setProp("@jobName", value);
  6187. }
  6188. const char *CLocalWorkUnit::queryJobName() const
  6189. {
  6190. CriticalBlock block(crit);
  6191. const char *ret = p->queryProp("@jobName");
  6192. if (!ret)
  6193. ret = "";
  6194. return ret;
  6195. }
  6196. void CLocalWorkUnit::setClusterName(const char *value)
  6197. {
  6198. CriticalBlock block(crit);
  6199. p->setProp("@clusterName", value);
  6200. }
  6201. const char *CLocalWorkUnit::queryClusterName() const
  6202. {
  6203. CriticalBlock block(crit);
  6204. const char *ret = p->queryProp("@clusterName");
  6205. if (!ret)
  6206. ret = "";
  6207. return ret;
  6208. }
  6209. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6210. {
  6211. setDebugValue("allowedclusters",value, true);
  6212. }
  6213. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6214. {
  6215. CriticalBlock block(crit);
  6216. getDebugValue("allowedclusters",str);
  6217. if (str.length()!=0)
  6218. return str;
  6219. str.set(p->queryProp("@clusterName"));
  6220. return str;
  6221. }
  6222. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6223. {
  6224. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6225. }
  6226. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6227. {
  6228. CriticalBlock block(crit);
  6229. return getDebugValueBool("allowautoqueueswitch",false);
  6230. }
  6231. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6232. {
  6233. StringBuffer suffix;
  6234. if (name && *name)
  6235. setApplicationValue("LibraryModule", "name", name, true);
  6236. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6237. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6238. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6239. }
  6240. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6241. {
  6242. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6243. if (writeaccess)
  6244. auditflags |= DALI_LDAP_WRITE_WANTED;
  6245. SecAccessFlags perm = SecAccess_Full;
  6246. const char *scopename = p->queryProp("@scope");
  6247. if (scopename&&*scopename) {
  6248. if (!user)
  6249. user = queryUserDescriptor();
  6250. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6251. if (perm<0) {
  6252. if (perm == SecAccess_Unavailable)
  6253. perm = SecAccess_Full;
  6254. else
  6255. perm = SecAccess_None;
  6256. }
  6257. }
  6258. if (!HASREADPERMISSION(perm))
  6259. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6260. if (writeaccess && !HASWRITEPERMISSION(perm))
  6261. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6262. }
  6263. void CLocalWorkUnit::setUser(const char * value)
  6264. {
  6265. CriticalBlock block(crit);
  6266. p->setProp("@submitID", value);
  6267. }
  6268. const char *CLocalWorkUnit::queryUser() const
  6269. {
  6270. CriticalBlock block(crit);
  6271. const char *ret = p->queryProp("@submitID");
  6272. if (!ret)
  6273. ret = "";
  6274. return ret;
  6275. }
  6276. void CLocalWorkUnit::setWuScope(const char * value)
  6277. {
  6278. if (value && *value)
  6279. {
  6280. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6281. {
  6282. CriticalBlock block(crit);
  6283. p->setProp("@scope", value);
  6284. }
  6285. }
  6286. }
  6287. const char *CLocalWorkUnit::queryWuScope() const
  6288. {
  6289. CriticalBlock block(crit);
  6290. const char *ret = p->queryProp("@scope");
  6291. if (!ret)
  6292. ret = "";
  6293. return ret;
  6294. }
  6295. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6296. {
  6297. CriticalBlock block(crit);
  6298. setEnum(p, "@priorityClass", cls, priorityClasses);
  6299. }
  6300. WUPriorityClass CLocalWorkUnit::getPriority() const
  6301. {
  6302. CriticalBlock block(crit);
  6303. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6304. }
  6305. const char *CLocalWorkUnit::queryPriorityDesc() const
  6306. {
  6307. return getEnumText(getPriority(), priorityClasses);
  6308. }
  6309. void CLocalWorkUnit::setState(WUState value)
  6310. {
  6311. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6312. {
  6313. if (factory)
  6314. factory->clearAborting(queryWuid());
  6315. }
  6316. CriticalBlock block(crit);
  6317. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6318. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6319. if (getDebugValueBool("monitorWorkunit", false))
  6320. {
  6321. switch(value)
  6322. {
  6323. case WUStateAborted:
  6324. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6325. break;
  6326. case WUStateCompleted:
  6327. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6328. break;
  6329. case WUStateFailed:
  6330. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6331. break;
  6332. }
  6333. }
  6334. p->removeProp("@stateEx");
  6335. }
  6336. void CLocalWorkUnit::setStateEx(const char * text)
  6337. {
  6338. CriticalBlock block(crit);
  6339. p->setProp("@stateEx", text);
  6340. }
  6341. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6342. {
  6343. CriticalBlock block(crit);
  6344. p->setPropInt64("@agentSession", sessionId);
  6345. }
  6346. bool CLocalWorkUnit::getIsQueryService() const
  6347. {
  6348. CriticalBlock block(crit);
  6349. return p->getPropBool("@isQueryService", false);
  6350. }
  6351. void CLocalWorkUnit::setIsQueryService(bool value)
  6352. {
  6353. CriticalBlock block(crit);
  6354. p->setPropBool("@isQueryService", value);
  6355. }
  6356. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6357. {
  6358. if (queryDaliServerVersion().compare("2.1")<0)
  6359. return;
  6360. switch(state)
  6361. {
  6362. case WUStateRunning:
  6363. case WUStateDebugPaused:
  6364. case WUStateDebugRunning:
  6365. case WUStateBlocked:
  6366. case WUStateAborting:
  6367. case WUStateCompiling:
  6368. case WUStatePaused:
  6369. {
  6370. SessionId agent = getAgentSession();
  6371. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6372. {
  6373. forceReload();
  6374. state = (WUState) getEnum(p, "@state", states);
  6375. bool isecl=state==WUStateCompiling;
  6376. if (aborting())
  6377. state = WUStateAborted;
  6378. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6379. state = WUStateFailed;
  6380. else
  6381. return;
  6382. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6383. Owned<IWorkUnit> w = &lock();
  6384. w->setState(state);
  6385. Owned<IWUException> e = w->createException();
  6386. WUAction action = w->getAction();
  6387. switch (action)
  6388. {
  6389. case WUActionPause:
  6390. case WUActionPauseNow:
  6391. case WUActionResume:
  6392. w->setAction(WUActionUnknown);
  6393. }
  6394. if(isecl)
  6395. {
  6396. e->setExceptionCode(1001);
  6397. e->setExceptionMessage("EclServer terminated unexpectedly");
  6398. }
  6399. else
  6400. {
  6401. e->setExceptionCode(1000);
  6402. e->setExceptionMessage("Workunit terminated unexpectedly");
  6403. }
  6404. }
  6405. }
  6406. }
  6407. }
  6408. WUState CLocalWorkUnit::getState() const
  6409. {
  6410. CriticalBlock block(crit);
  6411. WUState state = (WUState) getEnum(p, "@state", states);
  6412. switch (state)
  6413. {
  6414. case WUStateRunning:
  6415. case WUStateDebugPaused:
  6416. case WUStateDebugRunning:
  6417. case WUStateBlocked:
  6418. case WUStateCompiling:
  6419. if (aborting())
  6420. state = WUStateAborting;
  6421. break;
  6422. case WUStateSubmitted:
  6423. if (aborting())
  6424. state = WUStateAborted;
  6425. break;
  6426. }
  6427. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6428. return state;
  6429. }
  6430. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6431. {
  6432. CriticalBlock block(crit);
  6433. str.set(p->queryProp("@stateEx"));
  6434. return str;
  6435. }
  6436. __int64 CLocalWorkUnit::getAgentSession() const
  6437. {
  6438. CriticalBlock block(crit);
  6439. return p->getPropInt64("@agentSession", -1);
  6440. }
  6441. unsigned CLocalWorkUnit::getAgentPID() const
  6442. {
  6443. CriticalBlock block(crit);
  6444. return p->getPropInt("@agentPID", -1);
  6445. }
  6446. const char * CLocalWorkUnit::queryStateDesc() const
  6447. {
  6448. // MORE - not sure about this - may prefer a separate interface
  6449. CriticalBlock block(crit);
  6450. try
  6451. {
  6452. return getEnumText(getState(), states);
  6453. }
  6454. catch (...)
  6455. {
  6456. return "???";
  6457. }
  6458. }
  6459. void CLocalWorkUnit::setAction(WUAction value)
  6460. {
  6461. CriticalBlock block(crit);
  6462. setEnum(p, "Action", value, actions);
  6463. }
  6464. WUAction CLocalWorkUnit::getAction() const
  6465. {
  6466. CriticalBlock block(crit);
  6467. return (WUAction) getEnum(p, "Action", actions);
  6468. }
  6469. const char *CLocalWorkUnit::queryActionDesc() const
  6470. {
  6471. CriticalBlock block(crit);
  6472. return p->queryProp("Action");
  6473. }
  6474. bool CLocalWorkUnit::hasApplicationValue(const char *app, const char *propname) const
  6475. {
  6476. StringBuffer prop("Application/");
  6477. prop.append(app).append('/').append(propname);
  6478. CriticalBlock block(crit);
  6479. return p->hasProp(prop);
  6480. }
  6481. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6482. {
  6483. StringBuffer prop("Application/");
  6484. prop.append(app).append('/').append(propname);
  6485. CriticalBlock block(crit);
  6486. str.set(p->queryProp(prop.str()));
  6487. return str;
  6488. }
  6489. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6490. {
  6491. StringBuffer prop("Application/");
  6492. prop.append(app).append('/').append(propname);
  6493. CriticalBlock block(crit);
  6494. return p->getPropInt(prop.str(), defVal);
  6495. }
  6496. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6497. {
  6498. CriticalBlock block(crit);
  6499. appvalues.load(p,"Application/*");
  6500. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6501. }
  6502. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6503. {
  6504. CriticalBlock block(crit);
  6505. StringBuffer prop("Application/");
  6506. prop.append(app).append('/').append(propname);
  6507. if (overwrite || !p->hasProp(prop.str()))
  6508. {
  6509. StringBuffer sp;
  6510. p->setProp(sp.append("Application").str(), "");
  6511. p->setProp(sp.append('/').append(app).str(), "");
  6512. p->setProp(prop.str(), value);
  6513. }
  6514. }
  6515. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6516. {
  6517. VStringBuffer s("%d", value);
  6518. setApplicationValue(app, propname, s, overwrite);
  6519. }
  6520. void CLocalWorkUnit::setPriorityLevel(int level)
  6521. {
  6522. CriticalBlock block(crit);
  6523. p->setPropInt("PriorityFlag", level);
  6524. }
  6525. int CLocalWorkUnit::getPriorityLevel() const
  6526. {
  6527. CriticalBlock block(crit);
  6528. return p->getPropInt("PriorityFlag");
  6529. }
  6530. int calcPriorityValue(const IPropertyTree * p)
  6531. {
  6532. int priority = p->getPropInt("PriorityFlag");
  6533. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6534. {
  6535. case PriorityClassLow:
  6536. priority -= 100;
  6537. break;
  6538. case PriorityClassHigh:
  6539. priority += 100;
  6540. break;
  6541. }
  6542. return priority;
  6543. }
  6544. int CLocalWorkUnit::getPriorityValue() const
  6545. {
  6546. CriticalBlock block(crit);
  6547. return calcPriorityValue(p);
  6548. }
  6549. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6550. {
  6551. CriticalBlock block(crit);
  6552. p->setPropInt("RescheduleFlag", (int) value);
  6553. }
  6554. bool CLocalWorkUnit::getRescheduleFlag() const
  6555. {
  6556. CriticalBlock block(crit);
  6557. return p->getPropInt("RescheduleFlag") != 0;
  6558. }
  6559. class NullIStringIterator : implements IStringIterator, public CInterface
  6560. {
  6561. public:
  6562. IMPLEMENT_IINTERFACE;
  6563. bool first() { return false; }
  6564. bool next() { return false; }
  6565. bool isValid() { return false; }
  6566. IStringVal & str(IStringVal & str) { return str; }
  6567. };
  6568. ClusterType getClusterType(const char * platform, ClusterType dft)
  6569. {
  6570. if (stricmp(platform, "thor") == 0)
  6571. return ThorLCRCluster;
  6572. if (stricmp(platform, "thorlcr") == 0)
  6573. return ThorLCRCluster;
  6574. if (stricmp(platform, "hthor") == 0)
  6575. return HThorCluster;
  6576. if (stricmp(platform, "roxie") == 0)
  6577. return RoxieCluster;
  6578. return dft;
  6579. }
  6580. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6581. {
  6582. switch (clusterType)
  6583. {
  6584. case ThorLCRCluster:
  6585. if (lcrSensitive)
  6586. return "thorlcr";
  6587. return "thor";
  6588. case RoxieCluster:
  6589. return "roxie";
  6590. case HThorCluster:
  6591. return "hthor";
  6592. }
  6593. throwUnexpected();
  6594. }
  6595. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6596. {
  6597. if (!isWorkunitDAToken(distributedAccessToken))
  6598. {
  6599. DBGLOG("Not a valid workunit distributed access token");
  6600. return false;
  6601. }
  6602. //Extract the string between [ and ]
  6603. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6604. StringBuffer tokenValues;
  6605. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6606. StringArray nameValues;
  6607. nameValues.appendList(tokenValues.str(), ",",true);
  6608. if (user || wuid)
  6609. {
  6610. for (int x = 0; x < nameValues.ordinality(); x++)
  6611. {
  6612. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6613. user->append(nameValues[x] + 2);
  6614. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6615. wuid->append(nameValues[x] + 2);
  6616. }
  6617. }
  6618. if (privKey)
  6619. {
  6620. const char * finger = pEndBracket;
  6621. ++finger;
  6622. while (*finger && *finger != ';')
  6623. privKey->append(1, finger++);
  6624. }
  6625. return true;
  6626. }
  6627. //Verifies the given signed workunit distributed access token was created
  6628. //and signed by the given wuid and user, and that the workunit is still active
  6629. //Returns:
  6630. // 0 : Success, token is valid and workunit is active
  6631. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6632. // 2 : Workunit not active
  6633. // Throws if unable to open workunit
  6634. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6635. {
  6636. if (isEmptyString(daToken))
  6637. {
  6638. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6639. return wuTokenInvalid;
  6640. }
  6641. StringBuffer tokWuid;
  6642. StringBuffer tokUser;
  6643. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6644. {
  6645. //Not a valid workunit distributed access token
  6646. return wuTokenInvalid;
  6647. }
  6648. //Validate signature
  6649. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6650. if (pDSM && pDSM->isDigiVerifierConfigured())
  6651. {
  6652. const char * finger;
  6653. StringBuffer token;//receives copy of everything up until signature
  6654. for (finger = daToken; *finger && *finger != ';'; finger++)
  6655. token.append(1, finger);
  6656. token.append(1, finger);//append ;
  6657. StringBuffer sig(++finger);
  6658. if (!pDSM->digiVerify(sig, token))
  6659. {
  6660. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6661. return wuTokenInvalid;
  6662. }
  6663. }
  6664. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6665. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6666. if(!cw)
  6667. {
  6668. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6669. }
  6670. //Verify user matches
  6671. bool wuUserExist = !isEmptyString(cw->queryUser());
  6672. bool tokUserExist = !isEmptyString(tokUser.str());
  6673. bool ctxUserExist = !isEmptyString(ctxUser);
  6674. if (wuUserExist && tokUserExist)
  6675. {
  6676. //if both users are found, they must match
  6677. if (!streq(tokUser.str(), cw->queryUser()))
  6678. {
  6679. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6680. return wuTokenInvalid;//Possible Internal error
  6681. }
  6682. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6683. {
  6684. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6685. return wuTokenInvalid;
  6686. }
  6687. }
  6688. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6689. {
  6690. if (ctxUserExist)
  6691. {
  6692. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6693. return wuTokenInvalid;
  6694. }
  6695. //both users empty and no context user means if no security enabled
  6696. }
  6697. else
  6698. {
  6699. //one user found, but not the other, treat as an error
  6700. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6701. return wuTokenInvalid;
  6702. }
  6703. // no need to compare tokWuid with workunit wuid, because it will always match
  6704. bool wuActive;
  6705. switch (cw->getState())
  6706. {
  6707. case WUStateRunning:
  6708. case WUStateDebugRunning:
  6709. case WUStateBlocked:
  6710. case WUStateAborting:
  6711. case WUStateUploadingFiles:
  6712. #ifdef _DEBUG
  6713. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6714. #endif
  6715. wuActive = true;
  6716. break;
  6717. default:
  6718. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6719. wuActive = false;
  6720. break;
  6721. }
  6722. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6723. }
  6724. bool CLocalWorkUnit::resolveFilePrefix(StringBuffer & prefix, const char * queue) const
  6725. {
  6726. if (hasApplicationValue("prefix", queue))
  6727. {
  6728. getApplicationValue("prefix", queue, StringBufferAdaptor(prefix));
  6729. return true;
  6730. }
  6731. #ifndef _CONTAINERIZED
  6732. Owned<IConstWUClusterInfo> ci = getTargetClusterInfo(queue);
  6733. if (ci)
  6734. {
  6735. ci->getScope(StringBufferAdaptor(prefix));
  6736. return true;
  6737. }
  6738. #endif
  6739. return false;
  6740. }
  6741. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  6742. {
  6743. StringBuffer prefix;
  6744. CriticalBlock block(crit);
  6745. if (p->hasProp("Debug/ForceScope"))
  6746. {
  6747. prefix.append(p->queryProp("Debug/ForceScope")).toLowerCase();
  6748. }
  6749. else
  6750. {
  6751. resolveFilePrefix(prefix, p->queryProp("@clusterName"));
  6752. }
  6753. str.set(prefix.str());
  6754. return str;
  6755. }
  6756. //Queries
  6757. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  6758. {
  6759. CriticalBlock block(crit);
  6760. p->setPropInt("@codeVersion", codeVersion);
  6761. p->setProp("@buildVersion", buildVersion);
  6762. p->setProp("@eclVersion", eclVersion);
  6763. }
  6764. unsigned CLocalWorkUnit::getCodeVersion() const
  6765. {
  6766. CriticalBlock block(crit);
  6767. return p->getPropInt("@codeVersion");
  6768. }
  6769. unsigned CLocalWorkUnit::getWuidVersion() const
  6770. {
  6771. CriticalBlock block(crit);
  6772. return p->getPropInt("@wuidVersion");
  6773. }
  6774. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  6775. {
  6776. CriticalBlock block(crit);
  6777. buildVersion.set(p->queryProp("@buildVersion"));
  6778. eclVersion.set(p->queryProp("@eclVersion"));
  6779. }
  6780. void CLocalWorkUnit::setCloneable(bool value)
  6781. {
  6782. CriticalBlock block(crit);
  6783. p->setPropInt("@cloneable", value);
  6784. }
  6785. void CLocalWorkUnit::setIsClone(bool value)
  6786. {
  6787. CriticalBlock block(crit);
  6788. p->setPropInt("@isClone", value);
  6789. }
  6790. bool CLocalWorkUnit::getCloneable() const
  6791. {
  6792. CriticalBlock block(crit);
  6793. return p->getPropBool("@cloneable", false);
  6794. }
  6795. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  6796. {
  6797. CriticalBlock block(crit);
  6798. if (!userDesc)
  6799. {
  6800. userDesc.setown(createUserDescriptor());
  6801. SCMStringBuffer token;
  6802. getWorkunitDistributedAccessToken(token);
  6803. userDesc->set(queryUser(), token.str());//use token as password
  6804. }
  6805. return userDesc;
  6806. }
  6807. bool CLocalWorkUnit::isProtected() const
  6808. {
  6809. CriticalBlock block(crit);
  6810. return p->getPropBool("@protected", false);
  6811. }
  6812. bool CLocalWorkUnit::isPausing() const
  6813. {
  6814. CriticalBlock block(crit);
  6815. if (WUActionPause == getAction())
  6816. {
  6817. switch (getState())
  6818. {
  6819. case WUStateRunning:
  6820. case WUStateAborting:
  6821. return true;
  6822. }
  6823. }
  6824. return false;
  6825. }
  6826. void CLocalWorkUnit::protect(bool protectMode)
  6827. {
  6828. CriticalBlock block(crit);
  6829. p->setPropBool("@protected", protectMode);
  6830. }
  6831. void CLocalWorkUnit::setResultLimit(unsigned value)
  6832. {
  6833. CriticalBlock block(crit);
  6834. p->setPropInt("resultLimit", value);
  6835. }
  6836. unsigned CLocalWorkUnit::getResultLimit() const
  6837. {
  6838. CriticalBlock block(crit);
  6839. return p->getPropInt("resultLimit");
  6840. }
  6841. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  6842. {
  6843. CriticalBlock block(crit);
  6844. str.set(p->queryProp("SNAPSHOT"));
  6845. return str;
  6846. }
  6847. void CLocalWorkUnit::setSnapshot(const char * val)
  6848. {
  6849. CriticalBlock block(crit);
  6850. p->setProp("SNAPSHOT", val);
  6851. }
  6852. const static EnumMapping warningSeverityMap[] =
  6853. {
  6854. { SeverityInformation, "info" },
  6855. { SeverityWarning, "warning" },
  6856. { SeverityError, "error" },
  6857. { SeverityAlert, "alert" },
  6858. { SeverityIgnore, "ignore" },
  6859. { SeverityFatal, "fatal" },
  6860. { SeverityUnknown, NULL }
  6861. };
  6862. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  6863. {
  6864. StringBuffer xpath;
  6865. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6866. CriticalBlock block(crit);
  6867. IPropertyTree * mapping = p->queryPropTree(xpath);
  6868. if (mapping)
  6869. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  6870. return defaultSeverity;
  6871. }
  6872. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  6873. {
  6874. StringBuffer xpath;
  6875. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6876. CriticalBlock block(crit);
  6877. IPropertyTree * mapping = p->queryPropTree(xpath);
  6878. if (!mapping)
  6879. {
  6880. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  6881. mapping = onWarnings->addPropTree("OnWarning");
  6882. mapping->setPropInt("@code", code);
  6883. }
  6884. setEnum(mapping, "@severity", severity, warningSeverityMap);
  6885. }
  6886. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  6887. {
  6888. IPropertyTree *l = (IPropertyTree *) *ll;
  6889. IPropertyTree *r = (IPropertyTree *) *rr;
  6890. return stricmp(l->queryName(), r->queryName());
  6891. };
  6892. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  6893. {
  6894. // Any other values in the WU that could affect generated code should be crc'ed here
  6895. IPropertyTree *tree = p->queryBranch("Debug");
  6896. if (tree)
  6897. {
  6898. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  6899. ICopyArrayOf<IPropertyTree> subs;
  6900. for(sub->first(); sub->isValid(); sub->next())
  6901. subs.append(sub->query());
  6902. subs.sort(comparePropTrees);
  6903. ForEachItemIn(idx, subs)
  6904. {
  6905. const char *name = subs.item(idx).queryName();
  6906. const char *val = subs.item(idx).queryProp(NULL);
  6907. crc = crc32(name, (size32_t)strlen(name), crc);
  6908. if (val)
  6909. crc = crc32(val, (size32_t)strlen(val), crc);
  6910. }
  6911. }
  6912. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  6913. for (plugins->first();plugins->isValid();plugins->next())
  6914. {
  6915. IConstWUPlugin &thisplugin = plugins->query();
  6916. SCMStringBuffer version;
  6917. thisplugin.getPluginVersion(version);
  6918. crc = crc32(version.str(), version.length(), crc);
  6919. }
  6920. return crc;
  6921. }
  6922. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6923. {
  6924. if (!to->hasProp(xpath) && from->hasProp(xpath))
  6925. to->setProp(xpath, from->queryProp(xpath));
  6926. }
  6927. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6928. {
  6929. if (from->hasProp(xpath))
  6930. to->setProp(xpath, from->queryProp(xpath));
  6931. }
  6932. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6933. {
  6934. IPropertyTree * match = from->getBranch(xpath);
  6935. if (match)
  6936. to->setPropTree(xpath, match);
  6937. }
  6938. IPropertyTree *CLocalWorkUnit::queryPTree() const
  6939. {
  6940. return p;
  6941. }
  6942. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  6943. {
  6944. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  6945. if (!from)
  6946. {
  6947. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  6948. if (!fl)
  6949. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  6950. from = fl->c;
  6951. }
  6952. // Need to copy the query, the results, and the graphs from the cached query.
  6953. // The cache is made before the query is executed so there is no need to clear them.
  6954. if (!cached->getCloneable())
  6955. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  6956. const IPropertyTree * fromP = from->p;
  6957. IPropertyTree *pt;
  6958. CriticalBlock block(crit);
  6959. clearCached(false);
  6960. query.clear();
  6961. updateProp(p, fromP, "@jobName");
  6962. copyTree(p, fromP, "Query");
  6963. pt = fromP->getBranch("Application/LibraryModule");
  6964. if (pt)
  6965. {
  6966. ensurePTree(p, "Application");
  6967. p->setPropTree("Application/LibraryModule", pt);
  6968. }
  6969. pt = fromP->getBranch("Application/prefix");
  6970. if (pt)
  6971. {
  6972. ensurePTree(p, "Application");
  6973. p->setPropTree("Application/prefix", pt);
  6974. }
  6975. pt = fromP->queryBranch("Debug");
  6976. if (pt)
  6977. {
  6978. IPropertyTree *curDebug = p->queryPropTree("Debug");
  6979. if (curDebug)
  6980. {
  6981. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  6982. ForEach(*elems)
  6983. {
  6984. IPropertyTree *elem = &elems->query();
  6985. if (!curDebug->hasProp(elem->queryName()))
  6986. curDebug->setPropTree(elem->queryName(),LINK(elem));
  6987. }
  6988. }
  6989. else
  6990. p->setPropTree("Debug", LINK(pt));
  6991. }
  6992. copyTree(p, fromP, "OnWarnings");
  6993. copyTree(p, fromP, "Plugins");
  6994. copyTree(p, fromP, "Libraries");
  6995. copyTree(p, fromP, "Results");
  6996. copyTree(p, fromP, "Graphs");
  6997. copyTree(p, fromP, "Workflow");
  6998. copyTree(p, fromP, "WebServicesInfo");
  6999. if (copyStats)
  7000. {
  7001. // Merge timing info from both branches
  7002. pt = fromP->getBranch("Statistics");
  7003. if (pt)
  7004. {
  7005. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7006. mergePTree(tgtStatistics, pt);
  7007. pt->Release();
  7008. }
  7009. }
  7010. updateProp(p, fromP, "@clusterName");
  7011. updateProp(p, fromP, "allowedclusters");
  7012. updateProp(p, fromP, "@submitID");
  7013. updateProp(p, fromP, "SNAPSHOT");
  7014. setProp(p, fromP, "@eventScheduledCount");
  7015. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7016. if (all)
  7017. {
  7018. setProp(p, fromP, "PriorityFlag");
  7019. setProp(p, fromP, "@priorityClass");
  7020. setProp(p, fromP, "@protected");
  7021. setProp(p, fromP, "@clusterName");
  7022. updateProp(p, fromP, "@scope");
  7023. }
  7024. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7025. pt = fromP->getBranch("Variables");
  7026. if (pt)
  7027. {
  7028. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7029. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7030. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7031. {
  7032. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7033. const char *name = ptSrcVariable->queryProp("@name");
  7034. assertex(name);
  7035. StringBuffer xpath;
  7036. xpath.append("Variable[@name='").append(name).append("']");
  7037. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7038. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7039. merged->removeProp("Value"); // except value and status
  7040. merged->setProp("@status", "undefined");
  7041. if (!merged->getPropBool("@isScalar"))
  7042. merged->removeProp("totalRowCount");
  7043. merged->removeProp("rowCount");
  7044. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7045. if (ptTgtVariable)
  7046. {
  7047. // copy status and Value from what is already set in target
  7048. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7049. MemoryBuffer value;
  7050. if (ptTgtVariable->getPropBin("Value", value))
  7051. merged->setPropBin("Value", value.length(), value.toByteArray());
  7052. ptTgtVariable->removeProp(xpath.str());
  7053. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7054. }
  7055. ptTgtVariables->addPropTree("Variable", merged);
  7056. }
  7057. pt->Release();
  7058. }
  7059. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7060. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7061. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7062. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7063. p->setProp("@hash", fromP->queryProp("@hash"));
  7064. p->setPropBool("@cloneable", true);
  7065. p->setPropBool("@isClone", true);
  7066. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7067. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7068. ForEach(*results)
  7069. {
  7070. CLocalWUResult result(LINK(&results->query()));
  7071. result.setResultStatus(ResultStatusUndefined);
  7072. }
  7073. copyTree(p, fromP, "usedsources"); // field usage
  7074. }
  7075. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7076. {
  7077. StringBuffer lower;
  7078. lower.append(propname).toLowerCase();
  7079. CriticalBlock block(crit);
  7080. StringBuffer prop("Debug/");
  7081. return p->hasProp(prop.append(lower));
  7082. }
  7083. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7084. {
  7085. StringBuffer lower;
  7086. lower.append(propname).toLowerCase();
  7087. CriticalBlock block(crit);
  7088. StringBuffer prop("Debug/");
  7089. str.set(p->queryProp(prop.append(lower).str()));
  7090. return str;
  7091. }
  7092. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7093. {
  7094. return getDebugValues(NULL);
  7095. }
  7096. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7097. {
  7098. CriticalBlock block(crit);
  7099. StringBuffer path("Debug/");
  7100. if (prop)
  7101. {
  7102. StringBuffer lower;
  7103. lower.append(prop).toLowerCase();
  7104. path.append(lower);
  7105. }
  7106. else
  7107. path.append("*");
  7108. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7109. }
  7110. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7111. {
  7112. StringBuffer lower;
  7113. lower.append(propname).toLowerCase();
  7114. CriticalBlock block(crit);
  7115. StringBuffer prop("Debug/");
  7116. prop.append(lower);
  7117. return p->getPropInt(prop.str(), defVal);
  7118. }
  7119. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7120. {
  7121. StringBuffer lower;
  7122. lower.append(propname).toLowerCase();
  7123. CriticalBlock block(crit);
  7124. StringBuffer prop("Debug/");
  7125. prop.append(lower);
  7126. return p->getPropInt64(prop.str(), defVal);
  7127. }
  7128. double CLocalWorkUnit::getDebugValueReal(const char *propname, double defVal) const
  7129. {
  7130. StringBuffer lower;
  7131. lower.append(propname).toLowerCase();
  7132. CriticalBlock block(crit);
  7133. StringBuffer prop("Debug/");
  7134. prop.append(lower);
  7135. return p->getPropReal(prop.str(), defVal);
  7136. }
  7137. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7138. {
  7139. StringBuffer lower;
  7140. lower.append(propname).toLowerCase();
  7141. CriticalBlock block(crit);
  7142. StringBuffer prop("Debug/");
  7143. prop.append(lower);
  7144. return p->getPropBool(prop.str(), defVal);
  7145. }
  7146. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7147. {
  7148. VStringBuffer xpath("Process/%s/", type);
  7149. if (instance)
  7150. xpath.append(instance);
  7151. else
  7152. xpath.append("*");
  7153. CriticalBlock block(crit);
  7154. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7155. {
  7156. // NB: instance unused
  7157. if (streq("EclAgent", type))
  7158. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7159. else if (streq("Thor", type))
  7160. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7161. VStringBuffer xpath("Debug/%s", type);
  7162. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7163. }
  7164. else
  7165. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7166. }
  7167. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7168. {
  7169. VStringBuffer xpath("Process/%s/", type);
  7170. if (instance)
  7171. xpath.append(instance);
  7172. else
  7173. xpath.append("*");
  7174. CriticalBlock block(crit);
  7175. return p->getElements(xpath.str());
  7176. }
  7177. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7178. {
  7179. VStringBuffer xpath("Process/%s/*", type);
  7180. CriticalBlock block(crit);
  7181. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7182. }
  7183. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7184. {
  7185. VStringBuffer processType("Process/%s", type);
  7186. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7187. if (log)
  7188. xpath.appendf("[@log=\"%s\"]", log);
  7189. CriticalBlock block(crit);
  7190. if (!p->hasProp(xpath))
  7191. {
  7192. IPropertyTree *node = ensurePTree(p, processType.str());
  7193. node = node->addPropTree(instance);
  7194. node->setProp("@log", log);
  7195. node->setPropInt("@pid", pid);
  7196. }
  7197. }
  7198. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7199. {
  7200. StringBuffer lower;
  7201. lower.append(propname).toLowerCase();
  7202. CriticalBlock block(crit);
  7203. StringBuffer prop("Debug/");
  7204. prop.append(lower);
  7205. if (overwrite || !p->hasProp(prop.str()))
  7206. {
  7207. // MORE - not sure this line should be needed....
  7208. p->setProp("Debug", "");
  7209. p->setProp(prop.str(), value);
  7210. }
  7211. }
  7212. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7213. {
  7214. StringBuffer lower;
  7215. lower.append(propname).toLowerCase();
  7216. CriticalBlock block(crit);
  7217. StringBuffer prop("Debug/");
  7218. prop.append(lower);
  7219. if (overwrite || !p->hasProp(prop.str()))
  7220. {
  7221. // MORE - not sure this line should be needed....
  7222. p->setProp("Debug", "");
  7223. p->setPropInt(prop.str(), value);
  7224. }
  7225. }
  7226. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7227. {
  7228. CriticalBlock block(crit);
  7229. // MORE - not sure this line should be needed....
  7230. p->setProp("Tracing", "");
  7231. StringBuffer prop("Tracing/");
  7232. p->setProp(prop.append(propname).str(), value);
  7233. }
  7234. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7235. {
  7236. CriticalBlock block(crit);
  7237. StringBuffer prop("Tracing/");
  7238. p->setPropInt(prop.append(propname).str(), value);
  7239. }
  7240. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7241. {
  7242. CriticalBlock block(crit);
  7243. VStringBuffer prop("Tracing/%s", propname);
  7244. p->setPropInt64(prop.str(), value);
  7245. }
  7246. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7247. {
  7248. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7249. CriticalBlock block(crit);
  7250. if (!query)
  7251. {
  7252. IPropertyTree *s = p->getPropTree("Query");
  7253. if (s)
  7254. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7255. }
  7256. return query.getLink();
  7257. }
  7258. IWUQuery* CLocalWorkUnit::updateQuery()
  7259. {
  7260. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7261. CriticalBlock block(crit);
  7262. if (!query)
  7263. {
  7264. IPropertyTree *s = p->queryPropTree("Query");
  7265. if (!s)
  7266. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7267. s->Link();
  7268. query.setown(new CLocalWUQuery(s));
  7269. }
  7270. return query.getLink();
  7271. }
  7272. void CLocalWorkUnit::loadPlugins() const
  7273. {
  7274. CriticalBlock block(crit);
  7275. if (!pluginsCached)
  7276. {
  7277. assertex(plugins.length() == 0);
  7278. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7279. for (r->first(); r->isValid(); r->next())
  7280. {
  7281. IPropertyTree *rp = &r->query();
  7282. rp->Link();
  7283. plugins.append(*new CLocalWUPlugin(rp));
  7284. }
  7285. pluginsCached = true;
  7286. }
  7287. }
  7288. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7289. {
  7290. CriticalBlock block(crit);
  7291. loadPlugins();
  7292. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7293. }
  7294. void CLocalWorkUnit::loadLibraries() const
  7295. {
  7296. CriticalBlock block(crit);
  7297. if (!librariesCached)
  7298. {
  7299. assertex(libraries.length() == 0);
  7300. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7301. ForEach(*r)
  7302. {
  7303. IPropertyTree *rp = &r->query();
  7304. rp->Link();
  7305. libraries.append(*new CLocalWULibrary(rp));
  7306. }
  7307. librariesCached = true;
  7308. }
  7309. }
  7310. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7311. {
  7312. CriticalBlock block(crit);
  7313. loadLibraries();
  7314. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7315. }
  7316. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7317. {
  7318. CriticalBlock block(crit);
  7319. loadLibraries();
  7320. ForEachItemIn(idx, libraries)
  7321. {
  7322. SCMStringBuffer name;
  7323. IConstWULibrary &cur = libraries.item(idx);
  7324. cur.getName(name);
  7325. if (stricmp(name.str(), search)==0)
  7326. return &OLINK(cur);
  7327. }
  7328. return NULL;
  7329. }
  7330. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7331. {
  7332. str.append("Graph ").append(graphName);
  7333. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7334. else if (subId) str.append(" - id(").append(subId).append(")");
  7335. return str;
  7336. }
  7337. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7338. {
  7339. if (wfid)
  7340. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7341. str.append(graphName);
  7342. if (subId) str.append(":sg").append(subId);
  7343. return str;
  7344. }
  7345. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7346. {
  7347. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7348. unsigned len = (size32_t)strlen(label);
  7349. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7350. return false;
  7351. graphNum = 0;
  7352. subGraphNum = 0;
  7353. subId = 0;
  7354. const char *finger = label+6;
  7355. const char *finger2 = strchr(finger, '-');
  7356. if (NULL == finger2) // just graphName
  7357. graphName.set(finger);
  7358. else
  7359. {
  7360. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7361. finger = finger2+2; // skip '-' and space
  7362. finger2 = strchr(finger, ' ');
  7363. if (finger2)
  7364. {
  7365. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7366. finger = finger2+2; // skip space and '('
  7367. finger2 = strchr(finger, ')');
  7368. if (finger2)
  7369. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7370. }
  7371. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7372. {
  7373. finger += 3;
  7374. finger2 = strchr(finger, ')');
  7375. if (finger2)
  7376. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7377. }
  7378. }
  7379. if (graphName && !memicmp(graphName, "graph", 5))
  7380. graphNum = atoi(graphName + 5);
  7381. return true;
  7382. }
  7383. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7384. {
  7385. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7386. return false;
  7387. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7388. subGraphId = 0;
  7389. const char * colon = strchr(scope, ':');
  7390. if (!colon)
  7391. {
  7392. graphName.set(scope);
  7393. return true;
  7394. }
  7395. const char * subgraph = colon+1;
  7396. graphName.set(scope, (size32_t)(colon - scope));
  7397. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7398. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7399. return true;
  7400. }
  7401. 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)
  7402. {
  7403. if (!scope) scope = GLOBAL_SCOPE;
  7404. const char * kindName = queryStatisticName(kind);
  7405. StatisticMeasure measure = queryMeasure(kind);
  7406. //creator. scope and name must all be present, and must not contain semi colons.
  7407. assertex(creator && scope);
  7408. CriticalBlock block(crit);
  7409. IPropertyTree * stats = p->queryPropTree("Statistics");
  7410. if (!stats)
  7411. stats = p->addPropTree("Statistics");
  7412. IPropertyTree * statTree = NULL;
  7413. if (mergeAction != StatsMergeAppend)
  7414. {
  7415. StringBuffer xpath;
  7416. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7417. statTree = stats->queryPropTree(xpath.str());
  7418. }
  7419. if (!statTree)
  7420. {
  7421. /* NB: Sasha archive uses this structure directly
  7422. * if it changes, the code in saarch.cpp needs updating
  7423. */
  7424. statTree = stats->addPropTree("Statistic");
  7425. statTree->setProp("@creator", creator);
  7426. statTree->setProp("@scope", scope);
  7427. statTree->setProp("@kind", kindName);
  7428. //These items are primarily here to facilitate filtering.
  7429. statTree->setProp("@unit", queryMeasureName(measure));
  7430. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7431. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7432. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7433. if (optDescription)
  7434. statTree->setProp("@desc", optDescription);
  7435. if (statistics.cached)
  7436. statistics.append(LINK(statTree));
  7437. mergeAction = StatsMergeAppend;
  7438. }
  7439. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7440. {
  7441. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7442. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7443. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7444. if (oldMax < oldValue)
  7445. oldMax = oldValue;
  7446. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7447. statTree->setPropInt64("@count", count + oldCount);
  7448. if (maxValue > oldMax)
  7449. statTree->setPropInt64("@max", maxValue);
  7450. }
  7451. else
  7452. {
  7453. statTree->setPropInt64("@value", value);
  7454. statTree->setPropInt64("@count", count);
  7455. if (maxValue)
  7456. statTree->setPropInt64("@max", maxValue);
  7457. else
  7458. statTree->removeProp("@max");
  7459. }
  7460. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7461. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7462. {
  7463. _loadStatistics();
  7464. stat_type totalTime = 0;
  7465. ForEachItemIn(i, statistics)
  7466. {
  7467. IConstWUStatistic & cur = statistics.item(i);
  7468. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7469. totalTime += cur.getValue();
  7470. }
  7471. StringBuffer t;
  7472. formatTimeCollatable(t, totalTime, false);
  7473. p->setProp("@totalThorTime", t);
  7474. }
  7475. }
  7476. void CLocalWorkUnit::_loadStatistics() const
  7477. {
  7478. statistics.load(p,"Statistics/*");
  7479. }
  7480. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7481. {
  7482. //MORE: Optimize this....
  7483. WuScopeFilter filter;
  7484. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7485. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7486. if (stats->first())
  7487. return stats->getStat(kind, value);
  7488. return false;
  7489. }
  7490. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7491. {
  7492. assertex(filter.isOptimized());
  7493. WuScopeSourceFlags sources = filter.sourceFlags;
  7494. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7495. if (sources & SSFsearchGlobalStats)
  7496. {
  7497. CriticalBlock block(crit);
  7498. statistics.loadBranch(p,"Statistics");
  7499. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7500. compoundIter->addIter(localStats);
  7501. }
  7502. if (sources & SSFsearchGraphStats)
  7503. {
  7504. const char * wuid = p->queryName();
  7505. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7506. compoundIter->addIter(scopeIter);
  7507. }
  7508. if (sources & SSFsearchGraph)
  7509. {
  7510. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7511. compoundIter->addIter(graphIter);
  7512. }
  7513. if (sources & SSFsearchWorkflow)
  7514. {
  7515. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7516. if (iter)
  7517. {
  7518. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7519. compoundIter->addIter(workflowIter);
  7520. }
  7521. }
  7522. if (sources & SSFsearchExceptions)
  7523. {
  7524. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7525. compoundIter->addIter(notesIter);
  7526. }
  7527. return *compoundIter.getClear();
  7528. }
  7529. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7530. {
  7531. CriticalBlock block(crit);
  7532. IConstWUPlugin *existing = getPluginByName(qname);
  7533. if (existing)
  7534. return (IWUPlugin *) existing;
  7535. if (!plugins.length())
  7536. p->addPropTree("Plugins");
  7537. IPropertyTree *pl = p->queryPropTree("Plugins");
  7538. IPropertyTree *s = pl->addPropTree("Plugin");
  7539. s->Link();
  7540. IWUPlugin* q = new CLocalWUPlugin(s);
  7541. q->Link();
  7542. plugins.append(*q);
  7543. q->setPluginName(qname);
  7544. return q;
  7545. }
  7546. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  7547. {
  7548. CriticalBlock block(crit);
  7549. loadPlugins();
  7550. ForEachItemIn(idx, plugins)
  7551. {
  7552. SCMStringBuffer name;
  7553. IConstWUPlugin &cur = plugins.item(idx);
  7554. cur.getPluginName(name);
  7555. if (stricmp(name.str(), qname)==0)
  7556. {
  7557. cur.Link();
  7558. return &cur;
  7559. }
  7560. }
  7561. return NULL;
  7562. }
  7563. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  7564. {
  7565. CriticalBlock block(crit);
  7566. IConstWULibrary *existing = getLibraryByName(qname);
  7567. if (existing)
  7568. return (IWULibrary *) existing;
  7569. if (!libraries.length())
  7570. p->addPropTree("Libraries");
  7571. IPropertyTree *pl = p->queryPropTree("Libraries");
  7572. IPropertyTree *s = pl->addPropTree("Library");
  7573. s->Link();
  7574. IWULibrary* q = new CLocalWULibrary(s);
  7575. q->Link();
  7576. libraries.append(*q);
  7577. q->setName(qname);
  7578. return q;
  7579. }
  7580. void CLocalWorkUnit::_loadExceptions() const
  7581. {
  7582. assertex(exceptions.length() == 0);
  7583. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  7584. for (r->first(); r->isValid(); r->next())
  7585. {
  7586. IPropertyTree *rp = &r->query();
  7587. rp->Link();
  7588. exceptions.append(*new CLocalWUException(rp));
  7589. }
  7590. }
  7591. void CLocalWorkUnit::loadExceptions() const
  7592. {
  7593. CriticalBlock block(crit);
  7594. if (!exceptionsCached)
  7595. {
  7596. _loadExceptions();
  7597. exceptionsCached = true;
  7598. }
  7599. }
  7600. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  7601. {
  7602. CriticalBlock block(crit);
  7603. loadExceptions();
  7604. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  7605. }
  7606. unsigned CLocalWorkUnit::getExceptionCount() const
  7607. {
  7608. CriticalBlock block(crit);
  7609. loadExceptions();
  7610. return exceptions.length();
  7611. }
  7612. void CLocalWorkUnit::clearExceptions(const char *source)
  7613. {
  7614. CriticalBlock block(crit);
  7615. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7616. loadExceptions();
  7617. ForEachItemInRev(idx, exceptions)
  7618. {
  7619. IWUException &e = exceptions.item(idx);
  7620. SCMStringBuffer s;
  7621. e.getExceptionSource(s);
  7622. if (source)
  7623. {
  7624. if (!strieq(s.s, source))
  7625. continue;
  7626. }
  7627. else
  7628. {
  7629. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  7630. break;
  7631. }
  7632. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  7633. p->removeProp(xpath);
  7634. exceptions.remove(idx);
  7635. }
  7636. if (exceptions.length() == 0)
  7637. p->removeProp("Exceptions");
  7638. }
  7639. IWUException* CLocalWorkUnit::createException()
  7640. {
  7641. CriticalBlock block(crit);
  7642. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7643. loadExceptions();
  7644. if (!exceptions.length())
  7645. p->addPropTree("Exceptions");
  7646. IPropertyTree *r = p->queryPropTree("Exceptions");
  7647. IPropertyTree *s = r->addPropTree("Exception");
  7648. s->setPropInt("@sequence", exceptions.ordinality());
  7649. IWUException* q = new CLocalWUException(LINK(s));
  7650. exceptions.append(*LINK(q));
  7651. Owned<IJlibDateTime> now = createDateTimeNow();
  7652. SCMStringBuffer temp;
  7653. now->getString(temp);
  7654. q->setTimeStamp(temp.str());
  7655. return q;
  7656. }
  7657. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  7658. {
  7659. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7660. CriticalBlock block(crit);
  7661. if (!webServicesInfoCached)
  7662. {
  7663. assertex(!webServicesInfo);
  7664. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  7665. if (s)
  7666. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  7667. webServicesInfoCached = true;
  7668. }
  7669. return webServicesInfo.getLink();
  7670. }
  7671. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  7672. {
  7673. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7674. CriticalBlock block(crit);
  7675. if (!webServicesInfoCached)
  7676. {
  7677. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  7678. if (!s)
  7679. {
  7680. if (create)
  7681. s = p->addPropTree("WebServicesInfo");
  7682. else
  7683. return NULL;
  7684. }
  7685. s->Link();
  7686. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  7687. webServicesInfoCached = true;
  7688. }
  7689. return webServicesInfo.getLink();
  7690. }
  7691. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  7692. {
  7693. CLocalWUResult *l = (CLocalWUResult *) *ll;
  7694. CLocalWUResult *r = (CLocalWUResult *) *rr;
  7695. return l->getResultSequence() - r->getResultSequence();
  7696. }
  7697. void CLocalWorkUnit::_loadResults() const
  7698. {
  7699. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  7700. for (r->first(); r->isValid(); r->next())
  7701. {
  7702. IPropertyTree *rp = &r->query();
  7703. rp->Link();
  7704. results.append(*new CLocalWUResult(rp));
  7705. }
  7706. }
  7707. void CLocalWorkUnit::loadResults() const
  7708. {
  7709. if (!resultsCached)
  7710. {
  7711. assertex(results.length() == 0);
  7712. _loadResults();
  7713. results.sort(compareResults);
  7714. resultsCached = true;
  7715. }
  7716. }
  7717. void CLocalWorkUnit::_loadVariables() const
  7718. {
  7719. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  7720. for (r->first(); r->isValid(); r->next())
  7721. {
  7722. IPropertyTree *rp = &r->query();
  7723. rp->Link();
  7724. variables.append(*new CLocalWUResult(rp));
  7725. }
  7726. }
  7727. void CLocalWorkUnit::loadVariables() const
  7728. {
  7729. if (!variablesCached)
  7730. {
  7731. assertex(variables.length() == 0);
  7732. _loadVariables();
  7733. variablesCached = true;
  7734. }
  7735. }
  7736. void CLocalWorkUnit::_loadTemporaries() const
  7737. {
  7738. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  7739. for (r->first(); r->isValid(); r->next())
  7740. {
  7741. IPropertyTree *rp = &r->query();
  7742. rp->Link();
  7743. temporaries.append(*new CLocalWUResult(rp));
  7744. }
  7745. }
  7746. void CLocalWorkUnit::loadTemporaries() const
  7747. {
  7748. if (!temporariesCached)
  7749. {
  7750. assertex(temporaries.length() == 0);
  7751. _loadTemporaries();
  7752. temporariesCached = true;
  7753. }
  7754. }
  7755. void CLocalWorkUnit::deleteTemporaries()
  7756. {
  7757. CriticalBlock block(crit);
  7758. if (temporariesCached)
  7759. {
  7760. temporaries.kill();
  7761. temporariesCached = false;
  7762. }
  7763. p->removeProp("Temporaries");
  7764. }
  7765. IWUResult* CLocalWorkUnit::createResult()
  7766. {
  7767. CriticalBlock block(crit);
  7768. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7769. loadResults();
  7770. if (!results.length())
  7771. p->addPropTree("Results");
  7772. IPropertyTree *r = p->queryPropTree("Results");
  7773. IPropertyTree *s = r->addPropTree("Result");
  7774. s->Link();
  7775. IWUResult* q = new CLocalWUResult(s);
  7776. q->Link();
  7777. results.append(*q);
  7778. return q;
  7779. }
  7780. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  7781. {
  7782. CriticalBlock block(crit);
  7783. IConstWUResult *existing = getResultByName(qname);
  7784. if (existing)
  7785. return (IWUResult *) existing;
  7786. IWUResult* q = createResult();
  7787. q->setResultName(qname);
  7788. return q;
  7789. }
  7790. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  7791. {
  7792. CriticalBlock block(crit);
  7793. IConstWUResult *existing = getResultBySequence(seq);
  7794. if (existing)
  7795. return (IWUResult *) existing;
  7796. IWUResult* q = createResult();
  7797. q->setResultSequence(seq);
  7798. return q;
  7799. }
  7800. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  7801. {
  7802. CriticalBlock block(crit);
  7803. loadResults();
  7804. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  7805. }
  7806. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  7807. {
  7808. CriticalBlock block(crit);
  7809. loadResults();
  7810. ForEachItemIn(idx, results)
  7811. {
  7812. SCMStringBuffer name;
  7813. IConstWUResult &cur = results.item(idx);
  7814. cur.getResultName(name);
  7815. if (stricmp(name.str(), qname)==0)
  7816. {
  7817. cur.Link();
  7818. return &cur;
  7819. }
  7820. }
  7821. return NULL;
  7822. }
  7823. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  7824. {
  7825. CriticalBlock block(crit);
  7826. loadResults();
  7827. ForEachItemIn(idx, results)
  7828. {
  7829. IConstWUResult &cur = results.item(idx);
  7830. if (!isSpecialResultSequence(cur.getResultSequence()))
  7831. {
  7832. SCMStringBuffer name;
  7833. cur.getResultName(name);
  7834. if (stricmp(name.str(), qname)==0)
  7835. {
  7836. cur.Link();
  7837. return &cur;
  7838. }
  7839. }
  7840. }
  7841. return NULL;
  7842. }
  7843. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  7844. {
  7845. CriticalBlock block(crit);
  7846. loadResults();
  7847. ForEachItemIn(idx, results)
  7848. {
  7849. IConstWUResult &cur = results.item(idx);
  7850. if (cur.getResultSequence() == seq)
  7851. {
  7852. cur.Link();
  7853. return &cur;
  7854. }
  7855. }
  7856. return NULL;
  7857. }
  7858. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  7859. {
  7860. CriticalBlock block(crit);
  7861. loadVariables();
  7862. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  7863. }
  7864. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  7865. {
  7866. CriticalBlock block(crit);
  7867. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7868. return getVariableByName(qname);
  7869. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7870. return global->getVariableByName(qname);
  7871. }
  7872. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  7873. {
  7874. CriticalBlock block(crit);
  7875. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7876. return updateVariableByName(qname);
  7877. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7878. return global->updateVariableByName(qname);
  7879. }
  7880. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  7881. {
  7882. CriticalBlock block(crit);
  7883. loadVariables();
  7884. ForEachItemIn(idx, variables)
  7885. {
  7886. SCMStringBuffer name;
  7887. IConstWUResult &cur = variables.item(idx);
  7888. cur.getResultName(name);
  7889. if (stricmp(name.str(), qname)==0)
  7890. {
  7891. cur.Link();
  7892. return &cur;
  7893. }
  7894. }
  7895. return NULL;
  7896. }
  7897. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  7898. {
  7899. CriticalBlock block(crit);
  7900. loadTemporaries();
  7901. ForEachItemIn(idx, temporaries)
  7902. {
  7903. SCMStringBuffer name;
  7904. IConstWUResult &cur = temporaries.item(idx);
  7905. cur.getResultName(name);
  7906. if (stricmp(name.str(), qname)==0)
  7907. {
  7908. cur.Link();
  7909. return &cur;
  7910. }
  7911. }
  7912. return NULL;
  7913. }
  7914. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  7915. {
  7916. CriticalBlock block(crit);
  7917. loadTemporaries();
  7918. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  7919. }
  7920. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  7921. {
  7922. CriticalBlock block(crit);
  7923. IConstWUResult *existing = getTemporaryByName(qname);
  7924. if (existing)
  7925. return (IWUResult *) existing;
  7926. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  7927. IPropertyTree *s = vars->addPropTree("Variable");
  7928. s->Link();
  7929. IWUResult* q = new CLocalWUResult(s);
  7930. q->Link();
  7931. temporaries.append(*q);
  7932. q->setResultName(qname);
  7933. q->setResultSequence(ResultSequenceInternal);
  7934. return q;
  7935. }
  7936. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  7937. {
  7938. CriticalBlock block(crit);
  7939. IConstWUResult *existing = getVariableByName(qname);
  7940. if (existing)
  7941. return (IWUResult *) existing;
  7942. if (!variables.length())
  7943. p->addPropTree("Variables");
  7944. IPropertyTree *vars = p->queryPropTree("Variables");
  7945. IPropertyTree *s = vars->addPropTree("Variable");
  7946. s->Link();
  7947. IWUResult* q = new CLocalWUResult(s);
  7948. q->Link();
  7949. variables.append(*q);
  7950. q->setResultName(qname);
  7951. q->setResultSequence(ResultSequenceStored);
  7952. return q;
  7953. }
  7954. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  7955. {
  7956. CriticalBlock block(crit);
  7957. IPropertyTree *files = p->queryPropTree("Files");
  7958. if (!files) return;
  7959. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  7960. ICopyArrayOf<IPropertyTree> toRemove;
  7961. ForEach (*iter)
  7962. {
  7963. IPropertyTree &file = iter->query();
  7964. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  7965. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  7966. bool needDelete;
  7967. switch(fileKind)
  7968. {
  7969. case WUFileTemporary:
  7970. if(graph==NULL)
  7971. needDelete = true;
  7972. else
  7973. {
  7974. const char *graphOwner = file.queryProp("@graph");
  7975. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  7976. }
  7977. break;
  7978. case WUFileJobOwned:
  7979. needDelete = ((graph==NULL) && deleteJobOwned);
  7980. break;
  7981. case WUFileOwned:
  7982. needDelete = ((graph==NULL) && deleteOwned);
  7983. break;
  7984. default:
  7985. needDelete = false;
  7986. }
  7987. if(needDelete)
  7988. {
  7989. const char *name = file.queryProp("@name");
  7990. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  7991. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  7992. toRemove.append(file);
  7993. }
  7994. }
  7995. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  7996. }
  7997. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  7998. {
  7999. IDistributedSuperFile *super = file->querySuperFile();
  8000. StringBuffer fname;
  8001. file->getLogicalName(fname);
  8002. if (fname.length())
  8003. {
  8004. StringBuffer path("File[@name=\"");
  8005. path.append(fname).append("\"]");
  8006. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8007. if (fileTree)
  8008. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8009. else
  8010. {
  8011. StringBuffer cluster;
  8012. file->getClusterName(0,cluster);
  8013. fileTree = createPTree();
  8014. fileTree->setProp("@name", fname.str());
  8015. fileTree->setProp("@cluster", cluster.str());
  8016. fileTree->setPropInt("@useCount", 1);
  8017. fileTree = filesRead->addPropTree("File", fileTree);
  8018. }
  8019. if (super)
  8020. {
  8021. fileTree->setPropBool("@super", true);
  8022. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8023. ForEach (*iter)
  8024. {
  8025. IDistributedFile &file = iter->query();
  8026. StringBuffer fname;
  8027. file.getLogicalName(fname);
  8028. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8029. _noteFileRead(&file, filesRead);
  8030. }
  8031. }
  8032. }
  8033. }
  8034. void CLocalWorkUnit::_loadFilesRead() const
  8035. {
  8036. // Nothing to do
  8037. }
  8038. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8039. {
  8040. if (file)
  8041. {
  8042. CriticalBlock block(crit);
  8043. IPropertyTree *files = p->queryPropTree("FilesRead");
  8044. if (!files)
  8045. files = p->addPropTree("FilesRead");
  8046. _noteFileRead(file, files);
  8047. }
  8048. }
  8049. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8050. {
  8051. if (fieldUsage)
  8052. {
  8053. CriticalBlock block(crit);
  8054. p->addPropTree("usedsources", fieldUsage);
  8055. }
  8056. }
  8057. void CLocalWorkUnit::_loadFilesWritten() const
  8058. {
  8059. // Nothing to do
  8060. }
  8061. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8062. {
  8063. StringBuffer path("File[@name=\"");
  8064. path.append(fileName).append("\"]");
  8065. if (cluster)
  8066. path.append("[@cluster=\"").append(cluster).append("\"]");
  8067. IPropertyTree *file = files->queryPropTree(path.str());
  8068. if (file) files->removeTree(file);
  8069. file = createPTree();
  8070. file->setProp("@name", fileName);
  8071. if (cluster)
  8072. file->setProp("@cluster", cluster);
  8073. if (graphOwner)
  8074. file->setProp("@graph", graphOwner);
  8075. file->setPropInt("@kind", (unsigned)fileKind);
  8076. if (WUFileTemporary == fileKind)
  8077. file->setPropInt("@usageCount", usageCount);
  8078. files->addPropTree("File", file);
  8079. }
  8080. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8081. {
  8082. CriticalBlock block(crit);
  8083. IPropertyTree *files = p->queryPropTree("Files");
  8084. if (!files)
  8085. files = p->addPropTree("Files");
  8086. if (!clusters)
  8087. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8088. else
  8089. {
  8090. ForEachItemIn(c, *clusters)
  8091. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8092. }
  8093. }
  8094. void CLocalWorkUnit::releaseFile(const char *fileName)
  8095. {
  8096. StringBuffer path("File[@name=\"");
  8097. path.append(fileName).append("\"]");
  8098. CriticalBlock block(crit);
  8099. IPropertyTree *files = p->queryPropTree("Files");
  8100. if (!files) return;
  8101. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8102. ForEach (*fiter)
  8103. {
  8104. IPropertyTree *file = &fiter->query();
  8105. unsigned usageCount = file->getPropInt("@usageCount");
  8106. if (usageCount > 1)
  8107. file->setPropInt("@usageCount", usageCount-1);
  8108. else
  8109. {
  8110. StringAttr name(file->queryProp("@name"));
  8111. files->removeTree(file);
  8112. if (!name.isEmpty()&&(1 == usageCount))
  8113. {
  8114. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8115. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8116. }
  8117. }
  8118. }
  8119. }
  8120. void CLocalWorkUnit::clearGraphProgress() const
  8121. {
  8122. }
  8123. void CLocalWorkUnit::resetBeforeGeneration()
  8124. {
  8125. CriticalBlock block(crit);
  8126. //Remove all associated files
  8127. Owned<IWUQuery> q = updateQuery();
  8128. q->removeAssociatedFiles();
  8129. //Remove any pre-existing workflow information
  8130. workflowIterator.clear();
  8131. p->removeProp("Workflow");
  8132. }
  8133. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8134. {
  8135. StringBuffer path("Files/File[@name=\"");
  8136. path.append(fileName).append("\"]/@usageCount");
  8137. CriticalBlock block(crit);
  8138. return p->getPropInt(path.str());
  8139. }
  8140. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8141. {
  8142. CriticalBlock block(crit);
  8143. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8144. if (!fieldUsageTree)
  8145. return NULL;
  8146. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8147. return new CConstWUFileUsageIterator(iter);
  8148. }
  8149. bool isFilenameResolved(StringBuffer& filename)
  8150. {
  8151. size32_t length = filename.length();
  8152. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8153. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8154. return true;
  8155. else
  8156. return false;
  8157. }
  8158. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8159. {
  8160. bool scopeLoaded = false;
  8161. StringBuffer defaultScope;
  8162. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8163. if (!files)
  8164. return false; // this query was not compiled with recordFieldUsage option.
  8165. ForEach(*files)
  8166. {
  8167. Owned<IConstWUFileUsage> file = files->get();
  8168. StringBuffer filename(file->queryName());
  8169. size32_t length = filename.length();
  8170. if (length == 0)
  8171. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8172. StringBuffer normalizedFilename;
  8173. // Two cases to handle:
  8174. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8175. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8176. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8177. if (isFilenameResolved(filename))
  8178. {
  8179. // filename cannot be empty (i.e. empty single quotes '')
  8180. if (length == 2)
  8181. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8182. // Remove surrounding single quotes
  8183. StringAttr cleanFilename(filename.str()+1, length-2);
  8184. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8185. // We need to load a default scope from config and prefix the filename with it.
  8186. if (cleanFilename.str()[0] != '~')
  8187. {
  8188. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8189. if (!scopeLoaded)
  8190. {
  8191. //MORE: This should actually depend on the cluster that was active when the file was read!
  8192. if (!resolveFilePrefix(defaultScope, clusterName))
  8193. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8194. scopeLoaded = true;
  8195. }
  8196. normalizedFilename.append(defaultScope.str());
  8197. normalizedFilename.append(cleanFilename.str());
  8198. }
  8199. else
  8200. {
  8201. normalizedFilename.append(cleanFilename);
  8202. }
  8203. }
  8204. else
  8205. {
  8206. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8207. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8208. normalizedFilename.append(filename.str());
  8209. }
  8210. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8211. ForEach(*fields)
  8212. {
  8213. Owned<IConstWUFieldUsage> field = fields->get();
  8214. filenames.append(normalizedFilename.str());
  8215. columnnames.append(field->queryName());
  8216. }
  8217. }
  8218. return true;
  8219. }
  8220. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8221. {
  8222. return p->getPropTree("DiskUsageStats");
  8223. }
  8224. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8225. {
  8226. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8227. offset_t maxNodeUsage;
  8228. if (stats)
  8229. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8230. else
  8231. {
  8232. stats = p->addPropTree("DiskUsageStats");
  8233. maxNodeUsage = 0;
  8234. }
  8235. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8236. {
  8237. // record all details at time of max node usage.
  8238. stats->setPropInt("@minNode", _minNode);
  8239. stats->setPropInt("@maxNode", _maxNode);
  8240. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8241. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8242. stats->setPropInt64("@graphId", _graphId);
  8243. if (_avgNodeUsage)
  8244. {
  8245. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8246. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8247. stats->setPropInt("@skewHi", _skewHi);
  8248. stats->setPropInt("@skewLo", _skewLo);
  8249. }
  8250. }
  8251. }
  8252. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8253. {
  8254. CriticalBlock block(crit);
  8255. _loadFilesWritten();
  8256. return * p->getElements("Files/File");
  8257. }
  8258. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8259. {
  8260. CriticalBlock block(crit);
  8261. _loadFilesRead();
  8262. return * p->getElements("FilesRead/File");
  8263. }
  8264. //=================================================================================================
  8265. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8266. {
  8267. CriticalBlock block(crit);
  8268. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8269. return false;
  8270. const char * currentcluster = queryClusterName();
  8271. const char *wuid = p->queryName();
  8272. StringBuffer curqname;
  8273. getClusterThorQueueName(curqname, currentcluster);
  8274. void *qi = qs->getQ(curqname.str(),wuid);
  8275. if (!qi)
  8276. return false;
  8277. setClusterName(cluster);
  8278. StringBuffer newqname;
  8279. getClusterThorQueueName(newqname, cluster);
  8280. qs->putQ(newqname.str(),wuid,qi);
  8281. return true;
  8282. }
  8283. //=================================================================================================
  8284. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8285. {
  8286. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8287. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8288. ForEach(*graphIter)
  8289. {
  8290. IConstWUGraph &graph = graphIter->query();
  8291. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8292. SCMStringBuffer gName;
  8293. graph.getName(gName);
  8294. StringBuffer xpath("Graphs/Graph[@name=\"");
  8295. xpath.append(gName.s).append("\"]/xgmml");
  8296. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8297. if (xgmml) // don't know of any reason it shouldn't exist
  8298. {
  8299. xgmml->removeProp("graphBin");
  8300. xgmml->setPropTree("graph", graphTree.getClear());
  8301. }
  8302. }
  8303. return ret.getClear();
  8304. }
  8305. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8306. {
  8307. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8308. ForEach(*iter)
  8309. {
  8310. IPropertyTree &graph = iter->query();
  8311. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8312. }
  8313. }
  8314. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8315. {
  8316. if (graphsCached < (heavy ? 2 : 1))
  8317. {
  8318. graphs.kill();
  8319. _loadGraphs(heavy);
  8320. graphsCached = (heavy ? 2 : 1);
  8321. }
  8322. }
  8323. EnumMapping graphTypes[] = {
  8324. { GraphTypeAny, "unknown" },
  8325. { GraphTypeProgress, "progress" },
  8326. { GraphTypeEcl, "ECL" },
  8327. { GraphTypeActivities, "activities" },
  8328. { GraphTypeSubProgress, "subgraph" },
  8329. { GraphTypeSize, NULL },
  8330. };
  8331. WUGraphType getGraphTypeFromString(const char* type)
  8332. {
  8333. return (WUGraphType) getEnum(type, graphTypes);
  8334. }
  8335. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8336. {
  8337. wuidVersion = owner.getWuidVersion();
  8338. }
  8339. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8340. {
  8341. str.set(p->queryProp("@name"));
  8342. return str;
  8343. }
  8344. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8345. {
  8346. if (wuidVersion >= 2)
  8347. {
  8348. str.set(p->queryProp("@label"));
  8349. return str;
  8350. }
  8351. else
  8352. {
  8353. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8354. str.set(xgmml->queryProp("@label"));
  8355. return str;
  8356. }
  8357. }
  8358. WUGraphState CLocalWUGraph::getState() const
  8359. {
  8360. return owner.queryGraphState(p->queryProp("@name"));
  8361. }
  8362. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8363. {
  8364. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8365. if (xgmml)
  8366. {
  8367. StringBuffer x;
  8368. toXML(xgmml, x);
  8369. str.set(x.str());
  8370. }
  8371. return str;
  8372. }
  8373. unsigned CLocalWorkUnit::getGraphCount() const
  8374. {
  8375. CriticalBlock block(crit);
  8376. if (p->hasProp("Graphs"))
  8377. {
  8378. return p->queryPropTree("Graphs")->numChildren();
  8379. }
  8380. return 0;
  8381. }
  8382. unsigned CLocalWorkUnit::getSourceFileCount() const
  8383. {
  8384. CriticalBlock block(crit);
  8385. _loadFilesRead();
  8386. if (p->hasProp("FilesRead"))
  8387. {
  8388. return p->queryPropTree("FilesRead")->numChildren();
  8389. }
  8390. return 0;
  8391. }
  8392. unsigned CLocalWorkUnit::getResultCount() const
  8393. {
  8394. CriticalBlock block(crit);
  8395. if (p->hasProp("Results"))
  8396. {
  8397. return p->queryPropTree("Results")->numChildren();
  8398. }
  8399. return 0;
  8400. }
  8401. unsigned CLocalWorkUnit::getVariableCount() const
  8402. {
  8403. CriticalBlock block(crit);
  8404. if (p->hasProp("Variables"))
  8405. {
  8406. return p->queryPropTree("Variables")->numChildren();
  8407. }
  8408. return 0;
  8409. }
  8410. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8411. {
  8412. CriticalBlock block(crit);
  8413. if (p->hasProp("Application"))
  8414. {
  8415. return p->queryPropTree("Application")->numChildren();
  8416. }
  8417. return 0;
  8418. }
  8419. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8420. {
  8421. appendXMLOpenTag(s, name, NULL, false);
  8422. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8423. if (attrs->first())
  8424. {
  8425. unsigned attributeindent = indent + (size32_t) strlen(name);
  8426. unsigned count = attrs->count();
  8427. bool doindent = false;
  8428. ForEach(*attrs)
  8429. {
  8430. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8431. continue;
  8432. #ifndef _DEBUG
  8433. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8434. continue;
  8435. #endif
  8436. if (doindent)
  8437. s.append('\n').appendN(attributeindent, ' ');
  8438. else if (count > 3)
  8439. doindent = true;
  8440. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8441. }
  8442. }
  8443. s.append('>');
  8444. return s;
  8445. }
  8446. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8447. {
  8448. CriticalBlock block(crit);
  8449. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8450. if (!paramTree)
  8451. return str;
  8452. StringBuffer xml;
  8453. if (!hidePasswords)
  8454. toXML(paramTree, xml);
  8455. else
  8456. {
  8457. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8458. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8459. ForEach(*elems)
  8460. {
  8461. const char *paramname = elems->query().queryName();
  8462. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8463. if (p->getPropBool(xpath))
  8464. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8465. else
  8466. toXML(&elems->query(), xml, 2);
  8467. }
  8468. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8469. }
  8470. str.set(xml);
  8471. return str;
  8472. }
  8473. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8474. {
  8475. CriticalBlock block(crit);
  8476. return p->getPropTree("Parameters");
  8477. }
  8478. void CLocalWorkUnit::setXmlParams(const char *params)
  8479. {
  8480. CriticalBlock block(crit);
  8481. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8482. }
  8483. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8484. {
  8485. CriticalBlock block(crit);
  8486. p->setPropTree("Parameters", tree);
  8487. }
  8488. unsigned __int64 CLocalWorkUnit::getHash() const
  8489. {
  8490. CriticalBlock block(crit);
  8491. return p->getPropInt64("@hash");
  8492. }
  8493. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8494. {
  8495. CriticalBlock block(crit);
  8496. p->setPropInt64("@hash", hash);
  8497. }
  8498. // getGraphs / getGraphsMeta
  8499. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8500. // If a type other than any is requested, a postfilter is needed.
  8501. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8502. {
  8503. WUGraphType type;
  8504. Owned<T> base;
  8505. bool match()
  8506. {
  8507. return base->query().getType()==type;
  8508. }
  8509. public:
  8510. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8511. : base(_base), type(_type)
  8512. {
  8513. }
  8514. bool first()
  8515. {
  8516. if (!base->first())
  8517. return false;
  8518. if (match())
  8519. return true;
  8520. return next();
  8521. }
  8522. bool next()
  8523. {
  8524. while (base->next())
  8525. if (match())
  8526. return true;
  8527. return false;
  8528. }
  8529. virtual bool isValid()
  8530. {
  8531. return base->isValid();
  8532. }
  8533. U & query()
  8534. {
  8535. return base->query();
  8536. }
  8537. };
  8538. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  8539. {
  8540. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  8541. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  8542. */
  8543. CriticalBlock block(crit);
  8544. loadGraphs(false);
  8545. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  8546. if (type!=GraphTypeAny)
  8547. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  8548. return *giter;
  8549. }
  8550. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  8551. {
  8552. CriticalBlock block(crit);
  8553. loadGraphs(true);
  8554. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  8555. if (type!=GraphTypeAny)
  8556. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  8557. return *giter;
  8558. }
  8559. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  8560. {
  8561. CriticalBlock block(crit);
  8562. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  8563. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  8564. IPTree *graph = p->queryPropTree(xpath);
  8565. if (graph)
  8566. return new CLocalWUGraph(*this, LINK(graph));
  8567. return NULL;
  8568. }
  8569. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  8570. {
  8571. CriticalBlock block(crit);
  8572. if (!graphs.length())
  8573. p->addPropTree("Graphs");
  8574. IPropertyTree *r = p->queryPropTree("Graphs");
  8575. IPropertyTree *s = r->addPropTree("Graph");
  8576. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  8577. q->setName(name);
  8578. q->setLabel(label);
  8579. q->setType(type);
  8580. q->setWfid(wfid);
  8581. q->setXGMMLTree(xgmml);
  8582. graphs.append(*q);
  8583. }
  8584. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  8585. {
  8586. /* Owned<IRemoteConnection> conn = getProgressConnection();
  8587. if (conn)
  8588. {
  8589. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  8590. if (progress)
  8591. return new CConstGraphProgress(p->queryName(), graphName, progress);
  8592. }
  8593. */
  8594. return NULL;
  8595. }
  8596. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  8597. {
  8598. throwUnexpected(); // Should only be used for persisted workunits
  8599. }
  8600. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  8601. {
  8602. throwUnexpected(); // Should only be used for persisted workunits
  8603. }
  8604. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  8605. {
  8606. throwUnexpected(); // Should only be used for persisted workunits
  8607. }
  8608. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  8609. {
  8610. throwUnexpected(); // Should only be used for persisted workunits
  8611. }
  8612. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  8613. {
  8614. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  8615. }
  8616. void CLocalWUGraph::setName(const char *str)
  8617. {
  8618. p->setProp("@name", str);
  8619. }
  8620. void CLocalWUGraph::setLabel(const char *str)
  8621. {
  8622. p->setProp("@label", str);
  8623. }
  8624. void CLocalWUGraph::setWfid(unsigned wfid)
  8625. {
  8626. p->setPropInt("@wfid", wfid);
  8627. }
  8628. void CLocalWUGraph::setXGMML(const char *str)
  8629. {
  8630. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  8631. }
  8632. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  8633. {
  8634. assertex(strcmp(_graph->queryName(), "graph")==0);
  8635. IPropertyTree *xgmml = p->setPropTree("xgmml");
  8636. MemoryBuffer mb;
  8637. _graph->serialize(mb);
  8638. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  8639. // Cassandra workunit code actually lzw compresses the parent anyway
  8640. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  8641. graph.setown(_graph);
  8642. }
  8643. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  8644. {
  8645. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  8646. ForEach (*aIter)
  8647. {
  8648. const char *aName = aIter->queryName()+1;
  8649. if (0 != stricmp("id", aName)) // "id" reserved.
  8650. {
  8651. IPropertyTree *att = targetNode.addPropTree("att");
  8652. att->setProp("@name", aName);
  8653. att->setProp("@value", aIter->queryValue());
  8654. }
  8655. }
  8656. }
  8657. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  8658. {
  8659. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  8660. if (!graphNode) return;
  8661. unsigned nodeId = rootNode.getPropInt("@id");
  8662. StringBuffer progressNodePath("node[@id=\"");
  8663. progressNodePath.append(nodeId).append("\"]");
  8664. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  8665. if (progressNode)
  8666. {
  8667. expandAttributes(*graphNode, *progressNode);
  8668. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  8669. ForEach (*edges)
  8670. {
  8671. IPropertyTree &edge = edges->query();
  8672. StringBuffer edgePath("edge[@id=\"");
  8673. edgePath.append(edge.queryProp("@id")).append("\"]");
  8674. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  8675. if (graphEdge)
  8676. {
  8677. if (progressV < 1)
  8678. mergePTree(graphEdge, &edge);
  8679. else
  8680. { // must translate to XGMML format
  8681. expandAttributes(*graphEdge, edge);
  8682. // 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)
  8683. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  8684. ForEach (*iter)
  8685. {
  8686. IPropertyTree &t = iter->query();
  8687. IPropertyTree *att = graphEdge->addPropTree("att");
  8688. att->setProp("@name", t.queryName());
  8689. att->setProp("@value", t.queryProp(NULL));
  8690. }
  8691. }
  8692. }
  8693. }
  8694. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  8695. ForEach (*nodes)
  8696. {
  8697. IPropertyTree &node = nodes->query();
  8698. StringBuffer nodePath("node[@id=\"");
  8699. nodePath.append(node.queryProp("@id")).append("\"]");
  8700. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  8701. if (_node)
  8702. {
  8703. if (progressV < 1)
  8704. mergePTree(_node, &node);
  8705. else
  8706. { // must translate to XGMML format
  8707. expandAttributes(*_node, node);
  8708. }
  8709. }
  8710. }
  8711. }
  8712. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  8713. ForEach (*iter)
  8714. mergeProgress(iter->query(), progressTree, progressV);
  8715. }
  8716. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  8717. {
  8718. return p->getPropTree("xgmml");
  8719. }
  8720. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  8721. {
  8722. if (!graph)
  8723. {
  8724. // NB: although graphBin introduced in wuidVersion==2,
  8725. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  8726. MemoryBuffer mb;
  8727. if (p->getPropBin("xgmml/graphBin", mb))
  8728. graph.setown(createPTree(mb, ipt_lowmem));
  8729. else
  8730. graph.setown(p->getBranch("xgmml/graph"));
  8731. if (!graph)
  8732. return NULL;
  8733. }
  8734. if (!doMergeProgress)
  8735. return graph.getLink();
  8736. else
  8737. {
  8738. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  8739. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  8740. if (progress)
  8741. {
  8742. //MORE: Eventually this should directly access the new stats structure
  8743. unsigned progressV = progress->queryFormatVersion();
  8744. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  8745. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  8746. ForEach (*nodeIterator)
  8747. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  8748. }
  8749. return copy.getClear();
  8750. }
  8751. }
  8752. WUGraphType CLocalWUGraph::getType() const
  8753. {
  8754. return (WUGraphType) getEnum(p, "@type", graphTypes);
  8755. }
  8756. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  8757. {
  8758. str.set(p->queryProp("@type"));
  8759. if (!str.length())
  8760. str.set("unknown");
  8761. return str;
  8762. }
  8763. unsigned CLocalWUGraph::getWfid() const
  8764. {
  8765. return p->getPropInt("@wfid", 0);
  8766. }
  8767. void CLocalWUGraph::setType(WUGraphType _type)
  8768. {
  8769. setEnum(p, "@type", _type, graphTypes);
  8770. }
  8771. //=================================================================================================
  8772. EnumMapping queryFileTypes[] = {
  8773. { FileTypeCpp, "cpp" },
  8774. { FileTypeDll, "dll" },
  8775. { FileTypeResText, "res" },
  8776. { FileTypeHintXml, "hint" },
  8777. { FileTypeXml, "xml" },
  8778. { FileTypeLog, "log" },
  8779. { FileTypeSize, NULL },
  8780. };
  8781. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  8782. {
  8783. }
  8784. WUFileType CLocalWUAssociated::getType() const
  8785. {
  8786. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  8787. }
  8788. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  8789. {
  8790. str.set(p->queryProp("@desc"));
  8791. return str;
  8792. }
  8793. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  8794. {
  8795. str.set(p->queryProp("@ip"));
  8796. return str;
  8797. }
  8798. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  8799. {
  8800. str.set(p->queryProp("@filename"));
  8801. return str;
  8802. }
  8803. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  8804. {
  8805. str.set(pathTail(p->queryProp("@filename")));
  8806. return str;
  8807. }
  8808. unsigned CLocalWUAssociated::getCrc() const
  8809. {
  8810. return p->getPropInt("@crc", 0);
  8811. }
  8812. unsigned CLocalWUAssociated::getMinActivityId() const
  8813. {
  8814. return p->getPropInt("@minActivity", 0);
  8815. }
  8816. unsigned CLocalWUAssociated::getMaxActivityId() const
  8817. {
  8818. return p->getPropInt("@maxActivity", 0);
  8819. }
  8820. //=================================================================================================
  8821. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  8822. {
  8823. associatedCached = false;
  8824. }
  8825. EnumMapping queryTypes[] = {
  8826. { QueryTypeUnknown, "unknown" },
  8827. { QueryTypeEcl, "ECL" },
  8828. { QueryTypeSql, "SQL" },
  8829. { QueryTypeXml, "XML" },
  8830. { QueryTypeAttribute, "Attribute" },
  8831. { QueryTypeSize, NULL },
  8832. };
  8833. WUQueryType CLocalWUQuery::getQueryType() const
  8834. {
  8835. return (WUQueryType) getEnum(p, "@type", queryTypes);
  8836. }
  8837. void CLocalWUQuery::setQueryType(WUQueryType qt)
  8838. {
  8839. setEnum(p, "@type", qt, queryTypes);
  8840. }
  8841. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  8842. {
  8843. const char *text = p->queryProp("Text");
  8844. if (!text)
  8845. text = p->queryProp("ShortText");
  8846. str.set(text);
  8847. return str;
  8848. }
  8849. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  8850. {
  8851. const char * text = p->queryProp("ShortText");
  8852. if (text)
  8853. str.set(text);
  8854. else
  8855. {
  8856. text = p->queryProp("Text");
  8857. if (isArchiveQuery(text))
  8858. {
  8859. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8860. const char * path = xml->queryProp("Query/@attributePath");
  8861. if (path)
  8862. {
  8863. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8864. if (resolved)
  8865. str.set(resolved->queryProp(NULL));
  8866. }
  8867. else
  8868. str.set(xml->queryProp("Query"));
  8869. }
  8870. else
  8871. str.set(text);
  8872. }
  8873. return str;
  8874. }
  8875. bool CLocalWUQuery::isArchive() const
  8876. {
  8877. if (p->hasProp("@isArchive"))
  8878. return p->getPropBool("@isArchive");
  8879. const char *text = p->queryProp("Text");
  8880. return isArchiveQuery(text);
  8881. }
  8882. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  8883. {
  8884. str.set(p->queryProp("@name"));
  8885. return str;
  8886. }
  8887. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  8888. {
  8889. str.set(p->queryProp("@main"));
  8890. return str;
  8891. }
  8892. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  8893. {
  8894. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8895. if (entry)
  8896. entry->getNameTail(str);
  8897. return str;
  8898. }
  8899. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  8900. {
  8901. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  8902. if (entry)
  8903. entry->getName(str);
  8904. return str;
  8905. }
  8906. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  8907. {
  8908. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  8909. if (entry)
  8910. entry->getName(str);
  8911. return str;
  8912. }
  8913. unsigned CLocalWUQuery::getQueryDllCrc() const
  8914. {
  8915. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8916. if (entry)
  8917. return entry->getCrc();
  8918. return 0;
  8919. }
  8920. void CLocalWUQuery::setQueryText(const char *text)
  8921. {
  8922. bool isArchive = isArchiveQuery(text);
  8923. if (isArchive)
  8924. {
  8925. p->setProp("Text", text);
  8926. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8927. const char * path = xml->queryProp("Query/@attributePath");
  8928. if (path)
  8929. {
  8930. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8931. if (resolved)
  8932. p->setProp("ShortText", resolved->queryProp(NULL));
  8933. }
  8934. else
  8935. p->setProp("ShortText", xml->queryProp("Query"));
  8936. }
  8937. else
  8938. {
  8939. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  8940. // but as long as there may be new workunits compiled by old systems, we can't
  8941. p->setProp("ShortText", text);
  8942. }
  8943. p->setPropBool("@isArchive", isArchive);
  8944. if (isArchive)
  8945. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  8946. }
  8947. void CLocalWUQuery::setQueryName(const char *qname)
  8948. {
  8949. p->setProp("@name", qname);
  8950. }
  8951. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  8952. {
  8953. p->setProp("@main", str);
  8954. }
  8955. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  8956. {
  8957. CriticalBlock block(crit);
  8958. loadAssociated();
  8959. StringBuffer xpath;
  8960. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  8961. if (p->hasProp(xpath))
  8962. return;
  8963. if (!associated.length())
  8964. p->addPropTree("Associated");
  8965. IPropertyTree *pl = p->queryPropTree("Associated");
  8966. IPropertyTree *s = pl->addPropTree("File");
  8967. setEnum(s, "@type", type, queryFileTypes);
  8968. s->setProp("@filename", name);
  8969. s->setProp("@ip", ip);
  8970. s->setProp("@desc", desc);
  8971. if (crc)
  8972. s->setPropInt("@crc", crc);
  8973. if (minActivity)
  8974. s->setPropInt("@minActivity", minActivity);
  8975. if (maxActivity)
  8976. s->setPropInt("@maxActivity", maxActivity);
  8977. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  8978. associated.append(*q);
  8979. }
  8980. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  8981. {
  8982. CriticalBlock block(crit);
  8983. associatedCached = false;
  8984. associated.kill();
  8985. StringBuffer xpath;
  8986. xpath.append("Associated/File");
  8987. if (type)
  8988. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  8989. if (name)
  8990. xpath.append("[@filename=\"").append(name).append("\"]");
  8991. if (desc)
  8992. xpath.append("[@desc=\"").append(desc).append("\"]");
  8993. p->removeProp(xpath.str());
  8994. }
  8995. void CLocalWUQuery::removeAssociatedFiles()
  8996. {
  8997. associatedCached = false;
  8998. associated.kill();
  8999. p->removeProp("Associated");
  9000. }
  9001. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9002. {
  9003. CriticalBlock block(crit);
  9004. loadAssociated();
  9005. ForEachItemIn(idx, associated)
  9006. {
  9007. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9008. if (cur.getType() == type)
  9009. {
  9010. if (index-- == 0)
  9011. return &OLINK(cur);
  9012. }
  9013. }
  9014. return NULL;
  9015. }
  9016. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9017. {
  9018. const char * name = p->queryProp(propname);
  9019. if (name)
  9020. {
  9021. IPropertyTree *s = createPTree("File");
  9022. setEnum(s, "@type", type, queryFileTypes);
  9023. s->setProp("@filename", name);
  9024. if (crc)
  9025. s->setPropInt("@crc", crc);
  9026. associated.append(*new CLocalWUAssociated(s));
  9027. }
  9028. }
  9029. void CLocalWUQuery::loadAssociated() const
  9030. {
  9031. CriticalBlock block(crit);
  9032. if (!associatedCached)
  9033. {
  9034. assertex(associated.length() == 0);
  9035. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9036. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9037. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9038. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9039. for (r->first(); r->isValid(); r->next())
  9040. {
  9041. IPropertyTree *rp = &r->query();
  9042. rp->Link();
  9043. associated.append(*new CLocalWUAssociated(rp));
  9044. }
  9045. associatedCached = true;
  9046. }
  9047. }
  9048. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9049. {
  9050. CriticalBlock block(crit);
  9051. loadAssociated();
  9052. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9053. }
  9054. //========================================================================================
  9055. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9056. {
  9057. }
  9058. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9059. {
  9060. str.set(p->queryProp("@module"));
  9061. return str;
  9062. }
  9063. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9064. {
  9065. str.set(p->queryProp("@attribute"));
  9066. return str;
  9067. }
  9068. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9069. {
  9070. str.set(p->queryProp("@defaultName"));
  9071. return str;
  9072. }
  9073. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9074. {
  9075. return (unsigned) p->getPropInt("@crc");
  9076. }
  9077. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9078. {
  9079. if (!name)
  9080. {
  9081. StringBuffer ws_info;
  9082. ws_info.appendf("<%s ", p->queryName());
  9083. Owned<IAttributeIterator> attrs = p->getAttributes();
  9084. for(attrs->first(); attrs->isValid(); attrs->next())
  9085. {
  9086. const char *name = attrs->queryName()+1;
  9087. const char *value = attrs->queryValue();
  9088. ws_info.appendf("%s='%s' ", name, value);
  9089. }
  9090. ws_info.append("> \n");
  9091. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9092. ForEach(*info)
  9093. {
  9094. IPropertyTree &item = info->query();
  9095. const char *name = item.queryName();
  9096. if (name)
  9097. {
  9098. MemoryBuffer mb;
  9099. bool isbin = p->isBinary(name);
  9100. if (isbin)
  9101. {
  9102. p->getPropBin(name,mb);
  9103. if (mb.length())
  9104. {
  9105. unsigned len = 0;
  9106. mb.read(len);
  9107. StringBuffer encodedString;
  9108. StringBuffer val(len, (const char *) mb.readDirect(len));
  9109. encodeXML(val, encodedString);
  9110. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9111. }
  9112. }
  9113. else
  9114. {
  9115. StringBuffer tmp;
  9116. toXML(&item, tmp);
  9117. ws_info.append(tmp.str());
  9118. }
  9119. }
  9120. }
  9121. ws_info.appendf("</%s>", p->queryName());
  9122. str.setLen(ws_info.str(), ws_info.length());
  9123. }
  9124. else
  9125. {
  9126. MemoryBuffer mb;
  9127. p->getPropBin(name,mb);
  9128. if (mb.length())
  9129. {
  9130. unsigned len;
  9131. mb.read(len);
  9132. str.setLen((const char *) mb.readDirect(len), len);
  9133. }
  9134. }
  9135. return str;
  9136. }
  9137. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9138. {
  9139. str.set(p->queryProp(name));
  9140. return str;
  9141. }
  9142. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9143. {
  9144. p->setProp("@module", mname);
  9145. }
  9146. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9147. {
  9148. p->setProp("@attribute", aname);
  9149. }
  9150. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9151. {
  9152. p->setProp("@defaultName", dname);
  9153. }
  9154. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9155. {
  9156. p->setPropInt("@crc", crc);
  9157. }
  9158. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9159. {
  9160. MemoryBuffer m;
  9161. unsigned len = (size32_t)strlen(info);
  9162. serializeLPString(len, info, m);
  9163. p->setPropBin(name, m.length(), m.toByteArray());
  9164. }
  9165. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9166. {
  9167. p->setProp(name, info);
  9168. }
  9169. //========================================================================================
  9170. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9171. {
  9172. }
  9173. EnumMapping resultStatuses[] = {
  9174. { ResultStatusUndefined, "undefined" },
  9175. { ResultStatusCalculated, "calculated" },
  9176. { ResultStatusSupplied, "supplied" },
  9177. { ResultStatusFailed, "failed" },
  9178. { ResultStatusPartial, "partial" },
  9179. { ResultStatusSize, NULL }
  9180. };
  9181. WUResultStatus CLocalWUResult::getResultStatus() const
  9182. {
  9183. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9184. }
  9185. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9186. {
  9187. str.set(p->queryProp("@name"));
  9188. return str;
  9189. }
  9190. int CLocalWUResult::getResultSequence() const
  9191. {
  9192. return p->getPropInt("@sequence", -1);
  9193. }
  9194. bool CLocalWUResult::isResultScalar() const
  9195. {
  9196. return p->getPropInt("@isScalar", 1) != 0;
  9197. }
  9198. bool findSize(int size, IntArray &sizes)
  9199. {
  9200. ForEachItemIn(idx, sizes)
  9201. {
  9202. if (sizes.item(idx)==size)
  9203. return true;
  9204. }
  9205. return false;
  9206. }
  9207. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9208. {
  9209. MemoryBuffer schema;
  9210. p->getPropBin("SchemaRaw", schema);
  9211. if (schema.length())
  9212. {
  9213. for (;;)
  9214. {
  9215. StringAttr name;
  9216. schema.read(name);
  9217. if (*schema.readDirect(0)==type_void)
  9218. break;
  9219. names.append(*new StringAttrItem(name));
  9220. types.append(*deserializeType(schema)); // MORE - nested records!
  9221. }
  9222. schema.skip(1);
  9223. if (schema.length() != schema.getPos())
  9224. {
  9225. unsigned eclLen;
  9226. schema.read(eclLen);
  9227. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9228. if (eclText)
  9229. {
  9230. eclText->setLen(schemaData, eclLen);
  9231. if ((eclLen == 0) && names.ordinality())
  9232. {
  9233. const char * firstName = names.item(0).text;
  9234. StringBuffer temp;
  9235. temp.append("RECORD ");
  9236. types.item(0).getECLType(temp);
  9237. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9238. eclText->set(temp.str());
  9239. }
  9240. }
  9241. }
  9242. }
  9243. }
  9244. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9245. {
  9246. ForEachItemIn(idx, types)
  9247. {
  9248. StringAttrItem &name = names.item(idx);
  9249. ITypeInfo &type = types.item(idx);
  9250. unsigned size = type.getSize();
  9251. switch(type.getTypeCode())
  9252. {
  9253. case type_data:
  9254. if (size==UNKNOWN_LENGTH)
  9255. {
  9256. if (in.remaining() < sizeof(int))
  9257. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9258. in.read(size);
  9259. }
  9260. outputXmlData(size, in.readDirect(size), name.text, out);
  9261. break;
  9262. case type_string:
  9263. if (size==UNKNOWN_LENGTH)
  9264. {
  9265. if (in.remaining() < sizeof(int))
  9266. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9267. in.read(size);
  9268. }
  9269. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9270. break;
  9271. case type_varstring:
  9272. {
  9273. if (size == UNKNOWN_LENGTH)
  9274. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9275. const char * text = (const char *) in.readDirect(size);
  9276. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9277. break;
  9278. }
  9279. case type_unicode:
  9280. {
  9281. unsigned len = type.getStringLen();
  9282. if (size==UNKNOWN_LENGTH)
  9283. in.read(len);
  9284. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9285. }
  9286. break;
  9287. case type_utf8:
  9288. {
  9289. unsigned len = type.getStringLen();
  9290. if (size==UNKNOWN_LENGTH)
  9291. {
  9292. in.read(len);
  9293. size = rtlUtf8Size(len, in.readDirect(0));
  9294. }
  9295. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9296. }
  9297. break;
  9298. case type_qstring:
  9299. {
  9300. unsigned len = type.getStringLen();
  9301. if (size==UNKNOWN_LENGTH)
  9302. in.read(len);
  9303. unsigned outlen;
  9304. char *outstr;
  9305. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9306. outputXmlString(outlen, outstr, name.text, out);
  9307. free(outstr);
  9308. break;
  9309. }
  9310. case type_int:
  9311. case type_swapint:
  9312. if (type.isSigned())
  9313. {
  9314. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9315. unsigned __int64 cval8 = 0;
  9316. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9317. if (type.isSwappedEndian())
  9318. {
  9319. unsigned idx = 0;
  9320. if (raw[idx] & 0x80)
  9321. cval8 = (__int64)-1;
  9322. while (size--)
  9323. cval8 = (cval8 << 8) | raw[idx++];
  9324. }
  9325. else
  9326. {
  9327. if (raw[size-1] & 0x80)
  9328. cval8 = (__int64)-1;
  9329. while (size--)
  9330. cval8 = (cval8 << 8) | raw[size];
  9331. }
  9332. outputXmlInt((__int64) cval8, name.text, out);
  9333. }
  9334. else
  9335. {
  9336. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9337. unsigned __int64 cval8 = 0;
  9338. if (type.isSwappedEndian())
  9339. {
  9340. unsigned idx = 0;
  9341. while (size--)
  9342. cval8 = (cval8 << 8) | raw[idx++];
  9343. }
  9344. else
  9345. {
  9346. while (size--)
  9347. cval8 = (cval8 << 8) | raw[size];
  9348. }
  9349. outputXmlUInt(cval8, name.text, out);
  9350. }
  9351. break;
  9352. case type_boolean:
  9353. bool cvalb;
  9354. in.read(cvalb);
  9355. outputXmlBool(cvalb, name.text, out);
  9356. break;
  9357. case type_decimal:
  9358. if (type.isSigned())
  9359. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9360. else
  9361. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9362. break;
  9363. case type_real:
  9364. double cvald;
  9365. switch(size)
  9366. {
  9367. case 4:
  9368. float cvalf;
  9369. in.read(cvalf);
  9370. cvald = cvalf;
  9371. break;
  9372. case 8:
  9373. in.read(cvald);
  9374. break;
  9375. default:
  9376. throwUnexpected();
  9377. }
  9378. outputXmlReal(cvald, name.text, out);
  9379. break;
  9380. default:
  9381. assertex(!"unexpected type in raw record");
  9382. break;
  9383. }
  9384. }
  9385. }
  9386. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9387. {
  9388. TypeInfoArray types;
  9389. StringAttrArray names;
  9390. getSchema(types, names);
  9391. StringBuffer xml;
  9392. const char * name = p->queryProp("@name");
  9393. if (name)
  9394. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9395. else
  9396. xml.append("<Dataset>\n");
  9397. if (hidePassword && p->getPropBool("Format/@password"))
  9398. {
  9399. xml.append(" <Row>");
  9400. appendXMLTag(xml, name, "****");
  9401. xml.append("</Row>\n");
  9402. }
  9403. else if (p->hasProp("Value"))
  9404. {
  9405. MemoryBuffer raw;
  9406. p->getPropBin("Value", raw);
  9407. unsigned __int64 numrows = getResultRowCount();
  9408. while (numrows--)
  9409. {
  9410. xml.append(" <Row>");
  9411. readRow(xml, raw, types, names);
  9412. xml.append("</Row>\n");
  9413. }
  9414. }
  9415. else if (p->hasProp("xmlValue"))
  9416. {
  9417. xml.append(" <Row>");
  9418. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9419. xml.append("</Row>\n");
  9420. }
  9421. xml.append("</Dataset>\n");
  9422. str.set(xml.str());
  9423. return str;
  9424. }
  9425. IProperties *CLocalWUResult::queryResultXmlns()
  9426. {
  9427. CriticalBlock block(crit);
  9428. if (xmlns)
  9429. return xmlns;
  9430. xmlns.setown(createProperties());
  9431. Owned<IAttributeIterator> it = p->getAttributes();
  9432. unsigned prefixLen = strlen("@xmlns");
  9433. ForEach(*it)
  9434. {
  9435. const char *name = it->queryName();
  9436. if (!strncmp("@xmlns", name, prefixLen))
  9437. {
  9438. if (name[prefixLen]==':') //normal case
  9439. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9440. else if (!name[prefixLen]) //special case, unprefixed namespace
  9441. xmlns->setProp("xmlns", it->queryValue());
  9442. }
  9443. }
  9444. return xmlns;
  9445. }
  9446. unsigned CLocalWUResult::getResultFetchSize() const
  9447. {
  9448. return p->getPropInt("fetchSize", 100);
  9449. }
  9450. __int64 CLocalWUResult::getResultTotalRowCount() const
  9451. {
  9452. return p->getPropInt64("totalRowCount", -1);
  9453. }
  9454. __int64 CLocalWUResult::getResultRowCount() const
  9455. {
  9456. return p->getPropInt64("rowCount", 0);
  9457. }
  9458. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9459. {
  9460. ecl.set(p->queryProp("datasetEcl"));
  9461. defs.set(p->queryProp("datasetEclDefs"));
  9462. }
  9463. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9464. {
  9465. val.set(p->queryProp("logicalName"));
  9466. return val;
  9467. }
  9468. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9469. {
  9470. ecl.set(p->queryProp("keyField"));
  9471. return ecl;
  9472. }
  9473. unsigned CLocalWUResult::getResultRequestedRows() const
  9474. {
  9475. return p->getPropInt("requestedRows", 1);
  9476. }
  9477. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9478. {
  9479. TypeInfoArray types;
  9480. StringAttrArray names;
  9481. getSchema(types, names, &str);
  9482. return str;
  9483. }
  9484. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9485. {
  9486. str.set(p->queryProp("@recordSizeEntry"));
  9487. return str;
  9488. }
  9489. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9490. {
  9491. str.set(p->queryProp("@transformerEntry"));
  9492. return str;
  9493. }
  9494. __int64 CLocalWUResult::getResultRowLimit() const
  9495. {
  9496. return p->getPropInt64("@rowLimit");
  9497. }
  9498. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9499. {
  9500. str.set(p->queryProp("@tempFilename"));
  9501. return str;
  9502. }
  9503. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9504. {
  9505. str.clear();
  9506. if (!name || !*name)
  9507. return str;
  9508. IPropertyTree *format = p->queryPropTree("Format");
  9509. if (!format)
  9510. return str;
  9511. VStringBuffer xpath("@%s", name);
  9512. str.set(format->queryProp(xpath));
  9513. return str;
  9514. }
  9515. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9516. {
  9517. _graph.set(p->queryProp("@graph"));
  9518. _activityId = p->getPropInt("@activity", 0);
  9519. }
  9520. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9521. {
  9522. setEnum(p, "@status", status, resultStatuses);
  9523. if (status==ResultStatusUndefined)
  9524. {
  9525. p->removeProp("Value");
  9526. p->removeProp("totalRowCount");
  9527. p->removeProp("rowCount");
  9528. p->removeProp("@format");
  9529. p->removeProp("@tempFileNmae");
  9530. p->removeProp("logicalName");
  9531. }
  9532. }
  9533. void CLocalWUResult::setResultName(const char *s)
  9534. {
  9535. p->setProp("@name", s);
  9536. }
  9537. void CLocalWUResult::setResultSequence(unsigned seq)
  9538. {
  9539. p->setPropInt("@sequence", seq);
  9540. }
  9541. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  9542. {
  9543. p->setPropBin("SchemaRaw", size, schema);
  9544. }
  9545. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  9546. {
  9547. StringBuffer xpath("@xmlns");
  9548. if (prefix && *prefix)
  9549. xpath.append(':').append(prefix);
  9550. p->setProp(xpath, uri);
  9551. }
  9552. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  9553. {
  9554. if (!name || !*name)
  9555. return;
  9556. IPropertyTree *format = ensurePTree(p, "Format");
  9557. VStringBuffer xpath("@%s", name);
  9558. format->setProp(xpath, value);
  9559. }
  9560. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  9561. {
  9562. p->setProp("@graph", _graph);
  9563. p->setPropInt("@activity", _activityId);
  9564. }
  9565. void CLocalWUResult::setResultScalar(bool isScalar)
  9566. {
  9567. p->setPropInt("@isScalar", (int) isScalar);
  9568. if (isScalar)
  9569. setResultTotalRowCount(1);
  9570. }
  9571. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  9572. {
  9573. p->setPropBin("Value", len, data);
  9574. setResultStatus(ResultStatusSupplied);
  9575. setResultFormat(format);
  9576. }
  9577. void CLocalWUResult::setResultFormat(WUResultFormat format)
  9578. {
  9579. switch (format)
  9580. {
  9581. case ResultFormatXml:
  9582. p->setProp("@format","xml");
  9583. break;
  9584. case ResultFormatXmlSet:
  9585. p->setProp("@format","xmlSet");
  9586. break;
  9587. case ResultFormatCsv:
  9588. p->setProp("@format","csv");
  9589. break;
  9590. default:
  9591. p->removeProp("@format");
  9592. break;
  9593. }
  9594. }
  9595. void CLocalWUResult::setResultXML(const char *val)
  9596. {
  9597. p->setProp("xmlValue", val);
  9598. }
  9599. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  9600. {
  9601. p->appendPropBin("Value", len, data);
  9602. setResultStatus(ResultStatusPartial);
  9603. const char *existingFormat = p->queryProp("@format");
  9604. const char *formatStr = NULL;
  9605. switch (format)
  9606. {
  9607. case ResultFormatXml:
  9608. formatStr = "xml";
  9609. break;
  9610. case ResultFormatXmlSet:
  9611. formatStr = "xmlSet";
  9612. break;
  9613. case ResultFormatCsv:
  9614. formatStr = "csv";
  9615. break;
  9616. default:
  9617. existingFormat = nullptr;
  9618. p->removeProp("@format");
  9619. break;
  9620. }
  9621. if (format)
  9622. {
  9623. if (existingFormat)
  9624. {
  9625. if (0 != stricmp(formatStr, existingFormat))
  9626. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  9627. }
  9628. else
  9629. p->setProp("@format", formatStr);
  9630. }
  9631. }
  9632. void CLocalWUResult::setResultFetchSize(unsigned rows)
  9633. {
  9634. p->setPropInt("fetchSize", rows);
  9635. }
  9636. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  9637. {
  9638. p->setPropInt64("totalRowCount", rows);
  9639. }
  9640. void CLocalWUResult::setResultRowCount(__int64 rows)
  9641. {
  9642. p->setPropInt64("rowCount", rows);
  9643. }
  9644. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  9645. {
  9646. p->setProp("datasetEcl", ecl);
  9647. p->setProp("datasetEclDefs", defs);
  9648. }
  9649. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  9650. {
  9651. p->setProp("logicalName", logicalName);
  9652. }
  9653. void CLocalWUResult::setResultKeyField(const char *ecl)
  9654. {
  9655. p->setProp("keyField", ecl);
  9656. }
  9657. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  9658. {
  9659. p->setPropInt("requestedRows", rows);
  9660. }
  9661. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  9662. {
  9663. p->setProp("@recordSizeEntry", entry);
  9664. }
  9665. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  9666. {
  9667. p->setProp("@transformerEntry", entry);
  9668. }
  9669. void CLocalWUResult::setResultRowLimit(__int64 value)
  9670. {
  9671. p->setPropInt64("@rowLimit", value);
  9672. }
  9673. void CLocalWUResult::setResultFilename(const char * name)
  9674. {
  9675. p->setProp("@tempFilename", name);
  9676. }
  9677. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  9678. __int64 CLocalWUResult::getResultInt() const
  9679. {
  9680. __int64 result = 0;
  9681. MemoryBuffer s;
  9682. p->getPropBin("Value", s);
  9683. if (s.length())
  9684. s.read(result);
  9685. else
  9686. {
  9687. // NOTE - we use this rather than getPropInt64 since it handles uint64 values up to MAX_UINT better (for our purposes)
  9688. const char *val = p->queryProp("xmlValue");
  9689. if (val)
  9690. result = rtlStrToInt8(strlen(val), val);
  9691. }
  9692. return result;
  9693. }
  9694. bool CLocalWUResult::getResultBool() const
  9695. {
  9696. bool result = false;
  9697. MemoryBuffer s;
  9698. p->getPropBin("Value", s);
  9699. if (s.length())
  9700. s.read(result);
  9701. else
  9702. result = p->getPropBool("xmlValue");
  9703. return result;
  9704. }
  9705. double CLocalWUResult::getResultReal() const
  9706. {
  9707. double result = 0;
  9708. MemoryBuffer s;
  9709. p->getPropBin("Value", s);
  9710. if (s.length())
  9711. s.read(result);
  9712. else
  9713. {
  9714. const char *xmlVal = p->queryProp("xmlValue");
  9715. if (xmlVal)
  9716. result = atof(xmlVal);
  9717. }
  9718. return result;
  9719. }
  9720. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  9721. {
  9722. MemoryBuffer s;
  9723. p->getPropBin("Value", s);
  9724. if (s.length())
  9725. {
  9726. assertex(s.length() == len);
  9727. s.read(len, val);
  9728. }
  9729. else
  9730. {
  9731. const char *xmlVal = p->queryProp("xmlValue");
  9732. if (xmlVal)
  9733. {
  9734. Decimal d;
  9735. d.setString(strlen(xmlVal), xmlVal);
  9736. if (isSigned)
  9737. d.getDecimal(len, precision, val);
  9738. else
  9739. d.getUDecimal(len, precision, val);
  9740. }
  9741. else
  9742. memset(val, 0, len);
  9743. }
  9744. }
  9745. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  9746. {
  9747. if (hidePassword && p->getPropBool("@password"))
  9748. {
  9749. str.set("****");
  9750. return str;
  9751. }
  9752. MemoryBuffer s;
  9753. p->getPropBin("Value", s);
  9754. if (s.length())
  9755. {
  9756. unsigned len;
  9757. s.read(len);
  9758. str.setLen((const char *) s.readDirect(len), len);
  9759. }
  9760. else
  9761. {
  9762. p->getPropBin("xmlValue", s);
  9763. if (p->isBinary("xmlValue"))
  9764. str.setLen(s.toByteArray(), s.length());
  9765. else
  9766. {
  9767. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  9768. str.set(ascii);
  9769. rtlFree(ascii);
  9770. }
  9771. }
  9772. return str;
  9773. }
  9774. WUResultFormat CLocalWUResult::getResultFormat() const
  9775. {
  9776. const char * format = p->queryProp("@format");
  9777. if (!format)
  9778. return ResultFormatRaw;
  9779. else if (strcmp(format, "xml") == 0)
  9780. return ResultFormatXml;
  9781. else if (strcmp(format, "xmlSet") == 0)
  9782. return ResultFormatXmlSet;
  9783. else if (strcmp(format, "csv") == 0)
  9784. return ResultFormatCsv;
  9785. else
  9786. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  9787. }
  9788. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9789. {
  9790. MemoryBuffer s;
  9791. p->getPropBin("Value", s);
  9792. unsigned len = s.length();
  9793. if (len)
  9794. {
  9795. WUResultFormat format = getResultFormat();
  9796. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  9797. {
  9798. if (!xmlTransformer)
  9799. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  9800. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  9801. }
  9802. else if (format == ResultFormatCsv)
  9803. {
  9804. if (!csvTransformer)
  9805. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  9806. csvTransformer->transform(data, len, s.readDirect(len), true);
  9807. }
  9808. else
  9809. data.setLen(s.readDirect(len), len);
  9810. }
  9811. else
  9812. data.clear();
  9813. return data;
  9814. }
  9815. unsigned CLocalWUResult::getResultHash() const
  9816. {
  9817. MemoryBuffer s;
  9818. p->getPropBin("Value", s);
  9819. unsigned len = s.length();
  9820. const byte * data = (const byte *)s.toByteArray();
  9821. return ~hashc(data, len, ~0);
  9822. }
  9823. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  9824. {
  9825. MemoryBuffer s;
  9826. p->getPropBin("Value", s);
  9827. if (s.length())
  9828. {
  9829. unsigned len;
  9830. s.read(len);
  9831. data.setLen(s.readDirect(len*2), len*2);
  9832. }
  9833. else
  9834. {
  9835. StringBuffer utf8;
  9836. if (p->getProp("xmlValue", utf8))
  9837. {
  9838. unsigned outlen;
  9839. UChar *out;
  9840. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  9841. data.setLen(out, outlen*2);
  9842. rtlFree(out);
  9843. }
  9844. else
  9845. data.clear();
  9846. }
  9847. return data;
  9848. }
  9849. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9850. {
  9851. WUResultFormat format = getResultFormat();
  9852. if (format == ResultFormatRaw)
  9853. {
  9854. //MORE: This should not load the whole property...
  9855. MemoryBuffer s;
  9856. p->getPropBin("Value", s);
  9857. return s.length();
  9858. }
  9859. else
  9860. {
  9861. MemoryBuffer temp;
  9862. MemoryBuffer2IDataVal adaptor(temp);
  9863. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9864. return temp.length();
  9865. }
  9866. }
  9867. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9868. {
  9869. WUResultFormat format = getResultFormat();
  9870. if (format != ResultFormatRaw)
  9871. {
  9872. MemoryBuffer temp;
  9873. MemoryBuffer2IDataVal adaptor(temp);
  9874. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9875. unsigned len = temp.length();
  9876. if (from > len) from = len;
  9877. if (from + length > len) length = len - from;
  9878. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  9879. return data;
  9880. }
  9881. else
  9882. {
  9883. //MORE: This should not load the whole property, and should be different from the code above...
  9884. MemoryBuffer s;
  9885. p->getPropBin("Value", s);
  9886. unsigned len = s.length();
  9887. if (from > len) from = len;
  9888. if (from + length > len) length = len - from;
  9889. data.setLen(s.readDirect(len) + from, (size32_t)length);
  9890. return data;
  9891. }
  9892. }
  9893. bool CLocalWUResult::getResultIsAll() const
  9894. {
  9895. return p->getPropBool("@isAll", false);
  9896. }
  9897. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  9898. void CLocalWUResult::setResultInt(__int64 val)
  9899. {
  9900. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  9901. MemoryBuffer m;
  9902. serializeInt8(val, m);
  9903. p->setPropBin("Value", m.length(), m.toByteArray());
  9904. setResultRowCount(1);
  9905. setResultTotalRowCount(1);
  9906. }
  9907. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  9908. {
  9909. setResultInt((__int64) val);
  9910. }
  9911. void CLocalWUResult::setResultReal(double val)
  9912. {
  9913. // Note: we always serialize scalar real results as real8, and schema must reflect this
  9914. MemoryBuffer m;
  9915. serializeReal8(val, m);
  9916. p->setPropBin("Value", m.length(), m.toByteArray());
  9917. setResultRowCount(1);
  9918. setResultTotalRowCount(1);
  9919. }
  9920. void CLocalWUResult::setResultBool(bool val)
  9921. {
  9922. MemoryBuffer m;
  9923. serializeBool(val, m);
  9924. p->setPropBin("Value", m.length(), m.toByteArray());
  9925. setResultRowCount(1);
  9926. setResultTotalRowCount(1);
  9927. }
  9928. void CLocalWUResult::setResultString(const char *val, unsigned len)
  9929. {
  9930. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9931. MemoryBuffer m;
  9932. serializeLPString(len, val, m);
  9933. p->setPropBin("Value", m.length(), m.toByteArray());
  9934. setResultRowCount(1);
  9935. setResultTotalRowCount(1);
  9936. }
  9937. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  9938. {
  9939. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9940. MemoryBuffer m;
  9941. m.append(len).append(len*2, val);
  9942. p->setPropBin("Value", m.length(), m.toByteArray());
  9943. setResultRowCount(1);
  9944. setResultTotalRowCount(1);
  9945. }
  9946. void CLocalWUResult::setResultData(const void *val, unsigned len)
  9947. {
  9948. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  9949. MemoryBuffer m;
  9950. serializeLPString(len, (const char *)val, m);
  9951. p->setPropBin("Value", m.length(), m.toByteArray());
  9952. setResultRowCount(1);
  9953. setResultTotalRowCount(1);
  9954. }
  9955. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  9956. {
  9957. // Note: serialized as data but with length known from schema
  9958. MemoryBuffer m;
  9959. serializeFixedData(len, val, m);
  9960. p->setPropBin("Value", m.length(), m.toByteArray());
  9961. setResultRowCount(1);
  9962. setResultTotalRowCount(1);
  9963. }
  9964. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  9965. {
  9966. p->setPropBin("Value", len, data);
  9967. setResultRowCount(1);
  9968. setResultTotalRowCount(1);
  9969. setResultFormat(ResultFormatRaw);
  9970. }
  9971. void CLocalWUResult::setResultIsAll(bool value)
  9972. {
  9973. p->setPropBool("@isAll", value);
  9974. }
  9975. //==========================================================================================
  9976. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  9977. {
  9978. }
  9979. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  9980. {
  9981. str.set(p->queryProp("@dllname"));
  9982. return str;
  9983. }
  9984. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  9985. {
  9986. str.set(p->queryProp("@version"));
  9987. return str;
  9988. }
  9989. void CLocalWUPlugin::setPluginName(const char *str)
  9990. {
  9991. p->setProp("@dllname", str);
  9992. }
  9993. void CLocalWUPlugin::setPluginVersion(const char *str)
  9994. {
  9995. p->setProp("@version", str);
  9996. }
  9997. //==========================================================================================
  9998. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  9999. {
  10000. }
  10001. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10002. {
  10003. str.set(p->queryProp("@name"));
  10004. return str;
  10005. }
  10006. void CLocalWULibrary::setName(const char *str)
  10007. {
  10008. p->setProp("@name", str);
  10009. }
  10010. //==========================================================================================
  10011. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10012. {
  10013. }
  10014. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10015. {
  10016. str.set(p->queryProp("@source"));
  10017. return str;
  10018. }
  10019. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10020. {
  10021. str.set(p->queryProp(NULL));
  10022. return str;
  10023. }
  10024. unsigned CLocalWUException::getExceptionCode() const
  10025. {
  10026. return p->getPropInt("@code", 0);
  10027. }
  10028. ErrorSeverity CLocalWUException::getSeverity() const
  10029. {
  10030. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10031. }
  10032. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10033. {
  10034. dt.set(p->queryProp("@time"));
  10035. return dt;
  10036. }
  10037. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10038. {
  10039. str.set(p->queryProp("@filename"));
  10040. return str;
  10041. }
  10042. unsigned CLocalWUException::getExceptionLineNo() const
  10043. {
  10044. return p->getPropInt("@row", 0);
  10045. }
  10046. unsigned CLocalWUException::getExceptionColumn() const
  10047. {
  10048. return p->getPropInt("@col", 0);
  10049. }
  10050. unsigned CLocalWUException::getActivityId() const
  10051. {
  10052. const char * scope = queryScope();
  10053. if (scope)
  10054. {
  10055. const char * colon = strrchr(scope, ':');
  10056. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10057. return atoi(colon+1+strlen(ActivityScopePrefix));
  10058. }
  10059. return p->getPropInt("@activity", 0);
  10060. }
  10061. unsigned CLocalWUException::getSequence() const
  10062. {
  10063. return p->getPropInt("@sequence", 0);
  10064. }
  10065. const char * CLocalWUException::queryScope() const
  10066. {
  10067. return p->queryProp("@scope");
  10068. }
  10069. unsigned CLocalWUException::getPriority() const
  10070. {
  10071. return p->getPropInt("@prio", 0);
  10072. }
  10073. void CLocalWUException::setExceptionSource(const char *str)
  10074. {
  10075. p->setProp("@source", str);
  10076. }
  10077. void CLocalWUException::setExceptionMessage(const char *str)
  10078. {
  10079. p->setProp(NULL, str);
  10080. }
  10081. void CLocalWUException::setExceptionCode(unsigned code)
  10082. {
  10083. p->setPropInt("@code", code);
  10084. }
  10085. void CLocalWUException::setSeverity(ErrorSeverity level)
  10086. {
  10087. p->setPropInt("@severity", level);
  10088. }
  10089. void CLocalWUException::setTimeStamp(const char *str)
  10090. {
  10091. p->setProp("@time", str);
  10092. }
  10093. void CLocalWUException::setExceptionFileName(const char *str)
  10094. {
  10095. p->setProp("@filename", str);
  10096. }
  10097. void CLocalWUException::setExceptionLineNo(unsigned r)
  10098. {
  10099. p->setPropInt("@row", r);
  10100. }
  10101. void CLocalWUException::setExceptionColumn(unsigned c)
  10102. {
  10103. p->setPropInt("@col", c);
  10104. }
  10105. void CLocalWUException::setActivityId(unsigned _id)
  10106. {
  10107. p->setPropInt("@activity", _id);
  10108. }
  10109. void CLocalWUException::setScope(const char * _scope)
  10110. {
  10111. p->setProp("@scope", _scope);
  10112. }
  10113. void CLocalWUException::setPriority(unsigned _priority)
  10114. {
  10115. p->setPropInt("@prio", _priority);
  10116. }
  10117. //==========================================================================================
  10118. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10119. {
  10120. StringAttrBuilder propPath(prop);
  10121. propPath.append("*[").append(child).append("]");
  10122. }
  10123. const char * CLocalWUAppValue::queryApplication() const
  10124. {
  10125. return p->queryName();
  10126. }
  10127. const char * CLocalWUAppValue::queryName() const
  10128. {
  10129. IPropertyTree* val=p->queryPropTree(prop.str());
  10130. if(val)
  10131. return val->queryName();
  10132. return ""; // Should not happen in normal usage
  10133. }
  10134. const char * CLocalWUAppValue::queryValue() const
  10135. {
  10136. return p->queryProp(prop.str());
  10137. }
  10138. //==========================================================================================
  10139. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10140. {
  10141. }
  10142. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10143. {
  10144. const char * creator = p->queryProp("@creator");
  10145. str.set(creator);
  10146. return str;
  10147. }
  10148. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10149. {
  10150. const char * desc = p->queryProp("@desc");
  10151. if (desc)
  10152. {
  10153. str.set(desc); // legacy and in case it is overridden
  10154. }
  10155. else if (createDefault)
  10156. {
  10157. StatisticKind kind = getKind();
  10158. assertex(kind != StKindNone);
  10159. const char * scope = p->queryProp("@scope");
  10160. assertex(scope);
  10161. //Clean up the format of the scope when converting it to a description
  10162. StringBuffer descriptionText;
  10163. if (isGlobalScope(scope))
  10164. {
  10165. const char * creator = p->queryProp("@creator");
  10166. descriptionText.append(creator).append(":");
  10167. queryLongStatisticName(descriptionText, kind);
  10168. }
  10169. else
  10170. {
  10171. for (;;)
  10172. {
  10173. char c = *scope++;
  10174. if (!c)
  10175. break;
  10176. if (c == ':')
  10177. descriptionText.append(": ");
  10178. else
  10179. descriptionText.append(c);
  10180. }
  10181. if (kind != StTimeElapsed)
  10182. queryLongStatisticName(descriptionText.append(": "), kind);
  10183. }
  10184. str.set(descriptionText);
  10185. }
  10186. else
  10187. str.clear();
  10188. return str;
  10189. }
  10190. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10191. {
  10192. StringBuffer formatted;
  10193. formatStatistic(formatted, getValue(), getMeasure());
  10194. str.set(formatted);
  10195. return str;
  10196. }
  10197. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10198. {
  10199. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10200. }
  10201. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10202. {
  10203. return queryScopeType(p->queryProp("@s"), SSTnone);
  10204. }
  10205. StatisticKind CLocalWUStatistic::getKind() const
  10206. {
  10207. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10208. }
  10209. const char * CLocalWUStatistic::queryScope() const
  10210. {
  10211. const char * scope = p->queryProp("@scope");
  10212. if (!scope || streq(scope, LEGACY_GLOBAL_SCOPE))
  10213. scope = GLOBAL_SCOPE;
  10214. return scope;
  10215. }
  10216. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10217. {
  10218. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10219. }
  10220. unsigned __int64 CLocalWUStatistic::getValue() const
  10221. {
  10222. return p->getPropInt64("@value", 0);
  10223. }
  10224. unsigned __int64 CLocalWUStatistic::getCount() const
  10225. {
  10226. return p->getPropInt64("@count", 0);
  10227. }
  10228. unsigned __int64 CLocalWUStatistic::getMax() const
  10229. {
  10230. return p->getPropInt64("@max", 0);
  10231. }
  10232. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10233. {
  10234. return p->getPropInt64("@ts", 0);
  10235. }
  10236. //==========================================================================================
  10237. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10238. {
  10239. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10240. if (xml)
  10241. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10242. else
  10243. {
  10244. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10245. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10246. cw->loadPTree(p.getClear());
  10247. }
  10248. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10249. return ret;
  10250. }
  10251. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10252. {
  10253. const char *name = p->queryName();
  10254. if (!name)
  10255. name = "__unnamed__";
  10256. StringBuffer temp;
  10257. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10258. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10259. ForEach(*elems)
  10260. {
  10261. IPropertyTree &elem = elems->query();
  10262. if (streq(elem.queryName(), "Parameters"))
  10263. {
  10264. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10265. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10266. ForEach(*params)
  10267. {
  10268. IPropertyTree &param = params->query();
  10269. const char *paramname = param.queryName();
  10270. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10271. if (p->getPropBool(xpath))
  10272. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10273. else
  10274. {
  10275. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10276. }
  10277. }
  10278. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10279. }
  10280. else if (streq(elem.queryName(), "Variables"))
  10281. {
  10282. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10283. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10284. ForEach(*vars)
  10285. {
  10286. Owned<IPropertyTree> var = LINK(&vars->query());
  10287. if (var->getPropBool("Format/@password"))
  10288. {
  10289. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10290. var->removeProp("Value");
  10291. var->removeProp("xmlValue");
  10292. }
  10293. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10294. }
  10295. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10296. }
  10297. else
  10298. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10299. }
  10300. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10301. }
  10302. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10303. {
  10304. class CAdapter : public CInterface, implements IIOStream
  10305. {
  10306. StringBuffer &out;
  10307. public:
  10308. IMPLEMENT_IINTERFACE;
  10309. CAdapter(StringBuffer &_out) : out(_out) { }
  10310. virtual void flush() { }
  10311. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10312. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10313. } adapter(str);
  10314. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10315. return str;
  10316. }
  10317. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10318. {
  10319. OwnedIFile ifile = createIFile(filename);
  10320. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10321. Owned<IIOStream> stream = createIOStream(ifileio);
  10322. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10323. }
  10324. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10325. {
  10326. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10327. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10328. if (ewu)
  10329. {
  10330. Linked<IPropertyTree> p;
  10331. if (unpack||includeProgress)
  10332. p.setown(ewu->getUnpackedTree(includeProgress));
  10333. else
  10334. p.set(ewu->queryPTree());
  10335. if (hidePasswords)
  10336. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10337. else
  10338. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10339. }
  10340. else
  10341. return str.append("Unrecognized workunit format");
  10342. }
  10343. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10344. {
  10345. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10346. if (ewu)
  10347. {
  10348. Linked<IPropertyTree> p;
  10349. if (unpack||includeProgress)
  10350. p.setown(ewu->getUnpackedTree(includeProgress));
  10351. else if (regressionTest)
  10352. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10353. else
  10354. p.set(ewu->queryPTree());
  10355. if (hidePasswords)
  10356. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10357. if (regressionTest)
  10358. {
  10359. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10360. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10361. p->removeProp("@buildVersion");
  10362. p->removeProp("@eclVersion");
  10363. p->removeProp("@hash");
  10364. //Remove statistics, and extract them to a separate file
  10365. IPropertyTree * stats = p->queryPropTree("Statistics");
  10366. if (stats)
  10367. {
  10368. StringBuffer statsFilename;
  10369. statsFilename.append(filename).append(".stats");
  10370. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10371. p->removeProp("Statistics");
  10372. }
  10373. //Now remove timestamps from exceptions
  10374. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10375. ForEach(*elems)
  10376. {
  10377. IPropertyTree &elem = elems->query();
  10378. elem.removeProp("@time");
  10379. }
  10380. }
  10381. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10382. }
  10383. else
  10384. throw makeStringException(0, "Unrecognized workunit format");
  10385. }
  10386. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10387. {
  10388. MemoryBuffer buffer;
  10389. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10390. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10391. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10392. assertex(workunit);
  10393. StringAttr clusterName(workunit->queryClusterName());
  10394. if (!clusterName.length())
  10395. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10396. workunit->commit();
  10397. workunit.clear();
  10398. StringBuffer serverQueue;
  10399. getClusterEclCCServerQueueName(serverQueue, clusterName);
  10400. assertex(serverQueue.length());
  10401. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10402. if (!queue.get())
  10403. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10404. IJobQueueItem *item = createJobQueueItem(wuid);
  10405. queue->enqueue(item);
  10406. }
  10407. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10408. {
  10409. StringBuffer xpath("/WorkUnitAborts/");
  10410. xpath.append(wuid);
  10411. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10412. acon->queryRoot()->setPropInt(NULL, 1);
  10413. }
  10414. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10415. {
  10416. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10417. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10418. }
  10419. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10420. {
  10421. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10422. return;
  10423. abortWorkUnit(wuid);
  10424. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10425. if(!cw)
  10426. return;
  10427. WorkunitUpdate wu(&cw->lock());
  10428. const char *abortBy = secuser.getName();
  10429. if (abortBy && *abortBy)
  10430. wu->setTracingValue("AbortBy", abortBy);
  10431. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10432. }
  10433. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10434. {
  10435. if (secmgr && secuser)
  10436. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10437. if (secuser)
  10438. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10439. submitWorkUnit(wuid, "", "");
  10440. }
  10441. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10442. {
  10443. if (secmgr && secuser)
  10444. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10445. abortWorkUnit(wuid);
  10446. }
  10447. bool CLocalWorkUnit::hasWorkflow() const
  10448. {
  10449. return p->hasProp("Workflow");
  10450. }
  10451. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10452. {
  10453. CriticalBlock block(crit);
  10454. if (p->hasProp("@eventScheduledCount"))
  10455. return p->getPropInt("@eventScheduledCount", 0);
  10456. else
  10457. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10458. }
  10459. void CLocalWorkUnit::incEventScheduledCount()
  10460. {
  10461. CriticalBlock block(crit);
  10462. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10463. }
  10464. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10465. {
  10466. CriticalBlock block(crit);
  10467. return p->queryPropTree("Workflow");
  10468. }
  10469. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10470. {
  10471. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10472. CriticalBlock block(crit);
  10473. if(!workflowIteratorCached)
  10474. {
  10475. assertex(!workflowIterator);
  10476. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10477. if(s)
  10478. workflowIterator.setown(createWorkflowItemIterator(s));
  10479. workflowIteratorCached = true;
  10480. }
  10481. return workflowIterator.getLink();
  10482. }
  10483. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10484. {
  10485. unsigned count = 0;
  10486. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10487. for(iter->first(); iter->isValid(); iter->next())
  10488. count++;
  10489. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10490. for(iter->first(); iter->isValid(); iter->next())
  10491. array->addClone(iter->query());
  10492. return array.getLink();
  10493. }
  10494. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10495. {
  10496. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10497. CriticalBlock block(crit);
  10498. workflowIterator.clear();
  10499. workflowIteratorCached = false;
  10500. IPropertyTree * s = p->queryPropTree("Workflow");
  10501. if(!s)
  10502. s = p->addPropTree("Workflow");
  10503. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10504. }
  10505. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10506. {
  10507. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10508. CriticalBlock block(crit);
  10509. if(!workflowIterator)
  10510. {
  10511. IPropertyTree * s = p->queryPropTree("Workflow");
  10512. if(!s)
  10513. s = p->addPropTree("Workflow");
  10514. workflowIterator.setown(createWorkflowItemIterator(s));
  10515. workflowIteratorCached = true;
  10516. }
  10517. return workflowIterator.getLink();
  10518. }
  10519. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10520. {
  10521. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10522. Owned<IWorkflowItem> item;
  10523. for(iter->first(); iter->isValid(); iter->next())
  10524. {
  10525. item.setown(iter->get());
  10526. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10527. }
  10528. workflowIterator.clear();
  10529. workflowIteratorCached = false;
  10530. }
  10531. void CLocalWorkUnit::resetWorkflow()
  10532. {
  10533. if (hasWorkflow())
  10534. {
  10535. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10536. Owned<IWorkflowItem> wf;
  10537. for(iter->first(); iter->isValid(); iter->next())
  10538. {
  10539. wf.setown(iter->get());
  10540. wf->reset();
  10541. }
  10542. workflowIterator.clear();
  10543. workflowIteratorCached = false;
  10544. }
  10545. }
  10546. void CLocalWorkUnit::schedule()
  10547. {
  10548. CriticalBlock block(crit);
  10549. if(queryEventScheduledCount() == 0) return;
  10550. switch(getState())
  10551. {
  10552. case WUStateCompleted:
  10553. setState(WUStateWait);
  10554. break;
  10555. case WUStateFailed:
  10556. case WUStateArchived:
  10557. case WUStateAborting:
  10558. case WUStateAborted:
  10559. case WUStateScheduled:
  10560. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  10561. }
  10562. StringBuffer rootPath;
  10563. rootPath.append("/Schedule/").append(queryClusterName());
  10564. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10565. Owned<IPropertyTree> root = conn->getRoot();
  10566. if(!root->hasChildren())
  10567. {
  10568. StringBuffer addPath;
  10569. addPath.append("/Schedulers/").append(queryClusterName());
  10570. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10571. }
  10572. char const * wuid = p->queryName();
  10573. StringBuffer xpath("*/*/");
  10574. ncnameEscape(wuid, xpath);
  10575. bool more;
  10576. do more = root->removeProp(xpath.str()); while(more);
  10577. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10578. Owned<IWorkflowEvent> event;
  10579. Owned<IPropertyTree> branch1, branch2;
  10580. for(iter->first(); iter->isValid(); iter->next())
  10581. {
  10582. event.setown(iter->query()->getScheduleEvent());
  10583. if(!event) continue;
  10584. ncnameEscape(event->queryName(), xpath.clear());
  10585. ensurePTree(root, xpath.str());
  10586. branch1.setown(root->getPropTree(xpath.str()));
  10587. ncnameEscape(event->queryText(), xpath.clear());
  10588. ensurePTree(branch1, xpath.str());
  10589. branch2.setown(branch1->getPropTree(xpath.str()));
  10590. ncnameEscape(wuid, xpath.clear());
  10591. ensurePTree(branch2, xpath.str());
  10592. }
  10593. }
  10594. void CLocalWorkUnit::deschedule()
  10595. {
  10596. if(queryEventScheduledCount() == 0) return;
  10597. if(getState() == WUStateWait)
  10598. setState(WUStateCompleted);
  10599. doDescheduleWorkkunit(p->queryName());
  10600. }
  10601. EnumMapping localFileUploadTypes[] = {
  10602. { UploadTypeFileSpray, "FileSpray" },
  10603. { UploadTypeWUResult, "WUResult" },
  10604. { UploadTypeWUResultCsv, "WUResultCsv" },
  10605. { UploadTypeWUResultXml, "WUResultXml" },
  10606. { UploadTypeSize, NULL }
  10607. };
  10608. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  10609. {
  10610. public:
  10611. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  10612. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10613. {
  10614. tree.setown(createPTree());
  10615. tree->setPropInt("@id", id);
  10616. setEnum(tree, "@type", type, localFileUploadTypes);
  10617. tree->setProp("@source", source);
  10618. tree->setProp("@destination", destination);
  10619. if (eventTag)
  10620. tree->setProp("@eventTag", eventTag);
  10621. }
  10622. IMPLEMENT_IINTERFACE;
  10623. IPropertyTree * getTree() { return tree.getLink(); }
  10624. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  10625. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  10626. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  10627. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  10628. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  10629. private:
  10630. Owned<IPropertyTree> tree;
  10631. };
  10632. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  10633. {
  10634. public:
  10635. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  10636. IMPLEMENT_IINTERFACE;
  10637. bool first() { return iter->first(); }
  10638. bool isValid() { return iter->isValid(); }
  10639. bool next() { return iter->next(); }
  10640. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  10641. private:
  10642. Owned<IPropertyTree> tree;
  10643. Owned<IPropertyTreeIterator> iter;
  10644. };
  10645. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  10646. {
  10647. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10648. CriticalBlock block(crit);
  10649. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  10650. if(s)
  10651. return new CLocalFileUploadIterator(s.getClear());
  10652. else
  10653. return NULL;
  10654. }
  10655. bool CLocalWorkUnit::requiresLocalFileUpload() const
  10656. {
  10657. SCMStringBuffer dest;
  10658. Owned<IConstWUResult> result;
  10659. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  10660. if(!iter)
  10661. return false;
  10662. for(iter->first(); iter->isValid(); iter->next())
  10663. {
  10664. Owned<IConstLocalFileUpload> upload(iter->get());
  10665. switch(upload->queryType())
  10666. {
  10667. case UploadTypeWUResult:
  10668. case UploadTypeWUResultCsv:
  10669. case UploadTypeWUResultXml:
  10670. upload->getDestination(dest);
  10671. result.setown(getResultByName(dest.str()));
  10672. if(!result)
  10673. return true;
  10674. break;
  10675. default:
  10676. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  10677. }
  10678. }
  10679. return false;
  10680. }
  10681. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10682. {
  10683. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10684. CriticalBlock block(crit);
  10685. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  10686. if(!s)
  10687. s = p->addPropTree("LocalFileUploads");
  10688. unsigned id = s->numChildren();
  10689. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  10690. s->addPropTree("LocalFileUpload", upload->getTree());
  10691. return id;
  10692. }
  10693. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  10694. {
  10695. CriticalBlock block(crit);
  10696. str.set(p->queryProp("Tracing/AbortBy"));
  10697. return str;
  10698. }
  10699. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  10700. {
  10701. CriticalBlock block(crit);
  10702. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  10703. }
  10704. #if 0
  10705. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  10706. {
  10707. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  10708. unsigned deps = 0;
  10709. Owned<IWorkflowDependencyIterator> diter;
  10710. switch(cwf->queryWfid())
  10711. {
  10712. case 1:
  10713. assertex(!cwf->isScheduled());
  10714. assertex(cwf->queryType() == WFTypeNormal);
  10715. assertex(cwf->queryState() == WFStateNull);
  10716. diter.setown(cwf->getDependencies());
  10717. for(diter->first(); diter->isValid(); diter->next())
  10718. deps++;
  10719. assertex(deps==0);
  10720. okay[0] = true;
  10721. break;
  10722. case 2:
  10723. assertex(!cwf->isScheduled());
  10724. assertex(cwf->queryType() == WFTypeRecovery);
  10725. assertex(cwf->queryState() == WFStateSkip);
  10726. okay[1] = true;
  10727. break;
  10728. case 3:
  10729. assertex(cwf->queryContingencyFor() == 4);
  10730. okay[2] = true;
  10731. break;
  10732. case 4:
  10733. assertex(cwf->isScheduled());
  10734. assertex(cwf->queryType() == WFTypeNormal);
  10735. assertex(cwf->queryState() == WFStateReqd);
  10736. assertex(cwf->querySuccess() == 0);
  10737. assertex(cwf->queryFailure() == 3);
  10738. assertex(cwf->queryRecovery() == 2);
  10739. assertex(cwf->queryRetriesAllowed() == 10);
  10740. assertex(cwf->queryRetriesRemaining() == 10);
  10741. diter.setown(cwf->getDependencies());
  10742. for(diter->first(); diter->isValid(); diter->next())
  10743. {
  10744. dep[diter->query()-1] = true;
  10745. deps++;
  10746. }
  10747. assertex(deps==2);
  10748. assertex(dep[0]);
  10749. assertex(dep[1]);
  10750. okay[3] = true;
  10751. break;
  10752. case 5:
  10753. assertex(cwf->isScheduled());
  10754. assertex(!cwf->isScheduledNow());
  10755. assertex(cwf->querySchedulePriority() == 75);
  10756. assertex(cwf->queryScheduleCount() == 5);
  10757. assertex(cwf->queryScheduleCountRemaining() == 5);
  10758. okay[4] = true;
  10759. break;
  10760. case 6:
  10761. assertex(cwf->isScheduled());
  10762. assertex(!cwf->isScheduledNow());
  10763. assertex(cwf->querySchedulePriority() == 25);
  10764. assertex(!cwf->hasScheduleCount());
  10765. okay[5] = true;
  10766. break;
  10767. default:
  10768. assertex(!"unknown wfid in test");
  10769. }
  10770. }
  10771. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  10772. {
  10773. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  10774. switch(rwf->queryWfid())
  10775. {
  10776. case 1:
  10777. case 2:
  10778. case 3:
  10779. okay[rwf->queryWfid()-1] = true;
  10780. break;
  10781. case 4:
  10782. {
  10783. unsigned tries = 0;
  10784. while(rwf->testAndDecRetries())
  10785. tries++;
  10786. assertex(tries == 10);
  10787. assertex(rwf->queryRetriesRemaining() == 0);
  10788. rwf->setState(WFStateFail);
  10789. assertex(rwf->queryState() == WFStateFail);
  10790. rwf->reset();
  10791. assertex(rwf->queryRetriesRemaining() == 10);
  10792. assertex(rwf->queryState() == WFStateReqd);
  10793. }
  10794. okay[3] = true;
  10795. break;
  10796. case 5:
  10797. {
  10798. assertex(rwf->queryScheduleCountRemaining() == 5);
  10799. unsigned count = 0;
  10800. do count++; while(rwf->decAndTestScheduleCountRemaining());
  10801. assertex(count == 5);
  10802. assertex(rwf->queryScheduleCountRemaining() == 0);
  10803. rwf->reset();
  10804. assertex(rwf->queryScheduleCountRemaining() == 5);
  10805. }
  10806. okay[4] = true;
  10807. break;
  10808. case 6:
  10809. {
  10810. assertex(!rwf->hasScheduleCount());
  10811. unsigned count;
  10812. for(count=0; count<20; count++)
  10813. assertex(rwf->decAndTestScheduleCountRemaining());
  10814. }
  10815. okay[5] = true;
  10816. break;
  10817. default:
  10818. assertex(!"unknown wfid in test");
  10819. }
  10820. }
  10821. void testWorkflow()
  10822. {
  10823. DBGLOG("workunit.cpp : testWorkflow");
  10824. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  10825. Owned<IWorkflowItem> wf;
  10826. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  10827. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  10828. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  10829. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  10830. wf->setScheduledNow();
  10831. wf->addDependency(1);
  10832. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  10833. wf->setScheduledOn("test", "foo*");
  10834. wf->setSchedulePriority(75);
  10835. wf->setScheduleCount(5);
  10836. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  10837. wf->setScheduledOn("test", "bar*");
  10838. wf->setSchedulePriority(25);
  10839. unsigned const n = 6;
  10840. bool okay[n];
  10841. bool dep[n];
  10842. unsigned i;
  10843. for(i=0; i<n; i++)
  10844. okay[i] = dep[i] = 0;
  10845. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  10846. for(citer->first(); citer->isValid(); citer->next())
  10847. testConstWorkflow(citer->query(), okay, dep);
  10848. for(i=0; i<n; i++)
  10849. {
  10850. assertex(okay[i]);
  10851. okay[i] = false;
  10852. }
  10853. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  10854. for(miter->first(); miter->isValid(); miter->next())
  10855. {
  10856. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  10857. testRuntimeWorkflow(rwf, okay);
  10858. }
  10859. for(i=0; i<n; i++)
  10860. {
  10861. assertex(okay[i]);
  10862. okay[i] = dep[i] = false;
  10863. }
  10864. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  10865. unsigned wfid;
  10866. for(wfid = 1; array->isValid(wfid); wfid++)
  10867. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  10868. for(i=0; i<n; i++)
  10869. {
  10870. assertex(okay[i]);
  10871. okay[i] = false;
  10872. }
  10873. for(wfid = 1; array->isValid(wfid); wfid++)
  10874. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  10875. for(i=0; i<n; i++)
  10876. {
  10877. assertex(okay[i]);
  10878. okay[i] = false;
  10879. }
  10880. }
  10881. #endif
  10882. //------------------------------------------------------------------------------------------
  10883. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, std::list<WUState> expectedStates)
  10884. {
  10885. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, expectedStates);
  10886. }
  10887. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, std::list<WUState> expectedStates)
  10888. {
  10889. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  10890. return waitForWorkUnitToComplete(wuid, timeout, expectedStates);
  10891. return WUStateUnknown;
  10892. }
  10893. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  10894. {
  10895. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, { WUStateWait }))
  10896. {
  10897. case WUStateCompiled:
  10898. case WUStateCompleted:
  10899. case WUStateWait:
  10900. case WUStateUploadingFiles:
  10901. return true;
  10902. default:
  10903. return false;
  10904. }
  10905. }
  10906. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  10907. {
  10908. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  10909. return waitForWorkUnitToCompile(wuid, timeout);
  10910. return false;
  10911. }
  10912. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  10913. {
  10914. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  10915. {
  10916. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  10917. SCMStringBuffer ip;
  10918. unsigned port;
  10919. try
  10920. {
  10921. port = wu->getDebugAgentListenerPort();
  10922. wu->getDebugAgentListenerIP(ip);
  10923. SocketEndpoint debugEP(ip.str(), port);
  10924. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  10925. unsigned len = (size32_t)strlen(command);
  10926. unsigned revlen = len;
  10927. _WINREV(revlen);
  10928. socket->write(&revlen, sizeof(revlen));
  10929. socket->write(command, len);
  10930. for (;;)
  10931. {
  10932. socket->read(&len, sizeof(len));
  10933. _WINREV(len);
  10934. if (len == 0)
  10935. break;
  10936. if (len & 0x80000000)
  10937. {
  10938. throwUnexpected();
  10939. }
  10940. char * mem = (char*) response.reserve(len);
  10941. socket->read(mem, len);
  10942. }
  10943. return true;
  10944. }
  10945. catch (IException *E)
  10946. {
  10947. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  10948. EXCLOG(E, msg.str());
  10949. throw;
  10950. }
  10951. }
  10952. return false;
  10953. }
  10954. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  10955. {
  10956. TypeInfoArray types;
  10957. StringAttrArray names;
  10958. r->getSchema(types, names, NULL);
  10959. if (types.ordinality()==1)
  10960. type.set(&types.item(0));
  10961. }
  10962. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  10963. {
  10964. if (!r->isResultScalar())
  10965. return false;
  10966. if (!curVal.hasChildren())
  10967. return true;
  10968. getSimpleResultType(r, type);
  10969. return type && type->isScalar();
  10970. }
  10971. void updateSuppliedXmlParams(IWorkUnit * w)
  10972. {
  10973. Owned<const IPropertyTree> params = w->getXmlParams();
  10974. if (!params)
  10975. return;
  10976. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  10977. ForEach(*elems)
  10978. {
  10979. IPropertyTree & curVal = elems->query();
  10980. const char *name = curVal.queryName();
  10981. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  10982. if (r)
  10983. {
  10984. Owned<ITypeInfo> type;
  10985. StringBuffer s;
  10986. if (isSuppliedParamScalar(r, curVal, type))
  10987. {
  10988. curVal.getProp(".", s);
  10989. r->setResultXML(s);
  10990. r->setResultStatus(ResultStatusSupplied);
  10991. }
  10992. else
  10993. {
  10994. toXML(&curVal, s);
  10995. if (!type)
  10996. getSimpleResultType(r, type);
  10997. bool isSet = (type && type->getTypeCode()==type_set);
  10998. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  10999. }
  11000. }
  11001. else
  11002. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11003. }
  11004. }
  11005. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11006. {
  11007. switch ((int)sequence)
  11008. {
  11009. case ResultSequenceStored:
  11010. return w->updateVariableByName(name);
  11011. case ResultSequencePersist:
  11012. return w->updateGlobalByName(name);
  11013. case ResultSequenceInternal:
  11014. case ResultSequenceOnce:
  11015. return w->updateTemporaryByName(name);
  11016. default:
  11017. return w->updateResultBySequence(sequence);
  11018. }
  11019. }
  11020. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11021. {
  11022. switch ((int)sequence)
  11023. {
  11024. case ResultSequenceStored:
  11025. return w->getVariableByName(name);
  11026. case ResultSequencePersist:
  11027. return w->getGlobalByName(name);
  11028. case ResultSequenceInternal:
  11029. case ResultSequenceOnce:
  11030. return w->getTemporaryByName(name);
  11031. default:
  11032. if (name && name[0])
  11033. return w->getResultByName(name);//name takes precedence over sequence
  11034. else
  11035. return w->getResultBySequence(sequence);
  11036. }
  11037. }
  11038. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11039. {
  11040. if (wuid) {
  11041. char prefchar;
  11042. unsigned year,month,day,hour,min,sec;
  11043. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11044. time.set(year, month, day, hour, min, sec, 0, true);
  11045. // time.setDate(year, month, day);
  11046. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11047. return true;
  11048. }
  11049. }
  11050. return false;
  11051. }
  11052. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11053. {
  11054. return (WUState) getEnum(state, states);
  11055. }
  11056. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11057. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11058. {
  11059. public:
  11060. CWorkflowScheduleConnection(char const * wuid)
  11061. {
  11062. basexpath.append("/WorkflowSchedule/").append(wuid);
  11063. flagxpath.append(basexpath.str()).append("/Active");
  11064. }
  11065. IMPLEMENT_IINTERFACE;
  11066. virtual void lock()
  11067. {
  11068. LOG(MCschedconn, "Locking base schedule connection");
  11069. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11070. if(!baseconn)
  11071. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11072. }
  11073. virtual void unlock()
  11074. {
  11075. LOG(MCschedconn, "Unlocking base schedule connection");
  11076. baseconn.clear();
  11077. }
  11078. virtual void setActive()
  11079. {
  11080. LOG(MCschedconn, "Setting active flag in schedule connection");
  11081. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11082. if(!flagconn)
  11083. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11084. }
  11085. virtual void resetActive()
  11086. {
  11087. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11088. flagconn.clear();
  11089. }
  11090. virtual bool queryActive()
  11091. {
  11092. return baseconn->queryRoot()->hasProp("Active");
  11093. }
  11094. virtual bool pull(IWorkflowItemArray * workflow)
  11095. {
  11096. assertex(baseconn);
  11097. Owned<IPropertyTree> root = baseconn->getRoot();
  11098. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11099. if(!eventQueue) return false;
  11100. if(!eventQueue->hasProp("Item")) return false;
  11101. {
  11102. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11103. Owned<IPropertyTree> eventItem;
  11104. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11105. Owned<IRuntimeWorkflowItem> wfItem;
  11106. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11107. {
  11108. eventItem.setown(&eventItems->get());
  11109. const char * eventName = eventItem->queryProp("@name");
  11110. const char * eventText = eventItem->queryProp("@text");
  11111. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11112. {
  11113. wfItem.setown(wfItems->get());
  11114. if(wfItem->queryState() != WFStateWait)
  11115. continue;
  11116. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11117. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11118. continue;
  11119. wfItem->setEvent(eventName, eventText);
  11120. wfItem->setState(WFStateReqd);
  11121. resetDependentsState(workflow, *wfItem);
  11122. }
  11123. }
  11124. }
  11125. bool more;
  11126. do
  11127. more = eventQueue->removeProp("Item");
  11128. while(more);
  11129. return true;
  11130. }
  11131. virtual void push(char const * name, char const * text)
  11132. {
  11133. assertex(baseconn);
  11134. Owned<IPropertyTree> root = baseconn->getRoot();
  11135. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11136. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11137. eventItem->setProp("@name", name);
  11138. eventItem->setProp("@text", text);
  11139. }
  11140. virtual void remove()
  11141. {
  11142. if (baseconn)
  11143. {
  11144. baseconn->close(true);
  11145. baseconn.clear();
  11146. }
  11147. }
  11148. private:
  11149. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11150. {
  11151. if (wfid)
  11152. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11153. }
  11154. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11155. {
  11156. switch(item.queryState())
  11157. {
  11158. case WFStateDone:
  11159. case WFStateFail:
  11160. {
  11161. item.setState(WFStateNull);
  11162. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11163. resetDependentsState(workflow, item);
  11164. break;
  11165. }
  11166. }
  11167. }
  11168. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11169. {
  11170. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11171. for(iter->first(); iter->isValid(); iter->next())
  11172. {
  11173. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11174. resetItemStateAndDependents(workflow, dep);
  11175. }
  11176. }
  11177. private:
  11178. StringBuffer basexpath;
  11179. StringBuffer flagxpath;
  11180. Owned<IRemoteConnection> baseconn;
  11181. Owned<IRemoteConnection> flagconn;
  11182. };
  11183. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11184. {
  11185. return new CWorkflowScheduleConnection(wuid);
  11186. }
  11187. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11188. {
  11189. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11190. }
  11191. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11192. {
  11193. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11194. }
  11195. 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)
  11196. {
  11197. Owned<IWUException> we = wu->createException();
  11198. we->setSeverity(severity);
  11199. we->setExceptionMessage(text);
  11200. if (source)
  11201. we->setExceptionSource(source);
  11202. if (code)
  11203. we->setExceptionCode(code);
  11204. if (filename)
  11205. we->setExceptionFileName(filename);
  11206. if (lineno)
  11207. {
  11208. we->setExceptionLineNo(lineno);
  11209. if (column)
  11210. we->setExceptionColumn(lineno);
  11211. }
  11212. if (activity)
  11213. we->setActivityId(activity);
  11214. }
  11215. const char * skipLeadingXml(const char * text)
  11216. {
  11217. if (!text)
  11218. return NULL;
  11219. //skip utf8 BOM, probably excessive
  11220. if (memcmp(text, UTF8_BOM, 3) == 0)
  11221. text += 3;
  11222. for (;;)
  11223. {
  11224. if (isspace(*text))
  11225. text++;
  11226. else if (text[0] == '<' && text[1] == '?')
  11227. {
  11228. text += 2;
  11229. for (;;)
  11230. {
  11231. if (!*text) break;
  11232. if (text[0] == '?' && text[1] == '>')
  11233. {
  11234. text += 2;
  11235. break;
  11236. }
  11237. text++;
  11238. }
  11239. }
  11240. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11241. {
  11242. text += 4;
  11243. for (;;)
  11244. {
  11245. if (!*text) break;
  11246. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11247. {
  11248. text += 3;
  11249. break;
  11250. }
  11251. text++;
  11252. }
  11253. }
  11254. else
  11255. break;
  11256. }
  11257. return text;
  11258. }
  11259. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11260. {
  11261. text = skipLeadingXml(text);
  11262. if (!text)
  11263. return false;
  11264. const char * archivePrefix = "<Archive";
  11265. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11266. }
  11267. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11268. {
  11269. text = skipLeadingXml(text);
  11270. if (!text)
  11271. return false;
  11272. const char * manifestPrefix = "<Manifest";
  11273. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11274. }
  11275. //------------------------------------------------------------------------------
  11276. // Named Alias helper function
  11277. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11278. {
  11279. StringBuffer xpath;
  11280. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11281. return queryRegistry->getPropTree(xpath);
  11282. }
  11283. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11284. {
  11285. StringBuffer xpath;
  11286. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11287. return queryRegistry->getPropTree(xpath);
  11288. }
  11289. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11290. {
  11291. StringBuffer lcId(id);
  11292. lcId.toLowerCase();
  11293. StringBuffer xpath;
  11294. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11295. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11296. ForEach(*iter)
  11297. {
  11298. queryRegistry->removeProp(xpath.str());
  11299. }
  11300. }
  11301. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11302. {
  11303. StringBuffer lcName(name);
  11304. lcName.toLowerCase();
  11305. StringBuffer xpath;
  11306. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11307. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11308. unsigned seq = 1;
  11309. ForEach(*iter)
  11310. {
  11311. IPropertyTree &item = iter->query();
  11312. const char *thisWuid = item.queryProp("@wuid");
  11313. if (strieq(wuid, thisWuid))
  11314. return &item;
  11315. unsigned thisSeq = item.getPropInt("@seq");
  11316. if (thisSeq >= seq)
  11317. seq = thisSeq + 1;
  11318. }
  11319. StringBuffer id;
  11320. id.append(lcName).append(".").append(seq);
  11321. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11322. newEntry->setProp("@name", lcName);
  11323. newEntry->setProp("@wuid", wuid);
  11324. newEntry->setProp("@dll", dll);
  11325. newEntry->setProp("@id", id);
  11326. newEntry->setPropInt("@seq", seq);
  11327. if (library)
  11328. newEntry->setPropBool("@isLibrary", true);
  11329. if (userid && *userid)
  11330. newEntry->setProp("@publishedBy", userid);
  11331. if (snapshot && *snapshot)
  11332. newEntry->setProp("@snapshot", snapshot);
  11333. return queryRegistry->addPropTree("Query", newEntry);
  11334. }
  11335. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11336. {
  11337. StringBuffer lcId(id);
  11338. lcId.toLowerCase();
  11339. clearAliases(queryRegistry, lcId);
  11340. StringBuffer xpath;
  11341. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11342. queryRegistry->removeProp(xpath);
  11343. }
  11344. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11345. {
  11346. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11347. if (!match)
  11348. return;
  11349. clearAliases(queryRegistry, match->queryProp("@id"));
  11350. queryRegistry->removeTree(match);
  11351. }
  11352. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11353. {
  11354. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11355. if (!match)
  11356. return;
  11357. clearAliases(queryRegistry, match->queryProp("@id"));
  11358. queryRegistry->removeTree(match);
  11359. }
  11360. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11361. {
  11362. clearAliases(queryRegistry, id);
  11363. }
  11364. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11365. {
  11366. StringBuffer lcName(name);
  11367. lcName.toLowerCase();
  11368. StringBuffer xpath;
  11369. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11370. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11371. if (!match)
  11372. {
  11373. match = queryRegistry->addPropTree("Alias");
  11374. match->setProp("@name", lcName);
  11375. }
  11376. match->setProp("@id", value);
  11377. }
  11378. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11379. {
  11380. if (!queryRegistry || !queryid)
  11381. return NULL;
  11382. StringBuffer xpath;
  11383. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11384. return queryRegistry->getPropTree(xpath);
  11385. }
  11386. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11387. {
  11388. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11389. return getQueryById(queryRegistry, queryid);
  11390. }
  11391. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11392. {
  11393. if (!queryRegistry || !alias)
  11394. return NULL;
  11395. StringBuffer xpath;
  11396. unsigned cnt = 0;
  11397. StringBuffer lc(alias);
  11398. const char * search = lc.toLowerCase().str();
  11399. for (;;)
  11400. {
  11401. xpath.set("Alias[@name='").append(search).append("']/@id");
  11402. const char * queryId = queryRegistry->queryProp(xpath);
  11403. if (!queryId)
  11404. break;
  11405. //Check for too many alias indirections.
  11406. if (cnt++ > 10)
  11407. return NULL;
  11408. search = lc.set(queryId).toLowerCase().str();
  11409. }
  11410. return getQueryById(queryRegistry, search);
  11411. }
  11412. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11413. {
  11414. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11415. return resolveQueryAlias(queryRegistry, alias);
  11416. }
  11417. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11418. {
  11419. StringBuffer lcId(id);
  11420. lcId.toLowerCase();
  11421. StringBuffer xpath;
  11422. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11423. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11424. if (tree)
  11425. {
  11426. if (tree->getPropBool("@suspended", false) == suspend)
  11427. return;
  11428. if (suspend)
  11429. {
  11430. tree->addPropBool("@suspended", true);
  11431. if (userid && *userid)
  11432. tree->addProp("@suspendedBy", userid);
  11433. }
  11434. else
  11435. {
  11436. tree->removeProp("@suspended");
  11437. tree->removeProp("@suspendedBy");
  11438. }
  11439. }
  11440. else
  11441. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11442. }
  11443. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11444. {
  11445. if (queryComment)
  11446. {
  11447. StringBuffer lcId(id);
  11448. lcId.toLowerCase();
  11449. StringBuffer xpath;
  11450. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11451. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11452. if (tree)
  11453. tree->setProp("@queryComment", queryComment);
  11454. else
  11455. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11456. }
  11457. }
  11458. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11459. {
  11460. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11461. if (conn)
  11462. return conn->getRoot();
  11463. else
  11464. return NULL;
  11465. }
  11466. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11467. {
  11468. if (!queryTree || !libraries)
  11469. return;
  11470. if (queryTree->hasProp("@libCount")) //already added
  11471. return;
  11472. unsigned libCount=0;
  11473. ForEach(*libraries)
  11474. {
  11475. IConstWULibrary &library = libraries->query();
  11476. SCMStringBuffer libname;
  11477. if (!library.getName(libname).length())
  11478. continue;
  11479. queryTree->addProp("Library", libname.str());
  11480. libCount++;
  11481. }
  11482. queryTree->setPropInt("@libCount", libCount);
  11483. }
  11484. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11485. {
  11486. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11487. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11488. }
  11489. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11490. {
  11491. //Only lock the branch for the target we're interested in.
  11492. StringBuffer xpath;
  11493. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11494. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11495. if (conn)
  11496. return conn->getRoot();
  11497. if (readonly)
  11498. return NULL;
  11499. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11500. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11501. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11502. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11503. if (conn)
  11504. return conn->getRoot();
  11505. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11506. if (!conn)
  11507. throwUnexpected();
  11508. IPropertyTree * root = conn->queryRoot();
  11509. root->setProp("@id",wsEclId);
  11510. conn->commit();
  11511. return LINK(root);
  11512. }
  11513. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11514. {
  11515. StringBuffer xpath;
  11516. StringBuffer lcName(name);
  11517. lcName.toLowerCase();
  11518. // see if "name" already exists
  11519. xpath.append("Package[@id='").append(name).append("']");
  11520. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11521. if (pkgTree)
  11522. {
  11523. if (overWrite)
  11524. packageRegistry->removeTree(pkgTree);
  11525. else
  11526. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11527. }
  11528. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11529. tree->setProp("@id", lcName);
  11530. return tree;
  11531. }
  11532. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11533. {
  11534. StringBuffer lcId(id);
  11535. lcId.toLowerCase();
  11536. StringBuffer xpath;
  11537. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  11538. packageRegistry->removeProp(xpath);
  11539. }
  11540. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  11541. {
  11542. //Only lock the branch for the target we're interested in.
  11543. StringBuffer xpath;
  11544. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  11545. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11546. if (conn)
  11547. return conn->getRoot();
  11548. if (readonly)
  11549. return NULL;
  11550. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  11551. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11552. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  11553. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11554. if (conn)
  11555. return conn->getRoot();
  11556. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11557. if (!conn)
  11558. throwUnexpected();
  11559. IPropertyTree* root = conn->queryRoot();
  11560. root->setProp("@id",wsEclId);
  11561. conn->commit();
  11562. return LINK(root);
  11563. }
  11564. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11565. {
  11566. StringBuffer cleanQueryName;
  11567. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11568. SCMStringBuffer dllName;
  11569. Owned<IConstWUQuery> q = workunit->getQuery();
  11570. q->getQueryDllName(dllName);
  11571. if (!dllName.length())
  11572. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  11573. StringBuffer currentTargetClusterType;
  11574. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  11575. SCMStringBuffer targetClusterType;
  11576. workunit->getDebugValue("targetclustertype", targetClusterType);
  11577. SCMStringBuffer snapshot;
  11578. workunit->getSnapshot(snapshot);
  11579. if (currentTargetClusterType.length() < 1)
  11580. {
  11581. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  11582. }
  11583. else
  11584. {
  11585. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  11586. {
  11587. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  11588. }
  11589. }
  11590. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  11591. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  11592. checkAddLibrariesToQueryEntry(newEntry, libraries);
  11593. newQueryId.append(newEntry->queryProp("@id"));
  11594. workunit->setIsQueryService(true); //will check querysets before delete
  11595. workunit->commit();
  11596. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  11597. }
  11598. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  11599. {
  11600. StringBuffer cleanQueryName;
  11601. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11602. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  11603. {
  11604. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  11605. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11606. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  11607. {
  11608. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  11609. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  11610. else
  11611. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  11612. }
  11613. }
  11614. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  11615. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11616. }
  11617. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11618. {
  11619. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11620. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  11621. }
  11622. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  11623. {
  11624. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11625. StringBuffer xpath;
  11626. xpath.appendf("Alias[@name='%s']", alias);
  11627. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  11628. return queryRegistry->removeTree(t);
  11629. }
  11630. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  11631. {
  11632. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11633. setQueryAlias(queryRegistry, alias, id);
  11634. }
  11635. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  11636. {
  11637. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11638. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  11639. }
  11640. void deleteQuerySetQuery(const char *querySetName, const char *id)
  11641. {
  11642. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11643. removeNamedQuery(queryRegistry, id);
  11644. }
  11645. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  11646. {
  11647. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11648. clearAliases(queryRegistry, id);
  11649. }
  11650. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  11651. {
  11652. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11653. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  11654. }
  11655. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  11656. {
  11657. if (!queryRegistry)
  11658. return NULL;
  11659. StringBuffer xpath;
  11660. xpath.appendf("Query[@wuid='%s']", wuid);
  11661. if (queryName && *queryName)
  11662. xpath.appendf("[@name='%s']", queryName);
  11663. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  11664. if (q)
  11665. {
  11666. id.set(q->queryProp("@id"));
  11667. }
  11668. return id.str();
  11669. }
  11670. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  11671. {
  11672. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11673. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  11674. }
  11675. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  11676. {
  11677. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  11678. ForEach(*wulibraries)
  11679. {
  11680. SCMStringBuffer libname;
  11681. IConstWULibrary &wulibrary = wulibraries->query();
  11682. wulibrary.getName(libname);
  11683. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  11684. continue;
  11685. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  11686. if (query && query->getPropBool("@isLibrary"))
  11687. {
  11688. const char *wuid = query->queryProp("@wuid");
  11689. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  11690. if (libcw)
  11691. {
  11692. names.appendUniq(libname.str());
  11693. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  11694. continue;
  11695. }
  11696. }
  11697. unresolved.appendUniq(libname.str());
  11698. }
  11699. }
  11700. bool looksLikeAWuid(const char * wuid, const char firstChar)
  11701. {
  11702. if (!wuid)
  11703. return false;
  11704. if (wuid[0] != firstChar)
  11705. return false;
  11706. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  11707. return false;
  11708. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  11709. return false;
  11710. return (wuid[9]=='-');
  11711. }
  11712. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  11713. {
  11714. IPropertyTree * module = archive;
  11715. const char * dot = strrchr(path, '.');
  11716. StringBuffer xpath;
  11717. if (dot)
  11718. {
  11719. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  11720. module = archive->queryPropTree(xpath);
  11721. path = dot+1;
  11722. }
  11723. else
  11724. module = archive->queryPropTree("Module[@key='']");
  11725. if (!module)
  11726. return NULL;
  11727. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  11728. return module->queryPropTree(xpath);
  11729. }
  11730. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  11731. {
  11732. StringBuffer fullPathName;
  11733. makeAbsolutePath(name, fullPathName);
  11734. if (isContainerized())
  11735. {
  11736. const char *dllserver_root = getenv("HPCC_DLLSERVER_PATH");
  11737. assertex(dllserver_root != nullptr);
  11738. StringBuffer destPathName(dllserver_root);
  11739. addNonEmptyPathSepChar(destPathName);
  11740. splitFilename(fullPathName.str(), nullptr, nullptr, &destPathName, &destPathName);
  11741. OwnedIFile source = createIFile(fullPathName);
  11742. OwnedIFile target = createIFile(destPathName);
  11743. if (!target->exists())
  11744. {
  11745. source->copyTo(target, 0, NULL, true);
  11746. }
  11747. query->addAssociatedFile(type, destPathName, "localhost", description, crc, minActivity, maxActivity);
  11748. // Should we delete the local files? May not matter...
  11749. }
  11750. else
  11751. {
  11752. StringBuffer hostname;
  11753. queryHostIP().getIpText(hostname);
  11754. query->addAssociatedFile(type, fullPathName, hostname, description, crc, minActivity, maxActivity);
  11755. }
  11756. }
  11757. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  11758. {
  11759. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  11760. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  11761. if(workunit)
  11762. workunit->deschedule();
  11763. else
  11764. doDescheduleWorkkunit(wuid);
  11765. }
  11766. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  11767. {
  11768. StringBuffer scopestr;
  11769. if (wfid && scope && *scope)
  11770. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11771. else
  11772. scopestr.set(scope);
  11773. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  11774. }
  11775. class WuTimingUpdater : implements ITimeReportInfo
  11776. {
  11777. public:
  11778. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  11779. : wu(_wu), scopeType(_scopeType), kind(_kind)
  11780. { }
  11781. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  11782. {
  11783. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  11784. }
  11785. protected:
  11786. IWorkUnit * wu;
  11787. StatisticScopeType scopeType;
  11788. StatisticKind kind;
  11789. };
  11790. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  11791. {
  11792. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  11793. timer->report(target);
  11794. }
  11795. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  11796. {
  11797. WuTimingUpdater target(wu, scopeType, kind);
  11798. timer->report(target);
  11799. }
  11800. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  11801. {
  11802. StringBuffer scopestr;
  11803. if (wfid && scope && *scope)
  11804. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11805. else
  11806. scopestr.set(scope);
  11807. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  11808. }
  11809. extern WORKUNIT_API cost_type calculateThorCost(unsigned __int64 ms, unsigned clusterWidth)
  11810. {
  11811. IPropertyTree *costs = queryCostsConfiguration();
  11812. if (costs)
  11813. {
  11814. cost_type thor_master_rate = money2cost_type(costs->getPropReal("thor/@master"));
  11815. cost_type thor_slave_rate = money2cost_type(costs->getPropReal("thor/@slave"));
  11816. return calcCost(thor_master_rate, ms) + calcCost(thor_slave_rate, ms) * clusterWidth;
  11817. }
  11818. return 0;
  11819. }
  11820. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  11821. {
  11822. SimpleReferenceAggregator aggregator(search, result);
  11823. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  11824. ForEach(*it)
  11825. it->playProperties(aggregator);
  11826. }
  11827. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  11828. {
  11829. public:
  11830. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  11831. virtual void beginScope(const StatsScopeId & id)
  11832. {
  11833. prevLenStack.append(scope.length());
  11834. if (scope.length())
  11835. scope.append(":");
  11836. id.getScopeText(scope);
  11837. scopeTypeStack.append(id.queryScopeType());
  11838. }
  11839. virtual void beginSubGraphScope(unsigned id)
  11840. {
  11841. StatsScopeId scopeId(SSTsubgraph, id);
  11842. beginScope(scopeId);
  11843. }
  11844. virtual void beginActivityScope(unsigned id)
  11845. {
  11846. StatsScopeId scopeId(SSTactivity, id);
  11847. beginScope(scopeId);
  11848. }
  11849. virtual void beginEdgeScope(unsigned id, unsigned oid)
  11850. {
  11851. StatsScopeId scopeId(SSTedge, id, oid);
  11852. beginScope(scopeId);
  11853. }
  11854. virtual void beginChildGraphScope(unsigned id)
  11855. {
  11856. StatsScopeId scopeId(SSTchildgraph, id);
  11857. beginScope(scopeId);
  11858. }
  11859. virtual void endScope()
  11860. {
  11861. scope.setLength(prevLenStack.popGet());
  11862. scopeTypeStack.pop();
  11863. }
  11864. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  11865. {
  11866. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11867. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  11868. }
  11869. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  11870. {
  11871. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11872. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  11873. }
  11874. virtual IStatisticCollection * getResult()
  11875. {
  11876. return NULL;
  11877. }
  11878. protected:
  11879. Linked<IWorkUnit> wu;
  11880. StringBuffer scope;
  11881. UnsignedArray prevLenStack;
  11882. UnsignedArray scopeTypeStack;
  11883. };
  11884. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  11885. {
  11886. return new GlobalStatisticGatherer(wu);
  11887. }
  11888. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  11889. {
  11890. if (!wuid || !*wuid)
  11891. return NULL;
  11892. VStringBuffer path("/GraphProgress/%s", wuid);
  11893. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11894. if (conn)
  11895. return conn->getRoot();
  11896. else
  11897. return NULL;
  11898. }
  11899. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  11900. {
  11901. ErrorSeverity wuSeverity = SeverityInformation;
  11902. ErrorSeverity severity = error->getSeverity();
  11903. switch (severity)
  11904. {
  11905. case SeverityIgnore:
  11906. return;
  11907. case SeverityInformation:
  11908. break;
  11909. case SeverityWarning:
  11910. wuSeverity = SeverityWarning;
  11911. break;
  11912. case SeverityError:
  11913. case SeverityFatal:
  11914. wuSeverity = SeverityError;
  11915. break;
  11916. }
  11917. Owned<IWUException> exception = wu->createException();
  11918. exception->setSeverity(wuSeverity);
  11919. StringBuffer msg;
  11920. exception->setExceptionCode(error->errorCode());
  11921. exception->setExceptionMessage(error->errorMessage(msg).str());
  11922. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  11923. exception->setExceptionSource(source);
  11924. exception->setExceptionFileName(error->getFilename());
  11925. exception->setExceptionLineNo(error->getLine());
  11926. exception->setExceptionColumn(error->getColumn());
  11927. if (removeTimeStamp)
  11928. exception->setTimeStamp(nullptr);
  11929. if (error->getActivity())
  11930. exception->setActivityId(error->getActivity());
  11931. if (error->queryScope())
  11932. exception->setScope(error->queryScope());
  11933. }
  11934. IError * WorkUnitErrorReceiver::mapError(IError * error)
  11935. {
  11936. return LINK(error);
  11937. }
  11938. void WorkUnitErrorReceiver::report(IError* eclError)
  11939. {
  11940. addWorkunitException(wu, eclError, removeTimeStamp);
  11941. }
  11942. size32_t WorkUnitErrorReceiver::errCount()
  11943. {
  11944. unsigned count = 0;
  11945. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11946. ForEach(*exceptions)
  11947. if (exceptions->query().getSeverity() == SeverityError)
  11948. count++;
  11949. return count;
  11950. }
  11951. size32_t WorkUnitErrorReceiver::warnCount()
  11952. {
  11953. unsigned count = 0;
  11954. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11955. ForEach(*exceptions)
  11956. if (exceptions->query().getSeverity() == SeverityWarning)
  11957. count++;
  11958. return count;
  11959. }
  11960. bool isValidPriorityValue(const char *priority)
  11961. {
  11962. if (isEmptyString(priority))
  11963. return false;
  11964. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  11965. return true;
  11966. return false;
  11967. }
  11968. bool isValidMemoryValue(const char *memoryUnit)
  11969. {
  11970. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  11971. return false;
  11972. while (isdigit(*++memoryUnit));
  11973. if (!*memoryUnit)
  11974. return true;
  11975. switch (toupper(*memoryUnit++))
  11976. {
  11977. case 'E':
  11978. case 'P':
  11979. case 'T':
  11980. case 'G':
  11981. case 'M':
  11982. case 'K':
  11983. if (!*memoryUnit || strieq("B", memoryUnit))
  11984. return true;
  11985. break;
  11986. case 'B':
  11987. if (!*memoryUnit)
  11988. return true;
  11989. break;
  11990. }
  11991. return false;
  11992. }
  11993. // used by eclagent and roxie
  11994. #define ABORT_POLL_PERIOD (5*1000)
  11995. void executeThorGraph(const char * graphName, IConstWorkUnit &workunit, const IPropertyTree &config)
  11996. {
  11997. unsigned timelimit = workunit.getDebugValueInt("thorConnectTimeout", config.getPropInt("@thorConnectTimeout", 60));
  11998. StringAttr wuid(workunit.queryWuid());
  11999. #ifdef _CONTAINERIZED
  12000. // NB: If a single agent were to want to launch >1 Thor, then the threading could be in the workflow above this call.
  12001. {
  12002. Owned<IWorkUnit> w = &workunit.lock();
  12003. w->setState(WUStateBlocked);
  12004. }
  12005. WUState state = WUStateUnknown;
  12006. if (config.hasProp("@queue"))
  12007. {
  12008. bool multiJobLinger = config.getPropBool("@multiJobLinger");
  12009. if (executeGraphOnLingeringThor(workunit, graphName, multiJobLinger ? config.queryProp("@queue") : nullptr))
  12010. PROGLOG("Existing lingering Thor handled graph: %s", graphName);
  12011. else
  12012. {
  12013. VStringBuffer queueName("%s.thor", config.queryProp("@queue"));
  12014. DBGLOG("Queueing wuid=%s, graph=%s, on queue=%s, timelimit=%u seconds", wuid.str(), graphName, queueName.str(), timelimit);
  12015. Owned<IJobQueue> queue = createJobQueue(queueName);
  12016. VStringBuffer jobName("%s/%s", wuid.get(), graphName);
  12017. IJobQueueItem *item = createJobQueueItem(jobName);
  12018. queue->enqueue(item);
  12019. }
  12020. // NB: overall max runtime if guillotine set handled by abortmonitor
  12021. unsigned runningTimeLimit = workunit.getDebugValueInt("maxRunTime", 0);
  12022. runningTimeLimit = runningTimeLimit ? runningTimeLimit : INFINITE;
  12023. std::list<WUState> expectedStates = { WUStateRunning, WUStateWait };
  12024. for (unsigned i=0; i<2; i++)
  12025. {
  12026. WUState state = waitForWorkUnitToComplete(wuid, timelimit*1000, expectedStates);
  12027. DBGLOG("Got state: %s", getWorkunitStateStr(state));
  12028. if (WUStateWait == state) // already finished
  12029. break;
  12030. else if ((INFINITE != timelimit) && (WUStateUnknown == state))
  12031. throw makeStringExceptionV(0, "Query %s failed to start within specified timelimit (%u) seconds", wuid.str(), timelimit);
  12032. else
  12033. {
  12034. auto it = std::find(expectedStates.begin(), expectedStates.end(), state);
  12035. if (it == expectedStates.end())
  12036. throw makeStringExceptionV(0, "Query %s failed, state: %s", wuid.str(), getWorkunitStateStr(state));
  12037. }
  12038. timelimit = runningTimeLimit;
  12039. expectedStates = { WUStateWait };
  12040. }
  12041. }
  12042. else
  12043. {
  12044. VStringBuffer job("%s-%s", wuid.str(), graphName);
  12045. runK8sJob("thormaster", wuid, job, queryComponentConfig().getPropBool("@deleteJobs", true), { { "graphName", graphName} });
  12046. }
  12047. /* In k8s, Thor feeds back the terminating exception via the workunit.
  12048. * (in bare-metal it is returned via a socket the agent connect to Thor with)
  12049. */
  12050. workunit.forceReload();
  12051. if (workunit.getExceptionCount())
  12052. {
  12053. Owned<IConstWUExceptionIterator> iter = &workunit.getExceptions();
  12054. ForEach(*iter)
  12055. {
  12056. IConstWUException &e = iter->query();
  12057. SCMStringBuffer str;
  12058. e.getExceptionSource(str);
  12059. if (streq("thormasterexception", str.s))
  12060. {
  12061. str.clear();
  12062. e.getExceptionMessage(str);
  12063. unsigned errCode = e.getExceptionCode();
  12064. {
  12065. /* Clear the feedback exception (consume it),
  12066. * so that any future re-submissions of this workunit (e.g. due to workflow)
  12067. * don't see it again.
  12068. */
  12069. Owned<IWorkUnit> w = &workunit.lock();
  12070. w->clearExceptions("thormasterexception");
  12071. }
  12072. throw makeStringException(errCode, str.str());
  12073. }
  12074. }
  12075. }
  12076. else
  12077. {
  12078. Owned<IWorkUnit> w = &workunit.lock();
  12079. WUState state = w->getState();
  12080. if (WUStateFailed == state)
  12081. throw makeStringException(0, "Workunit failed");
  12082. }
  12083. {
  12084. Owned<IWorkUnit> w = &workunit.lock();
  12085. w->setState(WUStateRunning);
  12086. }
  12087. #else
  12088. StringAttr owner(workunit.queryUser());
  12089. StringAttr cluster(workunit.queryClusterName());
  12090. int priority = workunit.getPriorityValue();
  12091. Owned<IConstWUClusterInfo> c = getTargetClusterInfo(cluster);
  12092. if (!c)
  12093. throw MakeStringException(0, "Invalid thor cluster %s", cluster.str());
  12094. SCMStringBuffer queueName;
  12095. c->getThorQueue(queueName);
  12096. Owned<IJobQueue> jq = createJobQueue(queueName.str());
  12097. bool resubmit;
  12098. Owned<IWorkUnitFactory> wuFactory = getWorkUnitFactory();
  12099. do // loop if pause interrupted graph and needs resubmitting on resume
  12100. {
  12101. resubmit = false; // set if job interrupted in thor
  12102. if (WUStatePaused == workunit.getState()) // check initial state - and wait if paused
  12103. {
  12104. for (;;)
  12105. {
  12106. WUAction action = wuFactory->waitForWorkUnitAction(wuid, workunit.getAction());
  12107. if (action == WUActionUnknown)
  12108. throw new WorkflowException(0, "Workunit aborting", 0, WorkflowException::ABORT, MSGAUD_user);
  12109. if (action != WUActionPause && action != WUActionPauseNow)
  12110. break;
  12111. }
  12112. }
  12113. {
  12114. Owned<IWorkUnit> w = &workunit.lock();
  12115. w->setState(WUStateBlocked);
  12116. }
  12117. class cPollThread: public Thread // MORE - why do we ned a thread here?
  12118. {
  12119. Semaphore sem;
  12120. bool stopped;
  12121. IJobQueue *jq;
  12122. IConstWorkUnit *wu;
  12123. public:
  12124. bool timedout;
  12125. CTimeMon tm;
  12126. cPollThread(IJobQueue *_jq, IConstWorkUnit *_wu, unsigned timelimit)
  12127. : tm(timelimit)
  12128. {
  12129. stopped = false;
  12130. jq = _jq;
  12131. wu = _wu;
  12132. timedout = false;
  12133. }
  12134. ~cPollThread()
  12135. {
  12136. stop();
  12137. }
  12138. int run()
  12139. {
  12140. while (!stopped) {
  12141. sem.wait(ABORT_POLL_PERIOD);
  12142. if (stopped)
  12143. break;
  12144. if (tm.timedout()) {
  12145. timedout = true;
  12146. stopped = true;
  12147. jq->cancelInitiateConversation();
  12148. }
  12149. else if (wu->aborting()) {
  12150. stopped = true;
  12151. jq->cancelInitiateConversation();
  12152. }
  12153. }
  12154. return 0;
  12155. }
  12156. void stop()
  12157. {
  12158. stopped = true;
  12159. sem.signal();
  12160. }
  12161. } pollthread(jq, &workunit, timelimit*1000);
  12162. pollthread.start();
  12163. PROGLOG("Enqueuing on %s to run wuid=%s, graph=%s, timelimit=%d seconds, priority=%d", queueName.str(), wuid.str(), graphName, timelimit, priority);
  12164. IJobQueueItem* item = createJobQueueItem(wuid.str());
  12165. item->setOwner(owner.str());
  12166. item->setPriority(priority);
  12167. Owned<IConversation> conversation = jq->initiateConversation(item);
  12168. bool got = conversation.get()!=NULL;
  12169. pollthread.stop();
  12170. pollthread.join();
  12171. if (!got)
  12172. {
  12173. if (pollthread.timedout)
  12174. throw MakeStringException(0, "Query %s failed to start within specified timelimit (%d) seconds", wuid.str(), timelimit);
  12175. throw MakeStringException(0, "Query %s cancelled (1)",wuid.str());
  12176. }
  12177. // get the thor ep from whoever picked up
  12178. SocketEndpoint thorMaster;
  12179. MemoryBuffer msg;
  12180. if (!conversation->recv(msg,1000*60))
  12181. throw MakeStringException(0, "Query %s cancelled (2)",wuid.str());
  12182. thorMaster.deserialize(msg);
  12183. msg.clear().append(graphName);
  12184. SocketEndpoint myep;
  12185. myep.setLocalHost(0);
  12186. myep.serialize(msg); // only used for tracing
  12187. if (!conversation->send(msg)) {
  12188. StringBuffer s("Failed to send query to Thor on ");
  12189. thorMaster.getUrlStr(s);
  12190. throw MakeStringExceptionDirect(-1, s.str()); // maybe retry?
  12191. }
  12192. StringBuffer eps;
  12193. PROGLOG("Thor on %s running %s",thorMaster.getUrlStr(eps).str(),wuid.str());
  12194. MemoryBuffer reply;
  12195. try
  12196. {
  12197. if (!conversation->recv(reply,INFINITE))
  12198. {
  12199. StringBuffer s("Failed to receive reply from thor ");
  12200. thorMaster.getUrlStr(s);
  12201. throw MakeStringExceptionDirect(-1, s.str());
  12202. }
  12203. }
  12204. catch (IException *e)
  12205. {
  12206. StringBuffer s("Failed to receive reply from thor ");
  12207. thorMaster.getUrlStr(s);
  12208. s.append("; (").append(e->errorCode()).append(", ");
  12209. e->errorMessage(s).append(")");
  12210. e->Release();
  12211. throw MakeStringExceptionDirect(-1, s.str());
  12212. }
  12213. unsigned replyCode;
  12214. reply.read(replyCode);
  12215. switch ((ThorReplyCodes) replyCode)
  12216. {
  12217. case DAMP_THOR_REPLY_PAUSED:
  12218. {
  12219. bool isException;
  12220. reply.read(isException);
  12221. if (isException)
  12222. {
  12223. Owned<IException> e = deserializeException(reply);
  12224. VStringBuffer str("Pausing job %s caused exception", wuid.get());
  12225. EXCLOG(e, str.str());
  12226. }
  12227. Owned<IWorkUnit> w = &workunit.lock();
  12228. w->setState(WUStatePaused); // will trigger executeThorGraph to pause next time around.
  12229. WUAction action = w->getAction();
  12230. switch (action)
  12231. {
  12232. case WUActionPause:
  12233. case WUActionPauseNow:
  12234. w->setAction(WUActionUnknown);
  12235. }
  12236. resubmit = true; // JCSMORE - all subgraph _could_ be done, thor will check though and not rerun
  12237. break;
  12238. }
  12239. case DAMP_THOR_REPLY_GOOD:
  12240. break;
  12241. case DAMP_THOR_REPLY_ERROR:
  12242. {
  12243. throw deserializeException(reply);
  12244. }
  12245. case DAMP_THOR_REPLY_ABORT:
  12246. {
  12247. Owned<IException> e = deserializeException(reply);
  12248. StringBuffer msg;
  12249. e->errorMessage(msg);
  12250. throw new WorkflowException(e->errorCode(), msg.str(), 0, WorkflowException::ABORT, MSGAUD_user);
  12251. }
  12252. default:
  12253. throwUnexpected();
  12254. }
  12255. workunit.forceReload();
  12256. }
  12257. while (resubmit); // if pause interrupted job (i.e. with pausenow action), resubmit graph
  12258. #endif
  12259. }
  12260. #ifdef _CONTAINERIZED
  12261. bool executeGraphOnLingeringThor(IConstWorkUnit &workunit, const char *graphName, const char *multiJobLingerQueueName)
  12262. {
  12263. // check if lingering thor instance is up.
  12264. // Returns true if successfully submitted graph to a lingering Thor.
  12265. /* If code was dependent on reading a workunit in parallel, the whole area of
  12266. * workunit locking and reading will need revisiting, because at the moment the
  12267. * workunit reading code does not lock at all.
  12268. *
  12269. * Either,
  12270. * 1) multiJobThorLinger is set, meaning Thor instances will wait for any job's graph.
  12271. * OR
  12272. * 2) if not set, the Thor will wait for graphs from same job only, and will be
  12273. * notified to quit by the agent, when the last graph is complete.
  12274. *
  12275. * This code is called from the client (agent) when it wants to execute a Thor graph.
  12276. * This function checks to see if there any registered lingering Thor instances available.
  12277. *
  12278. * Lingering Thor's register when they are idle either with the workunit itself in
  12279. * the case of [2], or with a Dali psuedo queue (a branch under /Status/ThorLinger),
  12280. * in the case of [1]
  12281. * If they have not been contacted within the 'lingerPeriod' they shutdown and remove
  12282. * their registered instance from the queue.
  12283. *
  12284. * The client will attempt to find a lingering Thor in either the workunit or a global
  12285. * named dali queue (depending on the configuration), it will then remove that entry,
  12286. * and attempt to post the graph to that lingering Thor. If the Thor acknowledges the
  12287. * request, this function exits with success. If it it fails, or there are no more
  12288. * lingering Thor instances, it returns with false to indicate that the graph was not
  12289. * submitted to a lingering Thor.
  12290. * The client should then queue the wuid/graph normally, which will invoke a new Thor
  12291. * instance.
  12292. */
  12293. try
  12294. {
  12295. if (multiJobLingerQueueName && graphName)
  12296. {
  12297. // check a Dali queue for idle spare Thor's
  12298. DBGLOG("Checking multi job lingering queue: %s", multiJobLingerQueueName);
  12299. VStringBuffer xpath("/Status/ThorLinger/%s", multiJobLingerQueueName);
  12300. while (true)
  12301. {
  12302. Owned<IRemoteConnection> conn = querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE, 5*60*1000);
  12303. if (!conn)
  12304. break;
  12305. IPropertyTree *root = conn->queryRoot();
  12306. if (0 == root->numChildren())
  12307. break;
  12308. IPropertyTree *entry = root->queryPropTree("Thor*[1]");
  12309. const char *entryName = entry->queryName();
  12310. // get available instance and remove it
  12311. VStringBuffer entryXPath("%s/%s", xpath.str(), entryName);
  12312. Owned<IRemoteConnection> lingerInstanceConn = querySDS().connect(entryXPath, myProcessSession(), RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, 5*1000);
  12313. if (lingerInstanceConn)
  12314. {
  12315. StringBuffer instanceName;
  12316. lingerInstanceConn->queryRoot()->getProp(nullptr, instanceName);
  12317. lingerInstanceConn->close(true);
  12318. lingerInstanceConn.clear();
  12319. conn.clear();
  12320. Owned<INode> masterNode = createINode(instanceName);
  12321. CMessageBuffer msg;
  12322. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName);
  12323. msg.append(jobStr);
  12324. bool success = queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000);
  12325. DBGLOG("Found lingering Thor: %s, submitted: %s, success: %s", instanceName.str(), jobStr.str(), boolToStr(success));
  12326. if (success)
  12327. {
  12328. bool ok;
  12329. msg.read(ok);
  12330. return true;
  12331. }
  12332. }
  12333. }
  12334. }
  12335. else
  12336. {
  12337. /* NB: forcing a reload here to ensure Debug values are recent.
  12338. * Could be improved by refreshing only the specific area of interest (i.e. Debug/ in this case).
  12339. * The area of persisting a non-locked connection to workunits should be resivisted..
  12340. */
  12341. workunit.forceReload();
  12342. Owned<IStringIterator> iter = &workunit.getDebugValues("thorinstance_*");
  12343. ForEach(*iter)
  12344. {
  12345. /* NB: Thor's set their running endpoint into Debug values of workunit
  12346. * Check to see if workunit has any Thor's available lingering instances.
  12347. */
  12348. SCMStringBuffer thorInstance;
  12349. iter->str(thorInstance);
  12350. SCMStringBuffer thorInstanceValue;
  12351. if (workunit.getDebugValueBool(thorInstance.s, false))
  12352. {
  12353. {
  12354. Owned<IWorkUnit> w = &workunit.lock();
  12355. w->setDebugValue(thorInstance.s, "0", true);
  12356. }
  12357. /* NB: there's a window where Thor could shutdown here.
  12358. * In that case, the sendRecv will fail and it will fall through to queueing.
  12359. */
  12360. const char *instanceName = strchr(thorInstance.str(), '_') + 1;
  12361. Owned<INode> masterNode = createINode(instanceName);
  12362. CMessageBuffer msg;
  12363. VStringBuffer jobStr("%s/%s", workunit.queryWuid(), graphName?graphName:"");
  12364. msg.append(jobStr);
  12365. if (queryWorldCommunicator().sendRecv(msg, masterNode, MPTAG_THOR, 10000))
  12366. {
  12367. bool ok;
  12368. msg.read(ok);
  12369. if (graphName) // if graphName==nullptr, then continue around to look at others
  12370. {
  12371. if (ok)
  12372. return true;
  12373. }
  12374. }
  12375. }
  12376. }
  12377. }
  12378. }
  12379. catch (IException *e)
  12380. {
  12381. EXCLOG(e, "executeGraphOnLingeringThor");
  12382. e->Release();
  12383. }
  12384. return false;
  12385. }
  12386. static void setResources(StringBuffer &jobYaml, const IConstWorkUnit *workunit, const char *process)
  12387. {
  12388. StringBuffer s;
  12389. unsigned memRequest = workunit->getDebugValueInt(s.clear().appendf("%s-memRequest", process), 0);
  12390. unsigned memLimit = workunit->getDebugValueInt(s.clear().appendf("%s-memLimit", process), 0);
  12391. if (memLimit && memLimit < memRequest)
  12392. memLimit = memRequest;
  12393. if (memRequest)
  12394. jobYaml.replaceString("#request-memory", s.clear().appendf("memory: \"%uMi\"", memRequest));
  12395. if (memLimit)
  12396. jobYaml.replaceString("#limit-memory", s.clear().appendf("memory: \"%uMi\"", memLimit));
  12397. unsigned cpuRequest = workunit->getDebugValueInt(s.clear().appendf("%s-cpuRequest", process), 0);
  12398. unsigned cpuLimit = workunit->getDebugValueInt(s.clear().appendf("%s-cpuLimit", process), 0);
  12399. if (cpuLimit && cpuLimit < cpuRequest)
  12400. cpuLimit = cpuRequest;
  12401. if (cpuRequest)
  12402. jobYaml.replaceString("#request-cpu", s.clear().appendf("cpu: \"%um\"", cpuRequest));
  12403. if (cpuLimit)
  12404. jobYaml.replaceString("#limit-cpu", s.clear().appendf("cpu: \"%um\"", cpuLimit));
  12405. }
  12406. void deleteK8sJob(const char *componentName, const char *job)
  12407. {
  12408. VStringBuffer jobname("%s-%s", componentName, job);
  12409. jobname.toLowerCase();
  12410. VStringBuffer deleteJob("kubectl delete job/%s", jobname.str());
  12411. StringBuffer output, error;
  12412. bool ret = runExternalCommand(output, error, deleteJob.str(), nullptr);
  12413. DBGLOG("kubectl delete output: %s", output.str());
  12414. if (error.length())
  12415. DBGLOG("kubectl delete error: %s", error.str());
  12416. if (ret)
  12417. throw makeStringException(0, "Failed to run kubectl delete");
  12418. }
  12419. void waitK8sJob(const char *componentName, const char *job, const char *condition)
  12420. {
  12421. VStringBuffer jobname("%s-%s", componentName, job);
  12422. jobname.toLowerCase();
  12423. if (isEmptyString(condition))
  12424. condition = "condition=complete";
  12425. // MORE - blocks indefinitely here if you request too many resources
  12426. VStringBuffer waitJob("kubectl wait --for=%s --timeout=10h job/%s", condition, jobname.str()); // MORE - make timeout configurable
  12427. StringBuffer output, error;
  12428. bool ret = runExternalCommand(output, error, waitJob.str(), nullptr);
  12429. DBGLOG("kubectl wait output: %s", output.str());
  12430. if (error.length())
  12431. DBGLOG("kubectl wait error: %s", error.str());
  12432. if (ret)
  12433. throw makeStringException(0, "Failed to run kubectl wait");
  12434. }
  12435. void launchK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams)
  12436. {
  12437. VStringBuffer jobname("%s-%s", componentName, job);
  12438. jobname.toLowerCase();
  12439. VStringBuffer args("\"--workunit=%s\"", wuid);
  12440. for (const auto &p: extraParams)
  12441. args.append(',').newline().append("\"--").append(p.first.c_str()).append('=').append(p.second.c_str()).append("\"");
  12442. VStringBuffer jobSpecFilename("/etc/config/%s-jobspec.yaml", componentName);
  12443. StringBuffer jobYaml;
  12444. jobYaml.loadFile(jobSpecFilename, false);
  12445. jobYaml.replaceString("%jobname", jobname.str());
  12446. jobYaml.replaceString("%args", args.str());
  12447. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12448. if (factory)
  12449. {
  12450. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(wuid);
  12451. if (workunit)
  12452. setResources(jobYaml, workunit, componentName);
  12453. }
  12454. StringBuffer output, error;
  12455. unsigned ret = runExternalCommand(output, error, "kubectl replace --force -f -", jobYaml.str());
  12456. DBGLOG("kubectl output: %s", output.str());
  12457. if (error.length())
  12458. DBGLOG("kubectl error: %s", error.str());
  12459. if (ret)
  12460. {
  12461. DBGLOG("Using job yaml %s", jobYaml.str());
  12462. throw makeStringException(0, "Failed to start kubectl job");
  12463. }
  12464. }
  12465. void runK8sJob(const char *componentName, const char *wuid, const char *job, bool del, const std::list<std::pair<std::string, std::string>> &extraParams)
  12466. {
  12467. launchK8sJob(componentName, wuid, job, extraParams);
  12468. waitK8sJob(componentName, job);
  12469. if (del)
  12470. deleteK8sJob(componentName, job);
  12471. }
  12472. #endif