workunit.cpp 445 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777
  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 "jlib.hpp"
  14. #include "workunit.hpp"
  15. #include "jprop.hpp"
  16. #include "jmisc.hpp"
  17. #include "jexcept.hpp"
  18. #include "jiter.ipp"
  19. #include "jptree.hpp"
  20. #include "jtime.ipp"
  21. #include "jencrypt.hpp"
  22. #include "junicode.hpp"
  23. #include "jlzw.hpp"
  24. #include "jregexp.hpp"
  25. #include "eclrtl.hpp"
  26. #include "deftype.hpp"
  27. #include <time.h>
  28. #include "mpbase.hpp"
  29. #include "daclient.hpp"
  30. #include "dadfs.hpp"
  31. #include "dafdesc.hpp"
  32. #include "dasds.hpp"
  33. #include "danqs.hpp"
  34. #include "dautils.hpp"
  35. #include "dllserver.hpp"
  36. #include "thorplugin.hpp"
  37. #include "thorhelper.hpp"
  38. #include "workflow.hpp"
  39. #include "nbcd.hpp"
  40. #include "seclib.hpp"
  41. #include "wuerror.hpp"
  42. #include "wujobq.hpp"
  43. #include "environment.hpp"
  44. #include "workunit.ipp"
  45. #include "digisign.hpp"
  46. using namespace cryptohelper;
  47. static int workUnitTraceLevel = 1;
  48. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  49. {
  50. // MORE - can fold in the date
  51. return wuRoot.append("/WorkUnits/").append(wuid);
  52. }
  53. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  54. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  55. {
  56. #ifdef _WIN32
  57. suffix.append("W");
  58. #else
  59. suffix.append("L");
  60. #endif
  61. #ifdef __64BIT__
  62. suffix.append("64");
  63. #else
  64. suffix.append("32");
  65. #endif
  66. return suffix;
  67. }
  68. typedef MapStringTo<bool> UniqueScopes;
  69. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  70. {
  71. StringBuffer err;
  72. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  73. if (wuid)
  74. err.append(" workunit:").append(wuid);
  75. if (wuscope)
  76. err.append(" scope:").append(wuscope);
  77. //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
  78. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  79. if (log)
  80. LOG(MCuserError, "%s", err.str());
  81. if (excpt)
  82. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  83. }
  84. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  85. {
  86. if (!secmgr || !secuser)
  87. return true;
  88. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  89. if (!ret && (log || excpt))
  90. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  91. return ret;
  92. }
  93. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  94. {
  95. if (!scopes)
  96. return true;
  97. bool ret=true;
  98. if (wuscope)
  99. {
  100. Owned<ISecResource> res=scopes->getResource(wuscope);
  101. if (!res || res->getAccessFlags()<required)
  102. ret=false;
  103. }
  104. else
  105. {
  106. for (int seq=0; ret && seq<scopes->count(); seq++)
  107. {
  108. ISecResource *res=scopes->queryResource(seq);
  109. if (res && res->getAccessFlags()<required)
  110. return false;
  111. }
  112. }
  113. if (!ret && (log || excpt))
  114. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  115. return ret;
  116. }
  117. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  118. {
  119. if (!secmgr || !secuser)
  120. return true;
  121. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  122. if (!ret && (log || excpt))
  123. {
  124. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  125. }
  126. return ret;
  127. }
  128. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  129. {
  130. if (!secmgr || !secuser)
  131. return true;
  132. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  133. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  134. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw->queryWuScope())>=required;
  135. if (!ret && (log || excpt))
  136. {
  137. wuAccessError(secuser->getName(), action, cw->queryWuScope(), cw->queryWuid(), excpt, log);
  138. }
  139. return ret;
  140. }
  141. void doDescheduleWorkkunit(char const * wuid)
  142. {
  143. StringBuffer xpath;
  144. xpath.append("*/*/*/");
  145. ncnameEscape(wuid, xpath);
  146. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  147. if(!conn) return;
  148. Owned<IPropertyTree> root = conn->getRoot();
  149. bool more;
  150. do more = root->removeProp(xpath.str()); while(more);
  151. }
  152. //======================================================
  153. /*
  154. * Graph progress support
  155. */
  156. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, unsigned wfid, const char * _rootScope, unsigned _id)
  157. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  158. {
  159. StatsScopeId graphScopeId;
  160. verifyex(graphScopeId.setScopeText(_rootScope));
  161. StatsScopeId rootScopeId(SSTworkflow,wfid);
  162. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  163. collector->beginScope(graphScopeId);
  164. }
  165. void CWuGraphStats::beforeDispose()
  166. {
  167. Owned<IStatisticCollection> stats = collector->getResult();
  168. MemoryBuffer compressed;
  169. {
  170. MemoryBuffer serialized;
  171. serializeStatisticCollection(serialized, stats);
  172. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  173. }
  174. unsigned minActivity = 0;
  175. unsigned maxActivity = 0;
  176. stats->getMinMaxActivity(minActivity, maxActivity);
  177. StringBuffer tag;
  178. tag.append("sg").append(id);
  179. //Replace the particular subgraph statistics added by this creator
  180. StringBuffer qualified(tag);
  181. qualified.append("[@creator='").append(creator).append("']");
  182. progress->removeProp(qualified);
  183. IPropertyTree * subgraph = progress->addPropTree(tag);
  184. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  185. subgraph->setProp("@creator", creator);
  186. subgraph->setPropInt("@minActivity", minActivity);
  187. subgraph->setPropInt("@maxActivity", maxActivity);
  188. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  189. if (!progress->getPropBool("@stats", false))
  190. progress->setPropBool("@stats", true);
  191. }
  192. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  193. {
  194. return *collector;
  195. }
  196. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  197. {
  198. public:
  199. IMPLEMENT_IINTERFACE;
  200. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  201. {
  202. if (!progress)
  203. progress.setown(createPTree());
  204. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  205. }
  206. virtual IPropertyTree * getProgressTree()
  207. {
  208. if (progress->getPropBool("@stats"))
  209. return createProcessTreeFromStats(); // Should we cache that?
  210. return LINK(progress);
  211. }
  212. virtual unsigned queryFormatVersion()
  213. {
  214. return formatVersion;
  215. }
  216. protected:
  217. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  218. {
  219. formatVersion = PROGRESS_FORMAT_V;
  220. }
  221. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  222. {
  223. StringBuffer formattedValue;
  224. unsigned numStats = collection.getNumStatistics();
  225. for (unsigned i=0; i < numStats; i++)
  226. {
  227. StatisticKind kind;
  228. unsigned __int64 value;
  229. collection.getStatistic(kind, value, i);
  230. formatStatistic(formattedValue.clear(), value, kind);
  231. target->setProp(queryTreeTag(kind), formattedValue);
  232. }
  233. }
  234. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  235. {
  236. expandStats(target, *collection);
  237. StringBuffer scopeName;
  238. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL, false);
  239. ForEach(*activityIter)
  240. {
  241. IStatisticCollection & cur = activityIter->query();
  242. cur.getScope(scopeName.clear());
  243. const char * id = scopeName.str();
  244. const char * tag;
  245. IPropertyTree * curTarget = target;
  246. switch (cur.queryScopeType())
  247. {
  248. case SSTedge:
  249. tag = "edge";
  250. id += strlen(EdgeScopePrefix);
  251. break;
  252. case SSTactivity:
  253. tag = "node";
  254. id += strlen(ActivityScopePrefix);
  255. break;
  256. case SSTsubgraph:
  257. //All subgraphs are added a root elements in the progress tree
  258. curTarget = rootTarget;
  259. tag = "node";
  260. id += strlen(SubGraphScopePrefix);
  261. break;
  262. case SSTchildgraph:
  263. case SSTworkflow:
  264. case SSTgraph:
  265. // SSTworkflow and SSTgraph may be safely ignored. They are not required to produce the statistics.
  266. continue;
  267. case SSTfunction:
  268. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  269. continue;
  270. default:
  271. throwUnexpected();
  272. }
  273. IPropertyTree * next = curTarget->addPropTree(tag);
  274. next->setProp("@id", id);
  275. expandProcessTreeFromStats(rootTarget, next, &cur);
  276. }
  277. }
  278. IPropertyTree * createProcessTreeFromStats()
  279. {
  280. MemoryBuffer compressed;
  281. MemoryBuffer serialized;
  282. Owned<IPropertyTree> progressTree = createPTree();
  283. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  284. ForEach(*iter)
  285. {
  286. IPropertyTree & curSubGraph = iter->query();
  287. curSubGraph.getPropBin("Stats", compressed.clear());
  288. //Protect against updates that delete the stats while we are iterating
  289. if (compressed.length())
  290. {
  291. decompressToBuffer(serialized.clear(), compressed);
  292. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  293. expandProcessTreeFromStats(progressTree, progressTree, collection);
  294. }
  295. }
  296. return progressTree.getClear();
  297. }
  298. protected:
  299. Linked<IPropertyTree> progress;
  300. StringAttr wuid, graphName;
  301. unsigned formatVersion;
  302. };
  303. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  304. {
  305. return new CConstGraphProgress(_wuid, _graphName, _progress);
  306. }
  307. //--------------------------------------------------------------------------------------------------------------------
  308. /*
  309. * Create a user friendly description a scope/stats combination. Only currently used for elapsed time for root subgraphs
  310. */
  311. static void createDefaultDescription(StringBuffer & description, StatisticKind kind, StatisticScopeType scopeType, const char * scope)
  312. {
  313. switch (kind)
  314. {
  315. case StTimeElapsed:
  316. {
  317. if (scopeType != SSTsubgraph)
  318. break;
  319. //Create a default description for a root subgraph
  320. const char * colon = strchr(scope, ':');
  321. if (!colon)
  322. break;
  323. const char * subgraph = colon+1;
  324. //Check for nested subgraph
  325. if (strchr(subgraph, ':'))
  326. break;
  327. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  328. StringAttr graphname;
  329. graphname.set(scope, colon - scope);
  330. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  331. formatGraphTimerLabel(description, graphname, 0, subId);
  332. return;
  333. }
  334. }
  335. describeScope(description, scope);
  336. }
  337. /* Represents a single statistic */
  338. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  339. {
  340. public:
  341. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  342. {
  343. if (!description && createDefault)
  344. {
  345. StringBuffer desc;
  346. createDefaultDescription(desc, kind, scopeType, scope);
  347. str.set(desc);
  348. return str;
  349. }
  350. str.set(description);
  351. return str;
  352. }
  353. virtual IStringVal & getCreator(IStringVal & str) const
  354. {
  355. str.set(creator);
  356. return str;
  357. }
  358. virtual const char * queryScope() const
  359. {
  360. return scope;
  361. }
  362. virtual IStringVal & getFormattedValue(IStringVal & str) const
  363. {
  364. StringBuffer formatted;
  365. formatStatistic(formatted, value, measure);
  366. str.set(formatted);
  367. return str;
  368. }
  369. virtual StatisticMeasure getMeasure() const
  370. {
  371. return measure;
  372. }
  373. virtual StatisticKind getKind() const
  374. {
  375. return kind;
  376. }
  377. virtual StatisticCreatorType getCreatorType() const
  378. {
  379. return creatorType;
  380. }
  381. virtual StatisticScopeType getScopeType() const
  382. {
  383. return scopeType;
  384. }
  385. virtual unsigned __int64 getValue() const
  386. {
  387. return value;
  388. }
  389. virtual unsigned __int64 getCount() const
  390. {
  391. return count;
  392. }
  393. virtual unsigned __int64 getMax() const
  394. {
  395. return max;
  396. }
  397. virtual unsigned __int64 getTimestamp() const
  398. {
  399. return timeStamp;
  400. }
  401. public:
  402. StringBuffer creator;
  403. StringBuffer description;
  404. StringBuffer scope;
  405. StatisticMeasure measure;
  406. StatisticKind kind;
  407. StatisticCreatorType creatorType;
  408. StatisticScopeType scopeType;
  409. unsigned __int64 value;
  410. unsigned __int64 count;
  411. unsigned __int64 max;
  412. unsigned __int64 timeStamp;
  413. };
  414. //---------------------------------------------------------------------------------------------------------------------
  415. /*
  416. * The following compare functions are used to ensure that comparison are consistent with
  417. * compareScopeName() in jstats. This ensures that the scope iterators from different sources
  418. * are processed in a consistent order
  419. */
  420. static int compareGraphNode(IInterface * const *ll, IInterface * const *rr)
  421. {
  422. IPropertyTree *l = (IPropertyTree *) *ll;
  423. IPropertyTree *r = (IPropertyTree *) *rr;
  424. unsigned lwfid = l->getPropInt("@wfid");
  425. unsigned rwfid = r->getPropInt("@wfid");
  426. if (lwfid != rwfid)
  427. return lwfid > rwfid ? +1 : -1;
  428. const char * lname = l->queryName();
  429. const char * rname = r->queryName();
  430. return compareScopeName(lname, rname);
  431. }
  432. static int compareSubGraphStatsNode(IInterface * const *ll, IInterface * const *rr)
  433. {
  434. IPropertyTree *l = (IPropertyTree *) *ll;
  435. IPropertyTree *r = (IPropertyTree *) *rr;
  436. return compareScopeName(l->queryName(), r->queryName());
  437. }
  438. static int compareSubGraphNode(IInterface * const *ll, IInterface * const *rr)
  439. {
  440. IPropertyTree *l = (IPropertyTree *) *ll;
  441. IPropertyTree *r = (IPropertyTree *) *rr;
  442. return l->getPropInt("@id") - r->getPropInt("@id");
  443. }
  444. static int compareActivityNode(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 compareEdgeNode(IInterface * const *ll, IInterface * const *rr)
  451. {
  452. IPropertyTree *l = (IPropertyTree *) *ll;
  453. IPropertyTree *r = (IPropertyTree *) *rr;
  454. //MORE: Edge needs more work
  455. const char * leftId = l->queryProp("@id");
  456. const char * rightId = r->queryProp("@id");
  457. unsigned leftAc = atoi(leftId);
  458. unsigned rightAc = atoi(rightId);
  459. if (leftAc != rightAc)
  460. return (int)(leftAc - rightAc);
  461. const char * leftSep = strchr(leftId, '_');
  462. const char * rightSep = strchr(rightId, '_');
  463. assertex(leftSep && rightSep);
  464. return atoi(leftSep+1) - atoi(rightSep+1);
  465. }
  466. //---------------------------------------------------------------------------------------------------------------------
  467. /*
  468. * A class for implementing a scope iterator that walks through graph progress information
  469. */
  470. class CConstGraphProgressScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  471. {
  472. public:
  473. CConstGraphProgressScopeIterator(const char * wuid, const ScopeFilter & _filter, __uint64 _minVersion) : filter(_filter), minVersion(_minVersion)
  474. {
  475. //Examine the filter, and determine if we only need to look at a single graph/subgraph
  476. StringAttr singleGraph;
  477. const StringArray & scopesToMatch = filter.queryScopes();
  478. if (scopesToMatch)
  479. {
  480. bool seenGraph = false;
  481. bool seenSubGraph = false;
  482. ForEachItemIn(iScope, scopesToMatch)
  483. {
  484. StringArray ids;
  485. ids.appendList(scopesToMatch.item(iScope), ":");
  486. ForEachItemIn(i, ids)
  487. {
  488. const char * curId = ids.item(i);
  489. StatsScopeId id(curId);
  490. switch (id.queryScopeType())
  491. {
  492. case SSTgraph:
  493. if (seenGraph)
  494. {
  495. if (singleGraph && !streq(singleGraph, curId))
  496. singleGraph.clear();
  497. }
  498. else
  499. {
  500. if (!id.isWildcard())
  501. singleGraph.set(curId);
  502. seenGraph = true;
  503. }
  504. break;
  505. case SSTsubgraph:
  506. if (seenSubGraph)
  507. {
  508. if (singleSubGraph && !streq(singleSubGraph, curId))
  509. singleSubGraph.clear();
  510. }
  511. else
  512. {
  513. if (!id.isWildcard())
  514. singleSubGraph.set(curId);
  515. seenSubGraph = true;
  516. }
  517. break;
  518. }
  519. }
  520. }
  521. }
  522. rootPath.append("/GraphProgress/").append(wuid).append('/');
  523. if (singleGraph)
  524. rootPath.append(singleGraph).append("/");
  525. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  526. if (daliClientActive())
  527. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  528. if (conn && !singleGraph)
  529. {
  530. graphIter.setown(conn->queryRoot()->getElements("*"));
  531. graphIter.setown(createSortedIterator(*graphIter, compareGraphNode));
  532. }
  533. valid = false;
  534. }
  535. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IConstWUScopeIterator>)
  536. virtual bool first()
  537. {
  538. valid = false;
  539. if (!conn)
  540. return false;
  541. if (graphIter && !graphIter->first())
  542. return false;
  543. if (!firstSubGraph())
  544. {
  545. if (!nextGraph())
  546. return false;
  547. }
  548. valid = true;
  549. return true;
  550. }
  551. virtual bool next()
  552. {
  553. if (!nextChildScope())
  554. {
  555. if (!nextSubGraph())
  556. {
  557. if (!nextGraph())
  558. {
  559. valid = false;
  560. return false;
  561. }
  562. }
  563. }
  564. return true;
  565. }
  566. virtual bool nextSibling() override
  567. {
  568. if (collections.ordinality() == 0)
  569. return false;
  570. assertex(childIterators.ordinality() < collections.ordinality());
  571. collections.pop();
  572. //next will call childIterator.next() - walking the next sibling
  573. return next();
  574. }
  575. virtual bool nextParent() override
  576. {
  577. if (collections.ordinality() == 0)
  578. return false;
  579. assertex(childIterators.ordinality() < collections.ordinality());
  580. collections.pop();
  581. if (collections.ordinality() == 0)
  582. return false;
  583. //Finish with this node - so next will move onto the sibling of the parent node.
  584. finishCollection();
  585. return next();
  586. }
  587. virtual bool isValid()
  588. {
  589. return valid;
  590. }
  591. protected:
  592. bool firstSubGraph()
  593. {
  594. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  595. const char * xpath = "sg*";
  596. StringBuffer childXpath;
  597. if (singleSubGraph)
  598. {
  599. childXpath.append(singleSubGraph);
  600. xpath = childXpath.str();
  601. }
  602. subgraphIter.setown(graphNode.getElements(xpath));
  603. if (subgraphIter)
  604. {
  605. if (!singleSubGraph)
  606. subgraphIter.setown(createSortedIterator(*subgraphIter, compareSubGraphStatsNode));
  607. }
  608. else
  609. subgraphIter.setown(graphNode.getElements("sg0"));
  610. if (!subgraphIter->first())
  611. return false;
  612. if (firstStat())
  613. return true;
  614. return nextSubGraph();
  615. }
  616. bool nextSubGraph()
  617. {
  618. for (;;)
  619. {
  620. if (!subgraphIter->next())
  621. return false;
  622. if (firstStat())
  623. return true;
  624. }
  625. }
  626. bool nextGraph()
  627. {
  628. if (!graphIter)
  629. return false;
  630. for (;;)
  631. {
  632. if (!graphIter->next())
  633. return false;
  634. if (firstSubGraph())
  635. return true;
  636. }
  637. }
  638. bool firstStat()
  639. {
  640. IPropertyTree & curSubGraph = subgraphIter->query();
  641. if (!checkSubGraph())
  642. return false;
  643. curSubGraph.getPropBin("Stats", compressed.clear());
  644. //Don't crash on old format progress...
  645. if (compressed.length() == 0)
  646. return false;
  647. decompressToBuffer(serialized.clear(), compressed);
  648. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  649. statsIterator.timeStamp = collection->queryWhenCreated();
  650. if (!beginCollection(*collection))
  651. return false;
  652. // When workflow is root element, it is just a container. Ignore the workflow element here
  653. // as WorkUnitStatisticsScopeIterator will produce workflow scope - don't want duplicates.
  654. // (Note: workflow element never contains stats).
  655. if (collections.tos().queryScopeType() == SSTworkflow)
  656. {
  657. if (!next())
  658. return false;
  659. }
  660. //The root element of a collection is a graph - but it is only there to nest the subgraphs in.
  661. //Do not iterate it as a separate element - unless it has some stats.
  662. IStatisticCollection & curCollection = collections.tos();
  663. if ((curCollection.queryScopeType() != SSTgraph) || (curCollection.getNumStatistics() != 0))
  664. return true;
  665. return next();
  666. }
  667. bool beginCollection(IStatisticCollection & collection)
  668. {
  669. collections.append(OLINK(collection));
  670. curScopeType = collection.queryScopeType();
  671. collection.getFullScope(curScopeName.clear());
  672. ScopeCompare result = filter.compare(curScopeName);
  673. if (result & SCequal)
  674. return true;
  675. //If this scope cannot be the parent of a match then discard it.
  676. if (!(result & SCparent))
  677. collections.pop();
  678. //walk the next element
  679. return nextChildScope();
  680. }
  681. bool nextChildScope()
  682. {
  683. for (;;)
  684. {
  685. if (collections.ordinality() == 0)
  686. return false;
  687. IStatisticCollection * curCollection = &collections.tos();
  688. if (childIterators.ordinality() < collections.ordinality())
  689. {
  690. ScopeCompare result = filter.compare(curScopeName);
  691. //Do not walk children scopes if it is unrelated
  692. if (result & SCparent)
  693. {
  694. //Start iterating the children for the current collection
  695. childIterators.append(curCollection->getScopes(NULL, true));
  696. if (!childIterators.tos().first())
  697. {
  698. finishCollection();
  699. continue;
  700. }
  701. }
  702. else
  703. {
  704. //Don't walk the child scopes
  705. collections.pop();
  706. continue;
  707. }
  708. }
  709. else if (!childIterators.tos().next())
  710. {
  711. finishCollection();
  712. continue;
  713. }
  714. if (beginCollection(childIterators.tos().query()))
  715. return true;
  716. }
  717. }
  718. void finishCollection()
  719. {
  720. collections.pop();
  721. childIterators.pop();
  722. }
  723. bool checkSubGraph()
  724. {
  725. IPropertyTree & curSubGraph = subgraphIter->query();
  726. StatisticCreatorType creatorType = queryCreatorType(curSubGraph.queryProp("@c"), SCTnone);
  727. const char * creator = curSubGraph.queryProp("@creator");
  728. //MORE: Check minVersion and allow early filtering
  729. //MORE: Potentially filter by creator type??
  730. // if (!filter->matches(creatorType, creator, SSTall, NULL, SMeasureAll, StKindAll, AnyStatisticValue))
  731. // return false;
  732. statsIterator.creatorType = creatorType;
  733. statsIterator.creator.set(creator);
  734. return true;
  735. }
  736. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  737. {
  738. if ((whichProperties & PTstatistics))
  739. {
  740. /*
  741. MORE: Code from the statsIterator class should be inlined here - code will be much simpler
  742. but it currently needs an implementation of the IConstWUStatistic 3rd parameter
  743. IStatisticCollection & collection = collections.tos();
  744. ForEachItemIn(i, collection)
  745. {
  746. StatisticKind kind;
  747. unsigned __int64 value;
  748. collection->getStatistic(kind, value, i);
  749. visitor.noteStatistic(kind, value, *this);
  750. }
  751. */
  752. statsIterator.reset(curScopeName, curScopeType, collections.tos());
  753. ForEach(statsIterator)
  754. statsIterator.play(visitor);
  755. }
  756. }
  757. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  758. {
  759. return collections.tos().getStatistic(kind, value);
  760. }
  761. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  762. {
  763. return nullptr;
  764. }
  765. virtual const char * queryHint(const char * kind) const override
  766. {
  767. return nullptr;
  768. }
  769. virtual const char * queryScope() const override
  770. {
  771. return curScopeName;
  772. }
  773. virtual StatisticScopeType getScopeType() const override
  774. {
  775. return curScopeType;
  776. }
  777. private:
  778. class ScopeStatisticsIterator : public CInterfaceOf<IConstWUStatistic>
  779. {
  780. friend class CConstGraphProgressScopeIterator; // cleaner if this was removed + setScope() functions added.
  781. public:
  782. void reset(const char * _scopeName, StatisticScopeType _scopeType, IStatisticCollection & _collection)
  783. {
  784. scope.set(_scopeName);
  785. scopeType = _scopeType;
  786. collection = &_collection;
  787. numStats = collection->getNumStatistics();
  788. }
  789. // interface IConstWUStatisticIterator
  790. IConstWUStatistic & query()
  791. {
  792. return *this;
  793. }
  794. bool first()
  795. {
  796. curStatIndex = 0;
  797. if (curStatIndex >= numStats)
  798. return false;
  799. collection->getStatistic(kind, value, curStatIndex);
  800. //MORE: Allow filtering:
  801. /*
  802. * if (filter && !filter->matches(SCTall, NULL, SSTall, NULL, queryMeasure(kind), kind, value))
  803. continue;
  804. */
  805. return true;
  806. }
  807. bool next()
  808. {
  809. for (;;)
  810. {
  811. ++curStatIndex;
  812. if (curStatIndex >= numStats)
  813. return false;
  814. collection->getStatistic(kind, value, curStatIndex);
  815. //MORE: Allow stats filtering
  816. return true;
  817. }
  818. }
  819. bool isValid()
  820. {
  821. return curStatIndex < numStats;
  822. }
  823. //interface IConstWUStatistic
  824. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const override
  825. {
  826. if (createDefault)
  827. {
  828. StringBuffer description;
  829. createDefaultDescription(description, kind, scopeType, scope);
  830. str.set(description);
  831. }
  832. return str;
  833. }
  834. virtual IStringVal & getCreator(IStringVal & str) const override
  835. {
  836. str.set(creator);
  837. return str;
  838. }
  839. virtual const char * queryScope() const override
  840. {
  841. return scope;
  842. }
  843. virtual IStringVal & getFormattedValue(IStringVal & str) const override
  844. {
  845. StringBuffer formatted;
  846. formatStatistic(formatted, value, kind);
  847. str.set(formatted);
  848. return str;
  849. }
  850. virtual StatisticMeasure getMeasure() const override
  851. {
  852. return queryMeasure(kind);
  853. }
  854. virtual StatisticKind getKind() const override
  855. {
  856. return kind;
  857. }
  858. virtual StatisticCreatorType getCreatorType() const override
  859. {
  860. return creatorType;
  861. }
  862. virtual StatisticScopeType getScopeType() const override
  863. {
  864. return scopeType;
  865. }
  866. virtual unsigned __int64 getValue() const override
  867. {
  868. return value;
  869. }
  870. virtual unsigned __int64 getCount() const override
  871. {
  872. return 1;
  873. }
  874. virtual unsigned __int64 getMax() const override
  875. {
  876. return 0;
  877. }
  878. virtual unsigned __int64 getTimestamp() const override
  879. {
  880. return timeStamp;
  881. }
  882. void play(IWuScopeVisitor & visitor)
  883. {
  884. visitor.noteStatistic(kind, value, *this);
  885. }
  886. protected:
  887. IStatisticCollection * collection = nullptr;
  888. StringBuffer creator;
  889. StringBuffer scope;
  890. StatisticKind kind;
  891. StatisticCreatorType creatorType;
  892. StatisticScopeType scopeType;
  893. unsigned __int64 value = 0;
  894. unsigned __int64 timeStamp;
  895. unsigned curStatIndex = 0;
  896. unsigned numStats = 0;
  897. } statsIterator;
  898. Owned<IRemoteConnection> conn;
  899. StringBuffer curScopeName;
  900. StatisticScopeType curScopeType = SSTnone;
  901. __uint64 minVersion;
  902. const ScopeFilter & filter;
  903. StringBuffer rootPath;
  904. StringAttr singleSubGraph;
  905. Owned<IPropertyTreeIterator> graphIter;
  906. Owned<IPropertyTreeIterator> subgraphIter;
  907. IArrayOf<IStatisticCollection> collections;
  908. IArrayOf<IStatisticCollectionIterator> childIterators; // Iterator(n) through collections(n) - created once iterating children
  909. MemoryBuffer compressed;
  910. MemoryBuffer serialized;
  911. bool valid;
  912. };
  913. int compareNoteScopeOrder(IConstWUException & left, IConstWUException & right)
  914. {
  915. return compareScopeName(left.queryScope(), right.queryScope());
  916. }
  917. int compareNoteScopeOrder(IInterface * const * left, IInterface * const * right)
  918. {
  919. return compareNoteScopeOrder(*static_cast<IConstWUException *>(*left), *static_cast<IConstWUException *>(*right));
  920. }
  921. class NotesIterator : public CInterfaceOf<IConstWUScopeIterator>
  922. {
  923. public:
  924. NotesIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter)
  925. {
  926. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  927. ForEach(*exceptions)
  928. {
  929. IConstWUException & exception = exceptions->query();
  930. if (exception.queryScope()!=nullptr)
  931. notes.append(OLINK(exception));
  932. }
  933. notes.sort(compareNoteScopeOrder);
  934. }
  935. virtual bool first() override
  936. {
  937. baseIndex = 0;
  938. return updateCurrent();
  939. }
  940. virtual bool next() override
  941. {
  942. baseIndex += numCurrentScope;
  943. return updateCurrent();
  944. }
  945. virtual bool isValid() override
  946. {
  947. return notes.isItem(baseIndex);
  948. }
  949. virtual bool nextSibling() override
  950. {
  951. //Search until the current scope is not a child of the previous scope
  952. StringBuffer savedScope(queryScope());
  953. for (;;)
  954. {
  955. if (!next())
  956. return false;
  957. if (compareScopes(queryScope(), savedScope) != SCchild)
  958. return true;
  959. }
  960. }
  961. virtual bool nextParent() override
  962. {
  963. //Search until the current scope is not a child of the previous parent scope
  964. StringBuffer parentScope;
  965. if (getParentScope(parentScope, queryScope()))
  966. {
  967. for (;;)
  968. {
  969. if (!next())
  970. return false;
  971. if (compareScopes(queryScope(), parentScope) != SCchild)
  972. return true;
  973. }
  974. }
  975. else
  976. {
  977. finish();
  978. return false;
  979. }
  980. }
  981. virtual const char * queryScope() const override
  982. {
  983. return notes.item(baseIndex).queryScope();
  984. }
  985. virtual StatisticScopeType getScopeType() const override
  986. {
  987. const char * tail = queryScopeTail(queryScope());
  988. StatsScopeId id(tail);
  989. return id.queryScopeType();
  990. }
  991. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) override
  992. {
  993. if (whichProperties & PTnotes)
  994. {
  995. for (unsigned i=0; i < numCurrentScope; i++)
  996. {
  997. IConstWUException & cur = notes.item(baseIndex + i);
  998. visitor.noteException(cur);
  999. }
  1000. }
  1001. }
  1002. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1003. {
  1004. return false;
  1005. }
  1006. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1007. {
  1008. return nullptr;
  1009. }
  1010. virtual const char * queryHint(const char * kind) const override
  1011. {
  1012. return nullptr;
  1013. }
  1014. private:
  1015. bool updateCurrent()
  1016. {
  1017. if (!notes.isItem(baseIndex))
  1018. return false;
  1019. // set numCurrentScope to number of notes in the current scope
  1020. unsigned next = baseIndex+1;
  1021. while (next < notes.ordinality())
  1022. {
  1023. if (compareNoteScopeOrder(notes.item(baseIndex), notes.item(next)) != 0)
  1024. break;
  1025. next++;
  1026. }
  1027. numCurrentScope = (next - baseIndex);
  1028. return true;
  1029. }
  1030. void finish()
  1031. {
  1032. baseIndex = notes.ordinality();
  1033. }
  1034. unsigned baseIndex = 0;
  1035. unsigned numCurrentScope = 0;
  1036. IArrayOf<IConstWUException> notes;
  1037. };
  1038. int compareStatisticScopes(IConstWUStatistic & left, IConstWUStatistic & right)
  1039. {
  1040. return compareScopeName(left.queryScope(), right.queryScope());
  1041. }
  1042. int compareStatisticScopes(IInterface * const * left, IInterface * const * right)
  1043. {
  1044. return compareStatisticScopes(*static_cast<IConstWUStatistic *>(*left), *static_cast<IConstWUStatistic *>(*right));
  1045. }
  1046. /*
  1047. * An implementation of IConstWUScopeIterator for global workunit statistics.
  1048. */
  1049. class WorkUnitStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1050. {
  1051. public:
  1052. WorkUnitStatisticsScopeIterator(const IArrayOf<IConstWUStatistic> & _statistics, const ScopeFilter & _filter)
  1053. {
  1054. ForEachItemIn(i, _statistics)
  1055. {
  1056. IConstWUStatistic & cur = _statistics.item(i);
  1057. if (_filter.compare(cur.queryScope()) & SCequal)
  1058. statistics.append(OLINK(cur));
  1059. }
  1060. statistics.sort(compareStatisticScopes);
  1061. }
  1062. virtual bool first() override
  1063. {
  1064. curIndex = 0;
  1065. return initScope();
  1066. }
  1067. virtual bool next() override
  1068. {
  1069. curIndex += numStatistics;
  1070. return initScope();
  1071. }
  1072. virtual bool nextSibling() override
  1073. {
  1074. //Search until the current scope is not a child of the previous scope
  1075. StringBuffer savedScope(queryScope());
  1076. for (;;)
  1077. {
  1078. if (!next())
  1079. return false;
  1080. if (compareScopes(queryScope(), savedScope) != SCchild)
  1081. return true;
  1082. }
  1083. }
  1084. virtual bool nextParent() override
  1085. {
  1086. //Search until the current scope is not a child of the previous parent scope
  1087. StringBuffer parentScope;
  1088. if (getParentScope(parentScope, queryScope()))
  1089. {
  1090. for (;;)
  1091. {
  1092. if (!next())
  1093. return false;
  1094. if (compareScopes(queryScope(), parentScope) != SCchild)
  1095. return true;
  1096. }
  1097. }
  1098. else
  1099. {
  1100. finish();
  1101. return false;
  1102. }
  1103. }
  1104. virtual bool isValid() override
  1105. {
  1106. return statistics.isItem(curIndex);
  1107. }
  1108. virtual const char * queryScope() const override
  1109. {
  1110. return statistics.item(curIndex).queryScope();
  1111. }
  1112. virtual StatisticScopeType getScopeType() const override
  1113. {
  1114. return statistics.item(curIndex).getScopeType();
  1115. }
  1116. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1117. {
  1118. if (whichProperties & PTstatistics)
  1119. {
  1120. for (unsigned i=0; i < numStatistics; i++)
  1121. {
  1122. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1123. visitor.noteStatistic(cur.getKind(), cur.getValue(), cur);
  1124. }
  1125. }
  1126. }
  1127. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1128. {
  1129. for (unsigned i=0; i < numStatistics; i++)
  1130. {
  1131. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1132. if (cur.getKind() == kind)
  1133. {
  1134. value = cur.getValue();
  1135. return true;
  1136. }
  1137. }
  1138. return false;
  1139. }
  1140. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1141. {
  1142. return nullptr;
  1143. }
  1144. virtual const char * queryHint(const char * kind) const
  1145. {
  1146. return nullptr;
  1147. }
  1148. protected:
  1149. inline IConstWUStatistic & queryStatistic(unsigned i)
  1150. {
  1151. return statistics.item(curIndex + i);
  1152. }
  1153. bool initScope()
  1154. {
  1155. if (!statistics.isItem(curIndex))
  1156. return false;
  1157. unsigned next = curIndex+1;
  1158. while (next < statistics.ordinality())
  1159. {
  1160. if (compareStatisticScopes(statistics.item(curIndex), statistics.item(next)) != 0)
  1161. break;
  1162. next++;
  1163. }
  1164. numStatistics = (next - curIndex);
  1165. return true;
  1166. }
  1167. void finish()
  1168. {
  1169. curIndex = statistics.ordinality();
  1170. }
  1171. protected:
  1172. IArrayOf<IConstWUStatistic> statistics;
  1173. unsigned curIndex = 0;
  1174. unsigned numStatistics = 1;
  1175. };
  1176. /*
  1177. * An implementation of IConstWUScopeIterator for the query graphs.
  1178. */
  1179. class GraphScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1180. {
  1181. private:
  1182. //This uses a state machine - this enumeration contains the different states.
  1183. enum State
  1184. {
  1185. //Following are the states which represent valid scopes
  1186. SGraph,
  1187. SChildGraph,
  1188. SSubGraph,
  1189. SEdge,
  1190. SActivity,
  1191. //The following are internal states.
  1192. SGraphFirstEdge,
  1193. SGraphFirstSubGraph,
  1194. SGraphFirst,
  1195. SGraphEnd,
  1196. SGraphNext,
  1197. SSubGraphFirstEdge,
  1198. SSubGraphFirstActivity,
  1199. SSubGraphEnd,
  1200. SSubGraphNext,
  1201. SEdgeNext,
  1202. SEdgeEnd,
  1203. SActivityNext,
  1204. SActivityEnd,
  1205. SChildGraphFirstEdge,
  1206. SChildGraphFirstSubGraph,
  1207. SChildGraphFirst,
  1208. SChildGraphNext,
  1209. SChildGraphEnd,
  1210. SDone
  1211. };
  1212. State state = SDone;
  1213. State nextState = SDone;
  1214. public:
  1215. GraphScopeIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter) : graphIter(&wu->getGraphs(GraphTypeAny)), filter(_filter)
  1216. {
  1217. }
  1218. virtual bool first() override
  1219. {
  1220. state = SGraphFirst;
  1221. return nextScope();
  1222. }
  1223. virtual bool next() override
  1224. {
  1225. if (!selectNext())
  1226. return false;
  1227. return nextScope();
  1228. }
  1229. virtual bool nextSibling() override
  1230. {
  1231. if (!selectNextSibling())
  1232. return false;
  1233. return nextScope();
  1234. }
  1235. virtual bool nextParent() override
  1236. {
  1237. if (!selectNextParent())
  1238. return false;
  1239. return nextScope();
  1240. }
  1241. virtual bool isValid() override
  1242. {
  1243. return graphIter->isValid();
  1244. }
  1245. virtual const char * queryScope() const override
  1246. {
  1247. return curScopeName.str();
  1248. }
  1249. virtual StatisticScopeType getScopeType() const override
  1250. {
  1251. return scopeType;
  1252. }
  1253. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1254. {
  1255. switch (scopeType)
  1256. {
  1257. case SSTgraph:
  1258. return;
  1259. }
  1260. IPropertyTree & cur = treeIters.tos().query();
  1261. switch (scopeType)
  1262. {
  1263. case SSTgraph:
  1264. break;
  1265. case SSTsubgraph:
  1266. break;
  1267. case SSTactivity:
  1268. {
  1269. if (whichProperties & PTattributes)
  1270. {
  1271. playAttribute(visitor, WaLabel);
  1272. Owned<IPropertyTreeIterator> attrs = cur.getElements("att");
  1273. ForEach(*attrs)
  1274. {
  1275. IPropertyTree & cur = attrs->query();
  1276. WuAttr attr = queryGraphChildAttToWuAttr(cur.queryProp("@name"));
  1277. if (attr != WaNone)
  1278. visitor.noteAttribute(attr, cur.queryProp("@value"));
  1279. }
  1280. }
  1281. if (whichProperties & PThints)
  1282. {
  1283. Owned<IPropertyTreeIterator> hints = cur.getElements("hint");
  1284. ForEach(*hints)
  1285. {
  1286. IPropertyTree & cur = hints->query();
  1287. visitor.noteHint(cur.queryProp("@name"), cur.queryProp("@value"));
  1288. }
  1289. }
  1290. break;
  1291. }
  1292. case SSTedge:
  1293. if (whichProperties & PTattributes)
  1294. {
  1295. //MORE This will eventually need to walk the attributes and map the names.
  1296. //Need to be careful if they need to be mapped differently depending on the context.
  1297. playAttribute(visitor, WaLabel);
  1298. playAttribute(visitor, WaIdSource);
  1299. playAttribute(visitor, WaIdTarget);
  1300. playAttribute(visitor, WaSourceIndex);
  1301. playAttribute(visitor, WaTargetIndex);
  1302. playAttribute(visitor, WaIsDependency);
  1303. }
  1304. break;
  1305. }
  1306. }
  1307. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1308. {
  1309. return false;
  1310. }
  1311. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1312. {
  1313. if (!treeIters.ordinality())
  1314. return nullptr;
  1315. //MORE - check that the attribute is value for the current scope type (to prevent defaults being returned)
  1316. return queryAttributeValue(treeIters.tos().query(), attr, scratchpad);
  1317. }
  1318. virtual const char * queryHint(const char * kind) const override
  1319. {
  1320. //MORE: Needs to be implemented!
  1321. return nullptr;
  1322. }
  1323. private:
  1324. void playAttribute(IWuScopeVisitor & visitor, WuAttr kind)
  1325. {
  1326. StringBuffer scratchpad;
  1327. const char * value = queryAttributeValue(treeIters.tos().query(), kind, scratchpad);
  1328. if (value)
  1329. visitor.noteAttribute(kind, value);
  1330. }
  1331. void pushIterator(IPropertyTreeIterator * iter, State state)
  1332. {
  1333. treeIters.append(*LINK(iter));
  1334. stateStack.append(state);
  1335. }
  1336. State popIterator()
  1337. {
  1338. treeIters.pop();
  1339. return (State)stateStack.popGet();
  1340. }
  1341. void pushScope(const char * id)
  1342. {
  1343. scopeLengths.append(curScopeName.length());
  1344. curScopeName.append(":").append(id);
  1345. }
  1346. void popScope()
  1347. {
  1348. curScopeName.setLength(scopeLengths.popGet());
  1349. }
  1350. bool doNextScope()
  1351. {
  1352. for(;;)
  1353. {
  1354. switch (state)
  1355. {
  1356. case SGraph:
  1357. {
  1358. IConstWUGraph & graph = graphIter->query();
  1359. unsigned wfid = graph.getWfid();
  1360. curScopeName.clear();
  1361. if (wfid != 0)
  1362. curScopeName.append(WorkflowScopePrefix).append(wfid).append(':');
  1363. graph.getName(StringBufferAdaptor(curScopeName));
  1364. scopeType = SSTgraph;
  1365. return true;
  1366. }
  1367. case SSubGraph:
  1368. scopeId.set(SubGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1369. pushScope(scopeId);
  1370. scopeType = SSTsubgraph;
  1371. return true;
  1372. case SEdge:
  1373. scopeId.set(EdgeScopePrefix).append(treeIters.tos().query().queryProp("@id"));
  1374. pushScope(scopeId);
  1375. scopeType = SSTedge;
  1376. return true;
  1377. case SActivity:
  1378. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph)
  1379. {
  1380. state = SActivityNext;
  1381. break;
  1382. }
  1383. scopeId.set(ActivityScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1384. pushScope(scopeId);
  1385. scopeType = SSTactivity;
  1386. return true;
  1387. case SChildGraph:
  1388. {
  1389. unsigned numIters = treeIters.ordinality();
  1390. //This should really be implemented by a filter on the node - but it would require _kind/_parentActivity to move to the node tag
  1391. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1392. {
  1393. state = SChildGraphNext;
  1394. break;
  1395. }
  1396. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1397. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1398. if (parentId != parentActivityId)
  1399. {
  1400. state = SChildGraphNext;
  1401. break;
  1402. }
  1403. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1404. pushScope(scopeId);
  1405. scopeType = SSTchildgraph;
  1406. return true;
  1407. }
  1408. //Graph iteration
  1409. case SGraphFirst:
  1410. if (!graphIter->first())
  1411. state = SDone;
  1412. else
  1413. state = SGraph;
  1414. break;
  1415. case SGraphEnd:
  1416. state = SGraphNext;
  1417. break;
  1418. case SGraphNext:
  1419. if (!graphIter->next())
  1420. state = SDone;
  1421. else
  1422. state = SGraph;
  1423. break;
  1424. //Edge iteration
  1425. case SGraphFirstEdge:
  1426. {
  1427. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1428. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1429. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1430. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1431. if (treeIter && treeIter->first())
  1432. {
  1433. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1434. treeIter->first();
  1435. pushIterator(treeIter, SGraphFirstSubGraph);
  1436. state = SEdge;
  1437. }
  1438. else
  1439. state = SGraphFirstSubGraph;
  1440. break;
  1441. }
  1442. case SChildGraphFirstEdge:
  1443. {
  1444. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1445. if (treeIter && treeIter->first())
  1446. {
  1447. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1448. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1449. state = SEdge;
  1450. }
  1451. else
  1452. state = SChildGraphFirstSubGraph;
  1453. break;
  1454. }
  1455. case SEdgeEnd:
  1456. popScope();
  1457. state = SEdgeNext;
  1458. break;
  1459. case SEdgeNext:
  1460. if (treeIters.tos().next())
  1461. state = SEdge;
  1462. else
  1463. state = popIterator();
  1464. break;
  1465. //Subgraph iteration
  1466. case SGraphFirstSubGraph:
  1467. {
  1468. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1469. if (treeIter && treeIter->first())
  1470. {
  1471. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1472. treeIter->first();
  1473. pushIterator(treeIter, SGraphNext);
  1474. state = SSubGraph;
  1475. }
  1476. else
  1477. state = SGraphNext;
  1478. break;
  1479. }
  1480. case SChildGraphFirstSubGraph:
  1481. {
  1482. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1483. if (treeIter && treeIter->first())
  1484. {
  1485. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1486. pushIterator(treeIter, SChildGraphEnd);
  1487. state = SSubGraph;
  1488. }
  1489. else
  1490. state = SChildGraphEnd;
  1491. break;
  1492. }
  1493. case SSubGraphFirstEdge:
  1494. {
  1495. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1496. if (treeIter && treeIter->first())
  1497. {
  1498. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1499. pushIterator(treeIter, SSubGraphFirstActivity);
  1500. state = SEdge;
  1501. }
  1502. else
  1503. state = SSubGraphFirstActivity;
  1504. break;
  1505. }
  1506. case SSubGraphFirstActivity:
  1507. {
  1508. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1509. if (treeIter && treeIter->first())
  1510. {
  1511. treeIter.setown(createSortedIterator(*treeIter, compareActivityNode));
  1512. pushIterator(treeIter, SSubGraphEnd);
  1513. state = SActivity;
  1514. }
  1515. else
  1516. state = SSubGraphEnd;
  1517. break;
  1518. }
  1519. case SSubGraphEnd:
  1520. popScope();
  1521. state = SSubGraphNext;
  1522. break;
  1523. case SChildGraphEnd:
  1524. popScope();
  1525. state = SChildGraphNext;
  1526. break;
  1527. case SSubGraphNext:
  1528. if (treeIters.tos().next())
  1529. state = SSubGraph;
  1530. else
  1531. state = popIterator();
  1532. break;
  1533. case SActivityEnd:
  1534. popScope();
  1535. state = SActivityNext;
  1536. break;
  1537. case SActivityNext:
  1538. if (treeIters.tos().next())
  1539. state = SActivity;
  1540. else
  1541. state = popIterator();
  1542. break;
  1543. case SChildGraphNext:
  1544. if (treeIters.tos().next())
  1545. state = SChildGraph;
  1546. else
  1547. state = popIterator();
  1548. break;
  1549. case SChildGraphFirst:
  1550. {
  1551. unsigned numIters = treeIters.ordinality();
  1552. IPropertyTreeIterator & graphIter = treeIters.item(numIters-2);
  1553. Owned<IPropertyTreeIterator> treeIter = graphIter.query().getElements("att/graph/node");
  1554. //Really want to filter by <att name="_parentActivity" value="<parentid>">
  1555. if (treeIter && treeIter->first())
  1556. {
  1557. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1558. pushIterator(treeIter, SActivityEnd);
  1559. state = SChildGraph;
  1560. }
  1561. else
  1562. state = SActivityEnd;
  1563. break;
  1564. }
  1565. case SDone:
  1566. return false;
  1567. default:
  1568. throwUnexpected();
  1569. }
  1570. }
  1571. }
  1572. bool nextScope()
  1573. {
  1574. for(;;)
  1575. {
  1576. if (!doNextScope())
  1577. return false;
  1578. ScopeCompare cmp = filter.compare(curScopeName);
  1579. if (cmp & SCequal)
  1580. return true;
  1581. //MORE: Optimize next based on result of compare
  1582. if (!selectNext())
  1583. return false;
  1584. }
  1585. }
  1586. bool selectNext()
  1587. {
  1588. switch (state)
  1589. {
  1590. case SGraph:
  1591. state = SGraphFirstEdge;
  1592. break;
  1593. case SChildGraph:
  1594. state = SChildGraphFirstEdge;
  1595. break;
  1596. case SSubGraph:
  1597. state = SSubGraphFirstEdge;
  1598. break;
  1599. case SEdge:
  1600. state = SEdgeEnd;
  1601. break;
  1602. case SActivity:
  1603. state = SChildGraphFirst;
  1604. break;
  1605. case SDone:
  1606. return false;
  1607. default:
  1608. throwUnexpected();
  1609. }
  1610. return true;
  1611. }
  1612. bool selectNextSibling()
  1613. {
  1614. switch (state)
  1615. {
  1616. case SGraph:
  1617. state = SGraphEnd;
  1618. break;
  1619. case SChildGraph:
  1620. state = SChildGraphEnd;
  1621. break;
  1622. case SSubGraph:
  1623. state = SSubGraphEnd;
  1624. break;
  1625. case SEdge:
  1626. state = SEdgeEnd;
  1627. break;
  1628. case SActivity:
  1629. state = SActivityEnd;
  1630. break;
  1631. case SDone:
  1632. return false;
  1633. default:
  1634. throwUnexpected();
  1635. }
  1636. return true;
  1637. }
  1638. bool selectNextParent()
  1639. {
  1640. switch (state)
  1641. {
  1642. case SGraph:
  1643. state = SDone;
  1644. break;
  1645. case SChildGraph:
  1646. case SSubGraph:
  1647. case SEdge:
  1648. case SActivity:
  1649. popScope();
  1650. state = popIterator();
  1651. break;
  1652. case SDone:
  1653. return false;
  1654. default:
  1655. throwUnexpected();
  1656. }
  1657. return true;
  1658. }
  1659. protected:
  1660. const ScopeFilter & filter;
  1661. Owned<IConstWUGraphIterator> graphIter;
  1662. Owned<IPropertyTree> curGraph;
  1663. IArrayOf<IPropertyTreeIterator> treeIters;
  1664. UnsignedArray scopeLengths;
  1665. UnsignedArray stateStack;
  1666. StringBuffer curScopeName;
  1667. StringBuffer scopeId;
  1668. StatisticScopeType scopeType = SSTnone;
  1669. };
  1670. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1671. {
  1672. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1673. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1674. return left->queryWfid() - right->queryWfid();
  1675. }
  1676. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1677. /*
  1678. * An implementation of IConstWUScopeIterator for the workflow information.
  1679. */
  1680. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1681. {
  1682. public:
  1683. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1684. {
  1685. ForEach(*wfIter)
  1686. workflow.append(*LINK(wfIter->query()));
  1687. workflow.sort(compareWorkflow);
  1688. }
  1689. virtual bool first() override
  1690. {
  1691. if (workflow.empty())
  1692. return false;
  1693. curWorkflow = 0;
  1694. return initWorkflowItem();
  1695. }
  1696. virtual bool next() override
  1697. {
  1698. if (!workflow.isItem(++curWorkflow))
  1699. return false;
  1700. return initWorkflowItem();
  1701. }
  1702. virtual bool nextSibling() override
  1703. {
  1704. return next();
  1705. }
  1706. virtual bool nextParent() override
  1707. {
  1708. curWorkflow = NotFound;
  1709. return false;
  1710. }
  1711. virtual bool isValid() override
  1712. {
  1713. return workflow.isItem(curWorkflow);
  1714. }
  1715. virtual const char * queryScope() const override
  1716. {
  1717. return curScope.str();
  1718. }
  1719. virtual StatisticScopeType getScopeType() const override
  1720. {
  1721. return SSTworkflow;
  1722. }
  1723. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1724. {
  1725. if (whichProperties & PTattributes)
  1726. {
  1727. {
  1728. StringBuffer scratchpad;
  1729. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1730. ForEach(*depends)
  1731. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1732. }
  1733. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1734. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1735. }
  1736. }
  1737. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1738. {
  1739. return false;
  1740. }
  1741. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1742. {
  1743. auto wf = &workflow.item(curWorkflow);
  1744. StringBufferAdaptor adaptor(scratchpad);
  1745. switch (attr)
  1746. {
  1747. case WaIdDependencyList:
  1748. {
  1749. bool first = true;
  1750. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1751. ForEach(*depends)
  1752. {
  1753. if (first)
  1754. scratchpad.append("[");
  1755. else
  1756. scratchpad.append(",");
  1757. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1758. first = false;
  1759. }
  1760. if (first)
  1761. return nullptr;
  1762. scratchpad.append("]");
  1763. return scratchpad.str();
  1764. }
  1765. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1766. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1767. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1768. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1769. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1770. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1771. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1772. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1773. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1774. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1775. case WaState: return queryWorkflowStateText(wf->queryState());
  1776. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1777. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1778. /*
  1779. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1780. virtual bool isScheduledNow() const = 0;
  1781. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1782. virtual unsigned querySchedulePriority() const = 0;
  1783. virtual bool hasScheduleCount() const = 0;
  1784. virtual unsigned queryScheduleCount() const = 0;
  1785. virtual unsigned queryRetriesAllowed() const = 0;
  1786. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1787. virtual bool queryPersistRefresh() const = 0;
  1788. virtual unsigned queryScheduleCountRemaining() const = 0;
  1789. virtual unsigned queryRetriesRemaining() const = 0;
  1790. virtual int queryFailCode() const = 0;
  1791. virtual const char * queryFailMessage() const = 0;
  1792. virtual const char * queryEventName() const = 0;
  1793. virtual const char * queryEventExtra() const = 0;
  1794. */
  1795. }
  1796. return nullptr;
  1797. }
  1798. virtual const char * queryHint(const char * kind) const
  1799. {
  1800. return nullptr;
  1801. }
  1802. protected:
  1803. bool initWorkflowItem()
  1804. {
  1805. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1806. return true;
  1807. }
  1808. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1809. {
  1810. return scratchpad.clear().append(prefix).append(value).str();
  1811. }
  1812. const char * queryOptString(IStringVal & value) const
  1813. {
  1814. const char * text = value.str();
  1815. if (!text || !*text)
  1816. return nullptr;
  1817. return text;
  1818. }
  1819. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1820. {
  1821. if (!value)
  1822. return nullptr;
  1823. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1824. }
  1825. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1826. {
  1827. StringBuffer scratchpad;
  1828. for (auto attr : attrs)
  1829. {
  1830. const char * value = queryAttribute(attr, scratchpad.clear());
  1831. if (value)
  1832. visitor.noteAttribute(attr, value);
  1833. }
  1834. }
  1835. protected:
  1836. IArrayOf<IConstWorkflowItem> workflow;
  1837. unsigned curWorkflow = 0;
  1838. StringBuffer curScope;
  1839. };
  1840. /*
  1841. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1842. */
  1843. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1844. {
  1845. class VisitorMapper : implements IWuScopeVisitor
  1846. {
  1847. public:
  1848. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1849. filter(_filter), visitor(_visitor)
  1850. {}
  1851. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1852. {
  1853. if (filter.includeStatistic(kind))
  1854. visitor.noteStatistic(kind, value, extra);
  1855. }
  1856. virtual void noteAttribute(WuAttr attr, const char * value) override
  1857. {
  1858. if (filter.includeAttribute(attr))
  1859. visitor.noteAttribute(attr, value);
  1860. }
  1861. virtual void noteHint(const char * kind, const char * value) override
  1862. {
  1863. if (filter.includeHint(kind))
  1864. visitor.noteHint(kind, value);
  1865. }
  1866. virtual void noteException(IConstWUException & exception) override
  1867. {
  1868. visitor.noteException(exception);
  1869. }
  1870. protected:
  1871. const WuScopeFilter & filter;
  1872. IWuScopeVisitor & visitor;
  1873. };
  1874. public:
  1875. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1876. {
  1877. }
  1878. void addIter(IConstWUScopeIterator * iter)
  1879. {
  1880. if (iter)
  1881. {
  1882. iters.append(OLINK(*iter));
  1883. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1884. }
  1885. }
  1886. virtual bool first() override
  1887. {
  1888. activeIterMask = 0;
  1889. ForEachItemIn(i, iters)
  1890. {
  1891. if (iters.item(i).first())
  1892. activeIterMask |= (1U << i);
  1893. }
  1894. return findNextScope();
  1895. }
  1896. virtual bool next() override
  1897. {
  1898. selectNext();
  1899. return findNextScope();
  1900. }
  1901. virtual bool nextSibling() override
  1902. {
  1903. selectNextSibling();
  1904. return findNextScope();
  1905. }
  1906. virtual bool nextParent() override
  1907. {
  1908. selectNextParent();
  1909. return findNextScope();
  1910. }
  1911. virtual bool isValid() override
  1912. {
  1913. return (activeIterMask != 0);
  1914. }
  1915. virtual const char * queryScope() const override
  1916. {
  1917. return iters.item(firstMatchIter).queryScope();
  1918. }
  1919. virtual StatisticScopeType getScopeType() const override
  1920. {
  1921. return iters.item(firstMatchIter).getScopeType();
  1922. }
  1923. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1924. {
  1925. VisitorMapper mappedVisitor(filter, visitor);
  1926. whichProperties &= filter.properties;
  1927. ForEachItemIn(i, iters)
  1928. {
  1929. if (iterMatchesCurrentScope(i))
  1930. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1931. }
  1932. }
  1933. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1934. {
  1935. ForEachItemIn(i, iters)
  1936. {
  1937. if (iterMatchesCurrentScope(i))
  1938. {
  1939. if (iters.item(i).getStat(kind, value))
  1940. return true;
  1941. }
  1942. }
  1943. return false;
  1944. }
  1945. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1946. {
  1947. ForEachItemIn(i, iters)
  1948. {
  1949. if (iterMatchesCurrentScope(i))
  1950. {
  1951. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1952. if (value)
  1953. return value;
  1954. }
  1955. }
  1956. return nullptr;
  1957. }
  1958. virtual const char * queryHint(const char * kind) const override
  1959. {
  1960. ForEachItemIn(i, iters)
  1961. {
  1962. if (iterMatchesCurrentScope(i))
  1963. {
  1964. const char * value = iters.item(i).queryHint(kind);
  1965. if (value)
  1966. return value;
  1967. }
  1968. }
  1969. return nullptr;
  1970. }
  1971. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  1972. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  1973. protected:
  1974. //Calculate which iterators contain the scope that should come next
  1975. bool findNextScope()
  1976. {
  1977. for(;;)
  1978. {
  1979. if (activeIterMask == 0)
  1980. return false;
  1981. unsigned mask = 0;
  1982. const char * scope = nullptr;
  1983. ForEachItemIn(i, iters)
  1984. {
  1985. if (isAlive(i))
  1986. {
  1987. const char * iterScope = iters.item(i).queryScope();
  1988. if (mask)
  1989. {
  1990. int compare = compareScopeName(scope, iterScope);
  1991. if (compare == 0)
  1992. {
  1993. mask |= (1U << i);
  1994. }
  1995. else if (compare > 0)
  1996. {
  1997. scope = iterScope;
  1998. mask = (1U << i);
  1999. firstMatchIter = i;
  2000. }
  2001. }
  2002. else
  2003. {
  2004. scope = iterScope;
  2005. mask = (1U << i);
  2006. firstMatchIter = i;
  2007. }
  2008. }
  2009. }
  2010. matchIterMask = mask;
  2011. while (activeScopes)
  2012. {
  2013. const char * activeScope = activeScopes.tos();
  2014. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2015. if (compareScopes(scope, activeScope) & SCchild)
  2016. break;
  2017. activeScopes.pop();
  2018. }
  2019. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2020. bool include = false;
  2021. if (activeScopes)
  2022. {
  2023. const char * activeScope = activeScopes.tos();
  2024. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2025. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2026. if (nesting <= filter.include.nestedDepth)
  2027. include = true;
  2028. }
  2029. //Check to see if this is a new match
  2030. if (filter.compareMatchScopes(scope) & SCequal)
  2031. {
  2032. if (!include)
  2033. include = filter.include.matchedScope;
  2034. //Only add it to the list of active scopes if it can match child elements
  2035. if (filter.include.nestedDepth != 0)
  2036. activeScopes.append(scope);
  2037. }
  2038. if (include)
  2039. {
  2040. if (!filter.includeScope(scope))
  2041. include = false;
  2042. else if (filter.requiredStats.size())
  2043. {
  2044. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2045. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2046. {
  2047. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2048. unsigned __int64 value;
  2049. if (getStat(cur.queryKind(), value))
  2050. {
  2051. if (!cur.matches(value))
  2052. include = false;
  2053. }
  2054. else
  2055. include = false;
  2056. }
  2057. }
  2058. }
  2059. if (include)
  2060. return true;
  2061. //MORE: Optimize based on filter.compareScope()
  2062. selectNext();
  2063. }
  2064. }
  2065. void checkScopeOrder(unsigned input, const char * prevScope)
  2066. {
  2067. if (isAlive(input))
  2068. {
  2069. const char * curScope = iters.item(input).queryScope();
  2070. int compare = compareScopeName(prevScope, curScope);
  2071. if (compare >= 0)
  2072. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2073. }
  2074. }
  2075. void selectNext()
  2076. {
  2077. ForEachItemIn(i, iters)
  2078. {
  2079. if (iterMatchesCurrentScope(i))
  2080. {
  2081. #ifdef _DEBUG
  2082. StringBuffer prevScope(iters.item(i).queryScope());
  2083. #endif
  2084. if (!iters.item(i).next())
  2085. activeIterMask &= ~(1U << i);
  2086. #ifdef _DEBUG
  2087. checkScopeOrder(i, prevScope);
  2088. #endif
  2089. }
  2090. }
  2091. }
  2092. void selectNextSibling()
  2093. {
  2094. ForEachItemIn(i, iters)
  2095. {
  2096. if (iterMatchesCurrentScope(i))
  2097. {
  2098. #ifdef _DEBUG
  2099. StringBuffer prevScope(iters.item(i).queryScope());
  2100. #endif
  2101. if (!iters.item(i).nextSibling())
  2102. activeIterMask &= ~(1U << i);
  2103. #ifdef _DEBUG
  2104. checkScopeOrder(i, prevScope);
  2105. #endif
  2106. }
  2107. }
  2108. }
  2109. void selectNextParent()
  2110. {
  2111. ForEachItemIn(i, iters)
  2112. {
  2113. if (iterMatchesCurrentScope(i))
  2114. {
  2115. #ifdef _DEBUG
  2116. StringBuffer prevScope(iters.item(i).queryScope());
  2117. #endif
  2118. if (!iters.item(i).nextParent())
  2119. activeIterMask &= ~(1U << i);
  2120. #ifdef _DEBUG
  2121. checkScopeOrder(i, prevScope);
  2122. #endif
  2123. }
  2124. }
  2125. }
  2126. protected:
  2127. const WuScopeFilter & filter;
  2128. IArrayOf<IConstWUScopeIterator> iters;
  2129. unsigned curIter = 0;
  2130. unsigned firstMatchIter = 0;
  2131. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2132. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2133. StringArray activeScopes;
  2134. };
  2135. //---------------------------------------------------------------------------------------------------------------------
  2136. class AggregateFilter
  2137. {
  2138. public:
  2139. AggregateFilter(StatisticKind _search) : search(_search) {}
  2140. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2141. {
  2142. return (kind == search);
  2143. }
  2144. protected:
  2145. StatisticKind search;
  2146. //MORE: Allow filtering by scope?
  2147. };
  2148. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2149. {
  2150. public:
  2151. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2152. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2153. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2154. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2155. protected:
  2156. AggregateFilter filter;
  2157. };
  2158. class SimpleAggregator : public StatisticAggregator
  2159. {
  2160. public:
  2161. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2162. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2163. {
  2164. if (filter.matches(kind, value, extra))
  2165. summary.noteValue(value);
  2166. }
  2167. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2168. //with a noteAggregate(value, variant, value, grouping)?
  2169. protected:
  2170. StatsAggregation summary;
  2171. };
  2172. class SimpleReferenceAggregator : public StatisticAggregator
  2173. {
  2174. public:
  2175. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2176. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2177. {
  2178. if (filter.matches(kind, value, extra))
  2179. summary.noteValue(value);
  2180. }
  2181. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2182. //with a noteAggregate(value, variant, value, grouping)?
  2183. protected:
  2184. StatsAggregation & summary;
  2185. };
  2186. class GroupedAggregator : public StatisticAggregator
  2187. {
  2188. public:
  2189. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2190. {
  2191. if (filter.matches(kind, value, extra))
  2192. {
  2193. StatsAggregation & match = summary; // look up in hash table.
  2194. match.noteValue(value);
  2195. }
  2196. }
  2197. protected:
  2198. //HashTable of (possible groupings->summary)
  2199. StatsAggregation summary;
  2200. };
  2201. class CompoundAggregator : implements StatisticAggregator
  2202. {
  2203. public:
  2204. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2205. {
  2206. ForEachItemIn(i, aggregators)
  2207. aggregators.item(i).noteStatistic(kind, value, extra);
  2208. }
  2209. protected:
  2210. IArrayOf<StatisticAggregator> aggregators;
  2211. };
  2212. //To calculate aggregates, create a scope iterator, and an instance of a StatisticAggregator, and play the attributes through the interface
  2213. //---------------------------------------------------------------------------------------------------------------------
  2214. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2215. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2216. {
  2217. const char * start = finger;
  2218. if (!*start)
  2219. return false;
  2220. const char * cur = start;
  2221. const char * bra = nullptr;
  2222. const char * end = nullptr;
  2223. unsigned braDepth = 0;
  2224. char next;
  2225. arg.clear();
  2226. for (;;)
  2227. {
  2228. next = *cur;
  2229. if (!next || ((next == ',') && (braDepth == 0)))
  2230. break;
  2231. switch (next)
  2232. {
  2233. case '[':
  2234. if (braDepth == 0)
  2235. {
  2236. if (bra)
  2237. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2238. bra = cur;
  2239. }
  2240. braDepth++;
  2241. break;
  2242. case ']':
  2243. if (braDepth > 0)
  2244. {
  2245. if (--braDepth == 0)
  2246. {
  2247. end = cur;
  2248. arg.append(cur - (bra+1), bra+1);
  2249. }
  2250. }
  2251. break;
  2252. }
  2253. cur++;
  2254. }
  2255. if (braDepth != 0)
  2256. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2257. option.clear();
  2258. if (bra)
  2259. {
  2260. if (cur != end+1)
  2261. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2262. option.append(bra-start, start);
  2263. }
  2264. else
  2265. option.append(cur-start, start);
  2266. if (next)
  2267. finger = cur+1;
  2268. else
  2269. finger = cur;
  2270. return true;
  2271. }
  2272. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2273. {
  2274. if (start == end)
  2275. return dft;
  2276. char * next;
  2277. unsigned value = (unsigned)strtoll(start, &next, 10);
  2278. if (next != end)
  2279. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2280. return value;
  2281. }
  2282. static unsigned readValue(const char * start, const char * type)
  2283. {
  2284. if (*start == '\0')
  2285. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2286. char * next;
  2287. unsigned value = (unsigned)strtoll(start, &next, 10);
  2288. if (*next != '\0')
  2289. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2290. return value;
  2291. }
  2292. /*
  2293. Scope service matching Syntax: * indicates
  2294. Which items are matched:
  2295. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2296. depth[n | low..high] - range of depths to search for a match
  2297. source[global|stats|graph|all]* - which sources to search within the workunit
  2298. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2299. Which items are include in the results:
  2300. matched[true|false] - are the matched scopes returned?
  2301. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2302. includetype[<scope-type>] - which scope types should be included?
  2303. Which properties of the items are returned:
  2304. properties[statistics|hints|attributes|scope|all]
  2305. statistic[<statistic-kind>|none|all] - include statistic
  2306. attribute[<attribute-name>|none|all] - include attribute
  2307. hint[<hint-name>] - include hint
  2308. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2309. measure[<measure>] - all statistics with a particular measure
  2310. version[<version>] - minimum version to return
  2311. */
  2312. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2313. //Some of the following contains aliases for the same option e.g. stat and statistic
  2314. static constexpr EnumMapping filterOptions[] = {
  2315. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2316. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2317. { FOmatched, "matched" }, { FOnested, "nested" },
  2318. { FOinclude, "include" }, { FOinclude, "includetype" },
  2319. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2320. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2321. { FOproperty, "prop" }, { FOproperty, "property" },
  2322. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2323. static constexpr EnumMapping sourceMappings[] = {
  2324. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2325. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2326. static constexpr EnumMapping propertyMappings[] = {
  2327. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2328. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2329. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2330. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2331. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2332. WuScopeFilter::WuScopeFilter(const char * filter)
  2333. {
  2334. addFilter(filter);
  2335. finishedFilter();
  2336. }
  2337. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2338. {
  2339. if (!filter)
  2340. return *this;
  2341. StringBuffer option;
  2342. StringBuffer arg;
  2343. while (extractOption(filter, option, arg))
  2344. {
  2345. switch (getEnum(option, filterOptions, FOunknown))
  2346. {
  2347. case FOscope:
  2348. addScope(arg);
  2349. break;
  2350. case FOstype:
  2351. addScopeType(arg);
  2352. break;
  2353. case FOid:
  2354. addId(arg);
  2355. break;
  2356. case FOdepth:
  2357. {
  2358. //Allow depth[n], depth[a,b] or depth[a..b]
  2359. const char * comma = strchr(arg, ',');
  2360. const char * dotdot = strstr(arg, "..");
  2361. if (comma)
  2362. {
  2363. unsigned low = readOptValue(arg, comma, 0, "depth");
  2364. if (comma[1])
  2365. {
  2366. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2367. }
  2368. else
  2369. scopeFilter.setDepth(low, UINT_MAX);
  2370. }
  2371. else if (dotdot)
  2372. {
  2373. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2374. if (dotdot[2])
  2375. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2376. else
  2377. scopeFilter.setDepth(low, UINT_MAX);
  2378. }
  2379. else
  2380. {
  2381. scopeFilter.setDepth(readValue(arg, "depth"));
  2382. }
  2383. break;
  2384. }
  2385. case FOsource:
  2386. addSource(arg);
  2387. break;
  2388. case FOwhere: // where[stat<op>value]
  2389. addRequiredStat(arg);
  2390. break;
  2391. case FOmatched:
  2392. setIncludeMatch(strToBool(arg));
  2393. break;
  2394. case FOnested:
  2395. if (strieq(arg, "all"))
  2396. setIncludeNesting(UINT_MAX);
  2397. else if (isdigit(*arg))
  2398. setIncludeNesting(atoi(arg));
  2399. else
  2400. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2401. break;
  2402. case FOinclude:
  2403. setIncludeScopeType(arg);
  2404. break;
  2405. case FOproperties:
  2406. {
  2407. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2408. if (prop == PTunknown)
  2409. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2410. addOutputProperties(prop);
  2411. break;
  2412. }
  2413. case FOstatistic:
  2414. addOutputStatistic(arg);
  2415. break;
  2416. case FOattribute:
  2417. addOutputAttribute(arg);
  2418. break;
  2419. case FOhint:
  2420. addOutputHint(arg);
  2421. break;
  2422. case FOproperty:
  2423. addOutput(arg);
  2424. break;
  2425. case FOmeasure:
  2426. setMeasure(arg);
  2427. break;
  2428. case FOversion:
  2429. if (isdigit(*arg))
  2430. minVersion = atoi64(arg);
  2431. else
  2432. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2433. break;
  2434. default:
  2435. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2436. }
  2437. }
  2438. return *this;
  2439. }
  2440. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2441. {
  2442. if (scope)
  2443. {
  2444. validateScope(scope);
  2445. scopeFilter.addScope(scope);
  2446. }
  2447. return *this;
  2448. }
  2449. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2450. {
  2451. if (scopeType)
  2452. {
  2453. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2454. if (sst == SSTmax)
  2455. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2456. scopeFilter.addScopeType(sst);
  2457. }
  2458. return *this;
  2459. }
  2460. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2461. {
  2462. validateScopeId(id);
  2463. scopeFilter.addId(id);
  2464. return *this;
  2465. }
  2466. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2467. {
  2468. WuAttr attr = queryWuAttribute(prop, WaNone);
  2469. if (attr != WaNone)
  2470. {
  2471. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2472. if (singleKindAttr != WaNone)
  2473. addOutputAttribute(singleKindAttr);
  2474. else
  2475. addOutputAttribute(attr);
  2476. } else if (queryStatisticKind(prop, StMax) != StMax)
  2477. addOutputStatistic(prop);
  2478. else
  2479. addOutputHint(prop);
  2480. return *this;
  2481. }
  2482. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2483. {
  2484. if (!prop)
  2485. return *this;
  2486. StatisticKind kind = queryStatisticKind(prop, StMax);
  2487. if (kind == StMax)
  2488. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2489. return addOutputStatistic(kind);
  2490. }
  2491. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2492. {
  2493. if (stat != StKindNone)
  2494. {
  2495. if (stat != StKindAll)
  2496. desiredStats.append(stat);
  2497. else
  2498. desiredStats.kill();
  2499. properties |= PTstatistics;
  2500. }
  2501. else
  2502. properties &= ~PTstatistics;
  2503. return *this;
  2504. }
  2505. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2506. {
  2507. if (!prop)
  2508. return *this;
  2509. WuAttr attr = queryWuAttribute(prop, WaMax);
  2510. if (attr == WaMax)
  2511. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2512. return addOutputAttribute(attr);
  2513. }
  2514. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2515. {
  2516. if (attr != WaNone)
  2517. {
  2518. if (attr != WaAll)
  2519. desiredAttrs.append(attr);
  2520. else
  2521. desiredAttrs.kill();
  2522. properties |= PTattributes;
  2523. }
  2524. else
  2525. properties &= ~PTattributes;
  2526. return *this;
  2527. }
  2528. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2529. {
  2530. if (strieq(prop, "none"))
  2531. {
  2532. desiredHints.kill();
  2533. properties &= ~PThints;
  2534. }
  2535. else
  2536. {
  2537. if (!strieq(prop, "all"))
  2538. desiredHints.append(prop);
  2539. else
  2540. desiredHints.kill();
  2541. properties |= PThints;
  2542. }
  2543. return *this;
  2544. }
  2545. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2546. {
  2547. include.matchedScope = value;
  2548. return *this;
  2549. }
  2550. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2551. {
  2552. include.nestedDepth = depth;
  2553. return *this;
  2554. }
  2555. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2556. {
  2557. if (scopeType)
  2558. {
  2559. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2560. if (sst == SSTmax)
  2561. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2562. include.scopeTypes.append(sst);
  2563. }
  2564. return *this;
  2565. }
  2566. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2567. {
  2568. if (measure)
  2569. {
  2570. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2571. if (desiredMeasure == SMeasureNone)
  2572. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2573. properties |= PTstatistics;
  2574. }
  2575. return *this;
  2576. }
  2577. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2578. {
  2579. if (properties == PTnone)
  2580. properties = mask;
  2581. else
  2582. properties |= mask;
  2583. return *this;
  2584. }
  2585. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2586. {
  2587. requiredStats.emplace_back(statKind, lowValue, highValue);
  2588. return *this;
  2589. }
  2590. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2591. {
  2592. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2593. return *this;
  2594. }
  2595. //process a filter in one of the following forms:
  2596. // <statistic-name>
  2597. // <statistic-name> (=|<|<=|>|>=) <value>
  2598. // <statistic-name>=[<low>]..[<high>]
  2599. void WuScopeFilter::addRequiredStat(const char * filter)
  2600. {
  2601. const char * stat = filter;
  2602. const char * cur = stat;
  2603. while (isalpha(*cur))
  2604. cur++;
  2605. StringBuffer statisticName(cur-stat, stat);
  2606. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2607. if (statKind == StKindNone)
  2608. throw makeStringExceptionV(0, "Unknown statistic name '%s'", statisticName.str());
  2609. //Skip any spaces before a comparison operator.
  2610. while (*cur && isspace(*cur))
  2611. cur++;
  2612. //Save the operator, and skip over any non digits.
  2613. const char * op = cur;
  2614. switch (*op)
  2615. {
  2616. case '=':
  2617. cur++;
  2618. break;
  2619. case '<':
  2620. case '>':
  2621. if (op[1] == '=')
  2622. cur += 2;
  2623. else
  2624. cur++;
  2625. break;
  2626. case '\0':
  2627. break;
  2628. default:
  2629. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2630. }
  2631. const char * next;
  2632. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2633. stat_type lowValue = 0;
  2634. stat_type highValue = MaxStatisticValue;
  2635. switch (op[0])
  2636. {
  2637. case '=':
  2638. {
  2639. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2640. if (next[0] == ',')
  2641. {
  2642. lowValue = value;
  2643. next++;
  2644. if (*next != '\0')
  2645. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2646. }
  2647. else if (strncmp(next, "..", 2) == 0)
  2648. {
  2649. lowValue = value;
  2650. next += 2;
  2651. if (*next != '\0')
  2652. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2653. }
  2654. else
  2655. {
  2656. lowValue = value;
  2657. highValue = value;
  2658. }
  2659. break;
  2660. }
  2661. case '<':
  2662. if (op[1] == '=')
  2663. highValue = value;
  2664. else
  2665. highValue = value-1;
  2666. break;
  2667. case '>':
  2668. if (op[1] == '=')
  2669. lowValue = value;
  2670. else
  2671. lowValue = value+1;
  2672. break;
  2673. }
  2674. if (*next)
  2675. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2676. requiredStats.emplace_back(statKind, lowValue, highValue);
  2677. }
  2678. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2679. {
  2680. WuScopeSourceFlags mask = querySource(source);
  2681. if (mask == SSFunknown)
  2682. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2683. if (!mask)
  2684. sourceFlags = mask;
  2685. else
  2686. sourceFlags |= mask;
  2687. return *this;
  2688. }
  2689. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2690. {
  2691. scopeFilter.setDepth(low, high);
  2692. return *this;
  2693. }
  2694. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2695. {
  2696. //If there is a post filter on the scopeType, then check if it matches
  2697. if (include.scopeTypes.ordinality() == 1)
  2698. return (include.scopeTypes.item(0) == scopeType);
  2699. //If filter doesn't match nested items, then check if the scope filter matches.
  2700. if (include.nestedDepth == 0)
  2701. {
  2702. if (scopeFilter.matchOnly(scopeType))
  2703. return true;
  2704. }
  2705. return false;
  2706. }
  2707. //Called once the filter has been updated to optimize the filter
  2708. void WuScopeFilter::finishedFilter()
  2709. {
  2710. scopeFilter.finishedFilter();
  2711. assertex(!optimized);
  2712. optimized = true;
  2713. if ((include.nestedDepth == 0) && !include.matchedScope)
  2714. include.nestedDepth = UINT_MAX;
  2715. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2716. if (scopeFilter.canAlwaysPreFilter())
  2717. preFilterScope = true;
  2718. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2719. if (!sourceFlags)
  2720. {
  2721. sourceFlags = SSFsearchAll;
  2722. //Use the other options to reduce the number of elements that are searched.
  2723. //If not interested in scopes on their own then...
  2724. if (!(properties & PTscope))
  2725. {
  2726. //Global stats and graph stats only contain stats => remove if not interested in them
  2727. if (!(properties & PTstatistics))
  2728. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2729. //graph, workflow only contains attributes and hints => remove if not interested
  2730. if (!(properties & (PTattributes|PThints)))
  2731. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2732. }
  2733. if (!(properties & PTnotes))
  2734. sourceFlags &= ~SSFsearchExceptions;
  2735. }
  2736. //Optimize sources if they haven't been explicitly specified
  2737. //Most of the following are dependent on internal knowledge of the way that information is represented
  2738. if (matchOnly(SSTworkflow))
  2739. {
  2740. //Workflow is not nested within a graph
  2741. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2742. setDepth(1, 1);
  2743. }
  2744. else if (matchOnly(SSTgraph))
  2745. {
  2746. //Graph starts are stored globally, not in the graph stats.
  2747. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2748. if (!(properties & (PTattributes|PThints)))
  2749. sourceFlags &= ~(SSFsearchGraph);
  2750. setDepth(2, 2);
  2751. }
  2752. else if (matchOnly(SSTsubgraph))
  2753. {
  2754. sourceFlags &= ~(SSFsearchWorkflow);
  2755. }
  2756. else if (matchOnly(SSTcompilestage))
  2757. {
  2758. //compile stages are not stored in the graph
  2759. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2760. }
  2761. else if (matchOnly(SSTactivity))
  2762. {
  2763. //information about activities is not stored globally
  2764. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2765. }
  2766. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2767. if (include.nestedDepth == 0)
  2768. {
  2769. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2770. sourceFlags &= ~(SSFsearchGraphStats);
  2771. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2772. {
  2773. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2774. //then do not include the subgraph timings
  2775. if (desiredStats.ordinality())
  2776. {
  2777. bool needGraphStats = false;
  2778. ForEachItemIn(i, desiredStats)
  2779. {
  2780. unsigned stat = desiredStats.item(i);
  2781. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2782. needGraphStats = true;
  2783. }
  2784. if (!needGraphStats)
  2785. {
  2786. sourceFlags &= ~(SSFsearchGraphStats);
  2787. if (matchOnly(SSTsubgraph))
  2788. sourceFlags &= SSFsearchGlobalStats;
  2789. }
  2790. }
  2791. }
  2792. }
  2793. if (scopeFilter.compareDepth(1) < 0)
  2794. {
  2795. //If minimum match depth is > 1 then it will never match workflow
  2796. sourceFlags &= ~(SSFsearchWorkflow);
  2797. }
  2798. //The xml graph is never updated, so do not check it if minVersion != 0
  2799. if (minVersion != 0)
  2800. {
  2801. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2802. }
  2803. }
  2804. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2805. {
  2806. if (!(properties & PTstatistics))
  2807. return false;
  2808. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2809. return false;
  2810. if (desiredStats.empty())
  2811. return true;
  2812. return desiredStats.contains(kind);
  2813. }
  2814. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2815. {
  2816. if (!(properties & PTattributes))
  2817. return false;
  2818. if (desiredAttrs.empty())
  2819. return true;
  2820. return desiredAttrs.contains(attr);
  2821. }
  2822. bool WuScopeFilter::includeHint(const char * kind) const
  2823. {
  2824. if (!(properties & PThints))
  2825. return false;
  2826. if (desiredHints.empty())
  2827. return true;
  2828. return desiredHints.contains(kind);
  2829. }
  2830. bool WuScopeFilter::includeScope(const char * scope) const
  2831. {
  2832. if (include.scopeTypes)
  2833. {
  2834. const char * tail = queryScopeTail(scope);
  2835. StatsScopeId id(tail);
  2836. if (!include.scopeTypes.contains(id.queryScopeType()))
  2837. return false;
  2838. }
  2839. return true;
  2840. }
  2841. const static ScopeFilter nullScopeFilter {};
  2842. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2843. {
  2844. if (preFilterScope)
  2845. return scopeFilter;
  2846. else
  2847. return nullScopeFilter;
  2848. }
  2849. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2850. {
  2851. return scopeFilter.compare(scope);
  2852. }
  2853. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2854. {
  2855. scopeFilter.describe(out);
  2856. if (requiredStats.size())
  2857. {
  2858. out.append(",where[");
  2859. bool first = false;
  2860. for (const auto & stat : requiredStats)
  2861. {
  2862. if (!first)
  2863. out.append(",");
  2864. stat.describe(out);
  2865. first = false;
  2866. }
  2867. out.append("]");
  2868. }
  2869. {
  2870. StringBuffer sources;
  2871. for (unsigned mask=1; mask; mask *= 2)
  2872. {
  2873. if (sourceFlags & mask)
  2874. {
  2875. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2876. if (source)
  2877. sources.append(",").append(source);
  2878. }
  2879. }
  2880. if (sources)
  2881. out.append(",source[").append(sources.str()+1).append("]");
  2882. }
  2883. if (include.nestedDepth != UINT_MAX)
  2884. out.appendf(",nested[%u]", include.nestedDepth);
  2885. if (include.scopeTypes)
  2886. {
  2887. out.append(",include[");
  2888. ForEachItemIn(i, include.scopeTypes)
  2889. {
  2890. if (i)
  2891. out.append(",");
  2892. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  2893. }
  2894. out.append("]");
  2895. }
  2896. {
  2897. StringBuffer props;
  2898. if (properties == PTnone)
  2899. props.append(",none");
  2900. else if (properties == PTall)
  2901. props.append(",all");
  2902. else
  2903. {
  2904. if (properties & PTstatistics)
  2905. props.append(",stat");
  2906. if (properties & PTattributes)
  2907. props.append(",attr");
  2908. if (properties & PThints)
  2909. props.append(",hint");
  2910. if (properties & PTscope)
  2911. props.append(",scope");
  2912. if (properties & PTnotes)
  2913. props.append(",note");
  2914. }
  2915. out.append(",properties[").append(props.str()+1).append("]");
  2916. }
  2917. if (desiredStats)
  2918. {
  2919. out.append(",stat[");
  2920. ForEachItemIn(i, desiredStats)
  2921. {
  2922. if (i)
  2923. out.append(",");
  2924. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  2925. }
  2926. out.append("]");
  2927. }
  2928. if (desiredAttrs)
  2929. {
  2930. out.append(",attr[");
  2931. ForEachItemIn(i, desiredAttrs)
  2932. {
  2933. if (i)
  2934. out.append(",");
  2935. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  2936. }
  2937. out.append("]");
  2938. }
  2939. if (desiredHints)
  2940. {
  2941. out.append(",hint[");
  2942. ForEachItemIn(i, desiredHints)
  2943. {
  2944. if (i)
  2945. out.append(",");
  2946. out.append(desiredHints.item(i));
  2947. }
  2948. out.append("]");
  2949. }
  2950. if (desiredMeasure != SMeasureAll)
  2951. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  2952. if (minVersion != 0)
  2953. out.appendf(",version(%" I64F "u)", minVersion);
  2954. return out;
  2955. }
  2956. //--------------------------------------------------------------------------------------------------------------------
  2957. EnumMapping states[] = {
  2958. { WUStateUnknown, "unknown" },
  2959. { WUStateCompiled, "compiled" },
  2960. { WUStateRunning, "running" },
  2961. { WUStateCompleted, "completed" },
  2962. { WUStateFailed, "failed" },
  2963. { WUStateArchived, "archived" },
  2964. { WUStateAborting, "aborting" },
  2965. { WUStateAborted, "aborted" },
  2966. { WUStateBlocked, "blocked" },
  2967. { WUStateSubmitted, "submitted" },
  2968. { WUStateScheduled, "scheduled" },
  2969. { WUStateCompiling, "compiling" },
  2970. { WUStateWait, "wait" },
  2971. { WUStateUploadingFiles, "uploading_files" },
  2972. { WUStateDebugPaused, "debugging" },
  2973. { WUStateDebugRunning, "debug_running" },
  2974. { WUStatePaused, "paused" },
  2975. { WUStateSize, NULL }
  2976. };
  2977. EnumMapping actions[] = {
  2978. { WUActionUnknown, "unknown" },
  2979. { WUActionCompile, "compile" },
  2980. { WUActionCheck, "check" },
  2981. { WUActionRun, "run" },
  2982. { WUActionExecuteExisting, "execute" },
  2983. { WUActionPause, "pause" },
  2984. { WUActionPauseNow, "pausenow" },
  2985. { WUActionResume, "resume" },
  2986. { WUActionSize, NULL },
  2987. };
  2988. EnumMapping priorityClasses[] = {
  2989. { PriorityClassUnknown, "unknown" },
  2990. { PriorityClassLow, "low" },
  2991. { PriorityClassNormal, "normal" },
  2992. { PriorityClassHigh, "high" },
  2993. { PriorityClassSize, NULL },
  2994. };
  2995. const char * getWorkunitStateStr(WUState state)
  2996. {
  2997. dbgassertex(state < WUStateSize);
  2998. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  2999. }
  3000. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3001. {
  3002. const char *defval = map->str;
  3003. while (map->str)
  3004. {
  3005. if (value==map->val)
  3006. {
  3007. p->setProp(propname, map->str);
  3008. return;
  3009. }
  3010. map++;
  3011. }
  3012. assertex(!"Unexpected value in setEnum");
  3013. p->setProp(propname, defval);
  3014. }
  3015. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3016. {
  3017. return getEnum(p->queryProp(propname),map);
  3018. }
  3019. const char * getWorkunitActionStr(WUAction action)
  3020. {
  3021. return getEnumText(action, actions);
  3022. }
  3023. WUAction getWorkunitAction(const char *actionStr)
  3024. {
  3025. return (WUAction) getEnum(actionStr, actions);
  3026. }
  3027. //==========================================================================================
  3028. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3029. {
  3030. public:
  3031. CLightweightWorkunitInfo(IPropertyTree &p)
  3032. {
  3033. wuid.set(p.queryName());
  3034. user.set(p.queryProp("@submitID"));
  3035. jobName.set(p.queryProp("@jobName"));
  3036. clusterName.set(p.queryProp("@clusterName"));
  3037. timeScheduled.set(p.queryProp("@timeScheduled"));
  3038. state = (WUState) getEnum(&p, "@state", states);
  3039. action = (WUAction) getEnum(&p, "Action", actions);
  3040. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3041. priorityLevel = calcPriorityValue(&p);
  3042. wuscope.set(p.queryProp("@scope"));
  3043. appvalues.loadBranch(&p,"Application");
  3044. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3045. _isProtected = p.getPropBool("@protected", false);
  3046. }
  3047. virtual const char *queryWuid() const { return wuid.str(); }
  3048. virtual const char *queryUser() const { return user.str(); }
  3049. virtual const char *queryJobName() const { return jobName.str(); }
  3050. virtual const char *queryClusterName() const { return clusterName.str(); }
  3051. virtual const char *queryWuScope() const { return wuscope.str(); }
  3052. virtual WUState getState() const { return state; }
  3053. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3054. virtual WUAction getAction() const { return action; }
  3055. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3056. virtual WUPriorityClass getPriority() const { return priority; }
  3057. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3058. virtual int getPriorityLevel() const { return priorityLevel; }
  3059. virtual bool isProtected() const { return _isProtected; }
  3060. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3061. {
  3062. if (timeScheduled.length())
  3063. val.setGmtString(timeScheduled.str());
  3064. return val;
  3065. }
  3066. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3067. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3068. protected:
  3069. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3070. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3071. unsigned totalThorTime;
  3072. WUState state;
  3073. WUAction action;
  3074. WUPriorityClass priority;
  3075. int priorityLevel;
  3076. bool _isProtected;
  3077. };
  3078. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3079. {
  3080. return new CLightweightWorkunitInfo(p);
  3081. }
  3082. class CDaliWuGraphStats : public CWuGraphStats
  3083. {
  3084. public:
  3085. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3086. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3087. {
  3088. }
  3089. protected:
  3090. Owned<IRemoteConnection> conn;
  3091. };
  3092. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3093. {
  3094. abortId = 0;
  3095. stateId = 0;
  3096. actionId = 0;
  3097. assertex((flags & ~SubscribeOptionAbort) == 0);
  3098. if (flags & SubscribeOptionAbort)
  3099. {
  3100. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3101. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3102. }
  3103. }
  3104. CWorkUnitWatcher::~CWorkUnitWatcher()
  3105. {
  3106. assertex(abortId==0 && stateId==0 && actionId==0);
  3107. }
  3108. void CWorkUnitWatcher::unsubscribe()
  3109. {
  3110. CriticalBlock b(crit);
  3111. if (abortId)
  3112. querySDS().unsubscribe(abortId);
  3113. if (stateId)
  3114. querySDS().unsubscribe(stateId);
  3115. if (actionId)
  3116. querySDS().unsubscribe(actionId);
  3117. abortId = 0;
  3118. stateId = 0;
  3119. actionId = 0;
  3120. }
  3121. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3122. {
  3123. CriticalBlock b(crit);
  3124. if (id==stateId)
  3125. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3126. else if (id==actionId)
  3127. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3128. else if (id==abortId)
  3129. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3130. }
  3131. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3132. {
  3133. public:
  3134. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3135. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3136. {
  3137. if (flags & SubscribeOptionState)
  3138. {
  3139. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3140. stateId = querySDS().subscribe(xpath.str(), *this);
  3141. }
  3142. if (flags & SubscribeOptionAction)
  3143. {
  3144. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3145. actionId = querySDS().subscribe(xpath.str(), *this);
  3146. }
  3147. }
  3148. };
  3149. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3150. {
  3151. CriticalBlock block(crit);
  3152. assertex(options==SubscribeOptionAbort);
  3153. if (!abortWatcher)
  3154. {
  3155. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3156. abortDirty = true;
  3157. }
  3158. }
  3159. void CPersistedWorkUnit::unsubscribe()
  3160. {
  3161. CriticalBlock block(crit);
  3162. if (abortWatcher)
  3163. {
  3164. abortWatcher->unsubscribe();
  3165. abortWatcher.clear();
  3166. }
  3167. }
  3168. bool CPersistedWorkUnit::aborting() const
  3169. {
  3170. CriticalBlock block(crit);
  3171. if (abortDirty)
  3172. {
  3173. StringBuffer apath;
  3174. apath.append("/WorkUnitAborts/").append(p->queryName());
  3175. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3176. if (acon)
  3177. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3178. else
  3179. abortState = false;
  3180. abortDirty = false;
  3181. }
  3182. return abortState;
  3183. }
  3184. class CDaliWorkUnit : public CPersistedWorkUnit
  3185. {
  3186. public:
  3187. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3188. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3189. {
  3190. loadPTree(connection->getRoot());
  3191. }
  3192. ~CDaliWorkUnit()
  3193. {
  3194. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3195. // We use the beforeDispose() in base class to help ensure this
  3196. p.clear();
  3197. }
  3198. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3199. {
  3200. Owned<IRemoteConnection> conn = getProgressConnection();
  3201. if (conn)
  3202. {
  3203. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3204. if (progress)
  3205. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3206. }
  3207. return NULL;
  3208. }
  3209. virtual WUGraphState queryGraphState(const char *graphName) const
  3210. {
  3211. Owned<IRemoteConnection> conn = getProgressConnection();
  3212. if (conn)
  3213. {
  3214. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3215. if (progress)
  3216. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3217. }
  3218. return WUGraphUnknown;
  3219. }
  3220. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3221. {
  3222. Owned<IRemoteConnection> conn = getProgressConnection();
  3223. if (conn)
  3224. {
  3225. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3226. if (progress)
  3227. {
  3228. StringBuffer path;
  3229. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3230. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3231. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3232. }
  3233. }
  3234. return WUGraphUnknown;
  3235. }
  3236. virtual void clearGraphProgress() const
  3237. {
  3238. CriticalBlock block(crit);
  3239. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3240. StringBuffer path("/GraphProgress/");
  3241. path.append(p->queryName());
  3242. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3243. if (delconn)
  3244. delconn->close(true);
  3245. }
  3246. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3247. {
  3248. Owned<IRemoteConnection> conn = getProgressConnection();
  3249. if (!conn)
  3250. return false;
  3251. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3252. if (name)
  3253. {
  3254. graphName.set(name);
  3255. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3256. return true;
  3257. }
  3258. else
  3259. return false;
  3260. }
  3261. virtual void forceReload()
  3262. {
  3263. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3264. CriticalBlock block(crit);
  3265. clearCached(true);
  3266. connection->reload();
  3267. progressConnection.clear();
  3268. abortDirty = true;
  3269. p.setown(connection->getRoot());
  3270. }
  3271. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3272. {
  3273. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3274. clearGraphProgress();
  3275. connection->close(true);
  3276. connection.clear();
  3277. }
  3278. virtual void commit()
  3279. {
  3280. CPersistedWorkUnit::commit();
  3281. if (connection)
  3282. connection->commit();
  3283. }
  3284. virtual void _lockRemote()
  3285. {
  3286. StringBuffer wuRoot;
  3287. getXPath(wuRoot, p->queryName());
  3288. if (connection)
  3289. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3290. else
  3291. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3292. if (!connection)
  3293. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3294. clearCached(true);
  3295. p.setown(connection->getRoot());
  3296. }
  3297. virtual void _unlockRemote()
  3298. {
  3299. if (connection)
  3300. {
  3301. try
  3302. {
  3303. try
  3304. {
  3305. connection->commit();
  3306. }
  3307. catch (IException *e)
  3308. {
  3309. EXCLOG(e, "Error during workunit commit");
  3310. connection->rollback();
  3311. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3312. throw;
  3313. }
  3314. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3315. }
  3316. catch (IException *E)
  3317. {
  3318. StringBuffer s;
  3319. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3320. throw;
  3321. }
  3322. }
  3323. }
  3324. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3325. {
  3326. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3327. conn->queryRoot()->setPropInt("@_state", state);
  3328. }
  3329. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3330. {
  3331. CriticalBlock block(crit);
  3332. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3333. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3334. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3335. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3336. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3337. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3338. IPropertyTree *node = progress->queryPropTree(path.str());
  3339. if (!node)
  3340. {
  3341. node = progress->addPropTree("node");
  3342. node->setPropInt64("@id", nodeId);
  3343. }
  3344. node->setPropInt("@_state", (unsigned)state);
  3345. switch (state)
  3346. {
  3347. case WUGraphRunning:
  3348. {
  3349. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3350. running->setProp("@graph", graphName);
  3351. running->setPropInt64("@subId", nodeId);
  3352. break;
  3353. }
  3354. case WUGraphComplete:
  3355. {
  3356. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3357. break;
  3358. }
  3359. }
  3360. }
  3361. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3362. {
  3363. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3364. }
  3365. protected:
  3366. IRemoteConnection *getProgressConnection() const
  3367. {
  3368. CriticalBlock block(crit);
  3369. if (!progressConnection)
  3370. {
  3371. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3372. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3373. }
  3374. return progressConnection.getLink();
  3375. }
  3376. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3377. {
  3378. CriticalBlock block(crit);
  3379. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3380. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3381. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3382. IPropertyTree * root = conn->queryRoot();
  3383. assertex(wfid);
  3384. if (!root->hasProp("@wfid"))
  3385. {
  3386. root->setPropInt("@wfid", wfid);
  3387. }
  3388. else
  3389. {
  3390. //Ideally the following code would check that the wfids are passed consistently.
  3391. //However there is an obscure problem with out of line functions being called from multiple workflow
  3392. //ids, and possibly library graphs.
  3393. //Stats for library graphs should be nested below the library call activity
  3394. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3395. }
  3396. return conn.getClear();
  3397. }
  3398. IPropertyTree *getGraphProgressTree() const
  3399. {
  3400. Owned<IRemoteConnection> conn = getProgressConnection();
  3401. if (conn)
  3402. {
  3403. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3404. mergePTree(tmp,conn->queryRoot());
  3405. return tmp.getClear();
  3406. }
  3407. return NULL;
  3408. }
  3409. Owned<IRemoteConnection> connection;
  3410. mutable Owned<IRemoteConnection> progressConnection;
  3411. };
  3412. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3413. {
  3414. public:
  3415. Owned<CLocalWorkUnit> c;
  3416. IMPLEMENT_IINTERFACE;
  3417. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3418. ~CLockedWorkUnit()
  3419. {
  3420. if (workUnitTraceLevel > 1)
  3421. DBGLOG("Releasing locked workunit %s", queryWuid());
  3422. if (c)
  3423. c->unlockRemote();
  3424. }
  3425. virtual IConstWorkUnit * unlock()
  3426. {
  3427. c->unlockRemote();
  3428. return c.getClear();
  3429. }
  3430. virtual bool aborting() const
  3431. { return c->aborting(); }
  3432. virtual void forceReload()
  3433. { UNIMPLEMENTED; }
  3434. virtual WUAction getAction() const
  3435. { return c->getAction(); }
  3436. virtual const char *queryActionDesc() const
  3437. { return c->queryActionDesc(); }
  3438. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3439. { return c->getApplicationValue(application, propname, str); }
  3440. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3441. { return c->getApplicationValueInt(application, propname, defVal); }
  3442. virtual IConstWUAppValueIterator & getApplicationValues() const
  3443. { return c->getApplicationValues(); }
  3444. virtual bool hasWorkflow() const
  3445. { return c->hasWorkflow(); }
  3446. virtual unsigned queryEventScheduledCount() const
  3447. { return c->queryEventScheduledCount(); }
  3448. virtual IPropertyTree * queryWorkflowTree() const
  3449. { return c->queryWorkflowTree(); }
  3450. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3451. { return c->getWorkflowItems(); }
  3452. virtual IWorkflowItemArray * getWorkflowClone() const
  3453. { return c->getWorkflowClone(); }
  3454. virtual bool requiresLocalFileUpload() const
  3455. { return c->requiresLocalFileUpload(); }
  3456. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3457. { return c->getLocalFileUploads(); }
  3458. virtual bool getIsQueryService() const
  3459. { return c->getIsQueryService(); }
  3460. virtual bool getCloneable() const
  3461. { return c->getCloneable(); }
  3462. virtual IUserDescriptor * queryUserDescriptor() const
  3463. { return c->queryUserDescriptor(); }
  3464. virtual const char *queryClusterName() const
  3465. { return c->queryClusterName(); }
  3466. virtual unsigned getCodeVersion() const
  3467. { return c->getCodeVersion(); }
  3468. virtual unsigned getWuidVersion() const
  3469. { return c->getWuidVersion(); }
  3470. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3471. { c->getBuildVersion(buildVersion, eclVersion); }
  3472. virtual bool hasDebugValue(const char * propname) const
  3473. { return c->hasDebugValue(propname); }
  3474. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3475. { return c->getDebugValue(propname, str); }
  3476. virtual int getDebugValueInt(const char * propname, int defVal) const
  3477. { return c->getDebugValueInt(propname, defVal); }
  3478. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3479. { return c->getDebugValueInt64(propname, defVal); }
  3480. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3481. { return c->getDebugValueBool(propname, defVal); }
  3482. virtual IStringIterator & getDebugValues() const
  3483. { return c->getDebugValues(NULL); }
  3484. virtual IStringIterator & getDebugValues(const char *prop) const
  3485. { return c->getDebugValues(prop); }
  3486. virtual unsigned getExceptionCount() const
  3487. { return c->getExceptionCount(); }
  3488. virtual IConstWUExceptionIterator & getExceptions() const
  3489. { return c->getExceptions(); }
  3490. virtual unsigned getGraphCount() const
  3491. { return c->getGraphCount(); }
  3492. virtual unsigned getSourceFileCount() const
  3493. { return c->getSourceFileCount(); }
  3494. virtual unsigned getResultCount() const
  3495. { return c->getResultCount(); }
  3496. virtual unsigned getVariableCount() const
  3497. { return c->getVariableCount(); }
  3498. virtual unsigned getApplicationValueCount() const
  3499. { return c->getApplicationValueCount(); }
  3500. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3501. { return c->getGraphs(type); }
  3502. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3503. { return c->getGraphsMeta(type); }
  3504. virtual IConstWUGraph * getGraph(const char *name) const
  3505. { return c->getGraph(name); }
  3506. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3507. { return c->getGraphProgress(name); }
  3508. virtual const char *queryJobName() const
  3509. { return c->queryJobName(); }
  3510. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3511. { return c->getPluginByName(name); }
  3512. virtual IConstWUPluginIterator & getPlugins() const
  3513. { return c->getPlugins(); }
  3514. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3515. { return c->getLibraryByName(name); }
  3516. virtual IConstWULibraryIterator & getLibraries() const
  3517. { return c->getLibraries(); }
  3518. virtual WUPriorityClass getPriority() const
  3519. { return c->getPriority(); }
  3520. virtual const char *queryPriorityDesc() const
  3521. { return c->queryPriorityDesc(); }
  3522. virtual int getPriorityLevel() const
  3523. { return c->getPriorityLevel(); }
  3524. virtual int getPriorityValue() const
  3525. { return c->getPriorityValue(); }
  3526. virtual IConstWUQuery * getQuery() const
  3527. { return c->getQuery(); }
  3528. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3529. { return c->getWebServicesInfo(); }
  3530. virtual bool getRescheduleFlag() const
  3531. { return c->getRescheduleFlag(); }
  3532. virtual IConstWUResult * getResultByName(const char * name) const
  3533. { return c->getResultByName(name); }
  3534. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3535. { return c->getResultBySequence(seq); }
  3536. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3537. { return c->getQueryResultByName(name); }
  3538. virtual unsigned getResultLimit() const
  3539. { return c->getResultLimit(); }
  3540. virtual IConstWUResultIterator & getResults() const
  3541. { return c->getResults(); }
  3542. virtual IStringVal & getScope(IStringVal & str) const
  3543. { return c->getScope(str); }
  3544. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3545. { return c->getWorkunitDistributedAccessToken(str); }
  3546. virtual WUState getState() const
  3547. { return c->getState(); }
  3548. virtual IStringVal & getStateEx(IStringVal & str) const
  3549. { return c->getStateEx(str); }
  3550. virtual __int64 getAgentSession() const
  3551. { return c->getAgentSession(); }
  3552. virtual unsigned getAgentPID() const
  3553. { return c->getAgentPID(); }
  3554. virtual const char *queryStateDesc() const
  3555. { return c->queryStateDesc(); }
  3556. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3557. { return c->getRunningGraph(graphName, subId); }
  3558. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3559. { return c->getScopeIterator(filter); }
  3560. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3561. { return c->getStatistic(value, scope, kind); }
  3562. virtual IStringVal & getSnapshot(IStringVal & str) const
  3563. { return c->getSnapshot(str); }
  3564. virtual const char *queryUser() const
  3565. { return c->queryUser(); }
  3566. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3567. { return c->getWarningSeverity(code, defaultSeverity); }
  3568. virtual const char *queryWuScope() const
  3569. { return c->queryWuScope(); }
  3570. virtual const char *queryWuid() const
  3571. { return c->queryWuid(); }
  3572. virtual IConstWUResult * getGlobalByName(const char * name) const
  3573. { return c->getGlobalByName(name); }
  3574. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3575. { return c->getTemporaryByName(name); }
  3576. virtual IConstWUResultIterator & getTemporaries() const
  3577. { return c->getTemporaries(); }
  3578. virtual IConstWUResult * getVariableByName(const char * name) const
  3579. { return c->getVariableByName(name); }
  3580. virtual IConstWUResultIterator & getVariables() const
  3581. { return c->getVariables(); }
  3582. virtual bool isProtected() const
  3583. { return c->isProtected(); }
  3584. virtual bool isPausing() const
  3585. { return c->isPausing(); }
  3586. virtual IWorkUnit & lock()
  3587. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3588. virtual bool reload()
  3589. { UNIMPLEMENTED; }
  3590. virtual void subscribe(WUSubscribeOptions options)
  3591. { c->subscribe(options); }
  3592. virtual void requestAbort()
  3593. { c->requestAbort(); }
  3594. virtual unsigned calculateHash(unsigned prevHash)
  3595. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3596. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3597. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3598. virtual IPropertyTree *queryPTree() const
  3599. { return queryExtendedWU(c)->queryPTree(); }
  3600. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3601. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3602. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3603. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3604. virtual unsigned queryFileUsage(const char *filename) const
  3605. { return c->queryFileUsage(filename); }
  3606. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3607. { return c->getFieldUsage(); }
  3608. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3609. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3610. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3611. { return c->getTimeScheduled(val); }
  3612. virtual unsigned getDebugAgentListenerPort() const
  3613. { return c->getDebugAgentListenerPort(); }
  3614. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3615. { return c->getDebugAgentListenerIP(ip); }
  3616. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3617. { return c->getXmlParams(params, hidePasswords); }
  3618. virtual const IPropertyTree *getXmlParams() const
  3619. { return c->getXmlParams(); }
  3620. virtual unsigned __int64 getHash() const
  3621. { return c->getHash(); }
  3622. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3623. { return c->getLogs(type, instance); }
  3624. virtual IStringIterator *getProcesses(const char *type) const
  3625. { return c->getProcesses(type); }
  3626. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3627. { return c->getProcesses(type, instance); }
  3628. virtual unsigned getTotalThorTime() const
  3629. { return c->getTotalThorTime(); }
  3630. virtual WUGraphState queryGraphState(const char *graphName) const
  3631. { return c->queryGraphState(graphName); }
  3632. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3633. { return c->queryNodeState(graphName, nodeId); }
  3634. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3635. { c->setGraphState(graphName, wfid, state); }
  3636. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3637. { c->setNodeState(graphName, nodeId, state); }
  3638. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3639. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3640. virtual void clearGraphProgress() const
  3641. { c->clearGraphProgress(); }
  3642. virtual IStringVal & getAbortBy(IStringVal & str) const
  3643. { return c->getAbortBy(str); }
  3644. virtual unsigned __int64 getAbortTimeStamp() const
  3645. { return c->getAbortTimeStamp(); }
  3646. virtual void clearExceptions()
  3647. { c->clearExceptions(); }
  3648. virtual void commit()
  3649. { c->commit(); }
  3650. virtual IWUException * createException()
  3651. { return c->createException(); }
  3652. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3653. { c->addProcess(type, instance, pid, log); }
  3654. virtual void protect(bool protectMode)
  3655. { c->protect(protectMode); }
  3656. virtual void setAction(WUAction action)
  3657. { c->setAction(action); }
  3658. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3659. { c->setApplicationValue(application, propname, value, overwrite); }
  3660. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3661. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3662. virtual void incEventScheduledCount()
  3663. { c->incEventScheduledCount(); }
  3664. virtual void setIsQueryService(bool value)
  3665. { c->setIsQueryService(value); }
  3666. virtual void setCloneable(bool value)
  3667. { c->setCloneable(value); }
  3668. virtual void setIsClone(bool value)
  3669. { c->setIsClone(value); }
  3670. virtual void setClusterName(const char * value)
  3671. { c->setClusterName(value); }
  3672. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3673. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3674. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3675. { c->setDebugValue(propname, value, overwrite); }
  3676. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3677. { c->setDebugValueInt(propname, value, overwrite); }
  3678. virtual void setJobName(const char * value)
  3679. { c->setJobName(value); }
  3680. virtual void setPriority(WUPriorityClass cls)
  3681. { c->setPriority(cls); }
  3682. virtual void setPriorityLevel(int level)
  3683. { c->setPriorityLevel(level); }
  3684. virtual void setRescheduleFlag(bool value)
  3685. { c->setRescheduleFlag(value); }
  3686. virtual void setResultLimit(unsigned value)
  3687. { c->setResultLimit(value); }
  3688. virtual void setState(WUState state)
  3689. { c->setState(state); }
  3690. virtual void setStateEx(const char * text)
  3691. { c->setStateEx(text); }
  3692. virtual void setAgentSession(__int64 sessionId)
  3693. { c->setAgentSession(sessionId); }
  3694. 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)
  3695. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3696. virtual void setTracingValue(const char * propname, const char * value)
  3697. { c->setTracingValue(propname, value); }
  3698. virtual void setTracingValueInt(const char * propname, int value)
  3699. { c->setTracingValueInt(propname, value); }
  3700. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3701. { c->setTracingValueInt64(propname, value); }
  3702. virtual void setUser(const char * value)
  3703. { c->setUser(value); }
  3704. virtual void setWuScope(const char * value)
  3705. { c->setWuScope(value); }
  3706. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3707. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3708. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3709. { c->syncRuntimeWorkflow(array); }
  3710. virtual IWorkflowItemIterator * updateWorkflowItems()
  3711. { return c->updateWorkflowItems(); }
  3712. virtual void resetWorkflow()
  3713. { c->resetWorkflow(); }
  3714. virtual void schedule()
  3715. { c->schedule(); }
  3716. virtual void deschedule()
  3717. { c->deschedule(); }
  3718. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3719. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3720. virtual IWUResult * updateGlobalByName(const char * name)
  3721. { return c->updateGlobalByName(name); }
  3722. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3723. { c->createGraph(name, label, type, xgmml, wfid); }
  3724. virtual IWUQuery * updateQuery()
  3725. { return c->updateQuery(); }
  3726. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3727. { return c->updateWebServicesInfo(create); }
  3728. virtual IWUPlugin * updatePluginByName(const char * name)
  3729. { return c->updatePluginByName(name); }
  3730. virtual IWULibrary * updateLibraryByName(const char * name)
  3731. { return c->updateLibraryByName(name); }
  3732. virtual IWUResult * updateResultByName(const char * name)
  3733. { return c->updateResultByName(name); }
  3734. virtual IWUResult * updateResultBySequence(unsigned seq)
  3735. { return c->updateResultBySequence(seq); }
  3736. virtual IWUResult * updateTemporaryByName(const char * name)
  3737. { return c->updateTemporaryByName(name); }
  3738. virtual IWUResult * updateVariableByName(const char * name)
  3739. { return c->updateVariableByName(name); }
  3740. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3741. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3742. virtual void noteFileRead(IDistributedFile *file)
  3743. { c->noteFileRead(file); }
  3744. virtual void noteFieldUsage(IPropertyTree * usage)
  3745. { c->noteFieldUsage(usage); }
  3746. virtual void releaseFile(const char *fileName)
  3747. { c->releaseFile(fileName); }
  3748. virtual void resetBeforeGeneration()
  3749. { c->resetBeforeGeneration(); }
  3750. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3751. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3752. virtual void deleteTemporaries()
  3753. { c->deleteTemporaries(); }
  3754. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3755. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3756. virtual IPropertyTree * getDiskUsageStats()
  3757. { return c->getDiskUsageStats(); }
  3758. virtual IPropertyTreeIterator & getFileIterator() const
  3759. { return c->getFileIterator(); }
  3760. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3761. { return c->getFilesReadIterator(); }
  3762. virtual void setSnapshot(const char * value)
  3763. { c->setSnapshot(value); }
  3764. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3765. { c->setWarningSeverity(code, severity); }
  3766. virtual void setTimeScheduled(const IJlibDateTime &val)
  3767. { c->setTimeScheduled(val); }
  3768. virtual void setDebugAgentListenerPort(unsigned port)
  3769. { c->setDebugAgentListenerPort(port); }
  3770. virtual void setDebugAgentListenerIP(const char * ip)
  3771. { c->setDebugAgentListenerIP(ip); }
  3772. virtual void setXmlParams(const char *params)
  3773. { c->setXmlParams(params); }
  3774. virtual void setXmlParams(IPropertyTree *tree)
  3775. { c->setXmlParams(tree); }
  3776. virtual void setHash(unsigned __int64 hash)
  3777. { c->setHash(hash); }
  3778. // ILocalWorkUnit - used for debugging etc
  3779. virtual void serialize(MemoryBuffer &tgt)
  3780. { c->serialize(tgt); }
  3781. virtual void deserialize(MemoryBuffer &src)
  3782. { c->deserialize(src); }
  3783. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3784. { return c->switchThorQueue(cluster,qs); }
  3785. virtual void setAllowedClusters(const char *value)
  3786. { c->setAllowedClusters(value); }
  3787. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3788. { return c->getAllowedClusters(str); }
  3789. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3790. { c->remoteCheckAccess(user,writeaccess); }
  3791. virtual void setAllowAutoQueueSwitch(bool val)
  3792. { c->setAllowAutoQueueSwitch(val); }
  3793. virtual bool getAllowAutoQueueSwitch() const
  3794. { return c->getAllowAutoQueueSwitch(); }
  3795. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3796. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3797. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3798. { c->setResultInt(name, sequence, val); }
  3799. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3800. { c->setResultUInt(name, sequence, val); }
  3801. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3802. { c->setResultReal(name, sequence, val); }
  3803. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3804. { c->setResultVarString(stepname, sequence, val); }
  3805. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3806. { c->setResultVarUnicode(stepname, sequence, val); }
  3807. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3808. { c->setResultString(stepname, sequence, len, val); }
  3809. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3810. { c->setResultData(stepname, sequence, len, val); }
  3811. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3812. { c->setResultRaw(name, sequence, len, val); }
  3813. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3814. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3815. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3816. { c->setResultUnicode(name, sequence, len, val); }
  3817. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3818. { c->setResultBool(name, sequence, val); }
  3819. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3820. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3821. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3822. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3823. };
  3824. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3825. {
  3826. Owned<IPropertyTree> p;
  3827. public:
  3828. IMPLEMENT_IINTERFACE;
  3829. CLocalWUAssociated(IPropertyTree *p);
  3830. virtual WUFileType getType() const;
  3831. virtual IStringVal & getDescription(IStringVal & ret) const;
  3832. virtual IStringVal & getIp(IStringVal & ret) const;
  3833. virtual IStringVal & getName(IStringVal & ret) const;
  3834. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3835. virtual unsigned getCrc() const;
  3836. virtual unsigned getMinActivityId() const;
  3837. virtual unsigned getMaxActivityId() const;
  3838. };
  3839. class CLocalWUQuery : implements IWUQuery, public CInterface
  3840. {
  3841. Owned<IPropertyTree> p;
  3842. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3843. mutable CriticalSection crit;
  3844. mutable bool associatedCached;
  3845. private:
  3846. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3847. void loadAssociated() const;
  3848. public:
  3849. IMPLEMENT_IINTERFACE;
  3850. CLocalWUQuery(IPropertyTree *p);
  3851. virtual WUQueryType getQueryType() const;
  3852. virtual IStringVal& getQueryText(IStringVal &str) const;
  3853. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3854. virtual IStringVal& getQueryName(IStringVal &str) const;
  3855. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3856. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3857. virtual unsigned getQueryDllCrc() const;
  3858. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3859. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3860. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3861. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3862. virtual bool isArchive() const;
  3863. virtual bool hasArchive() const
  3864. {
  3865. return p->getPropBool("@hasArchive");
  3866. }
  3867. virtual void setQueryType(WUQueryType qt);
  3868. virtual void setQueryText(const char *pstr);
  3869. virtual void setQueryName(const char *);
  3870. virtual void setQueryMainDefinition(const char * str);
  3871. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  3872. virtual void removeAssociatedFiles();
  3873. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  3874. };
  3875. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  3876. {
  3877. Owned<IPropertyTree> p;
  3878. mutable CriticalSection crit;
  3879. private:
  3880. public:
  3881. IMPLEMENT_IINTERFACE;
  3882. CLocalWUWebServicesInfo(IPropertyTree *p);
  3883. virtual IStringVal& getModuleName(IStringVal &str) const;
  3884. virtual IStringVal& getAttributeName(IStringVal &str) const;
  3885. virtual IStringVal& getDefaultName(IStringVal &str) const;
  3886. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  3887. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  3888. virtual unsigned getWebServicesCRC() const;
  3889. virtual void setModuleName(const char *);
  3890. virtual void setAttributeName(const char *);
  3891. virtual void setDefaultName(const char *);
  3892. virtual void setInfo(const char *name, const char *info);
  3893. virtual void setText(const char *name, const char *info);
  3894. virtual void setWebServicesCRC(unsigned);
  3895. };
  3896. class CLocalWUResult : implements IWUResult, public CInterface
  3897. {
  3898. friend class CLocalWorkUnit;
  3899. mutable CriticalSection crit;
  3900. Owned<IPropertyTree> p;
  3901. Owned<IProperties> xmlns;
  3902. public:
  3903. IMPLEMENT_IINTERFACE;
  3904. CLocalWUResult(IPropertyTree *props);
  3905. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  3906. virtual WUResultStatus getResultStatus() const;
  3907. virtual IStringVal& getResultName(IStringVal &str) const;
  3908. virtual int getResultSequence() const;
  3909. virtual bool isResultScalar() const;
  3910. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  3911. virtual unsigned getResultFetchSize() const;
  3912. virtual __int64 getResultTotalRowCount() const;
  3913. virtual __int64 getResultRowCount() const;
  3914. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  3915. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  3916. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  3917. virtual unsigned getResultRequestedRows() const;
  3918. virtual __int64 getResultInt() const;
  3919. virtual bool getResultBool() const;
  3920. virtual double getResultReal() const;
  3921. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  3922. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3923. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  3924. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  3925. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  3926. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3927. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3928. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  3929. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  3930. virtual __int64 getResultRowLimit() const;
  3931. virtual IStringVal& getResultFilename(IStringVal & str) const;
  3932. virtual WUResultFormat getResultFormat() const;
  3933. virtual unsigned getResultHash() const;
  3934. virtual bool getResultIsAll() const;
  3935. virtual IProperties *queryResultXmlns();
  3936. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  3937. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  3938. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  3939. // interface IWUResult
  3940. virtual void setResultStatus(WUResultStatus status);
  3941. virtual void setResultName(const char *name);
  3942. virtual void setResultSequence(unsigned seq);
  3943. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  3944. virtual void setResultScalar(bool isScalar);
  3945. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  3946. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  3947. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  3948. virtual void setResultRowCount(__int64 rows);
  3949. virtual void setResultDataset(const char *ecl, const char *defs);
  3950. virtual void setResultLogicalName(const char *logicalName);
  3951. virtual void setResultKeyField(const char * name);
  3952. virtual void setResultRequestedRows(unsigned req);
  3953. virtual void setResultRecordSizeEntry(const char * val);
  3954. virtual void setResultTransformerEntry(const char * val);
  3955. virtual void setResultInt(__int64 val);
  3956. virtual void setResultReal(double val);
  3957. virtual void setResultBool(bool val);
  3958. virtual void setResultString(const char * val, unsigned length);
  3959. virtual void setResultUnicode(const void * val, unsigned length);
  3960. virtual void setResultData(const void * val, unsigned length);
  3961. virtual void setResultDecimal(const void * val, unsigned length);
  3962. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  3963. virtual void setResultRowLimit(__int64 value);
  3964. virtual void setResultFilename(const char * name);
  3965. virtual void setResultUInt(unsigned __int64 val);
  3966. virtual void setResultIsAll(bool value);
  3967. virtual void setResultFormat(WUResultFormat format);
  3968. virtual void setResultXML(const char *val);
  3969. virtual void setResultRow(unsigned len, const void * data);
  3970. virtual void setResultXmlns(const char *prefix, const char *uri);
  3971. virtual void setResultFieldOpt(const char *name, const char *value);
  3972. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  3973. virtual IPropertyTree *queryPTree() { return p; }
  3974. };
  3975. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  3976. {
  3977. Owned<IPropertyTree> p;
  3978. public:
  3979. IMPLEMENT_IINTERFACE;
  3980. CLocalWUPlugin(IPropertyTree *p);
  3981. virtual IStringVal& getPluginName(IStringVal &str) const;
  3982. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  3983. virtual void setPluginName(const char *str);
  3984. virtual void setPluginVersion(const char *str);
  3985. };
  3986. class CLocalWULibrary : implements IWULibrary, public CInterface
  3987. {
  3988. Owned<IPropertyTree> p;
  3989. public:
  3990. IMPLEMENT_IINTERFACE;
  3991. CLocalWULibrary(IPropertyTree *p);
  3992. virtual IStringVal & getName(IStringVal & str) const;
  3993. virtual void setName(const char * str);
  3994. };
  3995. class CLocalWUException : implements IWUException, public CInterface
  3996. {
  3997. Owned<IPropertyTree> p;
  3998. public:
  3999. IMPLEMENT_IINTERFACE;
  4000. CLocalWUException(IPropertyTree *p);
  4001. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4002. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4003. virtual unsigned getExceptionCode() const override;
  4004. virtual ErrorSeverity getSeverity() const override;
  4005. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4006. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4007. virtual unsigned getExceptionLineNo() const override;
  4008. virtual unsigned getExceptionColumn() const override;
  4009. virtual unsigned getActivityId() const override;
  4010. virtual unsigned getSequence() const override;
  4011. virtual const char * queryScope() const override;
  4012. virtual unsigned getPriority() const override;
  4013. virtual void setExceptionSource(const char *str) override;
  4014. virtual void setExceptionMessage(const char *str) override;
  4015. virtual void setExceptionCode(unsigned code) override;
  4016. virtual void setSeverity(ErrorSeverity level) override;
  4017. virtual void setTimeStamp(const char * dt) override;
  4018. virtual void setExceptionFileName(const char *str) override;
  4019. virtual void setExceptionLineNo(unsigned r) override;
  4020. virtual void setExceptionColumn(unsigned c) override;
  4021. virtual void setActivityId(unsigned _id) override;
  4022. virtual void setScope(const char * _scope) override;
  4023. virtual void setPriority(unsigned _priority) override;
  4024. };
  4025. //==========================================================================================
  4026. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4027. {
  4028. switch ((int) sequence)
  4029. {
  4030. case ResultSequenceInternal:
  4031. case ResultSequenceOnce:
  4032. case ResultSequencePersist:
  4033. case ResultSequenceStored:
  4034. return true;
  4035. default:
  4036. assertex(sequence <= INT_MAX);
  4037. if ((int) sequence >= LibraryBaseSequence)
  4038. return true;
  4039. return false;
  4040. }
  4041. }
  4042. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4043. {
  4044. unsigned curTreeNum;
  4045. IArrayOf<IPropertyTree> trees;
  4046. Owned<IConstWorkUnitInfo> cur;
  4047. void setCurrent()
  4048. {
  4049. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4050. }
  4051. public:
  4052. IMPLEMENT_IINTERFACE;
  4053. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4054. {
  4055. ForEachItemIn(t, _trees)
  4056. trees.append(*LINK(&_trees.item(t)));
  4057. curTreeNum = 0;
  4058. }
  4059. bool first()
  4060. {
  4061. curTreeNum = 0;
  4062. return next();
  4063. }
  4064. bool isValid()
  4065. {
  4066. return (NULL != cur.get());
  4067. }
  4068. bool next()
  4069. {
  4070. if (curTreeNum >= trees.ordinality())
  4071. {
  4072. cur.clear();
  4073. return false;
  4074. }
  4075. setCurrent();
  4076. ++curTreeNum;
  4077. return true;
  4078. }
  4079. IConstWorkUnitInfo & query() { return *cur; }
  4080. };
  4081. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4082. {
  4083. Owned<IPropertyTree> p;
  4084. public:
  4085. IMPLEMENT_IINTERFACE;
  4086. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4087. virtual const char * queryName() const { return p->queryProp("@name"); }
  4088. };
  4089. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4090. {
  4091. public:
  4092. IMPLEMENT_IINTERFACE;
  4093. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4094. bool first() override { return iter->first(); }
  4095. bool isValid() override { return iter->isValid(); }
  4096. bool next() override { return iter->next(); }
  4097. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4098. private:
  4099. Owned<IPropertyTreeIterator> iter;
  4100. };
  4101. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4102. {
  4103. Owned<IPropertyTree> p;
  4104. public:
  4105. IMPLEMENT_IINTERFACE;
  4106. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4107. virtual const char * queryName() const { return p->queryProp("@name"); }
  4108. virtual const char * queryType() const { return p->queryProp("@type"); }
  4109. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4110. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4111. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4112. };
  4113. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4114. {
  4115. public:
  4116. IMPLEMENT_IINTERFACE;
  4117. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4118. bool first() override { return iter->first(); }
  4119. bool isValid() override { return iter->isValid(); }
  4120. bool next() override { return iter->next(); }
  4121. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4122. private:
  4123. Owned<IPropertyTreeIterator> iter;
  4124. };
  4125. //==========================================================================================
  4126. class CStringArrayIterator : implements IStringIterator, public CInterface
  4127. {
  4128. unsigned idx;
  4129. StringArray strings;
  4130. public:
  4131. IMPLEMENT_IINTERFACE;
  4132. CStringArrayIterator() { idx = 0; };
  4133. void append(const char *str) { strings.append(str); }
  4134. virtual bool first() { idx = 0; return strings.isItem(idx); }
  4135. virtual bool next() { idx ++; return strings.isItem(idx); }
  4136. virtual bool isValid() { return strings.isItem(idx); }
  4137. virtual IStringVal & str(IStringVal &s) { s.set(strings.item(idx)); return s; }
  4138. };
  4139. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4140. {
  4141. Owned<IPropertyTreeIterator> it;
  4142. public:
  4143. IMPLEMENT_IINTERFACE;
  4144. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4145. virtual bool first() { return it->first(); }
  4146. virtual bool next() { return it->next(); }
  4147. virtual bool isValid() { return it->isValid(); }
  4148. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4149. };
  4150. class CEmptyStringIterator : implements IStringIterator, public CInterface
  4151. {
  4152. public:
  4153. IMPLEMENT_IINTERFACE;
  4154. virtual bool first() { return false; }
  4155. virtual bool next() { return false; }
  4156. virtual bool isValid() { return false; }
  4157. virtual IStringVal & str(IStringVal &s) { s.clear(); return s; }
  4158. };
  4159. EnumMapping workunitSortFields[] =
  4160. {
  4161. { WUSFuser, "@submitID" },
  4162. { WUSFcluster, "@clusterName" },
  4163. { WUSFjob, "@jobName" },
  4164. { WUSFstate, "@state" },
  4165. { WUSFpriority, "@priorityClass" },
  4166. { WUSFprotected, "@protected" },
  4167. { WUSFwuid, "@" },
  4168. { WUSFecl, "Query/ShortText" },
  4169. { WUSFfileread, "FilesRead/File/@name" },
  4170. { WUSFtotalthortime, "@totalThorTime|"
  4171. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4172. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4173. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4174. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4175. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4176. },
  4177. { WUSFwuidhigh, "@" },
  4178. { WUSFwildwuid, "@" },
  4179. { WUSFappvalue, "Application" },
  4180. { WUSFfilewritten, "Files/File/@name" },
  4181. { WUSFterm, NULL }
  4182. };
  4183. extern const char *queryFilterXPath(WUSortField field)
  4184. {
  4185. return getEnumText(field, workunitSortFields);
  4186. }
  4187. EnumMapping querySortFields[] =
  4188. {
  4189. { WUQSFId, "@id" },
  4190. { WUQSFwuid, "@wuid" },
  4191. { WUQSFname, "@name" },
  4192. { WUQSFdll, "@dll" },
  4193. { WUQSFmemoryLimit, "@memoryLimit" },
  4194. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4195. { WUQSFtimeLimit, "@timeLimit" },
  4196. { WUQSFtimeLimitHi, "@timeLimit" },
  4197. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4198. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4199. { WUQSFpriority, "@priority" },
  4200. { WUQSFpriorityHi, "@priority" },
  4201. { WUQSFQuerySet, "@querySetId" },
  4202. { WUQSFActivited, "@activated" },
  4203. { WUQSFSuspendedByUser, "@suspended" },
  4204. { WUQSFLibrary, "Library"},
  4205. { WUQSFPublishedBy, "@publishedBy" },
  4206. { WUQSFterm, NULL }
  4207. };
  4208. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4209. {
  4210. StringAttr name;
  4211. public:
  4212. IMPLEMENT_IINTERFACE;
  4213. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4214. {
  4215. }
  4216. void execute()
  4217. {
  4218. PROGLOG("WU removeDll %s", name.get());
  4219. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4220. }
  4221. };
  4222. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4223. {
  4224. RemoteFilename name;
  4225. public:
  4226. IMPLEMENT_IINTERFACE;
  4227. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4228. {
  4229. SocketEndpoint ep(_ip);
  4230. name.setPath(ep, _name);
  4231. }
  4232. void execute()
  4233. {
  4234. Owned<IFile> file = createIFile(name);
  4235. PROGLOG("WU removeDll %s",file->queryFilename());
  4236. file->remove();
  4237. }
  4238. };
  4239. //==========================================================================================
  4240. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4241. {
  4242. unsigned index;
  4243. IArrayOf<IPropertyTree> trees;
  4244. public:
  4245. IMPLEMENT_IINTERFACE;
  4246. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4247. {
  4248. ForEachItemIn(t, _trees)
  4249. trees.append(*LINK(&_trees.item(t)));
  4250. index = 0;
  4251. }
  4252. ~CConstQuerySetQueryIterator()
  4253. {
  4254. trees.kill();
  4255. }
  4256. bool first()
  4257. {
  4258. index = 0;
  4259. return (trees.ordinality()!=0);
  4260. }
  4261. bool next()
  4262. {
  4263. index++;
  4264. return (index<trees.ordinality());
  4265. }
  4266. bool isValid()
  4267. {
  4268. return (index<trees.ordinality());
  4269. }
  4270. IPropertyTree &query()
  4271. {
  4272. return trees.item(index);
  4273. }
  4274. };
  4275. class CSecurityCache
  4276. {
  4277. };
  4278. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4279. {
  4280. public:
  4281. IMPLEMENT_IINTERFACE;
  4282. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4283. : ptreeIter(_ptreeIter)
  4284. {
  4285. }
  4286. bool first()
  4287. {
  4288. if (!ptreeIter->first())
  4289. {
  4290. cur.clear();
  4291. return false;
  4292. }
  4293. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4294. return true;
  4295. }
  4296. bool isValid()
  4297. {
  4298. return (NULL != cur.get());
  4299. }
  4300. bool next()
  4301. {
  4302. if (!ptreeIter->next())
  4303. {
  4304. cur.clear();
  4305. return false;
  4306. }
  4307. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4308. return true;
  4309. }
  4310. IConstWorkUnitInfo & query() { return *cur; }
  4311. private:
  4312. Owned<IConstWorkUnitInfo> cur;
  4313. Owned<IPropertyTreeIterator> ptreeIter;
  4314. };
  4315. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4316. {
  4317. public:
  4318. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4319. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4320. {
  4321. assertex(_secuser && _secmgr);
  4322. }
  4323. bool first()
  4324. {
  4325. if (!parent->first())
  4326. return false;
  4327. return getNext();
  4328. }
  4329. bool next()
  4330. {
  4331. if (!parent->next())
  4332. return false;
  4333. return getNext();
  4334. }
  4335. virtual bool isValid()
  4336. {
  4337. return parent->isValid();
  4338. }
  4339. virtual IConstWorkUnitInfo &query()
  4340. {
  4341. return parent->query();
  4342. }
  4343. private:
  4344. Owned<IConstWorkUnitIterator> parent;
  4345. MapStringTo<int> scopePermissions;
  4346. Linked<ISecManager> secmgr;
  4347. Linked<ISecUser> secuser;
  4348. bool getNext() // scan for a workunit with permissions
  4349. {
  4350. do
  4351. {
  4352. const char *scopeName = parent->query().queryWuScope();
  4353. if (!scopeName || !*scopeName || checkScope(scopeName))
  4354. return true;
  4355. } while (parent->next());
  4356. return false;
  4357. }
  4358. bool checkScope(const char *scopeName)
  4359. {
  4360. int *perms = scopePermissions.getValue(scopeName);
  4361. SecAccessFlags perm;
  4362. if (!perms)
  4363. {
  4364. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4365. scopePermissions.setValue(scopeName, perm);
  4366. }
  4367. else
  4368. perm = (SecAccessFlags)*perms;
  4369. return perm >= SecAccess_Read;
  4370. }
  4371. };
  4372. CWorkUnitFactory::CWorkUnitFactory()
  4373. {
  4374. }
  4375. CWorkUnitFactory::~CWorkUnitFactory()
  4376. {
  4377. }
  4378. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4379. {
  4380. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4381. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4382. if (scope)
  4383. 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...
  4384. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4385. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4386. ret->setDebugValue("CREATED_BY", app, true);
  4387. ret->setDebugValue("CREATED_FOR", scope, true);
  4388. return ret;
  4389. }
  4390. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4391. {
  4392. StringBuffer wuid("W");
  4393. char result[32];
  4394. time_t ltime;
  4395. time( &ltime );
  4396. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4397. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4398. wuid.append(result);
  4399. if (workUnitTraceLevel > 1)
  4400. DBGLOG("createWorkUnit created %s", wuid.str());
  4401. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4402. if (workUnitTraceLevel > 1)
  4403. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4404. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4405. return ret;
  4406. }
  4407. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4408. {
  4409. if (workUnitTraceLevel > 1)
  4410. DBGLOG("deleteWorkUnit %s", wuid);
  4411. StringBuffer wuRoot;
  4412. getXPath(wuRoot, wuid);
  4413. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4414. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4415. return false;
  4416. if (throwException)
  4417. cw->cleanupAndDelete(true, true);
  4418. else
  4419. {
  4420. try
  4421. {
  4422. cw->cleanupAndDelete(true, true);
  4423. }
  4424. catch (IException *E)
  4425. {
  4426. StringBuffer s;
  4427. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4428. E->Release();
  4429. return false;
  4430. }
  4431. }
  4432. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4433. return true;
  4434. }
  4435. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4436. {
  4437. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4438. }
  4439. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4440. {
  4441. StringBuffer wuidStr(wuid);
  4442. wuidStr.trim();
  4443. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4444. wuidStr.setCharAt(0, 'W');
  4445. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4446. {
  4447. if (workUnitTraceLevel > 1)
  4448. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4449. return NULL;
  4450. }
  4451. if (workUnitTraceLevel > 1)
  4452. DBGLOG("openWorkUnit %s", wuidStr.str());
  4453. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4454. if (wu)
  4455. {
  4456. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4457. return NULL; // Actually throws exception on failure, so won't reach here
  4458. return wu.getClear();
  4459. }
  4460. else
  4461. {
  4462. if (workUnitTraceLevel > 0)
  4463. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4464. return NULL;
  4465. }
  4466. }
  4467. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4468. {
  4469. if (workUnitTraceLevel > 1)
  4470. DBGLOG("updateWorkUnit %s", wuid);
  4471. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4472. if (wu)
  4473. {
  4474. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4475. return NULL;
  4476. return &wu->lockRemote(false);
  4477. }
  4478. else
  4479. {
  4480. if (workUnitTraceLevel > 0)
  4481. IERRLOG("updateWorkUnit %s not found", wuid);
  4482. return NULL;
  4483. }
  4484. }
  4485. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4486. {
  4487. Owned<IPropertyTree> ret;
  4488. IPropertyTree * branch = from->queryPropTree(xpath);
  4489. if(branch)
  4490. {
  4491. ret.setown(createPTreeFromIPT(branch));
  4492. from->removeTree(branch);
  4493. }
  4494. return ret.getClear();
  4495. }
  4496. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4497. {
  4498. StringBuffer path(base);
  4499. addPathSepChar(path).append(wuid).append(".xml");
  4500. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4501. if (!pt)
  4502. return false;
  4503. CDateTime dt;
  4504. dt.setNow();
  4505. StringBuffer dts;
  4506. dt.getString(dts);
  4507. pt->setProp("@restoredDate", dts.str());
  4508. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4509. Owned<IPropertyTree> associatedFiles;
  4510. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4511. if (srcAssociated)
  4512. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4513. // The updating of the repo is implementation specific...
  4514. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4515. return false;
  4516. // now kludge back GeneratedDlls
  4517. if (generatedDlls)
  4518. {
  4519. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4520. for(dlls->first(); dlls->isValid(); dlls->next())
  4521. {
  4522. IPropertyTree & dll = dlls->query();
  4523. char const * name = dll.queryProp("@name");
  4524. char const * kind = dll.queryProp("@kind");
  4525. char const * location = dll.queryProp("@location");
  4526. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4527. if (!got)
  4528. {
  4529. RemoteFilename dstRfn;
  4530. dstRfn.setRemotePath(location);
  4531. StringBuffer srcPath(base);
  4532. addPathSepChar(srcPath);
  4533. dstRfn.getTail(srcPath);
  4534. OwnedIFile srcFile = createIFile(srcPath);
  4535. OwnedIFile dstFile = createIFile(dstRfn);
  4536. copyFile(dstFile, srcFile);
  4537. queryDllServer().registerDll(name, kind, location);
  4538. }
  4539. }
  4540. }
  4541. if (associatedFiles)
  4542. {
  4543. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4544. ForEach(*associated)
  4545. {
  4546. IPropertyTree &file = associated->query();
  4547. const char *filename = file.queryProp("@filename");
  4548. SocketEndpoint ep(file.queryProp("@ip"));
  4549. RemoteFilename rfn;
  4550. rfn.setPath(ep, filename);
  4551. OwnedIFile dstFile = createIFile(rfn);
  4552. StringBuffer srcPath(base), name;
  4553. addPathSepChar(srcPath);
  4554. rfn.getTail(name);
  4555. srcPath.append(name);
  4556. if (generatedDlls)
  4557. {
  4558. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4559. if (generatedDlls->hasProp(gDllPath))
  4560. continue; // generated dlls handled separately - see above
  4561. }
  4562. OwnedIFile srcFile = createIFile(srcPath);
  4563. if (srcFile->exists())
  4564. {
  4565. try
  4566. {
  4567. copyFile(dstFile, srcFile);
  4568. }
  4569. catch (IException *e)
  4570. {
  4571. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4572. EXCLOG(e, msg.str());
  4573. e->Release();
  4574. }
  4575. }
  4576. }
  4577. }
  4578. return true;
  4579. }
  4580. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4581. {
  4582. if (newLevel)
  4583. DBGLOG("Setting workunit trace level to %d", newLevel);
  4584. int level = workUnitTraceLevel;
  4585. workUnitTraceLevel = newLevel;
  4586. return level;
  4587. }
  4588. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4589. {
  4590. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4591. if(!conn) return;
  4592. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4593. KeptAtomTable entries;
  4594. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4595. StringBuffer wuid;
  4596. for(iter->first(); iter->isValid(); iter->next())
  4597. {
  4598. char const * entry = iter->query().queryName();
  4599. if(!entries.find(entry))
  4600. {
  4601. entries.addAtom(entry);
  4602. ncnameUnescape(entry, wuid.clear());
  4603. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4604. if(wu && (wu->getState() == WUStateWait))
  4605. wu->setState(WUStateCompleted);
  4606. }
  4607. }
  4608. bool more;
  4609. do more = root->removeProp("*"); while(more);
  4610. }
  4611. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4612. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4613. const void *filterbuf, // (appended) string values for filters
  4614. unsigned startoffset,
  4615. unsigned maxnum,
  4616. __int64 *cachehint,
  4617. unsigned *total,
  4618. const MapStringTo<bool> *_subset)
  4619. {
  4620. struct PostFilters
  4621. {
  4622. WUQueryFilterBoolean activatedFilter;
  4623. WUQueryFilterBoolean suspendedByUserFilter;
  4624. PostFilters()
  4625. {
  4626. activatedFilter = WUQFSAll;
  4627. suspendedByUserFilter = WUQFSAll;
  4628. };
  4629. } postFilters;
  4630. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4631. {
  4632. StringAttr querySet;
  4633. StringAttr xPath;
  4634. StringAttr sortOrder;
  4635. PostFilters postFilters;
  4636. StringArray unknownAttributes;
  4637. const MapStringTo<bool> *subset;
  4638. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4639. {
  4640. const char* querySetId = querySetTree->queryProp("@id");
  4641. VStringBuffer path("Query%s", xPath.get());
  4642. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4643. ForEach(*iter)
  4644. {
  4645. IPropertyTree &query = iter->query();
  4646. bool activated = false;
  4647. const char* queryId = query.queryProp("@id");
  4648. if (queryId && *queryId)
  4649. {
  4650. if (subset)
  4651. {
  4652. VStringBuffer match("%s/%s", querySetId, queryId);
  4653. if (!subset->getValue(match))
  4654. continue;
  4655. }
  4656. VStringBuffer aliasXPath("Alias[@id='%s']", queryId);
  4657. IPropertyTree *alias = querySetTree->queryPropTree(aliasXPath.str());
  4658. if (alias)
  4659. activated = true;
  4660. }
  4661. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4662. continue;
  4663. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4664. continue;
  4665. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4666. continue;
  4667. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4668. continue;
  4669. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4670. queryWithSetId->setProp("@querySetId", querySetId);
  4671. queryWithSetId->setPropBool("@activated", activated);
  4672. }
  4673. }
  4674. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4675. {
  4676. StringBuffer querySetXPath("QuerySets");
  4677. if (!querySet.isEmpty())
  4678. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4679. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4680. if (!conn)
  4681. return NULL;
  4682. if (querySet.isEmpty())
  4683. {
  4684. Owned<IPropertyTreeIterator> querySetIter = conn->queryRoot()->getElements("*");
  4685. ForEach(*querySetIter)
  4686. populateQueryTree(&querySetIter->query(), queryTree);
  4687. }
  4688. else
  4689. populateQueryTree(conn->queryRoot(), queryTree);
  4690. return conn.getClear();
  4691. }
  4692. public:
  4693. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4694. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  4695. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  4696. {
  4697. postFilters.activatedFilter = _postFilters.activatedFilter;
  4698. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  4699. ForEachItemIn(x, _unknownAttributes)
  4700. unknownAttributes.append(_unknownAttributes.item(x));
  4701. }
  4702. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4703. {
  4704. Owned<IPropertyTree> elementTree = createPTree("Queries");
  4705. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  4706. if (!conn)
  4707. return NULL;
  4708. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  4709. if (!iter)
  4710. return NULL;
  4711. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  4712. return conn.getClear();
  4713. }
  4714. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  4715. };
  4716. StringAttr querySet;
  4717. StringBuffer xPath;
  4718. StringBuffer so;
  4719. StringArray unknownAttributes;
  4720. if (filters)
  4721. {
  4722. const char *fv = (const char *)filterbuf;
  4723. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  4724. int fmt = filters[i];
  4725. int subfmt = (fmt&0xff);
  4726. if (subfmt==WUQSFQuerySet)
  4727. querySet.set(fv);
  4728. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  4729. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  4730. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  4731. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  4732. else if (subfmt==WUQSFActivited)
  4733. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  4734. else if (subfmt==WUQSFSuspendedByUser)
  4735. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  4736. else if (!fv || !*fv)
  4737. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  4738. else {
  4739. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  4740. if (fmt&WUQSFnocase)
  4741. xPath.append('?');
  4742. if (fmt&WUQSFnumeric)
  4743. xPath.append('#');
  4744. if (fmt&WUQSFwild)
  4745. xPath.append('~');
  4746. xPath.append('"').append(fv).append("\"]");
  4747. }
  4748. fv = fv + strlen(fv)+1;
  4749. }
  4750. }
  4751. if (sortorder) {
  4752. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  4753. if (so.length())
  4754. so.append(',');
  4755. int fmt = sortorder[i];
  4756. if (fmt&WUQSFreverse)
  4757. so.append('-');
  4758. if (fmt&WUQSFnocase)
  4759. so.append('?');
  4760. if (fmt&WUQSFnumeric)
  4761. so.append('#');
  4762. so.append(getEnumText(fmt&0xff,querySortFields));
  4763. }
  4764. }
  4765. IArrayOf<IPropertyTree> results;
  4766. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  4767. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  4768. return new CConstQuerySetQueryIterator(results);
  4769. }
  4770. bool CWorkUnitFactory::isAborting(const char *wuid) const
  4771. {
  4772. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4773. try
  4774. {
  4775. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4776. if (acon)
  4777. return acon->queryRoot()->getPropInt(NULL) != 0;
  4778. }
  4779. catch (IException *E)
  4780. {
  4781. EXCLOG(E);
  4782. E->Release();
  4783. }
  4784. return false;
  4785. }
  4786. void CWorkUnitFactory::clearAborting(const char *wuid)
  4787. {
  4788. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4789. try
  4790. {
  4791. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4792. if (acon)
  4793. acon->close(true);
  4794. }
  4795. catch (IException *E)
  4796. {
  4797. EXCLOG(E);
  4798. E->Release();
  4799. }
  4800. }
  4801. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  4802. {
  4803. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  4804. bool isEcl = false;
  4805. switch (state)
  4806. {
  4807. case WUStateAborting:
  4808. state = WUStateAborted;
  4809. break;
  4810. case WUStateCompiling:
  4811. isEcl = true;
  4812. // drop into
  4813. default:
  4814. state = WUStateFailed;
  4815. }
  4816. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  4817. wu->setState(state);
  4818. Owned<IWUException> e = wu->createException();
  4819. e->setExceptionCode(isEcl ? 1001 : 1000);
  4820. e->setExceptionMessage(isEcl ? "EclServer terminated unexpectedly" : "Workunit terminated unexpectedly");
  4821. }
  4822. static CriticalSection deleteDllLock;
  4823. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  4824. MODULE_INIT(INIT_PRIORITY_STANDARD)
  4825. {
  4826. return true;
  4827. }
  4828. MODULE_EXIT()
  4829. {
  4830. CriticalBlock b(deleteDllLock);
  4831. if (deleteDllWorkQ)
  4832. ::Release(deleteDllWorkQ);
  4833. deleteDllWorkQ = nullptr;
  4834. }
  4835. static void asyncRemoveDll(const char * name)
  4836. {
  4837. CriticalBlock b(deleteDllLock);
  4838. if (!deleteDllWorkQ)
  4839. deleteDllWorkQ = createWorkQueueThread();
  4840. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  4841. }
  4842. static void asyncRemoveFile(const char * ip, const char * name)
  4843. {
  4844. CriticalBlock b(deleteDllLock);
  4845. if (!deleteDllWorkQ)
  4846. deleteDllWorkQ = createWorkQueueThread();
  4847. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  4848. }
  4849. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  4850. {
  4851. public:
  4852. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  4853. CDaliWorkUnitFactory()
  4854. {
  4855. // Assumes dali client configuration has already been done
  4856. sdsManager = &querySDS();
  4857. session = myProcessSession();
  4858. addShutdownHook(*this);
  4859. }
  4860. ~CDaliWorkUnitFactory()
  4861. {
  4862. removeShutdownHook(*this);
  4863. }
  4864. virtual bool initializeStore()
  4865. {
  4866. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  4867. }
  4868. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  4869. {
  4870. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  4871. }
  4872. virtual unsigned validateRepository(bool fixErrors)
  4873. {
  4874. return 0;
  4875. }
  4876. virtual void deleteRepository(bool recreate)
  4877. {
  4878. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4879. if (conn)
  4880. conn->close(true);
  4881. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  4882. if (conn)
  4883. conn->close(true);
  4884. }
  4885. virtual void createRepository()
  4886. {
  4887. // Nothing to do
  4888. }
  4889. virtual const char *queryStoreType() const
  4890. {
  4891. return "Dali";
  4892. }
  4893. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4894. {
  4895. StringBuffer wuRoot;
  4896. getXPath(wuRoot, wuid);
  4897. IRemoteConnection *conn;
  4898. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  4899. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4900. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  4901. conn->queryRoot()->setProp("@totalThorTime", "");
  4902. return new CDaliWorkUnit(conn, secmgr, secuser);
  4903. }
  4904. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4905. {
  4906. StringBuffer wuRoot;
  4907. getXPath(wuRoot, wuid);
  4908. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  4909. if (conn)
  4910. return new CDaliWorkUnit(conn, secmgr, secuser);
  4911. else
  4912. return NULL;
  4913. }
  4914. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  4915. {
  4916. Owned<IPTree> pt(_pt);
  4917. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  4918. StringBuffer wuRoot;
  4919. getXPath(wuRoot, wuid);
  4920. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4921. if (!conn)
  4922. {
  4923. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  4924. return false;
  4925. }
  4926. IPropertyTree *root = conn->queryRoot();
  4927. if (root->hasChildren())
  4928. {
  4929. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  4930. return false;
  4931. }
  4932. root->setPropTree(NULL, pt.getClear());
  4933. conn.clear();
  4934. // now kludge back GraphProgress
  4935. if (gprogress)
  4936. {
  4937. VStringBuffer xpath("/GraphProgress/%s", wuid);
  4938. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  4939. if (conn)
  4940. {
  4941. IPropertyTree *groot = conn->queryRoot();
  4942. if (groot->hasChildren())
  4943. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  4944. groot->setPropTree(NULL, gprogress.getClear());
  4945. }
  4946. }
  4947. return true;
  4948. }
  4949. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4950. {
  4951. StringBuffer wuRoot;
  4952. getXPath(wuRoot, wuid);
  4953. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4954. if (conn)
  4955. return new CDaliWorkUnit(conn, secmgr, secuser);
  4956. else
  4957. return NULL;
  4958. }
  4959. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  4960. {
  4961. // MORE - should it check security?
  4962. StringBuffer wuRoot;
  4963. getXPath(wuRoot, GLOBAL_WORKUNIT);
  4964. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4965. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4966. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  4967. return &cw->lockRemote(false);
  4968. }
  4969. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  4970. {
  4971. StringBuffer path("*");
  4972. if (owner && *owner)
  4973. path.append("[@submitID=?~\"").append(owner).append("\"]");
  4974. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4975. }
  4976. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4977. {
  4978. StringBuffer path("*");
  4979. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  4980. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4981. }
  4982. virtual void clientShutdown();
  4983. virtual unsigned numWorkUnits()
  4984. {
  4985. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  4986. if (!conn)
  4987. return 0;
  4988. IPropertyTree *root = conn->queryRoot();
  4989. return root->numChildren();
  4990. }
  4991. /**
  4992. * Add a filter to an xpath query, with the appropriate filter flags
  4993. */
  4994. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  4995. {
  4996. query.append('[').append(name).append('=');
  4997. if (flags & WUSFnocase)
  4998. query.append('?');
  4999. if (flags & WUSFwild)
  5000. query.append('~');
  5001. query.append('"').append(value).append("\"]");
  5002. };
  5003. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  5004. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5005. const void *filterbuf, // (appended) string values for filters
  5006. unsigned startoffset,
  5007. unsigned maxnum,
  5008. __int64 *cachehint,
  5009. unsigned *total,
  5010. ISecManager *secmgr,
  5011. ISecUser *secuser)
  5012. {
  5013. class CQueryOrFilter : public CInterface
  5014. {
  5015. unsigned flags;
  5016. StringAttr name;
  5017. StringArray values;
  5018. public:
  5019. IMPLEMENT_IINTERFACE;
  5020. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5021. : flags(_flags), name(_name)
  5022. {
  5023. values.appendListUniq(_value, "|");
  5024. };
  5025. const char* queryName() { return name.get(); };
  5026. unsigned querySearchFlags() { return flags; };
  5027. const StringArray& queryValues() const { return values; };
  5028. };
  5029. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5030. {
  5031. public:
  5032. virtual bool first() override
  5033. {
  5034. curSource = 0;
  5035. while (sources.isItem(curSource))
  5036. {
  5037. if (sources.item(curSource).first())
  5038. return true;
  5039. curSource++;
  5040. }
  5041. return false;
  5042. }
  5043. virtual bool next() override
  5044. {
  5045. if (sources.isItem(curSource))
  5046. {
  5047. if (sources.item(curSource).next())
  5048. return true;
  5049. curSource++;
  5050. while (sources.isItem(curSource))
  5051. {
  5052. if (sources.item(curSource).first())
  5053. return true;
  5054. curSource++;
  5055. }
  5056. }
  5057. return false;
  5058. }
  5059. virtual bool isValid() override
  5060. {
  5061. return sources.isItem(curSource);
  5062. }
  5063. virtual IPropertyTree & query() override
  5064. {
  5065. return sources.item(curSource).query();
  5066. }
  5067. void addSource(IPropertyTreeIterator &source)
  5068. {
  5069. sources.append(source);
  5070. }
  5071. private:
  5072. IArrayOf<IPropertyTreeIterator> sources;
  5073. unsigned curSource = 0;
  5074. };
  5075. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5076. {
  5077. StringAttr xPath;
  5078. StringAttr sortOrder;
  5079. StringAttr nameFilterLo;
  5080. StringAttr nameFilterHi;
  5081. StringArray unknownAttributes;
  5082. Owned<CQueryOrFilter> orFilter;
  5083. public:
  5084. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5085. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5086. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5087. {
  5088. ForEachItemIn(x, _unknownAttributes)
  5089. unknownAttributes.append(_unknownAttributes.item(x));
  5090. }
  5091. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5092. {
  5093. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5094. if (!conn)
  5095. return NULL;
  5096. Owned<IPropertyTreeIterator> iter;
  5097. if (!orFilter)
  5098. {
  5099. iter.setown(conn->getElements(xPath.get()));
  5100. }
  5101. else
  5102. {
  5103. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5104. bool added = false;
  5105. const char* fieldName = orFilter->queryName();
  5106. unsigned flags = orFilter->querySearchFlags();
  5107. const StringArray& values = orFilter->queryValues();
  5108. ForEachItemIn(i, values)
  5109. {
  5110. StringBuffer path(xPath.get());
  5111. const char* value = values.item(i);
  5112. if (!isEmptyString(value))
  5113. {
  5114. appendFilterToQueryString(path, flags, fieldName, value);
  5115. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5116. if (itr)
  5117. {
  5118. multi->addSource(*itr);
  5119. added = true;
  5120. }
  5121. }
  5122. }
  5123. if (added)
  5124. iter.setown(multi.getClear());
  5125. }
  5126. if (!iter)
  5127. return NULL;
  5128. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5129. return conn.getClear();
  5130. }
  5131. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5132. };
  5133. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5134. {
  5135. UniqueScopes done;
  5136. ISecManager *secmgr;
  5137. ISecUser *secuser;
  5138. CriticalSection crit;
  5139. public:
  5140. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5141. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5142. {
  5143. secmgr = _secmgr;
  5144. secuser = _secuser;
  5145. }
  5146. bool isOK(IPropertyTree &tree)
  5147. {
  5148. const char *scopename = tree.queryProp("@scope");
  5149. if (!scopename||!*scopename)
  5150. return true;
  5151. {
  5152. CriticalBlock block(crit);
  5153. const bool *b = done.getValue(scopename);
  5154. if (b)
  5155. return *b;
  5156. }
  5157. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5158. {
  5159. // conceivably could have already been checked and added, but ok.
  5160. CriticalBlock block(crit);
  5161. done.setValue(scopename,ret);
  5162. }
  5163. return ret;
  5164. }
  5165. };
  5166. Owned<CQueryOrFilter> orFilter;
  5167. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5168. StringBuffer query;
  5169. StringBuffer so;
  5170. StringAttr namefilter("*");
  5171. StringAttr namefilterlo;
  5172. StringAttr namefilterhi;
  5173. StringArray unknownAttributes;
  5174. if (filters)
  5175. {
  5176. const char *fv = (const char *) filterbuf;
  5177. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5178. {
  5179. assertex(fv);
  5180. int fmt = filters[i];
  5181. int subfmt = (fmt&0xff);
  5182. if (subfmt==WUSFwuid)
  5183. namefilterlo.set(fv);
  5184. else if (subfmt==WUSFwuidhigh)
  5185. namefilterhi.set(fv);
  5186. else if (subfmt==WUSFwildwuid)
  5187. namefilter.set(fv);
  5188. else if (subfmt==WUSFappvalue)
  5189. {
  5190. const char *app = fv;
  5191. fv = fv + strlen(fv)+1;
  5192. query.append("[Application/").append(app);
  5193. if (*fv)
  5194. query.append("=?~\"").append(fv).append('\"');
  5195. query.append("]");
  5196. }
  5197. else if (!*fv)
  5198. {
  5199. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5200. if (subfmt==WUSFtotalthortime)
  5201. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5202. }
  5203. else
  5204. {
  5205. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5206. if (!strchr(fv, '|'))
  5207. appendFilterToQueryString(query, fmt, fieldName, fv);
  5208. else if (orFilter)
  5209. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5210. else
  5211. {
  5212. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5213. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5214. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5215. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5216. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5217. }
  5218. }
  5219. fv = fv + strlen(fv)+1;
  5220. }
  5221. }
  5222. if ((sortorder&0xff)==WUSFtotalthortime)
  5223. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5224. query.insert(0, namefilter.get());
  5225. if (sortorder)
  5226. {
  5227. if (so.length())
  5228. so.append(',');
  5229. if (sortorder & WUSFreverse)
  5230. so.append('-');
  5231. if (sortorder & WUSFnocase)
  5232. so.append('?');
  5233. if (sortorder & WUSFnumeric)
  5234. so.append('#');
  5235. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5236. }
  5237. IArrayOf<IPropertyTree> results;
  5238. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5239. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5240. return new CConstWUArrayIterator(results);
  5241. }
  5242. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  5243. {
  5244. WUState ret = WUStateUnknown;
  5245. StringBuffer wuRoot;
  5246. getXPath(wuRoot, wuid);
  5247. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5248. if (timeout == 0) //no need to subscribe
  5249. {
  5250. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5251. switch (ret)
  5252. {
  5253. case WUStateCompiled:
  5254. case WUStateUploadingFiles:
  5255. if (!compiled)
  5256. break;
  5257. //fall through
  5258. case WUStateCompleted:
  5259. case WUStateFailed:
  5260. case WUStateAborted:
  5261. return ret;
  5262. case WUStateWait:
  5263. if(returnOnWaitState)
  5264. return ret;
  5265. default:
  5266. break;
  5267. }
  5268. return WUStateUnknown;
  5269. }
  5270. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5271. LocalIAbortHandler abortHandler(*waiter);
  5272. if (conn)
  5273. {
  5274. SessionId agent = -1;
  5275. bool agentSessionStopped = false;
  5276. unsigned start = msTick();
  5277. for (;;)
  5278. {
  5279. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5280. switch (ret)
  5281. {
  5282. case WUStateCompiled:
  5283. case WUStateUploadingFiles:
  5284. if (!compiled)
  5285. break;
  5286. // fall into
  5287. case WUStateCompleted:
  5288. case WUStateFailed:
  5289. case WUStateAborted:
  5290. return ret;
  5291. case WUStateWait:
  5292. if(returnOnWaitState)
  5293. {
  5294. return ret;
  5295. }
  5296. break;
  5297. case WUStateCompiling:
  5298. case WUStateRunning:
  5299. case WUStateDebugPaused:
  5300. case WUStateDebugRunning:
  5301. case WUStateBlocked:
  5302. case WUStateAborting:
  5303. if (agentSessionStopped)
  5304. {
  5305. reportAbnormalTermination(wuid, ret, agent);
  5306. return ret;
  5307. }
  5308. if (queryDaliServerVersion().compare("2.1")>=0)
  5309. {
  5310. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5311. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5312. {
  5313. agentSessionStopped = true;
  5314. conn->reload();
  5315. continue;
  5316. }
  5317. }
  5318. break;
  5319. }
  5320. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5321. unsigned waited = msTick() - start;
  5322. if (timeout==-1 || waited + 20000 < timeout)
  5323. {
  5324. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5325. if (waiter->isAborted())
  5326. {
  5327. ret = WUStateUnknown; // MORE - throw an exception?
  5328. break;
  5329. }
  5330. }
  5331. else if (waited > timeout || !waiter->wait(timeout-waited))
  5332. {
  5333. ret = WUStateUnknown; // MORE - throw an exception?
  5334. break;
  5335. }
  5336. conn->reload();
  5337. }
  5338. }
  5339. return ret;
  5340. }
  5341. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5342. {
  5343. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5344. LocalIAbortHandler abortHandler(*waiter);
  5345. WUAction ret = WUActionUnknown;
  5346. StringBuffer wuRoot;
  5347. getXPath(wuRoot, wuid);
  5348. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5349. if (conn)
  5350. {
  5351. unsigned start = msTick();
  5352. for (;;)
  5353. {
  5354. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5355. if (ret != original)
  5356. break;
  5357. unsigned waited = msTick() - start;
  5358. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5359. if (waiter->isAborted())
  5360. {
  5361. ret = WUActionUnknown; // MORE - throw an exception?
  5362. break;
  5363. }
  5364. conn->reload();
  5365. }
  5366. }
  5367. waiter->unsubscribe();
  5368. return ret;
  5369. }
  5370. protected:
  5371. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5372. {
  5373. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5374. if (conn)
  5375. {
  5376. CDaliVersion serverVersionNeeded("3.2");
  5377. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5378. conn->queryRoot()->getElements(xpath) :
  5379. conn->getElements(xpath));
  5380. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5381. }
  5382. else
  5383. return NULL;
  5384. }
  5385. ISDSManager *sdsManager;
  5386. SessionId session;
  5387. };
  5388. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5389. {
  5390. if (secmgr)
  5391. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5392. else
  5393. return iter;
  5394. }
  5395. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5396. {
  5397. if (secmgr)
  5398. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5399. else
  5400. return new CConstWUIterator(iter);
  5401. }
  5402. static CriticalSection factoryCrit;
  5403. static Owned<IWorkUnitFactory> factory;
  5404. void CDaliWorkUnitFactory::clientShutdown()
  5405. {
  5406. CriticalBlock b(factoryCrit);
  5407. factory.clear();
  5408. }
  5409. void clientShutdownWorkUnit()
  5410. {
  5411. CriticalBlock b(factoryCrit);
  5412. factory.clear();
  5413. }
  5414. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5415. {
  5416. CriticalBlock b(factoryCrit);
  5417. factory.setown(_factory);
  5418. }
  5419. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5420. {
  5421. if (!factory)
  5422. {
  5423. CriticalBlock b(factoryCrit);
  5424. 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.
  5425. {
  5426. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5427. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5428. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5429. IPropertyTree *pluginInfo = NULL;
  5430. if (env)
  5431. {
  5432. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5433. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5434. if (daliInfo)
  5435. {
  5436. const char *daliName = daliInfo->queryProp("@name");
  5437. if (daliName)
  5438. {
  5439. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5440. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5441. }
  5442. if (!pluginInfo)
  5443. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5444. }
  5445. }
  5446. if (pluginInfo && !forceDali)
  5447. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5448. else
  5449. factory.setown(new CDaliWorkUnitFactory());
  5450. }
  5451. }
  5452. return factory.getLink();
  5453. }
  5454. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5455. {
  5456. if (!factory)
  5457. {
  5458. CriticalBlock b(factoryCrit);
  5459. 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.
  5460. factory.setown(new CDaliWorkUnitFactory());
  5461. }
  5462. return factory.getLink();
  5463. }
  5464. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5465. // They can still be supplied if you want...
  5466. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5467. {
  5468. public:
  5469. IMPLEMENT_IINTERFACE;
  5470. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5471. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5472. {
  5473. }
  5474. virtual bool initializeStore()
  5475. {
  5476. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5477. }
  5478. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5479. {
  5480. return baseFactory->getWatcher(subscriber, options, wuid);
  5481. }
  5482. virtual unsigned validateRepository(bool fix)
  5483. {
  5484. return baseFactory->validateRepository(fix);
  5485. }
  5486. virtual void deleteRepository(bool recreate)
  5487. {
  5488. return baseFactory->deleteRepository(recreate);
  5489. }
  5490. virtual void createRepository()
  5491. {
  5492. return baseFactory->createRepository();
  5493. }
  5494. virtual const char *queryStoreType() const
  5495. {
  5496. return baseFactory->queryStoreType();
  5497. }
  5498. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5499. {
  5500. return baseFactory->getUniqueValues(field, prefix, result);
  5501. }
  5502. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5503. {
  5504. if (!secMgr) secMgr = defaultSecMgr.get();
  5505. if (!secUser) secUser = defaultSecUser.get();
  5506. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5507. }
  5508. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5509. {
  5510. if (!secMgr) secMgr = defaultSecMgr.get();
  5511. if (!secUser) secUser = defaultSecUser.get();
  5512. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5513. }
  5514. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5515. {
  5516. if (!secMgr) secMgr = defaultSecMgr.get();
  5517. if (!secUser) secUser = defaultSecUser.get();
  5518. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5519. }
  5520. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5521. {
  5522. if (!secMgr) secMgr = defaultSecMgr.get();
  5523. if (!secUser) secUser = defaultSecUser.get();
  5524. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5525. }
  5526. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5527. {
  5528. if (!secMgr) secMgr = defaultSecMgr.get();
  5529. if (!secUser) secUser = defaultSecUser.get();
  5530. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5531. }
  5532. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5533. {
  5534. if (!secMgr) secMgr = defaultSecMgr.get();
  5535. if (!secUser) secUser = defaultSecUser.get();
  5536. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5537. }
  5538. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5539. {
  5540. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5541. }
  5542. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5543. {
  5544. if (!secMgr) secMgr = defaultSecMgr.get();
  5545. if (!secUser) secUser = defaultSecUser.get();
  5546. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5547. }
  5548. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5549. {
  5550. if (!secMgr) secMgr = defaultSecMgr.get();
  5551. if (!secUser) secUser = defaultSecUser.get();
  5552. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5553. }
  5554. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5555. {
  5556. if (!secMgr) secMgr = defaultSecMgr.get();
  5557. if (!secUser) secUser = defaultSecUser.get();
  5558. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5559. }
  5560. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5561. {
  5562. if (!secMgr) secMgr = defaultSecMgr.get();
  5563. if (!secUser) secUser = defaultSecUser.get();
  5564. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5565. }
  5566. virtual int setTracingLevel(int newLevel)
  5567. {
  5568. return baseFactory->setTracingLevel(newLevel);
  5569. }
  5570. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5571. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5572. const void *filterbuf, // (appended) string values for filters
  5573. unsigned startoffset,
  5574. unsigned maxnum,
  5575. __int64 *cachehint,
  5576. unsigned *total,
  5577. ISecManager *secMgr, ISecUser *secUser)
  5578. {
  5579. if (!secMgr) secMgr = defaultSecMgr.get();
  5580. if (!secUser) secUser = defaultSecUser.get();
  5581. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5582. }
  5583. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5584. WUQuerySortField *filters,
  5585. const void *filterbuf,
  5586. unsigned startoffset,
  5587. unsigned maxnum,
  5588. __int64 *cachehint,
  5589. unsigned *total,
  5590. const MapStringTo<bool> *subset)
  5591. {
  5592. // MORE - why no security?
  5593. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  5594. }
  5595. virtual unsigned numWorkUnits()
  5596. {
  5597. return baseFactory->numWorkUnits();
  5598. }
  5599. virtual bool isAborting(const char *wuid) const
  5600. {
  5601. return baseFactory->isAborting(wuid);
  5602. }
  5603. virtual void clearAborting(const char *wuid)
  5604. {
  5605. baseFactory->clearAborting(wuid);
  5606. }
  5607. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  5608. {
  5609. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, returnOnWaitState);
  5610. }
  5611. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5612. {
  5613. return baseFactory->waitForWorkUnitAction(wuid, original);
  5614. }
  5615. private:
  5616. Owned<IWorkUnitFactory> baseFactory;
  5617. Linked<ISecManager> defaultSecMgr;
  5618. Linked<ISecUser> defaultSecUser;
  5619. };
  5620. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5621. {
  5622. if (secmgr && secuser)
  5623. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5624. else
  5625. return getWorkUnitFactory();
  5626. }
  5627. //==========================================================================================
  5628. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5629. {
  5630. Owned<IPropertyTreeIterator> it;
  5631. public:
  5632. IMPLEMENT_IINTERFACE;
  5633. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5634. virtual bool first() { return it->first(); }
  5635. virtual bool next() { return it->next(); }
  5636. virtual bool isValid() { return it->isValid(); }
  5637. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5638. };
  5639. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5640. {
  5641. Owned<IPropertyTreeIterator> it;
  5642. public:
  5643. IMPLEMENT_IINTERFACE;
  5644. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5645. virtual bool first() { return it->first(); }
  5646. virtual bool next() { return it->next(); }
  5647. virtual bool isValid() { return it->isValid(); }
  5648. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5649. };
  5650. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5651. {
  5652. Owned<IPropertyTreeIterator> it;
  5653. StringAttr name;
  5654. public:
  5655. IMPLEMENT_IINTERFACE;
  5656. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  5657. virtual bool first() { return it->first(); }
  5658. virtual bool next() { return it->next(); }
  5659. virtual bool isValid() { return it->isValid(); }
  5660. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  5661. };
  5662. //==========================================================================================
  5663. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5664. {
  5665. clearCached(false);
  5666. secMgr.set(secmgr);
  5667. secUser.set(secuser);
  5668. workflowIteratorCached = false;
  5669. resultsCached = false;
  5670. graphsCached = false;
  5671. temporariesCached = false;
  5672. variablesCached = false;
  5673. exceptionsCached = false;
  5674. pluginsCached = false;
  5675. librariesCached = false;
  5676. activitiesCached = false;
  5677. webServicesInfoCached = false;
  5678. roxieQueryInfoCached = false;
  5679. }
  5680. void CLocalWorkUnit::clearCached(bool clearTree)
  5681. {
  5682. query.clear();
  5683. webServicesInfo.clear();
  5684. workflowIterator.clear();
  5685. graphs.kill();
  5686. results.kill();
  5687. variables.kill();
  5688. plugins.kill();
  5689. libraries.kill();
  5690. exceptions.kill();
  5691. temporaries.kill();
  5692. statistics.kill();
  5693. appvalues.kill();
  5694. if (clearTree)
  5695. p.clear();
  5696. workflowIteratorCached = false;
  5697. resultsCached = false;
  5698. graphsCached = false;
  5699. temporariesCached = false;
  5700. variablesCached = false;
  5701. exceptionsCached = false;
  5702. pluginsCached = false;
  5703. librariesCached = false;
  5704. activitiesCached = false;
  5705. webServicesInfoCached = false;
  5706. roxieQueryInfoCached = false;
  5707. }
  5708. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  5709. {
  5710. clearCached(false);
  5711. p.setown(ptree);
  5712. }
  5713. void CLocalWorkUnit::beforeDispose()
  5714. {
  5715. try
  5716. {
  5717. unsubscribe();
  5718. clearCached(true);
  5719. userDesc.clear();
  5720. secMgr.clear();
  5721. secUser.clear();
  5722. }
  5723. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  5724. }
  5725. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  5726. {
  5727. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  5728. // Delete any related things in SDS etc that might otherwise be forgotten
  5729. if (p->getPropBool("@protected", false))
  5730. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  5731. switch (getState())
  5732. {
  5733. case WUStateAborted:
  5734. case WUStateCompleted:
  5735. case WUStateFailed:
  5736. case WUStateArchived:
  5737. break;
  5738. case WUStateCompiled:
  5739. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  5740. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5741. break;
  5742. case WUStateWait:
  5743. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  5744. default:
  5745. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5746. break;
  5747. }
  5748. if (getIsQueryService())
  5749. {
  5750. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  5751. if (registry)
  5752. {
  5753. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  5754. if (registry->hasProp(xpath.str()))
  5755. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  5756. }
  5757. }
  5758. try
  5759. {
  5760. if (deldll && !p->getPropBool("@isClone", false))
  5761. {
  5762. Owned<IConstWUQuery> q = getQuery();
  5763. if (q)
  5764. {
  5765. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5766. SCMStringBuffer name;
  5767. ForEach(*iter)
  5768. {
  5769. IConstWUAssociatedFile & cur = iter->query();
  5770. cur.getNameTail(name);
  5771. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  5772. {
  5773. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5774. if (entry.get())
  5775. asyncRemoveDll(name.str());
  5776. else
  5777. {
  5778. SCMStringBuffer ip, localPath;
  5779. cur.getName(localPath);
  5780. cur.getIp(ip);
  5781. asyncRemoveFile(ip.str(), localPath.str());
  5782. }
  5783. }
  5784. }
  5785. }
  5786. }
  5787. factory->clearAborting(queryWuid());
  5788. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  5789. }
  5790. catch(IException *E)
  5791. {
  5792. StringBuffer s;
  5793. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  5794. E->Release();
  5795. }
  5796. catch (...)
  5797. {
  5798. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  5799. }
  5800. }
  5801. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  5802. {
  5803. SCMStringBuffer strval;
  5804. val.getGmtString(strval);
  5805. p->setProp("@timescheduled",strval.str());
  5806. }
  5807. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  5808. {
  5809. StringBuffer str;
  5810. p->getProp("@timescheduled",str);
  5811. if(str.length())
  5812. val.setGmtString(str.str());
  5813. return val;
  5814. }
  5815. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  5816. {
  5817. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  5818. if (extra.length())
  5819. {
  5820. const char *bufStart = buf.str();
  5821. const char *bufPtr = bufStart+buf.length();
  5822. while (bufStart != bufPtr)
  5823. {
  5824. --bufPtr;
  5825. if (!isspace(*bufPtr))
  5826. break;
  5827. }
  5828. assertex('>' == *bufPtr);
  5829. size_t l = strlen(wuid);
  5830. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  5831. bufPtr -= l+2; // skip back over </wuid
  5832. assertex(0 == memcmp(bufPtr, "</", 2) );
  5833. assertex(0 == memcmp(bufPtr+2, wuid, l));
  5834. buf.insert(bufPtr-bufStart, extra);
  5835. }
  5836. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  5837. }
  5838. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  5839. {
  5840. CriticalBlock block(crit);
  5841. StringBuffer path(base);
  5842. if (!p)
  5843. return false;
  5844. const char *wuid = p->queryName();
  5845. if (!wuid||!*wuid)
  5846. return false;
  5847. addPathSepChar(path).append(wuid).append(".xml");
  5848. Owned<IFile> file = createIFile(path.str());
  5849. if (!file)
  5850. return false;
  5851. Owned<IFileIO> fileio = file->open(IFOcreate);
  5852. if (!fileio)
  5853. return false;
  5854. StringBuffer buf;
  5855. exportWorkUnitToXML(this, buf, false, false, true);
  5856. StringBuffer extraWorkUnitXML;
  5857. Owned<IPTree> graphProgress = getGraphProgressTree();
  5858. if (graphProgress)
  5859. {
  5860. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  5861. graphProgress.clear();
  5862. }
  5863. Owned<IConstWUQuery> q = getQuery();
  5864. if (!q)
  5865. {
  5866. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5867. return false;
  5868. if (del)
  5869. {
  5870. if (getState()==WUStateUnknown)
  5871. setState(WUStateArchived); // to allow delete
  5872. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  5873. }
  5874. return false;
  5875. }
  5876. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  5877. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5878. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  5879. ForEach(*iter)
  5880. {
  5881. IConstWUAssociatedFile & cur = iter->query();
  5882. SCMStringBuffer name;
  5883. cur.getNameTail(name);
  5884. if (name.length())
  5885. {
  5886. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5887. SCMStringBuffer curPath, curIp;
  5888. cur.getName(curPath);
  5889. cur.getIp(curIp);
  5890. SocketEndpoint curEp(curIp.str());
  5891. RemoteFilename curRfn;
  5892. curRfn.setPath(curEp, curPath.str());
  5893. StringBuffer dst(base);
  5894. addPathSepChar(dst);
  5895. curRfn.getTail(dst);
  5896. Owned<IFile> dstFile = createIFile(dst.str());
  5897. if (entry.get())
  5898. {
  5899. Owned<IException> exception;
  5900. Owned<IDllLocation> loc;
  5901. Owned<IPropertyTree> generatedDllBranch = createPTree();
  5902. generatedDllBranch->setProp("@name", entry->queryName());
  5903. generatedDllBranch->setProp("@kind", entry->queryKind());
  5904. if (exportAssociatedFiles)
  5905. {
  5906. try
  5907. {
  5908. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  5909. }
  5910. catch(IException * e)
  5911. {
  5912. exception.setown(e);
  5913. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  5914. }
  5915. RemoteFilename filename;
  5916. loc->getDllFilename(filename);
  5917. if (!exception)
  5918. {
  5919. Owned<IFile> srcfile = createIFile(filename);
  5920. try
  5921. {
  5922. if (dstFile->exists())
  5923. {
  5924. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  5925. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  5926. // still want to delete if already archived but there are source file copies
  5927. }
  5928. else
  5929. copyFile(dstFile, srcfile);
  5930. }
  5931. catch(IException * e)
  5932. {
  5933. exception.setown(e);
  5934. }
  5935. }
  5936. if (exception)
  5937. {
  5938. if (ignoredllerrors)
  5939. {
  5940. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  5941. //copy failed, so don't delete the registered dll files
  5942. deleteExclusions.append(name.str());
  5943. }
  5944. else
  5945. throw exception.getClear();
  5946. }
  5947. }
  5948. // Record Associated path to restore back to
  5949. StringBuffer restorePath;
  5950. curRfn.getRemotePath(restorePath);
  5951. generatedDllBranch->setProp("@location", restorePath.str());
  5952. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  5953. }
  5954. else if (exportAssociatedFiles) // no generated dll entry
  5955. {
  5956. Owned<IFile> srcFile = createIFile(curRfn);
  5957. try
  5958. {
  5959. copyFile(dstFile, srcFile);
  5960. }
  5961. catch (IException *e)
  5962. {
  5963. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  5964. EXCLOG(e, msg.str());
  5965. e->Release();
  5966. deleteExclusions.append(name.str());
  5967. }
  5968. }
  5969. }
  5970. }
  5971. iter.clear();
  5972. if (generatedDlls->numChildren())
  5973. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  5974. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5975. return false;
  5976. if (del)
  5977. {
  5978. //setState(WUStateArchived); // this isn't useful as about to delete it!
  5979. q.clear();
  5980. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  5981. }
  5982. return true;
  5983. }
  5984. void CLocalWorkUnit::loadXML(const char *xml)
  5985. {
  5986. CriticalBlock block(crit);
  5987. clearCached(true);
  5988. assertex(xml);
  5989. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  5990. }
  5991. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  5992. {
  5993. CriticalBlock block(crit);
  5994. StringBuffer x;
  5995. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  5996. }
  5997. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  5998. {
  5999. CriticalBlock block(crit);
  6000. StringAttr value;
  6001. src.read(value);
  6002. loadXML(value);
  6003. }
  6004. void CLocalWorkUnit::requestAbort()
  6005. {
  6006. CriticalBlock block(crit);
  6007. abortWorkUnit(p->queryName());
  6008. }
  6009. void CLocalWorkUnit::unlockRemote()
  6010. {
  6011. CriticalBlock block(crit);
  6012. locked.unlock();
  6013. _unlockRemote();
  6014. }
  6015. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6016. {
  6017. if (secMgr)
  6018. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6019. locked.lock();
  6020. CriticalBlock block(crit);
  6021. if (commit)
  6022. {
  6023. try
  6024. {
  6025. _lockRemote();
  6026. }
  6027. catch (IException *E)
  6028. {
  6029. StringBuffer s;
  6030. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6031. locked.unlock();
  6032. throw;
  6033. }
  6034. }
  6035. return *new CLockedWorkUnit(LINK(this));
  6036. }
  6037. void CLocalWorkUnit::commit()
  6038. {
  6039. // Nothing to do if not backed by a persistent store
  6040. }
  6041. IWorkUnit& CLocalWorkUnit::lock()
  6042. {
  6043. return lockRemote(true);
  6044. }
  6045. const char *CLocalWorkUnit::queryWuid() const
  6046. {
  6047. CriticalBlock block(crit);
  6048. return p->queryName();
  6049. }
  6050. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6051. {
  6052. CriticalBlock block(crit);
  6053. return p->getPropInt("@DebugListenerPort", 0);
  6054. }
  6055. unsigned CLocalWorkUnit::getTotalThorTime() const
  6056. {
  6057. CriticalBlock block(crit);
  6058. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6059. }
  6060. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6061. {
  6062. CriticalBlock block(crit);
  6063. p->setPropInt("@DebugListenerPort", port);
  6064. }
  6065. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6066. {
  6067. CriticalBlock block(crit);
  6068. ip.set(p->queryProp("@DebugListenerIP"));
  6069. return ip;
  6070. }
  6071. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6072. {
  6073. CriticalBlock block(crit);
  6074. p->setProp("@DebugListenerIP", ip);
  6075. }
  6076. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6077. {
  6078. CriticalBlock block(crit);
  6079. datoken.set(p->queryProp("@distributedAccessToken"));
  6080. return datoken;
  6081. }
  6082. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6083. {
  6084. CriticalBlock block(crit);
  6085. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6086. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6087. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6088. if (pDSM && pDSM->isDigiSignerConfigured())
  6089. {
  6090. datoken.append(pDSM->queryKeyName()).append(';');
  6091. StringBuffer b64Signature;
  6092. if (pDSM->digiSign(b64Signature, datoken))
  6093. {
  6094. datoken.append(b64Signature.str());
  6095. }
  6096. else
  6097. {
  6098. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6099. return false;
  6100. }
  6101. }
  6102. else
  6103. {
  6104. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6105. datoken.append(";");
  6106. }
  6107. p->setProp("@distributedAccessToken", datoken);
  6108. return true;
  6109. }
  6110. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6111. {
  6112. // Only implemented in derived classes
  6113. return false;
  6114. }
  6115. void CLocalWorkUnit::setJobName(const char *value)
  6116. {
  6117. CriticalBlock block(crit);
  6118. p->setProp("@jobName", value);
  6119. }
  6120. const char *CLocalWorkUnit::queryJobName() const
  6121. {
  6122. CriticalBlock block(crit);
  6123. const char *ret = p->queryProp("@jobName");
  6124. if (!ret)
  6125. ret = "";
  6126. return ret;
  6127. }
  6128. void CLocalWorkUnit::setClusterName(const char *value)
  6129. {
  6130. CriticalBlock block(crit);
  6131. p->setProp("@clusterName", value);
  6132. }
  6133. const char *CLocalWorkUnit::queryClusterName() const
  6134. {
  6135. CriticalBlock block(crit);
  6136. const char *ret = p->queryProp("@clusterName");
  6137. if (!ret)
  6138. ret = "";
  6139. return ret;
  6140. }
  6141. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6142. {
  6143. setDebugValue("allowedclusters",value, true);
  6144. }
  6145. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6146. {
  6147. CriticalBlock block(crit);
  6148. getDebugValue("allowedclusters",str);
  6149. if (str.length()!=0)
  6150. return str;
  6151. str.set(p->queryProp("@clusterName"));
  6152. return str;
  6153. }
  6154. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6155. {
  6156. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6157. }
  6158. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6159. {
  6160. CriticalBlock block(crit);
  6161. return getDebugValueBool("allowautoqueueswitch",false);
  6162. }
  6163. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6164. {
  6165. StringBuffer suffix;
  6166. if (name && *name)
  6167. setApplicationValue("LibraryModule", "name", name, true);
  6168. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6169. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6170. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6171. }
  6172. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6173. {
  6174. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6175. if (writeaccess)
  6176. auditflags |= DALI_LDAP_WRITE_WANTED;
  6177. SecAccessFlags perm = SecAccess_Full;
  6178. const char *scopename = p->queryProp("@scope");
  6179. if (scopename&&*scopename) {
  6180. if (!user)
  6181. user = queryUserDescriptor();
  6182. CDateTime now;
  6183. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags,nullptr,now);
  6184. if (perm<0) {
  6185. if (perm == SecAccess_Unavailable)
  6186. perm = SecAccess_Full;
  6187. else
  6188. perm = SecAccess_None;
  6189. }
  6190. }
  6191. if (!HASREADPERMISSION(perm))
  6192. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6193. if (writeaccess && !HASWRITEPERMISSION(perm))
  6194. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6195. }
  6196. void CLocalWorkUnit::setUser(const char * value)
  6197. {
  6198. CriticalBlock block(crit);
  6199. p->setProp("@submitID", value);
  6200. }
  6201. const char *CLocalWorkUnit::queryUser() const
  6202. {
  6203. CriticalBlock block(crit);
  6204. const char *ret = p->queryProp("@submitID");
  6205. if (!ret)
  6206. ret = "";
  6207. return ret;
  6208. }
  6209. void CLocalWorkUnit::setWuScope(const char * value)
  6210. {
  6211. if (value && *value)
  6212. {
  6213. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6214. {
  6215. CriticalBlock block(crit);
  6216. p->setProp("@scope", value);
  6217. }
  6218. }
  6219. }
  6220. const char *CLocalWorkUnit::queryWuScope() const
  6221. {
  6222. CriticalBlock block(crit);
  6223. const char *ret = p->queryProp("@scope");
  6224. if (!ret)
  6225. ret = "";
  6226. return ret;
  6227. }
  6228. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6229. {
  6230. CriticalBlock block(crit);
  6231. setEnum(p, "@priorityClass", cls, priorityClasses);
  6232. }
  6233. WUPriorityClass CLocalWorkUnit::getPriority() const
  6234. {
  6235. CriticalBlock block(crit);
  6236. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6237. }
  6238. const char *CLocalWorkUnit::queryPriorityDesc() const
  6239. {
  6240. return getEnumText(getPriority(), priorityClasses);
  6241. }
  6242. void CLocalWorkUnit::setState(WUState value)
  6243. {
  6244. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6245. {
  6246. if (factory)
  6247. factory->clearAborting(queryWuid());
  6248. }
  6249. CriticalBlock block(crit);
  6250. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6251. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6252. if (getDebugValueBool("monitorWorkunit", false))
  6253. {
  6254. switch(value)
  6255. {
  6256. case WUStateAborted:
  6257. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6258. break;
  6259. case WUStateCompleted:
  6260. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6261. break;
  6262. case WUStateFailed:
  6263. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6264. break;
  6265. }
  6266. }
  6267. p->removeProp("@stateEx");
  6268. }
  6269. void CLocalWorkUnit::setStateEx(const char * text)
  6270. {
  6271. CriticalBlock block(crit);
  6272. p->setProp("@stateEx", text);
  6273. }
  6274. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6275. {
  6276. CriticalBlock block(crit);
  6277. p->setPropInt64("@agentSession", sessionId);
  6278. }
  6279. bool CLocalWorkUnit::getIsQueryService() const
  6280. {
  6281. CriticalBlock block(crit);
  6282. return p->getPropBool("@isQueryService", false);
  6283. }
  6284. void CLocalWorkUnit::setIsQueryService(bool value)
  6285. {
  6286. CriticalBlock block(crit);
  6287. p->setPropBool("@isQueryService", value);
  6288. }
  6289. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6290. {
  6291. if (queryDaliServerVersion().compare("2.1")<0)
  6292. return;
  6293. switch(state)
  6294. {
  6295. case WUStateRunning:
  6296. case WUStateDebugPaused:
  6297. case WUStateDebugRunning:
  6298. case WUStateBlocked:
  6299. case WUStateAborting:
  6300. case WUStateCompiling:
  6301. case WUStatePaused:
  6302. {
  6303. SessionId agent = getAgentSession();
  6304. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6305. {
  6306. forceReload();
  6307. state = (WUState) getEnum(p, "@state", states);
  6308. bool isecl=state==WUStateCompiling;
  6309. if (aborting())
  6310. state = WUStateAborted;
  6311. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6312. state = WUStateFailed;
  6313. else
  6314. return;
  6315. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6316. Owned<IWorkUnit> w = &lock();
  6317. w->setState(state);
  6318. Owned<IWUException> e = w->createException();
  6319. WUAction action = w->getAction();
  6320. switch (action)
  6321. {
  6322. case WUActionPause:
  6323. case WUActionPauseNow:
  6324. case WUActionResume:
  6325. w->setAction(WUActionUnknown);
  6326. }
  6327. if(isecl)
  6328. {
  6329. e->setExceptionCode(1001);
  6330. e->setExceptionMessage("EclServer terminated unexpectedly");
  6331. }
  6332. else
  6333. {
  6334. e->setExceptionCode(1000);
  6335. e->setExceptionMessage("Workunit terminated unexpectedly");
  6336. }
  6337. }
  6338. }
  6339. }
  6340. }
  6341. WUState CLocalWorkUnit::getState() const
  6342. {
  6343. CriticalBlock block(crit);
  6344. WUState state = (WUState) getEnum(p, "@state", states);
  6345. switch (state)
  6346. {
  6347. case WUStateRunning:
  6348. case WUStateDebugPaused:
  6349. case WUStateDebugRunning:
  6350. case WUStateBlocked:
  6351. case WUStateCompiling:
  6352. if (aborting())
  6353. state = WUStateAborting;
  6354. break;
  6355. case WUStateSubmitted:
  6356. if (aborting())
  6357. state = WUStateAborted;
  6358. break;
  6359. }
  6360. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6361. return state;
  6362. }
  6363. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6364. {
  6365. CriticalBlock block(crit);
  6366. str.set(p->queryProp("@stateEx"));
  6367. return str;
  6368. }
  6369. __int64 CLocalWorkUnit::getAgentSession() const
  6370. {
  6371. CriticalBlock block(crit);
  6372. return p->getPropInt64("@agentSession", -1);
  6373. }
  6374. unsigned CLocalWorkUnit::getAgentPID() const
  6375. {
  6376. CriticalBlock block(crit);
  6377. return p->getPropInt("@agentPID", -1);
  6378. }
  6379. const char * CLocalWorkUnit::queryStateDesc() const
  6380. {
  6381. // MORE - not sure about this - may prefer a separate interface
  6382. CriticalBlock block(crit);
  6383. try
  6384. {
  6385. return getEnumText(getState(), states);
  6386. }
  6387. catch (...)
  6388. {
  6389. return "???";
  6390. }
  6391. }
  6392. void CLocalWorkUnit::setAction(WUAction value)
  6393. {
  6394. CriticalBlock block(crit);
  6395. setEnum(p, "Action", value, actions);
  6396. }
  6397. WUAction CLocalWorkUnit::getAction() const
  6398. {
  6399. CriticalBlock block(crit);
  6400. return (WUAction) getEnum(p, "Action", actions);
  6401. }
  6402. const char *CLocalWorkUnit::queryActionDesc() const
  6403. {
  6404. CriticalBlock block(crit);
  6405. return p->queryProp("Action");
  6406. }
  6407. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6408. {
  6409. CriticalBlock block(crit);
  6410. StringBuffer prop("Application/");
  6411. prop.append(app).append('/').append(propname);
  6412. str.set(p->queryProp(prop.str()));
  6413. return str;
  6414. }
  6415. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6416. {
  6417. CriticalBlock block(crit);
  6418. StringBuffer prop("Application/");
  6419. prop.append(app).append('/').append(propname);
  6420. return p->getPropInt(prop.str(), defVal);
  6421. }
  6422. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6423. {
  6424. CriticalBlock block(crit);
  6425. appvalues.load(p,"Application/*");
  6426. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6427. }
  6428. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6429. {
  6430. CriticalBlock block(crit);
  6431. StringBuffer prop("Application/");
  6432. prop.append(app).append('/').append(propname);
  6433. if (overwrite || !p->hasProp(prop.str()))
  6434. {
  6435. StringBuffer sp;
  6436. p->setProp(sp.append("Application").str(), "");
  6437. p->setProp(sp.append('/').append(app).str(), "");
  6438. p->setProp(prop.str(), value);
  6439. }
  6440. }
  6441. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6442. {
  6443. VStringBuffer s("%d", value);
  6444. setApplicationValue(app, propname, s, overwrite);
  6445. }
  6446. void CLocalWorkUnit::setPriorityLevel(int level)
  6447. {
  6448. CriticalBlock block(crit);
  6449. p->setPropInt("PriorityFlag", level);
  6450. }
  6451. int CLocalWorkUnit::getPriorityLevel() const
  6452. {
  6453. CriticalBlock block(crit);
  6454. return p->getPropInt("PriorityFlag");
  6455. }
  6456. int calcPriorityValue(const IPropertyTree * p)
  6457. {
  6458. int priority = p->getPropInt("PriorityFlag");
  6459. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6460. {
  6461. case PriorityClassLow:
  6462. priority -= 100;
  6463. break;
  6464. case PriorityClassHigh:
  6465. priority += 100;
  6466. break;
  6467. }
  6468. return priority;
  6469. }
  6470. int CLocalWorkUnit::getPriorityValue() const
  6471. {
  6472. CriticalBlock block(crit);
  6473. return calcPriorityValue(p);
  6474. }
  6475. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6476. {
  6477. CriticalBlock block(crit);
  6478. p->setPropInt("RescheduleFlag", (int) value);
  6479. }
  6480. bool CLocalWorkUnit::getRescheduleFlag() const
  6481. {
  6482. CriticalBlock block(crit);
  6483. return p->getPropInt("RescheduleFlag") != 0;
  6484. }
  6485. class NullIStringIterator : implements IStringIterator, public CInterface
  6486. {
  6487. public:
  6488. IMPLEMENT_IINTERFACE;
  6489. bool first() { return false; }
  6490. bool next() { return false; }
  6491. bool isValid() { return false; }
  6492. IStringVal & str(IStringVal & str) { return str; }
  6493. };
  6494. ClusterType getClusterType(const char * platform, ClusterType dft)
  6495. {
  6496. if (stricmp(platform, "thor") == 0)
  6497. return ThorLCRCluster;
  6498. if (stricmp(platform, "thorlcr") == 0)
  6499. return ThorLCRCluster;
  6500. if (stricmp(platform, "hthor") == 0)
  6501. return HThorCluster;
  6502. if (stricmp(platform, "roxie") == 0)
  6503. return RoxieCluster;
  6504. return dft;
  6505. }
  6506. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6507. {
  6508. switch (clusterType)
  6509. {
  6510. case ThorLCRCluster:
  6511. if (lcrSensitive)
  6512. return "thorlcr";
  6513. return "thor";
  6514. case RoxieCluster:
  6515. return "roxie";
  6516. case HThorCluster:
  6517. return "hthor";
  6518. }
  6519. throwUnexpected();
  6520. }
  6521. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6522. {
  6523. if (!isWorkunitDAToken(distributedAccessToken))
  6524. {
  6525. DBGLOG("Not a valid workunit distributed access token");
  6526. return false;
  6527. }
  6528. //Extract the string between [ and ]
  6529. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6530. StringBuffer tokenValues;
  6531. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6532. StringArray nameValues;
  6533. nameValues.appendList(tokenValues.str(), ",",true);
  6534. if (user || wuid)
  6535. {
  6536. for (int x = 0; x < nameValues.ordinality(); x++)
  6537. {
  6538. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6539. user->append(nameValues[x] + 2);
  6540. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6541. wuid->append(nameValues[x] + 2);
  6542. }
  6543. }
  6544. if (privKey)
  6545. {
  6546. const char * finger = pEndBracket;
  6547. ++finger;
  6548. while (*finger && *finger != ';')
  6549. privKey->append(1, finger++);
  6550. }
  6551. return true;
  6552. }
  6553. //Verifies the given signed workunit distributed access token was created
  6554. //and signed by the given wuid and user, and that the workunit is still active
  6555. //Returns:
  6556. // 0 : Success, token is valid and workunit is active
  6557. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6558. // 2 : Workunit not active
  6559. // Throws if unable to open workunit
  6560. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6561. {
  6562. if (isEmptyString(daToken))
  6563. {
  6564. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6565. return wuTokenInvalid;
  6566. }
  6567. StringBuffer tokWuid;
  6568. StringBuffer tokUser;
  6569. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6570. {
  6571. //Not a valid workunit distributed access token
  6572. return wuTokenInvalid;
  6573. }
  6574. //Validate signature
  6575. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6576. if (pDSM && pDSM->isDigiVerifierConfigured())
  6577. {
  6578. const char * finger;
  6579. StringBuffer token;//receives copy of everything up until signature
  6580. for (finger = daToken; *finger && *finger != ';'; finger++)
  6581. token.append(1, finger);
  6582. token.append(1, finger);//append ;
  6583. StringBuffer sig(++finger);
  6584. if (!pDSM->digiVerify(sig, token))
  6585. {
  6586. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6587. return wuTokenInvalid;
  6588. }
  6589. }
  6590. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6591. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6592. if(!cw)
  6593. {
  6594. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6595. }
  6596. //Verify user matches
  6597. bool wuUserExist = !isEmptyString(cw->queryUser());
  6598. bool tokUserExist = !isEmptyString(tokUser.str());
  6599. bool ctxUserExist = !isEmptyString(ctxUser);
  6600. if (wuUserExist && tokUserExist)
  6601. {
  6602. //if both users are found, they must match
  6603. if (!streq(tokUser.str(), cw->queryUser()))
  6604. {
  6605. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6606. return wuTokenInvalid;//Possible Internal error
  6607. }
  6608. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6609. {
  6610. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6611. return wuTokenInvalid;
  6612. }
  6613. }
  6614. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6615. {
  6616. if (ctxUserExist)
  6617. {
  6618. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6619. return wuTokenInvalid;
  6620. }
  6621. //both users empty and no context user means if no security enabled
  6622. }
  6623. else
  6624. {
  6625. //one user found, but not the other, treat as an error
  6626. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6627. return wuTokenInvalid;
  6628. }
  6629. // no need to compare tokWuid with workunit wuid, because it will always match
  6630. bool wuActive;
  6631. switch (cw->getState())
  6632. {
  6633. case WUStateRunning:
  6634. case WUStateDebugRunning:
  6635. case WUStateBlocked:
  6636. case WUStateAborting:
  6637. case WUStateUploadingFiles:
  6638. #ifdef _DEBUG
  6639. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6640. #endif
  6641. wuActive = true;
  6642. break;
  6643. default:
  6644. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6645. wuActive = false;
  6646. break;
  6647. }
  6648. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6649. }
  6650. IPropertyTree *queryRoxieProcessTree(IPropertyTree *environment, const char *process)
  6651. {
  6652. if (!process || !*process)
  6653. return NULL;
  6654. VStringBuffer xpath("Software/RoxieCluster[@name=\"%s\"]", process);
  6655. return environment->queryPropTree(xpath.str());
  6656. }
  6657. void getRoxieProcessServers(IPropertyTree *roxie, SocketEndpointArray &endpoints)
  6658. {
  6659. if (!roxie)
  6660. return;
  6661. Owned<IPropertyTreeIterator> servers = roxie->getElements("RoxieServerProcess");
  6662. ForEach(*servers)
  6663. {
  6664. IPropertyTree &server = servers->query();
  6665. const char *netAddress = server.queryProp("@netAddress");
  6666. if (netAddress && *netAddress)
  6667. {
  6668. SocketEndpoint ep(netAddress, server.getPropInt("@port", 9876));
  6669. endpoints.append(ep);
  6670. }
  6671. }
  6672. }
  6673. void getRoxieProcessServers(const char *process, SocketEndpointArray &servers)
  6674. {
  6675. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6676. Owned<IConstEnvironment> env = factory->openEnvironment();
  6677. Owned<IPropertyTree> root = &env->getPTree();
  6678. getRoxieProcessServers(queryRoxieProcessTree(root, process), servers);
  6679. }
  6680. class CEnvironmentClusterInfo: implements IConstWUClusterInfo, public CInterface
  6681. {
  6682. StringAttr name;
  6683. StringAttr alias;
  6684. StringAttr serverQueue;
  6685. StringAttr agentQueue;
  6686. StringAttr agentName;
  6687. StringAttr roxieProcess;
  6688. SocketEndpointArray roxieServers;
  6689. StringAttr thorQueue;
  6690. StringArray thorProcesses;
  6691. StringArray primaryThorProcesses;
  6692. StringAttr prefix;
  6693. StringAttr ldapUser;
  6694. StringBuffer ldapPassword;
  6695. ClusterType platform;
  6696. unsigned clusterWidth;
  6697. unsigned roxieRedundancy;
  6698. unsigned channelsPerNode;
  6699. unsigned numberOfSlaveLogs;
  6700. int roxieReplicateOffset;
  6701. public:
  6702. IMPLEMENT_IINTERFACE;
  6703. CEnvironmentClusterInfo(const char *_name, const char *_prefix, const char *_alias, IPropertyTree *agent, IArrayOf<IPropertyTree> &thors, IPropertyTree *roxie)
  6704. : name(_name), prefix(_prefix), alias(_alias), roxieRedundancy(0), channelsPerNode(0), numberOfSlaveLogs(0), roxieReplicateOffset(1)
  6705. {
  6706. StringBuffer queue;
  6707. if (thors.ordinality())
  6708. {
  6709. thorQueue.set(getClusterThorQueueName(queue.clear(), name));
  6710. clusterWidth = 0;
  6711. bool isMultiThor = (thors.length() > 1);
  6712. ForEachItemIn(i,thors)
  6713. {
  6714. IPropertyTree &thor = thors.item(i);
  6715. const char* thorName = thor.queryProp("@name");
  6716. thorProcesses.append(thorName);
  6717. if (!isMultiThor)
  6718. primaryThorProcesses.append(thorName);
  6719. else
  6720. {
  6721. const char *nodeGroup = thor.queryProp("@nodeGroup");
  6722. if (!nodeGroup || strieq(nodeGroup, thorName))
  6723. primaryThorProcesses.append(thorName);
  6724. }
  6725. unsigned nodes = thor.getCount("ThorSlaveProcess");
  6726. if (!nodes)
  6727. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: Thor cluster can not have 0 slave processes");
  6728. unsigned slavesPerNode = thor.getPropInt("@slavesPerNode", 1);
  6729. unsigned channelsPerSlave = thor.getPropInt("@channelsPerSlave", 1);
  6730. unsigned ts = nodes * slavesPerNode * channelsPerSlave;
  6731. numberOfSlaveLogs = nodes * slavesPerNode;
  6732. if (clusterWidth && (ts!=clusterWidth))
  6733. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: mismatched thor sizes in cluster");
  6734. clusterWidth = ts;
  6735. bool islcr = !thor.getPropBool("@Legacy");
  6736. if (!islcr)
  6737. throw MakeStringException(WUERR_MismatchThorType,"CEnvironmentClusterInfo: Legacy Thor no longer supported");
  6738. }
  6739. platform = ThorLCRCluster;
  6740. }
  6741. else if (roxie)
  6742. {
  6743. roxieProcess.set(roxie->queryProp("@name"));
  6744. platform = RoxieCluster;
  6745. getRoxieProcessServers(roxie, roxieServers);
  6746. clusterWidth = roxieServers.length();
  6747. ldapUser.set(roxie->queryProp("@ldapUser"));
  6748. StringBuffer encPassword (roxie->queryProp("@ldapPassword"));
  6749. if (encPassword.length())
  6750. decrypt(ldapPassword, encPassword);
  6751. const char *redundancyMode = roxie->queryProp("@slaveConfig");
  6752. if (redundancyMode && *redundancyMode)
  6753. {
  6754. unsigned dataCopies = roxie->getPropInt("@numDataCopies", 1);
  6755. if (strieq(redundancyMode, "overloaded"))
  6756. channelsPerNode = roxie->getPropInt("@channelsPernode", 1);
  6757. else if (strieq(redundancyMode, "full redundancy"))
  6758. {
  6759. roxieRedundancy = dataCopies-1;
  6760. roxieReplicateOffset = 0;
  6761. }
  6762. else if (strieq(redundancyMode, "cyclic redundancy"))
  6763. {
  6764. roxieRedundancy = dataCopies-1;
  6765. channelsPerNode = dataCopies;
  6766. roxieReplicateOffset = roxie->getPropInt("@cyclicOffset", 1);
  6767. }
  6768. }
  6769. }
  6770. else
  6771. {
  6772. clusterWidth = 1;
  6773. platform = HThorCluster;
  6774. }
  6775. if (agent)
  6776. {
  6777. assertex(!roxie);
  6778. agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
  6779. agentName.set(agent->queryProp("@name"));
  6780. }
  6781. else if (roxie)
  6782. agentQueue.set(getClusterRoxieQueueName(queue.clear(), name));
  6783. // MORE - does this need to be conditional?
  6784. serverQueue.set(getClusterEclCCServerQueueName(queue.clear(), name));
  6785. }
  6786. IStringVal & getName(IStringVal & str) const
  6787. {
  6788. str.set(name.get());
  6789. return str;
  6790. }
  6791. const char *getAlias() const
  6792. {
  6793. return alias;
  6794. }
  6795. IStringVal & getScope(IStringVal & str) const
  6796. {
  6797. str.set(prefix.get());
  6798. return str;
  6799. }
  6800. IStringVal & getAgentQueue(IStringVal & str) const
  6801. {
  6802. str.set(agentQueue);
  6803. return str;
  6804. }
  6805. IStringVal & getAgentName(IStringVal & str) const
  6806. {
  6807. str.set(agentName);
  6808. return str;
  6809. }
  6810. virtual IStringVal & getServerQueue(IStringVal & str) const
  6811. {
  6812. str.set(serverQueue);
  6813. return str;
  6814. }
  6815. IStringVal & getThorQueue(IStringVal & str) const
  6816. {
  6817. str.set(thorQueue);
  6818. return str;
  6819. }
  6820. unsigned getSize() const
  6821. {
  6822. return clusterWidth;
  6823. }
  6824. unsigned getNumberOfSlaveLogs() const
  6825. {
  6826. return numberOfSlaveLogs;
  6827. }
  6828. virtual ClusterType getPlatform() const
  6829. {
  6830. return platform;
  6831. }
  6832. IStringVal & getRoxieProcess(IStringVal & str) const
  6833. {
  6834. str.set(roxieProcess.get());
  6835. return str;
  6836. }
  6837. const StringArray & getThorProcesses() const
  6838. {
  6839. return thorProcesses;
  6840. }
  6841. const StringArray & getPrimaryThorProcesses() const
  6842. {
  6843. return primaryThorProcesses;
  6844. }
  6845. const SocketEndpointArray & getRoxieServers() const
  6846. {
  6847. return roxieServers;
  6848. }
  6849. unsigned getRoxieRedundancy() const
  6850. {
  6851. return roxieRedundancy;
  6852. }
  6853. unsigned getChannelsPerNode() const
  6854. {
  6855. return channelsPerNode;
  6856. }
  6857. int getRoxieReplicateOffset() const
  6858. {
  6859. return roxieReplicateOffset;
  6860. }
  6861. const char *getLdapUser() const
  6862. {
  6863. return ldapUser.get();
  6864. }
  6865. virtual const char *getLdapPassword() const
  6866. {
  6867. return ldapPassword.str();
  6868. }
  6869. };
  6870. IStringVal &getProcessQueueNames(IStringVal &ret, const char *process, const char *type, const char *suffix)
  6871. {
  6872. if (process)
  6873. {
  6874. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6875. Owned<IConstEnvironment> env = factory->openEnvironment();
  6876. Owned<IPropertyTree> root = &env->getPTree();
  6877. StringBuffer queueNames;
  6878. StringBuffer xpath;
  6879. xpath.appendf("%s[@process=\"%s\"]", type, process);
  6880. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  6881. ForEach(*targets)
  6882. {
  6883. IPropertyTree &target = targets->query();
  6884. if (target.hasProp(xpath))
  6885. {
  6886. if (queueNames.length())
  6887. queueNames.append(',');
  6888. queueNames.append(target.queryProp("@name")).append(suffix);
  6889. }
  6890. }
  6891. ret.set(queueNames);
  6892. }
  6893. return ret;
  6894. }
  6895. #define ROXIE_QUEUE_EXT ".roxie"
  6896. #define THOR_QUEUE_EXT ".thor"
  6897. #define ECLCCSERVER_QUEUE_EXT ".eclserver"
  6898. #define ECLSERVER_QUEUE_EXT ECLCCSERVER_QUEUE_EXT
  6899. #define ECLSCHEDULER_QUEUE_EXT ".eclscheduler"
  6900. #define ECLAGENT_QUEUE_EXT ".agent"
  6901. extern WORKUNIT_API void getDFUServerQueueNames(StringArray &ret, const char *process)
  6902. {
  6903. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6904. Owned<IConstEnvironment> env = factory->openEnvironment();
  6905. StringBuffer xpath ("Software/DfuServerProcess");
  6906. if (!isEmptyString(process))
  6907. xpath.appendf("[@name=\"%s\"]", process);
  6908. Owned<IPropertyTree> root = &env->getPTree();
  6909. Owned<IPropertyTreeIterator> targets = root->getElements(xpath.str());
  6910. ForEach(*targets)
  6911. {
  6912. IPropertyTree &target = targets->query();
  6913. if (target.hasProp("@queue"))
  6914. ret.appendListUniq(target.queryProp("@queue"), ",");
  6915. }
  6916. return;
  6917. }
  6918. extern WORKUNIT_API IStringVal &getEclCCServerQueueNames(IStringVal &ret, const char *process)
  6919. {
  6920. return getProcessQueueNames(ret, process, "EclCCServerProcess", ECLCCSERVER_QUEUE_EXT);
  6921. }
  6922. extern WORKUNIT_API IStringVal &getEclServerQueueNames(IStringVal &ret, const char *process)
  6923. {
  6924. return getProcessQueueNames(ret, process, "EclServerProcess", ECLSERVER_QUEUE_EXT); // shares queue name with EclCCServer
  6925. }
  6926. extern WORKUNIT_API IStringVal &getEclSchedulerQueueNames(IStringVal &ret, const char *process)
  6927. {
  6928. return getProcessQueueNames(ret, process, "EclSchedulerProcess", ECLSCHEDULER_QUEUE_EXT); // Shares deployment/config with EclCCServer
  6929. }
  6930. extern WORKUNIT_API IStringVal &getAgentQueueNames(IStringVal &ret, const char *process)
  6931. {
  6932. return getProcessQueueNames(ret, process, "EclAgentProcess", ECLAGENT_QUEUE_EXT);
  6933. }
  6934. extern WORKUNIT_API IStringVal &getRoxieQueueNames(IStringVal &ret, const char *process)
  6935. {
  6936. return getProcessQueueNames(ret, process, "RoxieCluster", ROXIE_QUEUE_EXT);
  6937. }
  6938. extern WORKUNIT_API IStringVal &getThorQueueNames(IStringVal &ret, const char *process)
  6939. {
  6940. return getProcessQueueNames(ret, process, "ThorCluster", THOR_QUEUE_EXT);
  6941. }
  6942. extern WORKUNIT_API StringBuffer &getClusterThorQueueName(StringBuffer &ret, const char *cluster)
  6943. {
  6944. return ret.append(cluster).append(THOR_QUEUE_EXT);
  6945. }
  6946. extern WORKUNIT_API StringBuffer &getClusterThorGroupName(StringBuffer &ret, const char *cluster)
  6947. {
  6948. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6949. Owned<IConstEnvironment> env = factory->openEnvironment();
  6950. Owned<IPropertyTree> root = &env->getPTree();
  6951. StringBuffer path;
  6952. path.append("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6953. IPropertyTree * child = root->queryPropTree(path);
  6954. if (child)
  6955. getClusterGroupName(*child, ret);
  6956. return ret;
  6957. }
  6958. extern WORKUNIT_API StringBuffer &getClusterGroupName(StringBuffer &ret, const char *cluster)
  6959. {
  6960. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6961. Owned<IConstEnvironment> env = factory->openEnvironment();
  6962. Owned<IPropertyTree> root = &env->getPTree();
  6963. StringBuffer path;
  6964. path.set("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6965. IPropertyTree * child = root->queryPropTree(path);
  6966. if (child)
  6967. {
  6968. return getClusterGroupName(*child, ret);
  6969. }
  6970. path.set("Software/RoxieCluster[@name=\"").append(cluster).append("\"]");
  6971. child = root->queryPropTree(path);
  6972. if (child)
  6973. {
  6974. return getClusterGroupName(*child, ret);
  6975. }
  6976. path.set("Software/EclAgentProcess[@name=\"").append(cluster).append("\"]");
  6977. child = root->queryPropTree(path);
  6978. if (child)
  6979. {
  6980. return ret.setf("hthor__%s", cluster);
  6981. }
  6982. return ret;
  6983. }
  6984. extern WORKUNIT_API ClusterType getClusterTypeByClusterName(const char *cluster)
  6985. {
  6986. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6987. Owned<IConstEnvironment> env = factory->openEnvironment();
  6988. Owned<IPropertyTree> root = &env->getPTree();
  6989. StringBuffer path;
  6990. path.set("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6991. if (root->hasProp(path))
  6992. return ThorLCRCluster;
  6993. path.set("Software/RoxieCluster[@name=\"").append(cluster).append("\"]");
  6994. if (root->hasProp(path))
  6995. return RoxieCluster;
  6996. path.set("Software/EclAgentProcess[@name=\"").append(cluster).append("\"]");
  6997. if (root->hasProp(path))
  6998. return HThorCluster;
  6999. return NoCluster;
  7000. }
  7001. extern WORKUNIT_API StringBuffer &getClusterRoxieQueueName(StringBuffer &ret, const char *cluster)
  7002. {
  7003. return ret.append(cluster).append(ROXIE_QUEUE_EXT);
  7004. }
  7005. extern WORKUNIT_API StringBuffer &getClusterEclCCServerQueueName(StringBuffer &ret, const char *cluster)
  7006. {
  7007. return ret.append(cluster).append(ECLCCSERVER_QUEUE_EXT);
  7008. }
  7009. extern WORKUNIT_API StringBuffer &getClusterEclServerQueueName(StringBuffer &ret, const char *cluster)
  7010. {
  7011. return ret.append(cluster).append(ECLSERVER_QUEUE_EXT);
  7012. }
  7013. extern WORKUNIT_API StringBuffer &getClusterEclAgentQueueName(StringBuffer &ret, const char *cluster)
  7014. {
  7015. return ret.append(cluster).append(ECLAGENT_QUEUE_EXT);
  7016. }
  7017. extern WORKUNIT_API IStringIterator *getTargetClusters(const char *processType, const char *processName)
  7018. {
  7019. Owned<CStringArrayIterator> ret = new CStringArrayIterator;
  7020. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7021. Owned<IConstEnvironment> env = factory->openEnvironment();
  7022. Owned<IPropertyTree> root = &env->getPTree();
  7023. StringBuffer xpath;
  7024. xpath.appendf("%s", processType ? processType : "*");
  7025. if (processName && *processName)
  7026. xpath.appendf("[@process=\"%s\"]", processName);
  7027. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  7028. ForEach(*targets)
  7029. {
  7030. IPropertyTree &target = targets->query();
  7031. if (target.hasProp(xpath))
  7032. {
  7033. ret->append(target.queryProp("@name"));
  7034. }
  7035. }
  7036. return ret.getClear();
  7037. }
  7038. extern WORKUNIT_API bool isProcessCluster(const char *process)
  7039. {
  7040. if (!process || !*process)
  7041. return false;
  7042. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7043. Owned<IConstEnvironment> env = factory->openEnvironment();
  7044. Owned<IPropertyTree> root = &env->getPTree();
  7045. VStringBuffer xpath("Software/*Cluster[@name=\"%s\"]", process);
  7046. return root->hasProp(xpath.str());
  7047. }
  7048. extern WORKUNIT_API bool isProcessCluster(const char *remoteDali, const char *process)
  7049. {
  7050. if (!remoteDali || !*remoteDali)
  7051. return isProcessCluster(process);
  7052. if (!process || !*process)
  7053. return false;
  7054. Owned<INode> remote = createINode(remoteDali, 7070);
  7055. if (!remote)
  7056. return false;
  7057. //Cannot use getEnvironmentFactory() since it is using a remotedali
  7058. VStringBuffer xpath("Environment/Software/*Cluster[@name=\"%s\"]/@name", process);
  7059. try
  7060. {
  7061. Owned<IPropertyTreeIterator> clusters = querySDS().getElementsRaw(xpath, remote, 1000*60*1);
  7062. return clusters->first();
  7063. }
  7064. catch (IException *E)
  7065. {
  7066. StringBuffer msg;
  7067. E->errorMessage(msg);
  7068. DBGLOG("Exception validating cluster %s/%s: %s", remoteDali, xpath.str(), msg.str());
  7069. E->Release();
  7070. }
  7071. return true;
  7072. }
  7073. IConstWUClusterInfo* getTargetClusterInfo(IPropertyTree *environment, IPropertyTree *cluster)
  7074. {
  7075. const char *clustname = cluster->queryProp("@name");
  7076. // MORE - at the moment configenf specifies eclagent and thor queues by (in effect) placing an 'example' thor or eclagent in the topology
  7077. // that uses the queue that will be used.
  7078. // We should and I hope will change that, at which point the code below gets simpler
  7079. StringBuffer prefix(cluster->queryProp("@prefix"));
  7080. prefix.toLowerCase();
  7081. StringBuffer xpath;
  7082. StringBuffer querySetName;
  7083. IPropertyTree *agent = NULL;
  7084. const char *agentName = cluster->queryProp("EclAgentProcess/@process");
  7085. if (agentName)
  7086. {
  7087. xpath.clear().appendf("Software/EclAgentProcess[@name=\"%s\"]", agentName);
  7088. agent = environment->queryPropTree(xpath.str());
  7089. }
  7090. Owned<IPropertyTreeIterator> ti = cluster->getElements("ThorCluster");
  7091. IArrayOf<IPropertyTree> thors;
  7092. ForEach(*ti)
  7093. {
  7094. const char *thorName = ti->query().queryProp("@process");
  7095. if (thorName)
  7096. {
  7097. xpath.clear().appendf("Software/ThorCluster[@name=\"%s\"]", thorName);
  7098. thors.append(*environment->getPropTree(xpath.str()));
  7099. }
  7100. }
  7101. const char *roxieName = cluster->queryProp("RoxieCluster/@process");
  7102. return new CEnvironmentClusterInfo(clustname, prefix, cluster->queryProp("@alias"), agent, thors, queryRoxieProcessTree(environment, roxieName));
  7103. }
  7104. IPropertyTree* getTopologyCluster(Owned<IPropertyTree> &envRoot, const char *clustname)
  7105. {
  7106. if (!clustname || !*clustname)
  7107. return NULL;
  7108. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7109. Owned<IConstEnvironment> env = factory->openEnvironment();
  7110. envRoot.setown(&env->getPTree());
  7111. StringBuffer xpath;
  7112. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  7113. return envRoot->getPropTree(xpath.str());
  7114. }
  7115. bool validateTargetClusterName(const char *clustname)
  7116. {
  7117. Owned<IPropertyTree> envRoot;
  7118. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  7119. return (cluster.get()!=NULL);
  7120. }
  7121. IConstWUClusterInfo* getTargetClusterInfo(const char *clustname)
  7122. {
  7123. Owned<IPropertyTree> envRoot;
  7124. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  7125. if (!cluster)
  7126. return NULL;
  7127. return getTargetClusterInfo(envRoot, cluster);
  7128. }
  7129. unsigned getEnvironmentClusterInfo(CConstWUClusterInfoArray &clusters)
  7130. {
  7131. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7132. Owned<IConstEnvironment> env = factory->openEnvironment();
  7133. Owned<IPropertyTree> root = &env->getPTree();
  7134. return getEnvironmentClusterInfo(root, clusters);
  7135. }
  7136. unsigned getEnvironmentClusterInfo(IPropertyTree* environmentRoot, CConstWUClusterInfoArray &clusters)
  7137. {
  7138. if (!environmentRoot)
  7139. return 0;
  7140. Owned<IPropertyTreeIterator> clusterIter = environmentRoot->getElements("Software/Topology/Cluster");
  7141. ForEach(*clusterIter)
  7142. {
  7143. IPropertyTree &node = clusterIter->query();
  7144. Owned<IConstWUClusterInfo> cluster = getTargetClusterInfo(environmentRoot, &node);
  7145. clusters.append(*cluster.getClear());
  7146. }
  7147. return clusters.ordinality();
  7148. }
  7149. const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name)
  7150. {
  7151. if (!clustname)
  7152. return NULL;
  7153. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7154. Owned<IConstEnvironment> env = factory->openEnvironment();
  7155. Owned<IPropertyTree> root = &env->getPTree();
  7156. StringBuffer xpath;
  7157. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  7158. Owned<IPropertyTree> cluster = root->getPropTree(xpath.str());
  7159. if (!cluster)
  7160. return NULL;
  7161. StringBuffer xpath1;
  7162. xpath1.appendf("%s/@process", processType);
  7163. name.append(cluster->queryProp(xpath1.str()));
  7164. return name.str();
  7165. }
  7166. unsigned getEnvironmentThorClusterNames(StringArray &thorNames, StringArray &groupNames, StringArray &targetNames, StringArray &queueNames)
  7167. {
  7168. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7169. Owned<IConstEnvironment> env = factory->openEnvironment();
  7170. Owned<IPropertyTree> root = &env->getPTree();
  7171. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  7172. ForEach(*allTargets)
  7173. {
  7174. IPropertyTree &target = allTargets->query();
  7175. const char *targetName = target.queryProp("@name");
  7176. if (targetName && *targetName)
  7177. {
  7178. Owned<IPropertyTreeIterator> thorClusters = target.getElements("ThorCluster");
  7179. ForEach(*thorClusters)
  7180. {
  7181. const char *thorName = thorClusters->query().queryProp("@process");
  7182. VStringBuffer query("Software/ThorCluster[@name=\"%s\"]",thorName);
  7183. IPropertyTree *thorCluster = root->queryPropTree(query.str());
  7184. if (thorCluster)
  7185. {
  7186. const char *groupName = thorCluster->queryProp("@nodeGroup");
  7187. if (!groupName||!*groupName)
  7188. groupName = thorName;
  7189. thorNames.append(thorName);
  7190. groupNames.append(groupName);
  7191. targetNames.append(targetName);
  7192. StringBuffer queueName(targetName);
  7193. queueNames.append(queueName.append(THOR_QUEUE_EXT));
  7194. }
  7195. }
  7196. }
  7197. }
  7198. return thorNames.ordinality();
  7199. }
  7200. unsigned getEnvironmentHThorClusterNames(StringArray &eclAgentNames, StringArray &groupNames, StringArray &targetNames)
  7201. {
  7202. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7203. Owned<IConstEnvironment> env = factory->openEnvironment();
  7204. Owned<IPropertyTree> root = &env->getPTree();
  7205. Owned<IPropertyTreeIterator> allEclAgents = root->getElements("Software/EclAgentProcess");
  7206. ForEach(*allEclAgents)
  7207. {
  7208. IPropertyTree &eclAgent = allEclAgents->query();
  7209. const char *eclAgentName = eclAgent.queryProp("@name");
  7210. if (eclAgentName && *eclAgentName)
  7211. {
  7212. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  7213. ForEach(*allTargets)
  7214. {
  7215. IPropertyTree &target = allTargets->query();
  7216. const char *targetName = target.queryProp("@name");
  7217. if (targetName && *targetName)
  7218. {
  7219. StringBuffer xpath;
  7220. xpath.appendf("EclAgentProcess[@process=\"%s\"]", eclAgentName);
  7221. if (target.hasProp(xpath) && !target.hasProp("ThorCluster"))
  7222. {
  7223. StringBuffer groupName("hthor__");
  7224. groupName.append(eclAgentName);
  7225. groupNames.append(groupName);
  7226. eclAgentNames.append(eclAgentName);
  7227. targetNames.append(targetName);
  7228. }
  7229. }
  7230. }
  7231. }
  7232. }
  7233. return eclAgentNames.ordinality();
  7234. }
  7235. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  7236. {
  7237. CriticalBlock block(crit);
  7238. if (p->hasProp("Debug/ForceScope"))
  7239. {
  7240. StringBuffer prefix(p->queryProp("Debug/ForceScope"));
  7241. str.set(prefix.toLowerCase().str());
  7242. }
  7243. else
  7244. {
  7245. Owned <IConstWUClusterInfo> ci = getTargetClusterInfo(p->queryProp("@clusterName"));
  7246. if (ci)
  7247. ci->getScope(str);
  7248. else
  7249. str.clear();
  7250. }
  7251. return str;
  7252. }
  7253. //Queries
  7254. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  7255. {
  7256. CriticalBlock block(crit);
  7257. p->setPropInt("@codeVersion", codeVersion);
  7258. p->setProp("@buildVersion", buildVersion);
  7259. p->setProp("@eclVersion", eclVersion);
  7260. }
  7261. unsigned CLocalWorkUnit::getCodeVersion() const
  7262. {
  7263. CriticalBlock block(crit);
  7264. return p->getPropInt("@codeVersion");
  7265. }
  7266. unsigned CLocalWorkUnit::getWuidVersion() const
  7267. {
  7268. CriticalBlock block(crit);
  7269. return p->getPropInt("@wuidVersion");
  7270. }
  7271. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  7272. {
  7273. CriticalBlock block(crit);
  7274. buildVersion.set(p->queryProp("@buildVersion"));
  7275. eclVersion.set(p->queryProp("@eclVersion"));
  7276. }
  7277. void CLocalWorkUnit::setCloneable(bool value)
  7278. {
  7279. CriticalBlock block(crit);
  7280. p->setPropInt("@cloneable", value);
  7281. }
  7282. void CLocalWorkUnit::setIsClone(bool value)
  7283. {
  7284. CriticalBlock block(crit);
  7285. p->setPropInt("@isClone", value);
  7286. }
  7287. bool CLocalWorkUnit::getCloneable() const
  7288. {
  7289. CriticalBlock block(crit);
  7290. return p->getPropBool("@cloneable", false);
  7291. }
  7292. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  7293. {
  7294. CriticalBlock block(crit);
  7295. if (!userDesc)
  7296. {
  7297. userDesc.setown(createUserDescriptor());
  7298. SCMStringBuffer token;
  7299. getWorkunitDistributedAccessToken(token);
  7300. userDesc->set(queryUser(), token.str());//use token as password
  7301. }
  7302. return userDesc;
  7303. }
  7304. bool CLocalWorkUnit::isProtected() const
  7305. {
  7306. CriticalBlock block(crit);
  7307. return p->getPropBool("@protected", false);
  7308. }
  7309. bool CLocalWorkUnit::isPausing() const
  7310. {
  7311. CriticalBlock block(crit);
  7312. if (WUActionPause == getAction())
  7313. {
  7314. switch (getState())
  7315. {
  7316. case WUStateRunning:
  7317. case WUStateAborting:
  7318. return true;
  7319. }
  7320. }
  7321. return false;
  7322. }
  7323. void CLocalWorkUnit::protect(bool protectMode)
  7324. {
  7325. CriticalBlock block(crit);
  7326. p->setPropBool("@protected", protectMode);
  7327. }
  7328. void CLocalWorkUnit::setResultLimit(unsigned value)
  7329. {
  7330. CriticalBlock block(crit);
  7331. p->setPropInt("resultLimit", value);
  7332. }
  7333. unsigned CLocalWorkUnit::getResultLimit() const
  7334. {
  7335. CriticalBlock block(crit);
  7336. return p->getPropInt("resultLimit");
  7337. }
  7338. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  7339. {
  7340. CriticalBlock block(crit);
  7341. str.set(p->queryProp("SNAPSHOT"));
  7342. return str;
  7343. }
  7344. void CLocalWorkUnit::setSnapshot(const char * val)
  7345. {
  7346. CriticalBlock block(crit);
  7347. p->setProp("SNAPSHOT", val);
  7348. }
  7349. const static EnumMapping warningSeverityMap[] =
  7350. {
  7351. { SeverityInformation, "info" },
  7352. { SeverityWarning, "warning" },
  7353. { SeverityError, "error" },
  7354. { SeverityAlert, "alert" },
  7355. { SeverityIgnore, "ignore" },
  7356. { SeverityFatal, "fatal" },
  7357. { SeverityUnknown, NULL }
  7358. };
  7359. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  7360. {
  7361. StringBuffer xpath;
  7362. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7363. CriticalBlock block(crit);
  7364. IPropertyTree * mapping = p->queryPropTree(xpath);
  7365. if (mapping)
  7366. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  7367. return defaultSeverity;
  7368. }
  7369. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  7370. {
  7371. StringBuffer xpath;
  7372. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7373. CriticalBlock block(crit);
  7374. IPropertyTree * mapping = p->queryPropTree(xpath);
  7375. if (!mapping)
  7376. {
  7377. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  7378. mapping = onWarnings->addPropTree("OnWarning");
  7379. mapping->setPropInt("@code", code);
  7380. }
  7381. setEnum(mapping, "@severity", severity, warningSeverityMap);
  7382. }
  7383. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  7384. {
  7385. IPropertyTree *l = (IPropertyTree *) *ll;
  7386. IPropertyTree *r = (IPropertyTree *) *rr;
  7387. return stricmp(l->queryName(), r->queryName());
  7388. };
  7389. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  7390. {
  7391. // Any other values in the WU that could affect generated code should be crc'ed here
  7392. IPropertyTree *tree = p->queryBranch("Debug");
  7393. if (tree)
  7394. {
  7395. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  7396. ICopyArrayOf<IPropertyTree> subs;
  7397. for(sub->first(); sub->isValid(); sub->next())
  7398. subs.append(sub->query());
  7399. subs.sort(comparePropTrees);
  7400. ForEachItemIn(idx, subs)
  7401. {
  7402. const char *name = subs.item(idx).queryName();
  7403. const char *val = subs.item(idx).queryProp(NULL);
  7404. crc = crc32(name, (size32_t)strlen(name), crc);
  7405. if (val)
  7406. crc = crc32(val, (size32_t)strlen(val), crc);
  7407. }
  7408. }
  7409. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  7410. for (plugins->first();plugins->isValid();plugins->next())
  7411. {
  7412. IConstWUPlugin &thisplugin = plugins->query();
  7413. SCMStringBuffer version;
  7414. thisplugin.getPluginVersion(version);
  7415. crc = crc32(version.str(), version.length(), crc);
  7416. }
  7417. return crc;
  7418. }
  7419. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7420. {
  7421. if (!to->hasProp(xpath) && from->hasProp(xpath))
  7422. to->setProp(xpath, from->queryProp(xpath));
  7423. }
  7424. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7425. {
  7426. if (from->hasProp(xpath))
  7427. to->setProp(xpath, from->queryProp(xpath));
  7428. }
  7429. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7430. {
  7431. IPropertyTree * match = from->getBranch(xpath);
  7432. if (match)
  7433. to->setPropTree(xpath, match);
  7434. }
  7435. IPropertyTree *CLocalWorkUnit::queryPTree() const
  7436. {
  7437. return p;
  7438. }
  7439. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  7440. {
  7441. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  7442. if (!from)
  7443. {
  7444. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  7445. if (!fl)
  7446. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  7447. from = fl->c;
  7448. }
  7449. // Need to copy the query, the results, and the graphs from the cached query.
  7450. // The cache is made before the query is executed so there is no need to clear them.
  7451. if (!cached->getCloneable())
  7452. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  7453. const IPropertyTree * fromP = from->p;
  7454. IPropertyTree *pt;
  7455. CriticalBlock block(crit);
  7456. clearCached(false);
  7457. query.clear();
  7458. updateProp(p, fromP, "@jobName");
  7459. copyTree(p, fromP, "Query");
  7460. pt = fromP->getBranch("Application/LibraryModule");
  7461. if (pt)
  7462. {
  7463. ensurePTree(p, "Application");
  7464. p->setPropTree("Application/LibraryModule", pt);
  7465. }
  7466. pt = fromP->queryBranch("Debug");
  7467. if (pt)
  7468. {
  7469. IPropertyTree *curDebug = p->queryPropTree("Debug");
  7470. if (curDebug)
  7471. {
  7472. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  7473. ForEach(*elems)
  7474. {
  7475. IPropertyTree *elem = &elems->query();
  7476. if (!curDebug->hasProp(elem->queryName()))
  7477. curDebug->setPropTree(elem->queryName(),LINK(elem));
  7478. }
  7479. }
  7480. else
  7481. p->setPropTree("Debug", LINK(pt));
  7482. }
  7483. copyTree(p, fromP, "OnWarnings");
  7484. copyTree(p, fromP, "Plugins");
  7485. copyTree(p, fromP, "Libraries");
  7486. copyTree(p, fromP, "Results");
  7487. copyTree(p, fromP, "Graphs");
  7488. copyTree(p, fromP, "Workflow");
  7489. copyTree(p, fromP, "WebServicesInfo");
  7490. if (copyStats)
  7491. {
  7492. // Merge timing info from both branches
  7493. pt = fromP->getBranch("Statistics");
  7494. if (pt)
  7495. {
  7496. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7497. mergePTree(tgtStatistics, pt);
  7498. pt->Release();
  7499. }
  7500. }
  7501. updateProp(p, fromP, "@clusterName");
  7502. updateProp(p, fromP, "allowedclusters");
  7503. updateProp(p, fromP, "@submitID");
  7504. updateProp(p, fromP, "SNAPSHOT");
  7505. setProp(p, fromP, "@eventScheduledCount");
  7506. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7507. if (all)
  7508. {
  7509. setProp(p, fromP, "PriorityFlag");
  7510. setProp(p, fromP, "@priorityClass");
  7511. setProp(p, fromP, "@protected");
  7512. setProp(p, fromP, "@clusterName");
  7513. updateProp(p, fromP, "@scope");
  7514. }
  7515. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7516. pt = fromP->getBranch("Variables");
  7517. if (pt)
  7518. {
  7519. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7520. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7521. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7522. {
  7523. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7524. const char *name = ptSrcVariable->queryProp("@name");
  7525. assertex(name);
  7526. StringBuffer xpath;
  7527. xpath.append("Variable[@name='").append(name).append("']");
  7528. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7529. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7530. merged->removeProp("Value"); // except value and status
  7531. merged->setProp("@status", "undefined");
  7532. if (!merged->getPropBool("@isScalar"))
  7533. merged->removeProp("totalRowCount");
  7534. merged->removeProp("rowCount");
  7535. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7536. if (ptTgtVariable)
  7537. {
  7538. // copy status and Value from what is already set in target
  7539. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7540. MemoryBuffer value;
  7541. if (ptTgtVariable->getPropBin("Value", value))
  7542. merged->setPropBin("Value", value.length(), value.toByteArray());
  7543. ptTgtVariable->removeProp(xpath.str());
  7544. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7545. }
  7546. ptTgtVariables->addPropTree("Variable", merged);
  7547. }
  7548. pt->Release();
  7549. }
  7550. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7551. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7552. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7553. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7554. p->setProp("@hash", fromP->queryProp("@hash"));
  7555. p->setPropBool("@cloneable", true);
  7556. p->setPropBool("@isClone", true);
  7557. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7558. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7559. ForEach(*results)
  7560. {
  7561. CLocalWUResult result(LINK(&results->query()));
  7562. result.setResultStatus(ResultStatusUndefined);
  7563. }
  7564. copyTree(p, fromP, "usedsources"); // field usage
  7565. }
  7566. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7567. {
  7568. StringBuffer lower;
  7569. lower.append(propname).toLowerCase();
  7570. CriticalBlock block(crit);
  7571. StringBuffer prop("Debug/");
  7572. return p->hasProp(prop.append(lower));
  7573. }
  7574. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7575. {
  7576. StringBuffer lower;
  7577. lower.append(propname).toLowerCase();
  7578. CriticalBlock block(crit);
  7579. StringBuffer prop("Debug/");
  7580. str.set(p->queryProp(prop.append(lower).str()));
  7581. return str;
  7582. }
  7583. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7584. {
  7585. return getDebugValues(NULL);
  7586. }
  7587. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7588. {
  7589. CriticalBlock block(crit);
  7590. StringBuffer path("Debug/");
  7591. if (prop)
  7592. {
  7593. StringBuffer lower;
  7594. lower.append(prop).toLowerCase();
  7595. path.append(lower);
  7596. }
  7597. else
  7598. path.append("*");
  7599. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7600. }
  7601. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7602. {
  7603. StringBuffer lower;
  7604. lower.append(propname).toLowerCase();
  7605. CriticalBlock block(crit);
  7606. StringBuffer prop("Debug/");
  7607. prop.append(lower);
  7608. return p->getPropInt(prop.str(), defVal);
  7609. }
  7610. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7611. {
  7612. StringBuffer lower;
  7613. lower.append(propname).toLowerCase();
  7614. CriticalBlock block(crit);
  7615. StringBuffer prop("Debug/");
  7616. prop.append(lower);
  7617. return p->getPropInt64(prop.str(), defVal);
  7618. }
  7619. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7620. {
  7621. StringBuffer lower;
  7622. lower.append(propname).toLowerCase();
  7623. CriticalBlock block(crit);
  7624. StringBuffer prop("Debug/");
  7625. prop.append(lower);
  7626. return p->getPropBool(prop.str(), defVal);
  7627. }
  7628. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7629. {
  7630. VStringBuffer xpath("Process/%s/", type);
  7631. if (instance)
  7632. xpath.append(instance);
  7633. else
  7634. xpath.append("*");
  7635. CriticalBlock block(crit);
  7636. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7637. {
  7638. // NB: instance unused
  7639. if (streq("EclAgent", type))
  7640. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7641. else if (streq("Thor", type))
  7642. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7643. VStringBuffer xpath("Debug/%s", type);
  7644. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7645. }
  7646. else
  7647. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7648. }
  7649. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7650. {
  7651. VStringBuffer xpath("Process/%s/", type);
  7652. if (instance)
  7653. xpath.append(instance);
  7654. else
  7655. xpath.append("*");
  7656. CriticalBlock block(crit);
  7657. return p->getElements(xpath.str());
  7658. }
  7659. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7660. {
  7661. VStringBuffer xpath("Process/%s/*", type);
  7662. CriticalBlock block(crit);
  7663. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7664. }
  7665. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7666. {
  7667. VStringBuffer processType("Process/%s", type);
  7668. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7669. if (log)
  7670. xpath.appendf("[@log=\"%s\"]", log);
  7671. CriticalBlock block(crit);
  7672. if (!p->hasProp(xpath))
  7673. {
  7674. IPropertyTree *node = ensurePTree(p, processType.str());
  7675. node = node->addPropTree(instance);
  7676. node->setProp("@log", log);
  7677. node->setPropInt("@pid", pid);
  7678. }
  7679. }
  7680. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7681. {
  7682. StringBuffer lower;
  7683. lower.append(propname).toLowerCase();
  7684. CriticalBlock block(crit);
  7685. StringBuffer prop("Debug/");
  7686. prop.append(lower);
  7687. if (overwrite || !p->hasProp(prop.str()))
  7688. {
  7689. // MORE - not sure this line should be needed....
  7690. p->setProp("Debug", "");
  7691. p->setProp(prop.str(), value);
  7692. }
  7693. }
  7694. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7695. {
  7696. StringBuffer lower;
  7697. lower.append(propname).toLowerCase();
  7698. CriticalBlock block(crit);
  7699. StringBuffer prop("Debug/");
  7700. prop.append(lower);
  7701. if (overwrite || !p->hasProp(prop.str()))
  7702. {
  7703. // MORE - not sure this line should be needed....
  7704. p->setProp("Debug", "");
  7705. p->setPropInt(prop.str(), value);
  7706. }
  7707. }
  7708. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7709. {
  7710. CriticalBlock block(crit);
  7711. // MORE - not sure this line should be needed....
  7712. p->setProp("Tracing", "");
  7713. StringBuffer prop("Tracing/");
  7714. p->setProp(prop.append(propname).str(), value);
  7715. }
  7716. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7717. {
  7718. CriticalBlock block(crit);
  7719. StringBuffer prop("Tracing/");
  7720. p->setPropInt(prop.append(propname).str(), value);
  7721. }
  7722. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7723. {
  7724. CriticalBlock block(crit);
  7725. VStringBuffer prop("Tracing/%s", propname);
  7726. p->setPropInt64(prop.str(), value);
  7727. }
  7728. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7729. {
  7730. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7731. CriticalBlock block(crit);
  7732. if (!query)
  7733. {
  7734. IPropertyTree *s = p->getPropTree("Query");
  7735. if (s)
  7736. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7737. }
  7738. return query.getLink();
  7739. }
  7740. IWUQuery* CLocalWorkUnit::updateQuery()
  7741. {
  7742. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7743. CriticalBlock block(crit);
  7744. if (!query)
  7745. {
  7746. IPropertyTree *s = p->queryPropTree("Query");
  7747. if (!s)
  7748. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7749. s->Link();
  7750. query.setown(new CLocalWUQuery(s));
  7751. }
  7752. return query.getLink();
  7753. }
  7754. void CLocalWorkUnit::loadPlugins() const
  7755. {
  7756. CriticalBlock block(crit);
  7757. if (!pluginsCached)
  7758. {
  7759. assertex(plugins.length() == 0);
  7760. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7761. for (r->first(); r->isValid(); r->next())
  7762. {
  7763. IPropertyTree *rp = &r->query();
  7764. rp->Link();
  7765. plugins.append(*new CLocalWUPlugin(rp));
  7766. }
  7767. pluginsCached = true;
  7768. }
  7769. }
  7770. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7771. {
  7772. CriticalBlock block(crit);
  7773. loadPlugins();
  7774. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7775. }
  7776. void CLocalWorkUnit::loadLibraries() const
  7777. {
  7778. CriticalBlock block(crit);
  7779. if (!librariesCached)
  7780. {
  7781. assertex(libraries.length() == 0);
  7782. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7783. ForEach(*r)
  7784. {
  7785. IPropertyTree *rp = &r->query();
  7786. rp->Link();
  7787. libraries.append(*new CLocalWULibrary(rp));
  7788. }
  7789. librariesCached = true;
  7790. }
  7791. }
  7792. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7793. {
  7794. CriticalBlock block(crit);
  7795. loadLibraries();
  7796. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7797. }
  7798. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7799. {
  7800. CriticalBlock block(crit);
  7801. loadLibraries();
  7802. ForEachItemIn(idx, libraries)
  7803. {
  7804. SCMStringBuffer name;
  7805. IConstWULibrary &cur = libraries.item(idx);
  7806. cur.getName(name);
  7807. if (stricmp(name.str(), search)==0)
  7808. return &OLINK(cur);
  7809. }
  7810. return NULL;
  7811. }
  7812. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7813. {
  7814. str.append("Graph ").append(graphName);
  7815. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7816. else if (subId) str.append(" - id(").append(subId).append(")");
  7817. return str;
  7818. }
  7819. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7820. {
  7821. if (wfid)
  7822. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7823. str.append(graphName);
  7824. if (subId) str.append(":sg").append(subId);
  7825. return str;
  7826. }
  7827. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7828. {
  7829. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7830. unsigned len = (size32_t)strlen(label);
  7831. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7832. return false;
  7833. graphNum = 0;
  7834. subGraphNum = 0;
  7835. subId = 0;
  7836. const char *finger = label+6;
  7837. const char *finger2 = strchr(finger, '-');
  7838. if (NULL == finger2) // just graphName
  7839. graphName.set(finger);
  7840. else
  7841. {
  7842. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7843. finger = finger2+2; // skip '-' and space
  7844. finger2 = strchr(finger, ' ');
  7845. if (finger2)
  7846. {
  7847. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7848. finger = finger2+2; // skip space and '('
  7849. finger2 = strchr(finger, ')');
  7850. if (finger2)
  7851. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7852. }
  7853. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7854. {
  7855. finger += 3;
  7856. finger2 = strchr(finger, ')');
  7857. if (finger2)
  7858. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7859. }
  7860. }
  7861. if (graphName && !memicmp(graphName, "graph", 5))
  7862. graphNum = atoi(graphName + 5);
  7863. return true;
  7864. }
  7865. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7866. {
  7867. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7868. return false;
  7869. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7870. subGraphId = 0;
  7871. const char * colon = strchr(scope, ':');
  7872. if (!colon)
  7873. {
  7874. graphName.set(scope);
  7875. return true;
  7876. }
  7877. const char * subgraph = colon+1;
  7878. graphName.set(scope, (size32_t)(colon - scope));
  7879. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7880. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7881. return true;
  7882. }
  7883. 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)
  7884. {
  7885. if (!scope) scope = GLOBAL_SCOPE;
  7886. const char * kindName = queryStatisticName(kind);
  7887. StatisticMeasure measure = queryMeasure(kind);
  7888. //creator. scope and name must all be present, and must not contain semi colons.
  7889. assertex(creator && scope);
  7890. CriticalBlock block(crit);
  7891. IPropertyTree * stats = p->queryPropTree("Statistics");
  7892. if (!stats)
  7893. stats = p->addPropTree("Statistics");
  7894. IPropertyTree * statTree = NULL;
  7895. if (mergeAction != StatsMergeAppend)
  7896. {
  7897. StringBuffer xpath;
  7898. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7899. statTree = stats->queryPropTree(xpath.str());
  7900. }
  7901. if (!statTree)
  7902. {
  7903. statTree = stats->addPropTree("Statistic");
  7904. statTree->setProp("@creator", creator);
  7905. statTree->setProp("@scope", scope);
  7906. statTree->setProp("@kind", kindName);
  7907. //These items are primarily here to facilitate filtering.
  7908. statTree->setProp("@unit", queryMeasureName(measure));
  7909. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7910. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7911. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7912. if (optDescription)
  7913. statTree->setProp("@desc", optDescription);
  7914. if (statistics.cached)
  7915. statistics.append(LINK(statTree));
  7916. mergeAction = StatsMergeAppend;
  7917. }
  7918. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7919. {
  7920. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7921. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7922. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7923. if (oldMax < oldValue)
  7924. oldMax = oldValue;
  7925. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7926. statTree->setPropInt64("@count", count + oldCount);
  7927. if (maxValue > oldMax)
  7928. statTree->setPropInt64("@max", maxValue);
  7929. }
  7930. else
  7931. {
  7932. statTree->setPropInt64("@value", value);
  7933. statTree->setPropInt64("@count", count);
  7934. if (maxValue)
  7935. statTree->setPropInt64("@max", maxValue);
  7936. else
  7937. statTree->removeProp("@max");
  7938. }
  7939. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7940. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7941. {
  7942. _loadStatistics();
  7943. stat_type totalTime = 0;
  7944. ForEachItemIn(i, statistics)
  7945. {
  7946. IConstWUStatistic & cur = statistics.item(i);
  7947. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7948. totalTime += cur.getValue();
  7949. }
  7950. StringBuffer t;
  7951. formatTimeCollatable(t, totalTime, false);
  7952. p->setProp("@totalThorTime", t);
  7953. }
  7954. }
  7955. void CLocalWorkUnit::_loadStatistics() const
  7956. {
  7957. statistics.load(p,"Statistics/*");
  7958. }
  7959. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7960. {
  7961. //MORE: Optimize this....
  7962. WuScopeFilter filter;
  7963. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7964. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7965. if (stats->first())
  7966. return stats->getStat(kind, value);
  7967. return false;
  7968. }
  7969. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7970. {
  7971. assertex(filter.isOptimized());
  7972. WuScopeSourceFlags sources = filter.sourceFlags;
  7973. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7974. if (sources & SSFsearchGlobalStats)
  7975. {
  7976. {
  7977. CriticalBlock block(crit);
  7978. statistics.loadBranch(p,"Statistics");
  7979. }
  7980. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7981. compoundIter->addIter(localStats);
  7982. }
  7983. if (sources & SSFsearchGraphStats)
  7984. {
  7985. const char * wuid = p->queryName();
  7986. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7987. compoundIter->addIter(scopeIter);
  7988. }
  7989. if (sources & SSFsearchGraph)
  7990. {
  7991. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7992. compoundIter->addIter(graphIter);
  7993. }
  7994. if (sources & SSFsearchWorkflow)
  7995. {
  7996. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7997. if (iter)
  7998. {
  7999. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  8000. compoundIter->addIter(workflowIter);
  8001. }
  8002. }
  8003. if (sources & SSFsearchExceptions)
  8004. {
  8005. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  8006. compoundIter->addIter(notesIter);
  8007. }
  8008. return *compoundIter.getClear();
  8009. }
  8010. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  8011. {
  8012. CriticalBlock block(crit);
  8013. IConstWUPlugin *existing = getPluginByName(qname);
  8014. if (existing)
  8015. return (IWUPlugin *) existing;
  8016. if (!plugins.length())
  8017. p->addPropTree("Plugins");
  8018. IPropertyTree *pl = p->queryPropTree("Plugins");
  8019. IPropertyTree *s = pl->addPropTree("Plugin");
  8020. s->Link();
  8021. IWUPlugin* q = new CLocalWUPlugin(s);
  8022. q->Link();
  8023. plugins.append(*q);
  8024. q->setPluginName(qname);
  8025. return q;
  8026. }
  8027. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  8028. {
  8029. CriticalBlock block(crit);
  8030. loadPlugins();
  8031. ForEachItemIn(idx, plugins)
  8032. {
  8033. SCMStringBuffer name;
  8034. IConstWUPlugin &cur = plugins.item(idx);
  8035. cur.getPluginName(name);
  8036. if (stricmp(name.str(), qname)==0)
  8037. {
  8038. cur.Link();
  8039. return &cur;
  8040. }
  8041. }
  8042. return NULL;
  8043. }
  8044. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  8045. {
  8046. CriticalBlock block(crit);
  8047. IConstWULibrary *existing = getLibraryByName(qname);
  8048. if (existing)
  8049. return (IWULibrary *) existing;
  8050. if (!libraries.length())
  8051. p->addPropTree("Libraries");
  8052. IPropertyTree *pl = p->queryPropTree("Libraries");
  8053. IPropertyTree *s = pl->addPropTree("Library");
  8054. s->Link();
  8055. IWULibrary* q = new CLocalWULibrary(s);
  8056. q->Link();
  8057. libraries.append(*q);
  8058. q->setName(qname);
  8059. return q;
  8060. }
  8061. void CLocalWorkUnit::_loadExceptions() const
  8062. {
  8063. assertex(exceptions.length() == 0);
  8064. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  8065. for (r->first(); r->isValid(); r->next())
  8066. {
  8067. IPropertyTree *rp = &r->query();
  8068. rp->Link();
  8069. exceptions.append(*new CLocalWUException(rp));
  8070. }
  8071. }
  8072. void CLocalWorkUnit::loadExceptions() const
  8073. {
  8074. CriticalBlock block(crit);
  8075. if (!exceptionsCached)
  8076. {
  8077. _loadExceptions();
  8078. exceptionsCached = true;
  8079. }
  8080. }
  8081. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  8082. {
  8083. CriticalBlock block(crit);
  8084. loadExceptions();
  8085. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  8086. }
  8087. unsigned CLocalWorkUnit::getExceptionCount() const
  8088. {
  8089. CriticalBlock block(crit);
  8090. loadExceptions();
  8091. return exceptions.length();
  8092. }
  8093. void CLocalWorkUnit::clearExceptions()
  8094. {
  8095. CriticalBlock block(crit);
  8096. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8097. loadExceptions();
  8098. ForEachItemInRev(idx, exceptions)
  8099. {
  8100. IWUException &e = exceptions.item(idx);
  8101. SCMStringBuffer s;
  8102. e.getExceptionSource(s);
  8103. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  8104. break;
  8105. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  8106. p->removeProp(xpath);
  8107. exceptions.remove(idx);
  8108. }
  8109. if (exceptions.length() == 0)
  8110. p->removeProp("Exceptions");
  8111. }
  8112. IWUException* CLocalWorkUnit::createException()
  8113. {
  8114. CriticalBlock block(crit);
  8115. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8116. loadExceptions();
  8117. if (!exceptions.length())
  8118. p->addPropTree("Exceptions");
  8119. IPropertyTree *r = p->queryPropTree("Exceptions");
  8120. IPropertyTree *s = r->addPropTree("Exception");
  8121. s->setPropInt("@sequence", exceptions.ordinality());
  8122. IWUException* q = new CLocalWUException(LINK(s));
  8123. exceptions.append(*LINK(q));
  8124. Owned<IJlibDateTime> now = createDateTimeNow();
  8125. SCMStringBuffer temp;
  8126. now->getString(temp);
  8127. q->setTimeStamp(temp.str());
  8128. return q;
  8129. }
  8130. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  8131. {
  8132. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8133. CriticalBlock block(crit);
  8134. if (!webServicesInfoCached)
  8135. {
  8136. assertex(!webServicesInfo);
  8137. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  8138. if (s)
  8139. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  8140. webServicesInfoCached = true;
  8141. }
  8142. return webServicesInfo.getLink();
  8143. }
  8144. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  8145. {
  8146. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8147. CriticalBlock block(crit);
  8148. if (!webServicesInfoCached)
  8149. {
  8150. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  8151. if (!s)
  8152. {
  8153. if (create)
  8154. s = p->addPropTree("WebServicesInfo");
  8155. else
  8156. return NULL;
  8157. }
  8158. s->Link();
  8159. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  8160. webServicesInfoCached = true;
  8161. }
  8162. return webServicesInfo.getLink();
  8163. }
  8164. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  8165. {
  8166. CLocalWUResult *l = (CLocalWUResult *) *ll;
  8167. CLocalWUResult *r = (CLocalWUResult *) *rr;
  8168. return l->getResultSequence() - r->getResultSequence();
  8169. }
  8170. void CLocalWorkUnit::_loadResults() const
  8171. {
  8172. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  8173. for (r->first(); r->isValid(); r->next())
  8174. {
  8175. IPropertyTree *rp = &r->query();
  8176. rp->Link();
  8177. results.append(*new CLocalWUResult(rp));
  8178. }
  8179. }
  8180. void CLocalWorkUnit::loadResults() const
  8181. {
  8182. if (!resultsCached)
  8183. {
  8184. assertex(results.length() == 0);
  8185. _loadResults();
  8186. results.sort(compareResults);
  8187. resultsCached = true;
  8188. }
  8189. }
  8190. void CLocalWorkUnit::_loadVariables() const
  8191. {
  8192. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  8193. for (r->first(); r->isValid(); r->next())
  8194. {
  8195. IPropertyTree *rp = &r->query();
  8196. rp->Link();
  8197. variables.append(*new CLocalWUResult(rp));
  8198. }
  8199. }
  8200. void CLocalWorkUnit::loadVariables() const
  8201. {
  8202. if (!variablesCached)
  8203. {
  8204. assertex(variables.length() == 0);
  8205. _loadVariables();
  8206. variablesCached = true;
  8207. }
  8208. }
  8209. void CLocalWorkUnit::_loadTemporaries() const
  8210. {
  8211. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  8212. for (r->first(); r->isValid(); r->next())
  8213. {
  8214. IPropertyTree *rp = &r->query();
  8215. rp->Link();
  8216. temporaries.append(*new CLocalWUResult(rp));
  8217. }
  8218. }
  8219. void CLocalWorkUnit::loadTemporaries() const
  8220. {
  8221. if (!temporariesCached)
  8222. {
  8223. assertex(temporaries.length() == 0);
  8224. _loadTemporaries();
  8225. temporariesCached = true;
  8226. }
  8227. }
  8228. void CLocalWorkUnit::deleteTemporaries()
  8229. {
  8230. CriticalBlock block(crit);
  8231. if (temporariesCached)
  8232. {
  8233. temporaries.kill();
  8234. temporariesCached = false;
  8235. }
  8236. p->removeProp("Temporaries");
  8237. }
  8238. IWUResult* CLocalWorkUnit::createResult()
  8239. {
  8240. CriticalBlock block(crit);
  8241. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8242. loadResults();
  8243. if (!results.length())
  8244. p->addPropTree("Results");
  8245. IPropertyTree *r = p->queryPropTree("Results");
  8246. IPropertyTree *s = r->addPropTree("Result");
  8247. s->Link();
  8248. IWUResult* q = new CLocalWUResult(s);
  8249. q->Link();
  8250. results.append(*q);
  8251. return q;
  8252. }
  8253. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  8254. {
  8255. CriticalBlock block(crit);
  8256. IConstWUResult *existing = getResultByName(qname);
  8257. if (existing)
  8258. return (IWUResult *) existing;
  8259. IWUResult* q = createResult();
  8260. q->setResultName(qname);
  8261. return q;
  8262. }
  8263. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  8264. {
  8265. CriticalBlock block(crit);
  8266. IConstWUResult *existing = getResultBySequence(seq);
  8267. if (existing)
  8268. return (IWUResult *) existing;
  8269. IWUResult* q = createResult();
  8270. q->setResultSequence(seq);
  8271. return q;
  8272. }
  8273. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  8274. {
  8275. CriticalBlock block(crit);
  8276. loadResults();
  8277. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  8278. }
  8279. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  8280. {
  8281. CriticalBlock block(crit);
  8282. loadResults();
  8283. ForEachItemIn(idx, results)
  8284. {
  8285. SCMStringBuffer name;
  8286. IConstWUResult &cur = results.item(idx);
  8287. cur.getResultName(name);
  8288. if (stricmp(name.str(), qname)==0)
  8289. {
  8290. cur.Link();
  8291. return &cur;
  8292. }
  8293. }
  8294. return NULL;
  8295. }
  8296. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  8297. {
  8298. CriticalBlock block(crit);
  8299. loadResults();
  8300. ForEachItemIn(idx, results)
  8301. {
  8302. IConstWUResult &cur = results.item(idx);
  8303. if (!isSpecialResultSequence(cur.getResultSequence()))
  8304. {
  8305. SCMStringBuffer name;
  8306. cur.getResultName(name);
  8307. if (stricmp(name.str(), qname)==0)
  8308. {
  8309. cur.Link();
  8310. return &cur;
  8311. }
  8312. }
  8313. }
  8314. return NULL;
  8315. }
  8316. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  8317. {
  8318. CriticalBlock block(crit);
  8319. loadResults();
  8320. ForEachItemIn(idx, results)
  8321. {
  8322. IConstWUResult &cur = results.item(idx);
  8323. if (cur.getResultSequence() == seq)
  8324. {
  8325. cur.Link();
  8326. return &cur;
  8327. }
  8328. }
  8329. return NULL;
  8330. }
  8331. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  8332. {
  8333. CriticalBlock block(crit);
  8334. loadVariables();
  8335. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  8336. }
  8337. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  8338. {
  8339. CriticalBlock block(crit);
  8340. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8341. return getVariableByName(qname);
  8342. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8343. return global->getVariableByName(qname);
  8344. }
  8345. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  8346. {
  8347. CriticalBlock block(crit);
  8348. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8349. return updateVariableByName(qname);
  8350. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8351. return global->updateVariableByName(qname);
  8352. }
  8353. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  8354. {
  8355. CriticalBlock block(crit);
  8356. loadVariables();
  8357. ForEachItemIn(idx, variables)
  8358. {
  8359. SCMStringBuffer name;
  8360. IConstWUResult &cur = variables.item(idx);
  8361. cur.getResultName(name);
  8362. if (stricmp(name.str(), qname)==0)
  8363. {
  8364. cur.Link();
  8365. return &cur;
  8366. }
  8367. }
  8368. return NULL;
  8369. }
  8370. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  8371. {
  8372. CriticalBlock block(crit);
  8373. loadTemporaries();
  8374. ForEachItemIn(idx, temporaries)
  8375. {
  8376. SCMStringBuffer name;
  8377. IConstWUResult &cur = temporaries.item(idx);
  8378. cur.getResultName(name);
  8379. if (stricmp(name.str(), qname)==0)
  8380. {
  8381. cur.Link();
  8382. return &cur;
  8383. }
  8384. }
  8385. return NULL;
  8386. }
  8387. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  8388. {
  8389. CriticalBlock block(crit);
  8390. loadTemporaries();
  8391. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  8392. }
  8393. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  8394. {
  8395. CriticalBlock block(crit);
  8396. IConstWUResult *existing = getTemporaryByName(qname);
  8397. if (existing)
  8398. return (IWUResult *) existing;
  8399. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  8400. IPropertyTree *s = vars->addPropTree("Variable");
  8401. s->Link();
  8402. IWUResult* q = new CLocalWUResult(s);
  8403. q->Link();
  8404. temporaries.append(*q);
  8405. q->setResultName(qname);
  8406. q->setResultSequence(ResultSequenceInternal);
  8407. return q;
  8408. }
  8409. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  8410. {
  8411. CriticalBlock block(crit);
  8412. IConstWUResult *existing = getVariableByName(qname);
  8413. if (existing)
  8414. return (IWUResult *) existing;
  8415. if (!variables.length())
  8416. p->addPropTree("Variables");
  8417. IPropertyTree *vars = p->queryPropTree("Variables");
  8418. IPropertyTree *s = vars->addPropTree("Variable");
  8419. s->Link();
  8420. IWUResult* q = new CLocalWUResult(s);
  8421. q->Link();
  8422. variables.append(*q);
  8423. q->setResultName(qname);
  8424. q->setResultSequence(ResultSequenceStored);
  8425. return q;
  8426. }
  8427. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  8428. {
  8429. CriticalBlock block(crit);
  8430. IPropertyTree *files = p->queryPropTree("Files");
  8431. if (!files) return;
  8432. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  8433. ICopyArrayOf<IPropertyTree> toRemove;
  8434. ForEach (*iter)
  8435. {
  8436. IPropertyTree &file = iter->query();
  8437. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  8438. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  8439. bool needDelete;
  8440. switch(fileKind)
  8441. {
  8442. case WUFileTemporary:
  8443. if(graph==NULL)
  8444. needDelete = true;
  8445. else
  8446. {
  8447. const char *graphOwner = file.queryProp("@graph");
  8448. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  8449. }
  8450. break;
  8451. case WUFileJobOwned:
  8452. needDelete = ((graph==NULL) && deleteJobOwned);
  8453. break;
  8454. case WUFileOwned:
  8455. needDelete = ((graph==NULL) && deleteOwned);
  8456. break;
  8457. default:
  8458. needDelete = false;
  8459. }
  8460. if(needDelete)
  8461. {
  8462. const char *name = file.queryProp("@name");
  8463. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  8464. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  8465. toRemove.append(file);
  8466. }
  8467. }
  8468. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  8469. }
  8470. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  8471. {
  8472. IDistributedSuperFile *super = file->querySuperFile();
  8473. StringBuffer fname;
  8474. file->getLogicalName(fname);
  8475. if (fname.length())
  8476. {
  8477. StringBuffer path("File[@name=\"");
  8478. path.append(fname).append("\"]");
  8479. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8480. if (fileTree)
  8481. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8482. else
  8483. {
  8484. StringBuffer cluster;
  8485. file->getClusterName(0,cluster);
  8486. fileTree = createPTree();
  8487. fileTree->setProp("@name", fname.str());
  8488. fileTree->setProp("@cluster", cluster.str());
  8489. fileTree->setPropInt("@useCount", 1);
  8490. fileTree = filesRead->addPropTree("File", fileTree);
  8491. }
  8492. if (super)
  8493. {
  8494. fileTree->setPropBool("@super", true);
  8495. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8496. ForEach (*iter)
  8497. {
  8498. IDistributedFile &file = iter->query();
  8499. StringBuffer fname;
  8500. file.getLogicalName(fname);
  8501. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8502. _noteFileRead(&file, filesRead);
  8503. }
  8504. }
  8505. }
  8506. }
  8507. void CLocalWorkUnit::_loadFilesRead() const
  8508. {
  8509. // Nothing to do
  8510. }
  8511. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8512. {
  8513. if (file)
  8514. {
  8515. CriticalBlock block(crit);
  8516. IPropertyTree *files = p->queryPropTree("FilesRead");
  8517. if (!files)
  8518. files = p->addPropTree("FilesRead");
  8519. _noteFileRead(file, files);
  8520. }
  8521. }
  8522. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8523. {
  8524. if (fieldUsage)
  8525. {
  8526. CriticalBlock block(crit);
  8527. p->addPropTree("usedsources", fieldUsage);
  8528. }
  8529. }
  8530. void CLocalWorkUnit::_loadFilesWritten() const
  8531. {
  8532. // Nothing to do
  8533. }
  8534. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8535. {
  8536. StringBuffer path("File[@name=\"");
  8537. path.append(fileName).append("\"]");
  8538. if (cluster)
  8539. path.append("[@cluster=\"").append(cluster).append("\"]");
  8540. IPropertyTree *file = files->queryPropTree(path.str());
  8541. if (file) files->removeTree(file);
  8542. file = createPTree();
  8543. file->setProp("@name", fileName);
  8544. if (cluster)
  8545. file->setProp("@cluster", cluster);
  8546. if (graphOwner)
  8547. file->setProp("@graph", graphOwner);
  8548. file->setPropInt("@kind", (unsigned)fileKind);
  8549. if (WUFileTemporary == fileKind)
  8550. file->setPropInt("@usageCount", usageCount);
  8551. files->addPropTree("File", file);
  8552. }
  8553. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8554. {
  8555. CriticalBlock block(crit);
  8556. IPropertyTree *files = p->queryPropTree("Files");
  8557. if (!files)
  8558. files = p->addPropTree("Files");
  8559. if (!clusters)
  8560. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8561. else
  8562. {
  8563. ForEachItemIn(c, *clusters)
  8564. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8565. }
  8566. }
  8567. void CLocalWorkUnit::releaseFile(const char *fileName)
  8568. {
  8569. StringBuffer path("File[@name=\"");
  8570. path.append(fileName).append("\"]");
  8571. CriticalBlock block(crit);
  8572. IPropertyTree *files = p->queryPropTree("Files");
  8573. if (!files) return;
  8574. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8575. ForEach (*fiter)
  8576. {
  8577. IPropertyTree *file = &fiter->query();
  8578. unsigned usageCount = file->getPropInt("@usageCount");
  8579. if (usageCount > 1)
  8580. file->setPropInt("@usageCount", usageCount-1);
  8581. else
  8582. {
  8583. StringAttr name(file->queryProp("@name"));
  8584. files->removeTree(file);
  8585. if (!name.isEmpty()&&(1 == usageCount))
  8586. {
  8587. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8588. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8589. }
  8590. }
  8591. }
  8592. }
  8593. void CLocalWorkUnit::clearGraphProgress() const
  8594. {
  8595. }
  8596. void CLocalWorkUnit::resetBeforeGeneration()
  8597. {
  8598. CriticalBlock block(crit);
  8599. //Remove all associated files
  8600. Owned<IWUQuery> q = updateQuery();
  8601. q->removeAssociatedFiles();
  8602. //Remove any pre-existing workflow information
  8603. workflowIterator.clear();
  8604. p->removeProp("Workflow");
  8605. }
  8606. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8607. {
  8608. StringBuffer path("Files/File[@name=\"");
  8609. path.append(fileName).append("\"]/@usageCount");
  8610. CriticalBlock block(crit);
  8611. return p->getPropInt(path.str());
  8612. }
  8613. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8614. {
  8615. CriticalBlock block(crit);
  8616. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8617. if (!fieldUsageTree)
  8618. return NULL;
  8619. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8620. return new CConstWUFileUsageIterator(iter);
  8621. }
  8622. bool isFilenameResolved(StringBuffer& filename)
  8623. {
  8624. size32_t length = filename.length();
  8625. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8626. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8627. return true;
  8628. else
  8629. return false;
  8630. }
  8631. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8632. {
  8633. bool scopeLoaded = false;
  8634. SCMStringBuffer defaultScope;
  8635. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8636. if (!files)
  8637. return false; // this query was not compiled with recordFieldUsage option.
  8638. ForEach(*files)
  8639. {
  8640. Owned<IConstWUFileUsage> file = files->get();
  8641. StringBuffer filename(file->queryName());
  8642. size32_t length = filename.length();
  8643. if (length == 0)
  8644. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8645. StringBuffer normalizedFilename;
  8646. // Two cases to handle:
  8647. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8648. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8649. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8650. if (isFilenameResolved(filename))
  8651. {
  8652. // filename cannot be empty (i.e. empty single quotes '')
  8653. if (length == 2)
  8654. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8655. // Remove surrounding single quotes
  8656. StringAttr cleanFilename(filename.str()+1, length-2);
  8657. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8658. // We need to load a default scope from config and prefix the filename with it.
  8659. if (cleanFilename.str()[0] != '~')
  8660. {
  8661. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8662. if (!scopeLoaded)
  8663. {
  8664. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName);
  8665. if (!clusterInfo)
  8666. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8667. clusterInfo->getScope(defaultScope);
  8668. scopeLoaded = true;
  8669. }
  8670. normalizedFilename.append(defaultScope.str());
  8671. normalizedFilename.append(cleanFilename.str());
  8672. }
  8673. else
  8674. {
  8675. normalizedFilename.append(cleanFilename);
  8676. }
  8677. }
  8678. else
  8679. {
  8680. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8681. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8682. normalizedFilename.append(filename.str());
  8683. }
  8684. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8685. ForEach(*fields)
  8686. {
  8687. Owned<IConstWUFieldUsage> field = fields->get();
  8688. filenames.append(normalizedFilename.str());
  8689. columnnames.append(field->queryName());
  8690. }
  8691. }
  8692. return true;
  8693. }
  8694. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8695. {
  8696. return p->getPropTree("DiskUsageStats");
  8697. }
  8698. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8699. {
  8700. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8701. offset_t maxNodeUsage;
  8702. if (stats)
  8703. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8704. else
  8705. {
  8706. stats = p->addPropTree("DiskUsageStats");
  8707. maxNodeUsage = 0;
  8708. }
  8709. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8710. {
  8711. // record all details at time of max node usage.
  8712. stats->setPropInt("@minNode", _minNode);
  8713. stats->setPropInt("@maxNode", _maxNode);
  8714. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8715. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8716. stats->setPropInt64("@graphId", _graphId);
  8717. if (_avgNodeUsage)
  8718. {
  8719. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8720. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8721. stats->setPropInt("@skewHi", _skewHi);
  8722. stats->setPropInt("@skewLo", _skewLo);
  8723. }
  8724. }
  8725. }
  8726. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8727. {
  8728. CriticalBlock block(crit);
  8729. _loadFilesWritten();
  8730. return * p->getElements("Files/File");
  8731. }
  8732. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8733. {
  8734. CriticalBlock block(crit);
  8735. _loadFilesRead();
  8736. return * p->getElements("FilesRead/File");
  8737. }
  8738. //=================================================================================================
  8739. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8740. {
  8741. CriticalBlock block(crit);
  8742. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8743. return false;
  8744. Owned<IConstWUClusterInfo> newci = getTargetClusterInfo(cluster);
  8745. if (!newci)
  8746. return false;
  8747. StringBuffer currentcluster;
  8748. if (!p->getProp("@clusterName",currentcluster))
  8749. return false;
  8750. Owned<IConstWUClusterInfo> curci = getTargetClusterInfo(currentcluster.str());
  8751. if (!curci)
  8752. return false;
  8753. SCMStringBuffer curqname;
  8754. curci->getThorQueue(curqname);
  8755. const char *wuid = p->queryName();
  8756. void *qi = qs->getQ(curqname.str(),wuid);
  8757. if (!qi)
  8758. return false;
  8759. setClusterName(cluster);
  8760. SCMStringBuffer newqname;
  8761. newci->getThorQueue(newqname);
  8762. qs->putQ(newqname.str(),wuid,qi);
  8763. return true;
  8764. }
  8765. //=================================================================================================
  8766. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8767. {
  8768. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8769. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8770. ForEach(*graphIter)
  8771. {
  8772. IConstWUGraph &graph = graphIter->query();
  8773. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8774. SCMStringBuffer gName;
  8775. graph.getName(gName);
  8776. StringBuffer xpath("Graphs/Graph[@name=\"");
  8777. xpath.append(gName.s).append("\"]/xgmml");
  8778. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8779. if (xgmml) // don't know of any reason it shouldn't exist
  8780. {
  8781. xgmml->removeProp("graphBin");
  8782. xgmml->setPropTree("graph", graphTree.getClear());
  8783. }
  8784. }
  8785. return ret.getClear();
  8786. }
  8787. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8788. {
  8789. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8790. ForEach(*iter)
  8791. {
  8792. IPropertyTree &graph = iter->query();
  8793. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8794. }
  8795. }
  8796. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8797. {
  8798. if (graphsCached < (heavy ? 2 : 1))
  8799. {
  8800. graphs.kill();
  8801. _loadGraphs(heavy);
  8802. graphsCached = (heavy ? 2 : 1);
  8803. }
  8804. }
  8805. EnumMapping graphTypes[] = {
  8806. { GraphTypeAny, "unknown" },
  8807. { GraphTypeProgress, "progress" },
  8808. { GraphTypeEcl, "ECL" },
  8809. { GraphTypeActivities, "activities" },
  8810. { GraphTypeSubProgress, "subgraph" },
  8811. { GraphTypeSize, NULL },
  8812. };
  8813. WUGraphType getGraphTypeFromString(const char* type)
  8814. {
  8815. return (WUGraphType) getEnum(type, graphTypes);
  8816. }
  8817. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8818. {
  8819. wuidVersion = owner.getWuidVersion();
  8820. }
  8821. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8822. {
  8823. str.set(p->queryProp("@name"));
  8824. return str;
  8825. }
  8826. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8827. {
  8828. if (wuidVersion >= 2)
  8829. {
  8830. str.set(p->queryProp("@label"));
  8831. return str;
  8832. }
  8833. else
  8834. {
  8835. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8836. str.set(xgmml->queryProp("@label"));
  8837. return str;
  8838. }
  8839. }
  8840. WUGraphState CLocalWUGraph::getState() const
  8841. {
  8842. return owner.queryGraphState(p->queryProp("@name"));
  8843. }
  8844. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8845. {
  8846. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8847. if (xgmml)
  8848. {
  8849. StringBuffer x;
  8850. toXML(xgmml, x);
  8851. str.set(x.str());
  8852. }
  8853. return str;
  8854. }
  8855. unsigned CLocalWorkUnit::getGraphCount() const
  8856. {
  8857. CriticalBlock block(crit);
  8858. if (p->hasProp("Graphs"))
  8859. {
  8860. return p->queryPropTree("Graphs")->numChildren();
  8861. }
  8862. return 0;
  8863. }
  8864. unsigned CLocalWorkUnit::getSourceFileCount() const
  8865. {
  8866. CriticalBlock block(crit);
  8867. _loadFilesRead();
  8868. if (p->hasProp("FilesRead"))
  8869. {
  8870. return p->queryPropTree("FilesRead")->numChildren();
  8871. }
  8872. return 0;
  8873. }
  8874. unsigned CLocalWorkUnit::getResultCount() const
  8875. {
  8876. CriticalBlock block(crit);
  8877. if (p->hasProp("Results"))
  8878. {
  8879. return p->queryPropTree("Results")->numChildren();
  8880. }
  8881. return 0;
  8882. }
  8883. unsigned CLocalWorkUnit::getVariableCount() const
  8884. {
  8885. CriticalBlock block(crit);
  8886. if (p->hasProp("Variables"))
  8887. {
  8888. return p->queryPropTree("Variables")->numChildren();
  8889. }
  8890. return 0;
  8891. }
  8892. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8893. {
  8894. CriticalBlock block(crit);
  8895. if (p->hasProp("Application"))
  8896. {
  8897. return p->queryPropTree("Application")->numChildren();
  8898. }
  8899. return 0;
  8900. }
  8901. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8902. {
  8903. appendXMLOpenTag(s, name, NULL, false);
  8904. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8905. if (attrs->first())
  8906. {
  8907. unsigned attributeindent = indent + (size32_t) strlen(name);
  8908. unsigned count = attrs->count();
  8909. bool doindent = false;
  8910. ForEach(*attrs)
  8911. {
  8912. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8913. continue;
  8914. #ifndef _DEBUG
  8915. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8916. continue;
  8917. #endif
  8918. if (doindent)
  8919. s.append('\n').appendN(attributeindent, ' ');
  8920. else if (count > 3)
  8921. doindent = true;
  8922. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8923. }
  8924. }
  8925. s.append('>');
  8926. return s;
  8927. }
  8928. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8929. {
  8930. CriticalBlock block(crit);
  8931. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8932. if (!paramTree)
  8933. return str;
  8934. StringBuffer xml;
  8935. if (!hidePasswords)
  8936. toXML(paramTree, xml);
  8937. else
  8938. {
  8939. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8940. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8941. ForEach(*elems)
  8942. {
  8943. const char *paramname = elems->query().queryName();
  8944. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8945. if (p->getPropBool(xpath))
  8946. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8947. else
  8948. toXML(&elems->query(), xml, 2);
  8949. }
  8950. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8951. }
  8952. str.set(xml);
  8953. return str;
  8954. }
  8955. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8956. {
  8957. CriticalBlock block(crit);
  8958. return p->getPropTree("Parameters");
  8959. }
  8960. void CLocalWorkUnit::setXmlParams(const char *params)
  8961. {
  8962. CriticalBlock block(crit);
  8963. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8964. }
  8965. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8966. {
  8967. CriticalBlock block(crit);
  8968. p->setPropTree("Parameters", tree);
  8969. }
  8970. unsigned __int64 CLocalWorkUnit::getHash() const
  8971. {
  8972. CriticalBlock block(crit);
  8973. return p->getPropInt64("@hash");
  8974. }
  8975. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8976. {
  8977. CriticalBlock block(crit);
  8978. p->setPropInt64("@hash", hash);
  8979. }
  8980. // getGraphs / getGraphsMeta
  8981. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8982. // If a type other than any is requested, a postfilter is needed.
  8983. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8984. {
  8985. WUGraphType type;
  8986. Owned<T> base;
  8987. bool match()
  8988. {
  8989. return base->query().getType()==type;
  8990. }
  8991. public:
  8992. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8993. : base(_base), type(_type)
  8994. {
  8995. }
  8996. bool first()
  8997. {
  8998. if (!base->first())
  8999. return false;
  9000. if (match())
  9001. return true;
  9002. return next();
  9003. }
  9004. bool next()
  9005. {
  9006. while (base->next())
  9007. if (match())
  9008. return true;
  9009. return false;
  9010. }
  9011. virtual bool isValid()
  9012. {
  9013. return base->isValid();
  9014. }
  9015. U & query()
  9016. {
  9017. return base->query();
  9018. }
  9019. };
  9020. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  9021. {
  9022. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  9023. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  9024. */
  9025. CriticalBlock block(crit);
  9026. loadGraphs(false);
  9027. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  9028. if (type!=GraphTypeAny)
  9029. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  9030. return *giter;
  9031. }
  9032. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  9033. {
  9034. CriticalBlock block(crit);
  9035. loadGraphs(true);
  9036. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  9037. if (type!=GraphTypeAny)
  9038. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  9039. return *giter;
  9040. }
  9041. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  9042. {
  9043. CriticalBlock block(crit);
  9044. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  9045. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  9046. IPTree *graph = p->queryPropTree(xpath);
  9047. if (graph)
  9048. return new CLocalWUGraph(*this, LINK(graph));
  9049. return NULL;
  9050. }
  9051. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  9052. {
  9053. CriticalBlock block(crit);
  9054. if (!graphs.length())
  9055. p->addPropTree("Graphs");
  9056. IPropertyTree *r = p->queryPropTree("Graphs");
  9057. IPropertyTree *s = r->addPropTree("Graph");
  9058. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  9059. q->setName(name);
  9060. q->setLabel(label);
  9061. q->setType(type);
  9062. q->setWfid(wfid);
  9063. q->setXGMMLTree(xgmml);
  9064. graphs.append(*q);
  9065. }
  9066. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  9067. {
  9068. /* Owned<IRemoteConnection> conn = getProgressConnection();
  9069. if (conn)
  9070. {
  9071. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  9072. if (progress)
  9073. return new CConstGraphProgress(p->queryName(), graphName, progress);
  9074. }
  9075. */
  9076. return NULL;
  9077. }
  9078. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  9079. {
  9080. throwUnexpected(); // Should only be used for persisted workunits
  9081. }
  9082. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  9083. {
  9084. throwUnexpected(); // Should only be used for persisted workunits
  9085. }
  9086. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  9087. {
  9088. throwUnexpected(); // Should only be used for persisted workunits
  9089. }
  9090. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  9091. {
  9092. throwUnexpected(); // Should only be used for persisted workunits
  9093. }
  9094. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  9095. {
  9096. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  9097. }
  9098. void CLocalWUGraph::setName(const char *str)
  9099. {
  9100. p->setProp("@name", str);
  9101. }
  9102. void CLocalWUGraph::setLabel(const char *str)
  9103. {
  9104. p->setProp("@label", str);
  9105. }
  9106. void CLocalWUGraph::setWfid(unsigned wfid)
  9107. {
  9108. p->setPropInt("@wfid", wfid);
  9109. }
  9110. void CLocalWUGraph::setXGMML(const char *str)
  9111. {
  9112. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  9113. }
  9114. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  9115. {
  9116. assertex(strcmp(_graph->queryName(), "graph")==0);
  9117. IPropertyTree *xgmml = p->setPropTree("xgmml");
  9118. MemoryBuffer mb;
  9119. _graph->serialize(mb);
  9120. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  9121. // Cassandra workunit code actually lzw compresses the parent anyway
  9122. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  9123. graph.setown(_graph);
  9124. }
  9125. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  9126. {
  9127. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  9128. ForEach (*aIter)
  9129. {
  9130. const char *aName = aIter->queryName()+1;
  9131. if (0 != stricmp("id", aName)) // "id" reserved.
  9132. {
  9133. IPropertyTree *att = targetNode.addPropTree("att");
  9134. att->setProp("@name", aName);
  9135. att->setProp("@value", aIter->queryValue());
  9136. }
  9137. }
  9138. }
  9139. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  9140. {
  9141. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  9142. if (!graphNode) return;
  9143. unsigned nodeId = rootNode.getPropInt("@id");
  9144. StringBuffer progressNodePath("node[@id=\"");
  9145. progressNodePath.append(nodeId).append("\"]");
  9146. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  9147. if (progressNode)
  9148. {
  9149. expandAttributes(*graphNode, *progressNode);
  9150. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  9151. ForEach (*edges)
  9152. {
  9153. IPropertyTree &edge = edges->query();
  9154. StringBuffer edgePath("edge[@id=\"");
  9155. edgePath.append(edge.queryProp("@id")).append("\"]");
  9156. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  9157. if (graphEdge)
  9158. {
  9159. if (progressV < 1)
  9160. mergePTree(graphEdge, &edge);
  9161. else
  9162. { // must translate to XGMML format
  9163. expandAttributes(*graphEdge, edge);
  9164. // 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)
  9165. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  9166. ForEach (*iter)
  9167. {
  9168. IPropertyTree &t = iter->query();
  9169. IPropertyTree *att = graphEdge->addPropTree("att");
  9170. att->setProp("@name", t.queryName());
  9171. att->setProp("@value", t.queryProp(NULL));
  9172. }
  9173. }
  9174. }
  9175. }
  9176. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  9177. ForEach (*nodes)
  9178. {
  9179. IPropertyTree &node = nodes->query();
  9180. StringBuffer nodePath("node[@id=\"");
  9181. nodePath.append(node.queryProp("@id")).append("\"]");
  9182. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  9183. if (_node)
  9184. {
  9185. if (progressV < 1)
  9186. mergePTree(_node, &node);
  9187. else
  9188. { // must translate to XGMML format
  9189. expandAttributes(*_node, node);
  9190. }
  9191. }
  9192. }
  9193. }
  9194. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  9195. ForEach (*iter)
  9196. mergeProgress(iter->query(), progressTree, progressV);
  9197. }
  9198. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  9199. {
  9200. return p->getPropTree("xgmml");
  9201. }
  9202. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  9203. {
  9204. if (!graph)
  9205. {
  9206. // NB: although graphBin introduced in wuidVersion==2,
  9207. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  9208. MemoryBuffer mb;
  9209. if (p->getPropBin("xgmml/graphBin", mb))
  9210. graph.setown(createPTree(mb, ipt_lowmem));
  9211. else
  9212. graph.setown(p->getBranch("xgmml/graph"));
  9213. if (!graph)
  9214. return NULL;
  9215. }
  9216. if (!doMergeProgress)
  9217. return graph.getLink();
  9218. else
  9219. {
  9220. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  9221. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  9222. if (progress)
  9223. {
  9224. //MORE: Eventually this should directly access the new stats structure
  9225. unsigned progressV = progress->queryFormatVersion();
  9226. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  9227. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  9228. ForEach (*nodeIterator)
  9229. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  9230. }
  9231. return copy.getClear();
  9232. }
  9233. }
  9234. WUGraphType CLocalWUGraph::getType() const
  9235. {
  9236. return (WUGraphType) getEnum(p, "@type", graphTypes);
  9237. }
  9238. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  9239. {
  9240. str.set(p->queryProp("@type"));
  9241. if (!str.length())
  9242. str.set("unknown");
  9243. return str;
  9244. }
  9245. unsigned CLocalWUGraph::getWfid() const
  9246. {
  9247. return p->getPropInt("@wfid", 0);
  9248. }
  9249. void CLocalWUGraph::setType(WUGraphType _type)
  9250. {
  9251. setEnum(p, "@type", _type, graphTypes);
  9252. }
  9253. //=================================================================================================
  9254. EnumMapping queryFileTypes[] = {
  9255. { FileTypeCpp, "cpp" },
  9256. { FileTypeDll, "dll" },
  9257. { FileTypeResText, "res" },
  9258. { FileTypeHintXml, "hint" },
  9259. { FileTypeXml, "xml" },
  9260. { FileTypeLog, "log" },
  9261. { FileTypeSize, NULL },
  9262. };
  9263. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  9264. {
  9265. }
  9266. WUFileType CLocalWUAssociated::getType() const
  9267. {
  9268. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  9269. }
  9270. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  9271. {
  9272. str.set(p->queryProp("@desc"));
  9273. return str;
  9274. }
  9275. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  9276. {
  9277. str.set(p->queryProp("@ip"));
  9278. return str;
  9279. }
  9280. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  9281. {
  9282. str.set(p->queryProp("@filename"));
  9283. return str;
  9284. }
  9285. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  9286. {
  9287. str.set(pathTail(p->queryProp("@filename")));
  9288. return str;
  9289. }
  9290. unsigned CLocalWUAssociated::getCrc() const
  9291. {
  9292. return p->getPropInt("@crc", 0);
  9293. }
  9294. unsigned CLocalWUAssociated::getMinActivityId() const
  9295. {
  9296. return p->getPropInt("@minActivity", 0);
  9297. }
  9298. unsigned CLocalWUAssociated::getMaxActivityId() const
  9299. {
  9300. return p->getPropInt("@maxActivity", 0);
  9301. }
  9302. //=================================================================================================
  9303. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  9304. {
  9305. associatedCached = false;
  9306. }
  9307. EnumMapping queryTypes[] = {
  9308. { QueryTypeUnknown, "unknown" },
  9309. { QueryTypeEcl, "ECL" },
  9310. { QueryTypeSql, "SQL" },
  9311. { QueryTypeXml, "XML" },
  9312. { QueryTypeAttribute, "Attribute" },
  9313. { QueryTypeSize, NULL },
  9314. };
  9315. WUQueryType CLocalWUQuery::getQueryType() const
  9316. {
  9317. return (WUQueryType) getEnum(p, "@type", queryTypes);
  9318. }
  9319. void CLocalWUQuery::setQueryType(WUQueryType qt)
  9320. {
  9321. setEnum(p, "@type", qt, queryTypes);
  9322. }
  9323. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  9324. {
  9325. const char *text = p->queryProp("Text");
  9326. if (!text)
  9327. text = p->queryProp("ShortText");
  9328. str.set(text);
  9329. return str;
  9330. }
  9331. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  9332. {
  9333. const char * text = p->queryProp("ShortText");
  9334. if (text)
  9335. str.set(text);
  9336. else
  9337. {
  9338. text = p->queryProp("Text");
  9339. if (isArchiveQuery(text))
  9340. {
  9341. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9342. const char * path = xml->queryProp("Query/@attributePath");
  9343. if (path)
  9344. {
  9345. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9346. if (resolved)
  9347. str.set(resolved->queryProp(NULL));
  9348. }
  9349. else
  9350. str.set(xml->queryProp("Query"));
  9351. }
  9352. else
  9353. str.set(text);
  9354. }
  9355. return str;
  9356. }
  9357. bool CLocalWUQuery::isArchive() const
  9358. {
  9359. if (p->hasProp("@isArchive"))
  9360. return p->getPropBool("@isArchive");
  9361. const char *text = p->queryProp("Text");
  9362. return isArchiveQuery(text);
  9363. }
  9364. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  9365. {
  9366. str.set(p->queryProp("@name"));
  9367. return str;
  9368. }
  9369. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  9370. {
  9371. str.set(p->queryProp("@main"));
  9372. return str;
  9373. }
  9374. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  9375. {
  9376. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9377. if (entry)
  9378. entry->getNameTail(str);
  9379. return str;
  9380. }
  9381. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  9382. {
  9383. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  9384. if (entry)
  9385. entry->getName(str);
  9386. return str;
  9387. }
  9388. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  9389. {
  9390. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  9391. if (entry)
  9392. entry->getName(str);
  9393. return str;
  9394. }
  9395. unsigned CLocalWUQuery::getQueryDllCrc() const
  9396. {
  9397. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9398. if (entry)
  9399. return entry->getCrc();
  9400. return 0;
  9401. }
  9402. void CLocalWUQuery::setQueryText(const char *text)
  9403. {
  9404. bool isArchive = isArchiveQuery(text);
  9405. if (isArchive)
  9406. {
  9407. p->setProp("Text", text);
  9408. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9409. const char * path = xml->queryProp("Query/@attributePath");
  9410. if (path)
  9411. {
  9412. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9413. if (resolved)
  9414. p->setProp("ShortText", resolved->queryProp(NULL));
  9415. }
  9416. else
  9417. p->setProp("ShortText", xml->queryProp("Query"));
  9418. }
  9419. else
  9420. {
  9421. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  9422. // but as long as there may be new workunits compiled by old systems, we can't
  9423. p->setProp("ShortText", text);
  9424. }
  9425. p->setPropBool("@isArchive", isArchive);
  9426. if (isArchive)
  9427. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  9428. }
  9429. void CLocalWUQuery::setQueryName(const char *qname)
  9430. {
  9431. p->setProp("@name", qname);
  9432. }
  9433. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  9434. {
  9435. p->setProp("@main", str);
  9436. }
  9437. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  9438. {
  9439. CriticalBlock block(crit);
  9440. loadAssociated();
  9441. StringBuffer xpath;
  9442. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  9443. if (p->hasProp(xpath))
  9444. return;
  9445. if (!associated.length())
  9446. p->addPropTree("Associated");
  9447. IPropertyTree *pl = p->queryPropTree("Associated");
  9448. IPropertyTree *s = pl->addPropTree("File");
  9449. setEnum(s, "@type", type, queryFileTypes);
  9450. s->setProp("@filename", name);
  9451. s->setProp("@ip", ip);
  9452. s->setProp("@desc", desc);
  9453. if (crc)
  9454. s->setPropInt("@crc", crc);
  9455. if (minActivity)
  9456. s->setPropInt("@minActivity", minActivity);
  9457. if (maxActivity)
  9458. s->setPropInt("@maxActivity", maxActivity);
  9459. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  9460. associated.append(*q);
  9461. }
  9462. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  9463. {
  9464. CriticalBlock block(crit);
  9465. associatedCached = false;
  9466. associated.kill();
  9467. StringBuffer xpath;
  9468. xpath.append("Associated/File");
  9469. if (type)
  9470. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  9471. if (name)
  9472. xpath.append("[@filename=\"").append(name).append("\"]");
  9473. if (desc)
  9474. xpath.append("[@desc=\"").append(desc).append("\"]");
  9475. p->removeProp(xpath.str());
  9476. }
  9477. void CLocalWUQuery::removeAssociatedFiles()
  9478. {
  9479. associatedCached = false;
  9480. associated.kill();
  9481. p->removeProp("Associated");
  9482. }
  9483. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9484. {
  9485. CriticalBlock block(crit);
  9486. loadAssociated();
  9487. ForEachItemIn(idx, associated)
  9488. {
  9489. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9490. if (cur.getType() == type)
  9491. {
  9492. if (index-- == 0)
  9493. return &OLINK(cur);
  9494. }
  9495. }
  9496. return NULL;
  9497. }
  9498. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9499. {
  9500. const char * name = p->queryProp(propname);
  9501. if (name)
  9502. {
  9503. IPropertyTree *s = createPTree("File");
  9504. setEnum(s, "@type", type, queryFileTypes);
  9505. s->setProp("@filename", name);
  9506. if (crc)
  9507. s->setPropInt("@crc", crc);
  9508. associated.append(*new CLocalWUAssociated(s));
  9509. }
  9510. }
  9511. void CLocalWUQuery::loadAssociated() const
  9512. {
  9513. CriticalBlock block(crit);
  9514. if (!associatedCached)
  9515. {
  9516. assertex(associated.length() == 0);
  9517. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9518. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9519. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9520. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9521. for (r->first(); r->isValid(); r->next())
  9522. {
  9523. IPropertyTree *rp = &r->query();
  9524. rp->Link();
  9525. associated.append(*new CLocalWUAssociated(rp));
  9526. }
  9527. associatedCached = true;
  9528. }
  9529. }
  9530. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9531. {
  9532. CriticalBlock block(crit);
  9533. loadAssociated();
  9534. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9535. }
  9536. //========================================================================================
  9537. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9538. {
  9539. }
  9540. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9541. {
  9542. str.set(p->queryProp("@module"));
  9543. return str;
  9544. }
  9545. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9546. {
  9547. str.set(p->queryProp("@attribute"));
  9548. return str;
  9549. }
  9550. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9551. {
  9552. str.set(p->queryProp("@defaultName"));
  9553. return str;
  9554. }
  9555. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9556. {
  9557. return (unsigned) p->getPropInt("@crc");
  9558. }
  9559. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9560. {
  9561. if (!name)
  9562. {
  9563. StringBuffer ws_info;
  9564. ws_info.appendf("<%s ", p->queryName());
  9565. Owned<IAttributeIterator> attrs = p->getAttributes();
  9566. for(attrs->first(); attrs->isValid(); attrs->next())
  9567. {
  9568. const char *name = attrs->queryName()+1;
  9569. const char *value = attrs->queryValue();
  9570. ws_info.appendf("%s='%s' ", name, value);
  9571. }
  9572. ws_info.append("> \n");
  9573. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9574. ForEach(*info)
  9575. {
  9576. IPropertyTree &item = info->query();
  9577. const char *name = item.queryName();
  9578. if (name)
  9579. {
  9580. MemoryBuffer mb;
  9581. bool isbin = p->isBinary(name);
  9582. if (isbin)
  9583. {
  9584. p->getPropBin(name,mb);
  9585. if (mb.length())
  9586. {
  9587. unsigned len = 0;
  9588. mb.read(len);
  9589. StringBuffer encodedString;
  9590. StringBuffer val(len, (const char *) mb.readDirect(len));
  9591. encodeXML(val, encodedString);
  9592. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9593. }
  9594. }
  9595. else
  9596. {
  9597. StringBuffer tmp;
  9598. toXML(&item, tmp);
  9599. ws_info.append(tmp.str());
  9600. }
  9601. }
  9602. }
  9603. ws_info.appendf("</%s>", p->queryName());
  9604. str.setLen(ws_info.str(), ws_info.length());
  9605. }
  9606. else
  9607. {
  9608. MemoryBuffer mb;
  9609. p->getPropBin(name,mb);
  9610. if (mb.length())
  9611. {
  9612. unsigned len;
  9613. mb.read(len);
  9614. str.setLen((const char *) mb.readDirect(len), len);
  9615. }
  9616. }
  9617. return str;
  9618. }
  9619. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9620. {
  9621. str.set(p->queryProp(name));
  9622. return str;
  9623. }
  9624. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9625. {
  9626. p->setProp("@module", mname);
  9627. }
  9628. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9629. {
  9630. p->setProp("@attribute", aname);
  9631. }
  9632. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9633. {
  9634. p->setProp("@defaultName", dname);
  9635. }
  9636. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9637. {
  9638. p->setPropInt("@crc", crc);
  9639. }
  9640. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9641. {
  9642. MemoryBuffer m;
  9643. unsigned len = (size32_t)strlen(info);
  9644. serializeLPString(len, info, m);
  9645. p->setPropBin(name, m.length(), m.toByteArray());
  9646. }
  9647. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9648. {
  9649. p->setProp(name, info);
  9650. }
  9651. //========================================================================================
  9652. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9653. {
  9654. }
  9655. EnumMapping resultStatuses[] = {
  9656. { ResultStatusUndefined, "undefined" },
  9657. { ResultStatusCalculated, "calculated" },
  9658. { ResultStatusSupplied, "supplied" },
  9659. { ResultStatusFailed, "failed" },
  9660. { ResultStatusPartial, "partial" },
  9661. { ResultStatusSize, NULL }
  9662. };
  9663. WUResultStatus CLocalWUResult::getResultStatus() const
  9664. {
  9665. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9666. }
  9667. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9668. {
  9669. str.set(p->queryProp("@name"));
  9670. return str;
  9671. }
  9672. int CLocalWUResult::getResultSequence() const
  9673. {
  9674. return p->getPropInt("@sequence", -1);
  9675. }
  9676. bool CLocalWUResult::isResultScalar() const
  9677. {
  9678. return p->getPropInt("@isScalar", 1) != 0;
  9679. }
  9680. bool findSize(int size, IntArray &sizes)
  9681. {
  9682. ForEachItemIn(idx, sizes)
  9683. {
  9684. if (sizes.item(idx)==size)
  9685. return true;
  9686. }
  9687. return false;
  9688. }
  9689. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9690. {
  9691. MemoryBuffer schema;
  9692. p->getPropBin("SchemaRaw", schema);
  9693. if (schema.length())
  9694. {
  9695. for (;;)
  9696. {
  9697. StringAttr name;
  9698. schema.read(name);
  9699. if (*schema.readDirect(0)==type_void)
  9700. break;
  9701. names.append(*new StringAttrItem(name));
  9702. types.append(*deserializeType(schema)); // MORE - nested records!
  9703. }
  9704. schema.skip(1);
  9705. if (schema.length() != schema.getPos())
  9706. {
  9707. unsigned eclLen;
  9708. schema.read(eclLen);
  9709. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9710. if (eclText)
  9711. {
  9712. eclText->setLen(schemaData, eclLen);
  9713. if ((eclLen == 0) && names.ordinality())
  9714. {
  9715. const char * firstName = names.item(0).text;
  9716. StringBuffer temp;
  9717. temp.append("RECORD ");
  9718. types.item(0).getECLType(temp);
  9719. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9720. eclText->set(temp.str());
  9721. }
  9722. }
  9723. }
  9724. }
  9725. }
  9726. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9727. {
  9728. ForEachItemIn(idx, types)
  9729. {
  9730. StringAttrItem &name = names.item(idx);
  9731. ITypeInfo &type = types.item(idx);
  9732. unsigned size = type.getSize();
  9733. switch(type.getTypeCode())
  9734. {
  9735. case type_data:
  9736. if (size==UNKNOWN_LENGTH)
  9737. {
  9738. if (in.remaining() < sizeof(int))
  9739. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9740. in.read(size);
  9741. }
  9742. outputXmlData(size, in.readDirect(size), name.text, out);
  9743. break;
  9744. case type_string:
  9745. if (size==UNKNOWN_LENGTH)
  9746. {
  9747. if (in.remaining() < sizeof(int))
  9748. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9749. in.read(size);
  9750. }
  9751. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9752. break;
  9753. case type_varstring:
  9754. {
  9755. if (size == UNKNOWN_LENGTH)
  9756. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9757. const char * text = (const char *) in.readDirect(size);
  9758. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9759. break;
  9760. }
  9761. case type_unicode:
  9762. {
  9763. unsigned len = type.getStringLen();
  9764. if (size==UNKNOWN_LENGTH)
  9765. in.read(len);
  9766. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9767. }
  9768. break;
  9769. case type_utf8:
  9770. {
  9771. unsigned len = type.getStringLen();
  9772. if (size==UNKNOWN_LENGTH)
  9773. {
  9774. in.read(len);
  9775. size = rtlUtf8Size(len, in.readDirect(0));
  9776. }
  9777. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9778. }
  9779. break;
  9780. case type_qstring:
  9781. {
  9782. unsigned len = type.getStringLen();
  9783. if (size==UNKNOWN_LENGTH)
  9784. in.read(len);
  9785. unsigned outlen;
  9786. char *outstr;
  9787. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9788. outputXmlString(outlen, outstr, name.text, out);
  9789. free(outstr);
  9790. break;
  9791. }
  9792. case type_int:
  9793. case type_swapint:
  9794. if (type.isSigned())
  9795. {
  9796. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9797. unsigned __int64 cval8 = 0;
  9798. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9799. if (type.isSwappedEndian())
  9800. {
  9801. unsigned idx = 0;
  9802. if (raw[idx] & 0x80)
  9803. cval8 = (__int64)-1;
  9804. while (size--)
  9805. cval8 = (cval8 << 8) | raw[idx++];
  9806. }
  9807. else
  9808. {
  9809. if (raw[size-1] & 0x80)
  9810. cval8 = (__int64)-1;
  9811. while (size--)
  9812. cval8 = (cval8 << 8) | raw[size];
  9813. }
  9814. outputXmlInt((__int64) cval8, name.text, out);
  9815. }
  9816. else
  9817. {
  9818. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9819. unsigned __int64 cval8 = 0;
  9820. if (type.isSwappedEndian())
  9821. {
  9822. unsigned idx = 0;
  9823. while (size--)
  9824. cval8 = (cval8 << 8) | raw[idx++];
  9825. }
  9826. else
  9827. {
  9828. while (size--)
  9829. cval8 = (cval8 << 8) | raw[size];
  9830. }
  9831. outputXmlUInt(cval8, name.text, out);
  9832. }
  9833. break;
  9834. case type_boolean:
  9835. bool cvalb;
  9836. in.read(cvalb);
  9837. outputXmlBool(cvalb, name.text, out);
  9838. break;
  9839. case type_decimal:
  9840. if (type.isSigned())
  9841. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9842. else
  9843. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9844. break;
  9845. case type_real:
  9846. double cvald;
  9847. switch(size)
  9848. {
  9849. case 4:
  9850. float cvalf;
  9851. in.read(cvalf);
  9852. cvald = cvalf;
  9853. break;
  9854. case 8:
  9855. in.read(cvald);
  9856. break;
  9857. }
  9858. outputXmlReal(cvald, name.text, out);
  9859. break;
  9860. default:
  9861. assertex(!"unexpected type in raw record");
  9862. break;
  9863. }
  9864. }
  9865. }
  9866. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9867. {
  9868. TypeInfoArray types;
  9869. StringAttrArray names;
  9870. getSchema(types, names);
  9871. StringBuffer xml;
  9872. const char * name = p->queryProp("@name");
  9873. if (name)
  9874. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9875. else
  9876. xml.append("<Dataset>\n");
  9877. if (hidePassword && p->getPropBool("Format/@password"))
  9878. {
  9879. xml.append(" <Row>");
  9880. appendXMLTag(xml, name, "****");
  9881. xml.append("</Row>\n");
  9882. }
  9883. else if (p->hasProp("Value"))
  9884. {
  9885. MemoryBuffer raw;
  9886. p->getPropBin("Value", raw);
  9887. unsigned __int64 numrows = getResultRowCount();
  9888. while (numrows--)
  9889. {
  9890. xml.append(" <Row>");
  9891. readRow(xml, raw, types, names);
  9892. xml.append("</Row>\n");
  9893. }
  9894. }
  9895. else if (p->hasProp("xmlValue"))
  9896. {
  9897. xml.append(" <Row>");
  9898. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9899. xml.append("</Row>\n");
  9900. }
  9901. xml.append("</Dataset>\n");
  9902. str.set(xml.str());
  9903. return str;
  9904. }
  9905. IProperties *CLocalWUResult::queryResultXmlns()
  9906. {
  9907. CriticalBlock block(crit);
  9908. if (xmlns)
  9909. return xmlns;
  9910. xmlns.setown(createProperties());
  9911. Owned<IAttributeIterator> it = p->getAttributes();
  9912. unsigned prefixLen = strlen("@xmlns");
  9913. ForEach(*it)
  9914. {
  9915. const char *name = it->queryName();
  9916. if (!strncmp("@xmlns", name, prefixLen))
  9917. {
  9918. if (name[prefixLen]==':') //normal case
  9919. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9920. else if (!name[prefixLen]) //special case, unprefixed namespace
  9921. xmlns->setProp("xmlns", it->queryValue());
  9922. }
  9923. }
  9924. return xmlns;
  9925. }
  9926. unsigned CLocalWUResult::getResultFetchSize() const
  9927. {
  9928. return p->getPropInt("fetchSize", 100);
  9929. }
  9930. __int64 CLocalWUResult::getResultTotalRowCount() const
  9931. {
  9932. return p->getPropInt64("totalRowCount", -1);
  9933. }
  9934. __int64 CLocalWUResult::getResultRowCount() const
  9935. {
  9936. return p->getPropInt64("rowCount", 0);
  9937. }
  9938. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9939. {
  9940. ecl.set(p->queryProp("datasetEcl"));
  9941. defs.set(p->queryProp("datasetEclDefs"));
  9942. }
  9943. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9944. {
  9945. val.set(p->queryProp("logicalName"));
  9946. return val;
  9947. }
  9948. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9949. {
  9950. ecl.set(p->queryProp("keyField"));
  9951. return ecl;
  9952. }
  9953. unsigned CLocalWUResult::getResultRequestedRows() const
  9954. {
  9955. return p->getPropInt("requestedRows", 1);
  9956. }
  9957. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9958. {
  9959. TypeInfoArray types;
  9960. StringAttrArray names;
  9961. getSchema(types, names, &str);
  9962. return str;
  9963. }
  9964. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9965. {
  9966. str.set(p->queryProp("@recordSizeEntry"));
  9967. return str;
  9968. }
  9969. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9970. {
  9971. str.set(p->queryProp("@transformerEntry"));
  9972. return str;
  9973. }
  9974. __int64 CLocalWUResult::getResultRowLimit() const
  9975. {
  9976. return p->getPropInt64("@rowLimit");
  9977. }
  9978. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9979. {
  9980. str.set(p->queryProp("@tempFilename"));
  9981. return str;
  9982. }
  9983. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9984. {
  9985. str.clear();
  9986. if (!name || !*name)
  9987. return str;
  9988. IPropertyTree *format = p->queryPropTree("Format");
  9989. if (!format)
  9990. return str;
  9991. VStringBuffer xpath("@%s", name);
  9992. str.set(format->queryProp(xpath));
  9993. return str;
  9994. }
  9995. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9996. {
  9997. _graph.set(p->queryProp("@graph"));
  9998. _activityId = p->getPropInt("@activity", 0);
  9999. }
  10000. void CLocalWUResult::setResultStatus(WUResultStatus status)
  10001. {
  10002. setEnum(p, "@status", status, resultStatuses);
  10003. if (status==ResultStatusUndefined)
  10004. {
  10005. p->removeProp("Value");
  10006. p->removeProp("totalRowCount");
  10007. p->removeProp("rowCount");
  10008. p->removeProp("@format");
  10009. p->removeProp("@tempFileNmae");
  10010. p->removeProp("logicalName");
  10011. }
  10012. }
  10013. void CLocalWUResult::setResultName(const char *s)
  10014. {
  10015. p->setProp("@name", s);
  10016. }
  10017. void CLocalWUResult::setResultSequence(unsigned seq)
  10018. {
  10019. p->setPropInt("@sequence", seq);
  10020. }
  10021. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  10022. {
  10023. p->setPropBin("SchemaRaw", size, schema);
  10024. }
  10025. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  10026. {
  10027. StringBuffer xpath("@xmlns");
  10028. if (prefix && *prefix)
  10029. xpath.append(':').append(prefix);
  10030. p->setProp(xpath, uri);
  10031. }
  10032. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  10033. {
  10034. if (!name || !*name)
  10035. return;
  10036. IPropertyTree *format = ensurePTree(p, "Format");
  10037. VStringBuffer xpath("@%s", name);
  10038. format->setProp(xpath, value);
  10039. }
  10040. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  10041. {
  10042. p->setProp("@graph", _graph);
  10043. p->setPropInt("@activity", _activityId);
  10044. }
  10045. void CLocalWUResult::setResultScalar(bool isScalar)
  10046. {
  10047. p->setPropInt("@isScalar", (int) isScalar);
  10048. if (isScalar)
  10049. setResultTotalRowCount(1);
  10050. }
  10051. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  10052. {
  10053. p->setPropBin("Value", len, data);
  10054. setResultStatus(ResultStatusSupplied);
  10055. setResultFormat(format);
  10056. }
  10057. void CLocalWUResult::setResultFormat(WUResultFormat format)
  10058. {
  10059. switch (format)
  10060. {
  10061. case ResultFormatXml:
  10062. p->setProp("@format","xml");
  10063. break;
  10064. case ResultFormatXmlSet:
  10065. p->setProp("@format","xmlSet");
  10066. break;
  10067. case ResultFormatCsv:
  10068. p->setProp("@format","csv");
  10069. break;
  10070. default:
  10071. p->removeProp("@format");
  10072. break;
  10073. }
  10074. }
  10075. void CLocalWUResult::setResultXML(const char *val)
  10076. {
  10077. p->setProp("xmlValue", val);
  10078. }
  10079. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  10080. {
  10081. p->appendPropBin("Value", len, data);
  10082. setResultStatus(ResultStatusPartial);
  10083. const char *existingFormat = p->queryProp("@format");
  10084. const char *formatStr = NULL;
  10085. switch (format)
  10086. {
  10087. case ResultFormatXml:
  10088. formatStr = "xml";
  10089. break;
  10090. case ResultFormatXmlSet:
  10091. formatStr = "xmlSet";
  10092. break;
  10093. case ResultFormatCsv:
  10094. formatStr = "csv";
  10095. break;
  10096. default:
  10097. p->removeProp("@format");
  10098. break;
  10099. }
  10100. if (format)
  10101. {
  10102. if (existingFormat)
  10103. {
  10104. if (0 != stricmp(formatStr, existingFormat))
  10105. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  10106. }
  10107. else
  10108. p->setProp("@format", formatStr);
  10109. }
  10110. }
  10111. void CLocalWUResult::setResultFetchSize(unsigned rows)
  10112. {
  10113. p->setPropInt("fetchSize", rows);
  10114. }
  10115. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  10116. {
  10117. p->setPropInt64("totalRowCount", rows);
  10118. }
  10119. void CLocalWUResult::setResultRowCount(__int64 rows)
  10120. {
  10121. p->setPropInt64("rowCount", rows);
  10122. }
  10123. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  10124. {
  10125. p->setProp("datasetEcl", ecl);
  10126. p->setProp("datasetEclDefs", defs);
  10127. }
  10128. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  10129. {
  10130. p->setProp("logicalName", logicalName);
  10131. }
  10132. void CLocalWUResult::setResultKeyField(const char *ecl)
  10133. {
  10134. p->setProp("keyField", ecl);
  10135. }
  10136. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  10137. {
  10138. p->setPropInt("requestedRows", rows);
  10139. }
  10140. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  10141. {
  10142. p->setProp("@recordSizeEntry", entry);
  10143. }
  10144. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  10145. {
  10146. p->setProp("@transformerEntry", entry);
  10147. }
  10148. void CLocalWUResult::setResultRowLimit(__int64 value)
  10149. {
  10150. p->setPropInt64("@rowLimit", value);
  10151. }
  10152. void CLocalWUResult::setResultFilename(const char * name)
  10153. {
  10154. p->setProp("@tempFilename", name);
  10155. }
  10156. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  10157. __int64 CLocalWUResult::getResultInt() const
  10158. {
  10159. __int64 result = 0;
  10160. MemoryBuffer s;
  10161. p->getPropBin("Value", s);
  10162. if (s.length())
  10163. s.read(result);
  10164. else
  10165. result = p->getPropInt64("xmlValue");
  10166. return result;
  10167. }
  10168. bool CLocalWUResult::getResultBool() const
  10169. {
  10170. bool result = false;
  10171. MemoryBuffer s;
  10172. p->getPropBin("Value", s);
  10173. if (s.length())
  10174. s.read(result);
  10175. else
  10176. result = p->getPropBool("xmlValue");
  10177. return result;
  10178. }
  10179. double CLocalWUResult::getResultReal() const
  10180. {
  10181. double result = 0;
  10182. MemoryBuffer s;
  10183. p->getPropBin("Value", s);
  10184. if (s.length())
  10185. s.read(result);
  10186. else
  10187. {
  10188. const char *xmlVal = p->queryProp("xmlValue");
  10189. if (xmlVal)
  10190. result = atof(xmlVal);
  10191. }
  10192. return result;
  10193. }
  10194. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  10195. {
  10196. MemoryBuffer s;
  10197. p->getPropBin("Value", s);
  10198. if (s.length())
  10199. {
  10200. assertex(s.length() == len);
  10201. s.read(len, val);
  10202. }
  10203. else
  10204. {
  10205. const char *xmlVal = p->queryProp("xmlValue");
  10206. if (xmlVal)
  10207. {
  10208. Decimal d;
  10209. d.setString(strlen(xmlVal), xmlVal);
  10210. if (isSigned)
  10211. d.getDecimal(len, precision, val);
  10212. else
  10213. d.getUDecimal(len, precision, val);
  10214. }
  10215. else
  10216. memset(val, 0, len);
  10217. }
  10218. }
  10219. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  10220. {
  10221. if (hidePassword && p->getPropBool("@password"))
  10222. {
  10223. str.set("****");
  10224. return str;
  10225. }
  10226. MemoryBuffer s;
  10227. p->getPropBin("Value", s);
  10228. if (s.length())
  10229. {
  10230. unsigned len;
  10231. s.read(len);
  10232. str.setLen((const char *) s.readDirect(len), len);
  10233. }
  10234. else
  10235. {
  10236. p->getPropBin("xmlValue", s);
  10237. if (p->isBinary("xmlValue"))
  10238. str.setLen(s.toByteArray(), s.length());
  10239. else
  10240. {
  10241. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  10242. str.set(ascii);
  10243. rtlFree(ascii);
  10244. }
  10245. }
  10246. return str;
  10247. }
  10248. WUResultFormat CLocalWUResult::getResultFormat() const
  10249. {
  10250. const char * format = p->queryProp("@format");
  10251. if (!format)
  10252. return ResultFormatRaw;
  10253. else if (strcmp(format, "xml") == 0)
  10254. return ResultFormatXml;
  10255. else if (strcmp(format, "xmlSet") == 0)
  10256. return ResultFormatXmlSet;
  10257. else if (strcmp(format, "csv") == 0)
  10258. return ResultFormatCsv;
  10259. else
  10260. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  10261. }
  10262. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10263. {
  10264. MemoryBuffer s;
  10265. p->getPropBin("Value", s);
  10266. unsigned len = s.length();
  10267. if (len)
  10268. {
  10269. WUResultFormat format = getResultFormat();
  10270. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  10271. {
  10272. if (!xmlTransformer)
  10273. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  10274. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  10275. }
  10276. else if (format == ResultFormatCsv)
  10277. {
  10278. if (!csvTransformer)
  10279. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  10280. csvTransformer->transform(data, len, s.readDirect(len), true);
  10281. }
  10282. else
  10283. data.setLen(s.readDirect(len), len);
  10284. }
  10285. else
  10286. data.clear();
  10287. return data;
  10288. }
  10289. unsigned CLocalWUResult::getResultHash() const
  10290. {
  10291. MemoryBuffer s;
  10292. p->getPropBin("Value", s);
  10293. unsigned len = s.length();
  10294. const byte * data = (const byte *)s.toByteArray();
  10295. return ~hashc(data, len, ~0);
  10296. }
  10297. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  10298. {
  10299. MemoryBuffer s;
  10300. p->getPropBin("Value", s);
  10301. if (s.length())
  10302. {
  10303. unsigned len;
  10304. s.read(len);
  10305. data.setLen(s.readDirect(len*2), len*2);
  10306. }
  10307. else
  10308. {
  10309. StringBuffer utf8;
  10310. if (p->getProp("xmlValue", utf8))
  10311. {
  10312. unsigned outlen;
  10313. UChar *out;
  10314. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  10315. data.setLen(out, outlen*2);
  10316. rtlFree(out);
  10317. }
  10318. else
  10319. data.clear();
  10320. }
  10321. return data;
  10322. }
  10323. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10324. {
  10325. WUResultFormat format = getResultFormat();
  10326. if (format == ResultFormatRaw)
  10327. {
  10328. //MORE: This should not load the whole property...
  10329. MemoryBuffer s;
  10330. p->getPropBin("Value", s);
  10331. return s.length();
  10332. }
  10333. else
  10334. {
  10335. MemoryBuffer temp;
  10336. MemoryBuffer2IDataVal adaptor(temp);
  10337. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10338. return temp.length();
  10339. }
  10340. }
  10341. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10342. {
  10343. WUResultFormat format = getResultFormat();
  10344. if (format != ResultFormatRaw)
  10345. {
  10346. MemoryBuffer temp;
  10347. MemoryBuffer2IDataVal adaptor(temp);
  10348. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10349. unsigned len = temp.length();
  10350. if (from > len) from = len;
  10351. if (from + length > len) length = len - from;
  10352. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  10353. return data;
  10354. }
  10355. else
  10356. {
  10357. //MORE: This should not load the whole property, and should be different from the code above...
  10358. MemoryBuffer s;
  10359. p->getPropBin("Value", s);
  10360. unsigned len = s.length();
  10361. if (from > len) from = len;
  10362. if (from + length > len) length = len - from;
  10363. data.setLen(s.readDirect(len) + from, (size32_t)length);
  10364. return data;
  10365. }
  10366. }
  10367. bool CLocalWUResult::getResultIsAll() const
  10368. {
  10369. return p->getPropBool("@isAll", false);
  10370. }
  10371. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  10372. void CLocalWUResult::setResultInt(__int64 val)
  10373. {
  10374. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  10375. MemoryBuffer m;
  10376. serializeInt8(val, m);
  10377. p->setPropBin("Value", m.length(), m.toByteArray());
  10378. setResultRowCount(1);
  10379. setResultTotalRowCount(1);
  10380. }
  10381. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  10382. {
  10383. setResultInt((__int64) val);
  10384. }
  10385. void CLocalWUResult::setResultReal(double val)
  10386. {
  10387. // Note: we always serialize scalar real results as real8, and schema must reflect this
  10388. MemoryBuffer m;
  10389. serializeReal8(val, m);
  10390. p->setPropBin("Value", m.length(), m.toByteArray());
  10391. setResultRowCount(1);
  10392. setResultTotalRowCount(1);
  10393. }
  10394. void CLocalWUResult::setResultBool(bool val)
  10395. {
  10396. MemoryBuffer m;
  10397. serializeBool(val, m);
  10398. p->setPropBin("Value", m.length(), m.toByteArray());
  10399. setResultRowCount(1);
  10400. setResultTotalRowCount(1);
  10401. }
  10402. void CLocalWUResult::setResultString(const char *val, unsigned len)
  10403. {
  10404. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10405. MemoryBuffer m;
  10406. serializeLPString(len, val, m);
  10407. p->setPropBin("Value", m.length(), m.toByteArray());
  10408. setResultRowCount(1);
  10409. setResultTotalRowCount(1);
  10410. }
  10411. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  10412. {
  10413. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10414. MemoryBuffer m;
  10415. m.append(len).append(len*2, val);
  10416. p->setPropBin("Value", m.length(), m.toByteArray());
  10417. setResultRowCount(1);
  10418. setResultTotalRowCount(1);
  10419. }
  10420. void CLocalWUResult::setResultData(const void *val, unsigned len)
  10421. {
  10422. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  10423. MemoryBuffer m;
  10424. serializeLPString(len, (const char *)val, m);
  10425. p->setPropBin("Value", m.length(), m.toByteArray());
  10426. setResultRowCount(1);
  10427. setResultTotalRowCount(1);
  10428. }
  10429. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  10430. {
  10431. // Note: serialized as data but with length known from schema
  10432. MemoryBuffer m;
  10433. serializeFixedData(len, val, m);
  10434. p->setPropBin("Value", m.length(), m.toByteArray());
  10435. setResultRowCount(1);
  10436. setResultTotalRowCount(1);
  10437. }
  10438. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  10439. {
  10440. p->setPropBin("Value", len, data);
  10441. setResultRowCount(1);
  10442. setResultTotalRowCount(1);
  10443. setResultFormat(ResultFormatRaw);
  10444. }
  10445. void CLocalWUResult::setResultIsAll(bool value)
  10446. {
  10447. p->setPropBool("@isAll", value);
  10448. }
  10449. //==========================================================================================
  10450. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  10451. {
  10452. }
  10453. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  10454. {
  10455. str.set(p->queryProp("@dllname"));
  10456. return str;
  10457. }
  10458. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  10459. {
  10460. str.set(p->queryProp("@version"));
  10461. return str;
  10462. }
  10463. void CLocalWUPlugin::setPluginName(const char *str)
  10464. {
  10465. p->setProp("@dllname", str);
  10466. }
  10467. void CLocalWUPlugin::setPluginVersion(const char *str)
  10468. {
  10469. p->setProp("@version", str);
  10470. }
  10471. //==========================================================================================
  10472. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  10473. {
  10474. }
  10475. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10476. {
  10477. str.set(p->queryProp("@name"));
  10478. return str;
  10479. }
  10480. void CLocalWULibrary::setName(const char *str)
  10481. {
  10482. p->setProp("@name", str);
  10483. }
  10484. //==========================================================================================
  10485. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10486. {
  10487. }
  10488. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10489. {
  10490. str.set(p->queryProp("@source"));
  10491. return str;
  10492. }
  10493. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10494. {
  10495. str.set(p->queryProp(NULL));
  10496. return str;
  10497. }
  10498. unsigned CLocalWUException::getExceptionCode() const
  10499. {
  10500. return p->getPropInt("@code", 0);
  10501. }
  10502. ErrorSeverity CLocalWUException::getSeverity() const
  10503. {
  10504. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10505. }
  10506. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10507. {
  10508. dt.set(p->queryProp("@time"));
  10509. return dt;
  10510. }
  10511. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10512. {
  10513. str.set(p->queryProp("@filename"));
  10514. return str;
  10515. }
  10516. unsigned CLocalWUException::getExceptionLineNo() const
  10517. {
  10518. return p->getPropInt("@row", 0);
  10519. }
  10520. unsigned CLocalWUException::getExceptionColumn() const
  10521. {
  10522. return p->getPropInt("@col", 0);
  10523. }
  10524. unsigned CLocalWUException::getActivityId() const
  10525. {
  10526. const char * scope = queryScope();
  10527. if (scope)
  10528. {
  10529. const char * colon = strrchr(scope, ':');
  10530. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10531. return atoi(colon+1+strlen(ActivityScopePrefix));
  10532. }
  10533. return p->getPropInt("@activity", 0);
  10534. }
  10535. unsigned CLocalWUException::getSequence() const
  10536. {
  10537. return p->getPropInt("@sequence", 0);
  10538. }
  10539. const char * CLocalWUException::queryScope() const
  10540. {
  10541. return p->queryProp("@scope");
  10542. }
  10543. unsigned CLocalWUException::getPriority() const
  10544. {
  10545. return p->getPropInt("@prio", 0);
  10546. }
  10547. void CLocalWUException::setExceptionSource(const char *str)
  10548. {
  10549. p->setProp("@source", str);
  10550. }
  10551. void CLocalWUException::setExceptionMessage(const char *str)
  10552. {
  10553. p->setProp(NULL, str);
  10554. }
  10555. void CLocalWUException::setExceptionCode(unsigned code)
  10556. {
  10557. p->setPropInt("@code", code);
  10558. }
  10559. void CLocalWUException::setSeverity(ErrorSeverity level)
  10560. {
  10561. p->setPropInt("@severity", level);
  10562. }
  10563. void CLocalWUException::setTimeStamp(const char *str)
  10564. {
  10565. p->setProp("@time", str);
  10566. }
  10567. void CLocalWUException::setExceptionFileName(const char *str)
  10568. {
  10569. p->setProp("@filename", str);
  10570. }
  10571. void CLocalWUException::setExceptionLineNo(unsigned r)
  10572. {
  10573. p->setPropInt("@row", r);
  10574. }
  10575. void CLocalWUException::setExceptionColumn(unsigned c)
  10576. {
  10577. p->setPropInt("@col", c);
  10578. }
  10579. void CLocalWUException::setActivityId(unsigned _id)
  10580. {
  10581. p->setPropInt("@activity", _id);
  10582. }
  10583. void CLocalWUException::setScope(const char * _scope)
  10584. {
  10585. p->setProp("@scope", _scope);
  10586. }
  10587. void CLocalWUException::setPriority(unsigned _priority)
  10588. {
  10589. p->setPropInt("@prio", _priority);
  10590. }
  10591. //==========================================================================================
  10592. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10593. {
  10594. StringAttrBuilder propPath(prop);
  10595. propPath.append("*[").append(child).append("]");
  10596. }
  10597. const char * CLocalWUAppValue::queryApplication() const
  10598. {
  10599. return p->queryName();
  10600. }
  10601. const char * CLocalWUAppValue::queryName() const
  10602. {
  10603. IPropertyTree* val=p->queryPropTree(prop.str());
  10604. if(val)
  10605. return val->queryName();
  10606. return ""; // Should not happen in normal usage
  10607. }
  10608. const char * CLocalWUAppValue::queryValue() const
  10609. {
  10610. return p->queryProp(prop.str());
  10611. }
  10612. //==========================================================================================
  10613. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10614. {
  10615. }
  10616. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10617. {
  10618. const char * creator = p->queryProp("@creator");
  10619. str.set(creator);
  10620. return str;
  10621. }
  10622. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10623. {
  10624. const char * desc = p->queryProp("@desc");
  10625. if (desc)
  10626. {
  10627. str.set(desc); // legacy and in case it is overridden
  10628. }
  10629. else if (createDefault)
  10630. {
  10631. StatisticKind kind = getKind();
  10632. assertex(kind != StKindNone);
  10633. const char * scope = p->queryProp("@scope");
  10634. assertex(scope);
  10635. //Clean up the format of the scope when converting it to a description
  10636. StringBuffer descriptionText;
  10637. if (isGlobalScope(scope))
  10638. {
  10639. const char * creator = p->queryProp("@creator");
  10640. descriptionText.append(creator).append(":");
  10641. queryLongStatisticName(descriptionText, kind);
  10642. }
  10643. else
  10644. {
  10645. for (;;)
  10646. {
  10647. char c = *scope++;
  10648. if (!c)
  10649. break;
  10650. if (c == ':')
  10651. descriptionText.append(": ");
  10652. else
  10653. descriptionText.append(c);
  10654. }
  10655. if (kind != StTimeElapsed)
  10656. queryLongStatisticName(descriptionText.append(": "), kind);
  10657. }
  10658. str.set(descriptionText);
  10659. }
  10660. else
  10661. str.clear();
  10662. return str;
  10663. }
  10664. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10665. {
  10666. StringBuffer formatted;
  10667. formatStatistic(formatted, getValue(), getMeasure());
  10668. str.set(formatted);
  10669. return str;
  10670. }
  10671. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10672. {
  10673. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10674. }
  10675. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10676. {
  10677. return queryScopeType(p->queryProp("@s"), SSTnone);
  10678. }
  10679. StatisticKind CLocalWUStatistic::getKind() const
  10680. {
  10681. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10682. }
  10683. const char * CLocalWUStatistic::queryScope() const
  10684. {
  10685. const char * scope = p->queryProp("@scope");
  10686. if (scope && streq(scope, LEGACY_GLOBAL_SCOPE))
  10687. scope = GLOBAL_SCOPE;
  10688. return scope;
  10689. }
  10690. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10691. {
  10692. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10693. }
  10694. unsigned __int64 CLocalWUStatistic::getValue() const
  10695. {
  10696. return p->getPropInt64("@value", 0);
  10697. }
  10698. unsigned __int64 CLocalWUStatistic::getCount() const
  10699. {
  10700. return p->getPropInt64("@count", 0);
  10701. }
  10702. unsigned __int64 CLocalWUStatistic::getMax() const
  10703. {
  10704. return p->getPropInt64("@max", 0);
  10705. }
  10706. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10707. {
  10708. return p->getPropInt64("@ts", 0);
  10709. }
  10710. //==========================================================================================
  10711. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10712. {
  10713. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10714. if (xml)
  10715. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10716. else
  10717. {
  10718. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10719. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10720. cw->loadPTree(p.getClear());
  10721. }
  10722. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10723. return ret;
  10724. }
  10725. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10726. {
  10727. const char *name = p->queryName();
  10728. if (!name)
  10729. name = "__unnamed__";
  10730. StringBuffer temp;
  10731. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10732. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10733. ForEach(*elems)
  10734. {
  10735. IPropertyTree &elem = elems->query();
  10736. if (streq(elem.queryName(), "Parameters"))
  10737. {
  10738. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10739. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10740. ForEach(*params)
  10741. {
  10742. IPropertyTree &param = params->query();
  10743. const char *paramname = param.queryName();
  10744. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10745. if (p->getPropBool(xpath))
  10746. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10747. else
  10748. {
  10749. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10750. }
  10751. }
  10752. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10753. }
  10754. else if (streq(elem.queryName(), "Variables"))
  10755. {
  10756. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10757. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10758. ForEach(*vars)
  10759. {
  10760. Owned<IPropertyTree> var = LINK(&vars->query());
  10761. if (var->getPropBool("Format/@password"))
  10762. {
  10763. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10764. var->removeProp("Value");
  10765. var->removeProp("xmlValue");
  10766. }
  10767. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10768. }
  10769. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10770. }
  10771. else
  10772. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10773. }
  10774. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10775. }
  10776. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10777. {
  10778. class CAdapter : public CInterface, implements IIOStream
  10779. {
  10780. StringBuffer &out;
  10781. public:
  10782. IMPLEMENT_IINTERFACE;
  10783. CAdapter(StringBuffer &_out) : out(_out) { }
  10784. virtual void flush() { }
  10785. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10786. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10787. } adapter(str);
  10788. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10789. return str;
  10790. }
  10791. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10792. {
  10793. OwnedIFile ifile = createIFile(filename);
  10794. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10795. Owned<IIOStream> stream = createIOStream(ifileio);
  10796. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10797. }
  10798. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10799. {
  10800. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10801. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10802. if (ewu)
  10803. {
  10804. Linked<IPropertyTree> p;
  10805. if (unpack||includeProgress)
  10806. p.setown(ewu->getUnpackedTree(includeProgress));
  10807. else
  10808. p.set(ewu->queryPTree());
  10809. if (hidePasswords)
  10810. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10811. else
  10812. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10813. }
  10814. else
  10815. return str.append("Unrecognized workunit format");
  10816. }
  10817. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10818. {
  10819. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10820. if (ewu)
  10821. {
  10822. Linked<IPropertyTree> p;
  10823. if (unpack||includeProgress)
  10824. p.setown(ewu->getUnpackedTree(includeProgress));
  10825. else if (regressionTest)
  10826. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10827. else
  10828. p.set(ewu->queryPTree());
  10829. if (hidePasswords)
  10830. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10831. if (regressionTest)
  10832. {
  10833. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10834. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10835. p->removeProp("@buildVersion");
  10836. p->removeProp("@eclVersion");
  10837. p->removeProp("@hash");
  10838. //Remove statistics, and extract them to a separate file
  10839. IPropertyTree * stats = p->queryPropTree("Statistics");
  10840. if (stats)
  10841. {
  10842. StringBuffer statsFilename;
  10843. statsFilename.append(filename).append(".stats");
  10844. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10845. p->removeProp("Statistics");
  10846. }
  10847. //Now remove timestamps from exceptions
  10848. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10849. ForEach(*elems)
  10850. {
  10851. IPropertyTree &elem = elems->query();
  10852. elem.removeProp("@time");
  10853. }
  10854. }
  10855. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10856. }
  10857. else
  10858. throw makeStringException(0, "Unrecognized workunit format");
  10859. }
  10860. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10861. {
  10862. MemoryBuffer buffer;
  10863. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10864. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10865. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10866. assertex(workunit);
  10867. StringAttr clusterName(workunit->queryClusterName());
  10868. if (!clusterName.length())
  10869. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10870. workunit->commit();
  10871. workunit.clear();
  10872. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  10873. if (!clusterInfo)
  10874. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName.str());
  10875. SCMStringBuffer serverQueue;
  10876. clusterInfo->getServerQueue(serverQueue);
  10877. assertex(serverQueue.length());
  10878. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10879. if (!queue.get())
  10880. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10881. IJobQueueItem *item = createJobQueueItem(wuid);
  10882. queue->enqueue(item);
  10883. }
  10884. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10885. {
  10886. StringBuffer xpath("/WorkUnitAborts/");
  10887. xpath.append(wuid);
  10888. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10889. acon->queryRoot()->setPropInt(NULL, 1);
  10890. }
  10891. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10892. {
  10893. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10894. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10895. }
  10896. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10897. {
  10898. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10899. return;
  10900. abortWorkUnit(wuid);
  10901. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10902. if(!cw)
  10903. return;
  10904. WorkunitUpdate wu(&cw->lock());
  10905. const char *abortBy = secuser.getName();
  10906. if (abortBy && *abortBy)
  10907. wu->setTracingValue("AbortBy", abortBy);
  10908. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10909. }
  10910. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10911. {
  10912. if (secmgr && secuser)
  10913. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10914. if (secuser)
  10915. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10916. submitWorkUnit(wuid, "", "");
  10917. }
  10918. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10919. {
  10920. if (secmgr && secuser)
  10921. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10922. abortWorkUnit(wuid);
  10923. }
  10924. bool CLocalWorkUnit::hasWorkflow() const
  10925. {
  10926. return p->hasProp("Workflow");
  10927. }
  10928. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10929. {
  10930. CriticalBlock block(crit);
  10931. if (p->hasProp("@eventScheduledCount"))
  10932. return p->getPropInt("@eventScheduledCount", 0);
  10933. else
  10934. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10935. }
  10936. void CLocalWorkUnit::incEventScheduledCount()
  10937. {
  10938. CriticalBlock block(crit);
  10939. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10940. }
  10941. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10942. {
  10943. CriticalBlock block(crit);
  10944. return p->queryPropTree("Workflow");
  10945. }
  10946. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10947. {
  10948. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10949. CriticalBlock block(crit);
  10950. if(!workflowIteratorCached)
  10951. {
  10952. assertex(!workflowIterator);
  10953. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10954. if(s)
  10955. workflowIterator.setown(createWorkflowItemIterator(s));
  10956. workflowIteratorCached = true;
  10957. }
  10958. return workflowIterator.getLink();
  10959. }
  10960. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10961. {
  10962. unsigned count = 0;
  10963. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10964. for(iter->first(); iter->isValid(); iter->next())
  10965. count++;
  10966. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10967. for(iter->first(); iter->isValid(); iter->next())
  10968. array->addClone(iter->query());
  10969. return array.getLink();
  10970. }
  10971. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10972. {
  10973. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10974. CriticalBlock block(crit);
  10975. workflowIterator.clear();
  10976. workflowIteratorCached = false;
  10977. IPropertyTree * s = p->queryPropTree("Workflow");
  10978. if(!s)
  10979. s = p->addPropTree("Workflow");
  10980. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10981. }
  10982. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10983. {
  10984. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10985. CriticalBlock block(crit);
  10986. if(!workflowIterator)
  10987. {
  10988. IPropertyTree * s = p->queryPropTree("Workflow");
  10989. if(!s)
  10990. s = p->addPropTree("Workflow");
  10991. workflowIterator.setown(createWorkflowItemIterator(s));
  10992. workflowIteratorCached = true;
  10993. }
  10994. return workflowIterator.getLink();
  10995. }
  10996. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10997. {
  10998. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10999. Owned<IWorkflowItem> item;
  11000. for(iter->first(); iter->isValid(); iter->next())
  11001. {
  11002. item.setown(iter->get());
  11003. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  11004. }
  11005. workflowIterator.clear();
  11006. workflowIteratorCached = false;
  11007. }
  11008. void CLocalWorkUnit::resetWorkflow()
  11009. {
  11010. if (hasWorkflow())
  11011. {
  11012. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  11013. Owned<IWorkflowItem> wf;
  11014. for(iter->first(); iter->isValid(); iter->next())
  11015. {
  11016. wf.setown(iter->get());
  11017. wf->reset();
  11018. }
  11019. workflowIterator.clear();
  11020. workflowIteratorCached = false;
  11021. }
  11022. }
  11023. void CLocalWorkUnit::schedule()
  11024. {
  11025. CriticalBlock block(crit);
  11026. if(queryEventScheduledCount() == 0) return;
  11027. switch(getState())
  11028. {
  11029. case WUStateCompleted:
  11030. setState(WUStateWait);
  11031. break;
  11032. case WUStateFailed:
  11033. case WUStateArchived:
  11034. case WUStateAborting:
  11035. case WUStateAborted:
  11036. case WUStateScheduled:
  11037. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  11038. }
  11039. StringBuffer rootPath;
  11040. rootPath.append("/Schedule/").append(queryClusterName());
  11041. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11042. Owned<IPropertyTree> root = conn->getRoot();
  11043. if(!root->hasChildren())
  11044. {
  11045. StringBuffer addPath;
  11046. addPath.append("/Schedulers/").append(queryClusterName());
  11047. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11048. }
  11049. char const * wuid = p->queryName();
  11050. StringBuffer xpath("*/*/");
  11051. ncnameEscape(wuid, xpath);
  11052. bool more;
  11053. do more = root->removeProp(xpath.str()); while(more);
  11054. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  11055. Owned<IWorkflowEvent> event;
  11056. Owned<IPropertyTree> branch1, branch2;
  11057. for(iter->first(); iter->isValid(); iter->next())
  11058. {
  11059. event.setown(iter->query()->getScheduleEvent());
  11060. if(!event) continue;
  11061. ncnameEscape(event->queryName(), xpath.clear());
  11062. ensurePTree(root, xpath.str());
  11063. branch1.setown(root->getPropTree(xpath.str()));
  11064. ncnameEscape(event->queryText(), xpath.clear());
  11065. ensurePTree(branch1, xpath.str());
  11066. branch2.setown(branch1->getPropTree(xpath.str()));
  11067. ncnameEscape(wuid, xpath.clear());
  11068. ensurePTree(branch2, xpath.str());
  11069. }
  11070. }
  11071. void CLocalWorkUnit::deschedule()
  11072. {
  11073. if(queryEventScheduledCount() == 0) return;
  11074. if(getState() == WUStateWait)
  11075. setState(WUStateCompleted);
  11076. doDescheduleWorkkunit(p->queryName());
  11077. }
  11078. EnumMapping localFileUploadTypes[] = {
  11079. { UploadTypeFileSpray, "FileSpray" },
  11080. { UploadTypeWUResult, "WUResult" },
  11081. { UploadTypeWUResultCsv, "WUResultCsv" },
  11082. { UploadTypeWUResultXml, "WUResultXml" },
  11083. { UploadTypeSize, NULL }
  11084. };
  11085. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  11086. {
  11087. public:
  11088. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  11089. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  11090. {
  11091. tree.setown(createPTree());
  11092. tree->setPropInt("@id", id);
  11093. setEnum(tree, "@type", type, localFileUploadTypes);
  11094. tree->setProp("@source", source);
  11095. tree->setProp("@destination", destination);
  11096. if (eventTag)
  11097. tree->setProp("@eventTag", eventTag);
  11098. }
  11099. IMPLEMENT_IINTERFACE;
  11100. IPropertyTree * getTree() { return tree.getLink(); }
  11101. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  11102. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  11103. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  11104. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  11105. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  11106. private:
  11107. Owned<IPropertyTree> tree;
  11108. };
  11109. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  11110. {
  11111. public:
  11112. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  11113. IMPLEMENT_IINTERFACE;
  11114. bool first() { return iter->first(); }
  11115. bool isValid() { return iter->isValid(); }
  11116. bool next() { return iter->next(); }
  11117. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  11118. private:
  11119. Owned<IPropertyTree> tree;
  11120. Owned<IPropertyTreeIterator> iter;
  11121. };
  11122. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  11123. {
  11124. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  11125. CriticalBlock block(crit);
  11126. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  11127. if(s)
  11128. return new CLocalFileUploadIterator(s.getClear());
  11129. else
  11130. return NULL;
  11131. }
  11132. bool CLocalWorkUnit::requiresLocalFileUpload() const
  11133. {
  11134. SCMStringBuffer dest;
  11135. Owned<IConstWUResult> result;
  11136. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  11137. if(!iter)
  11138. return false;
  11139. for(iter->first(); iter->isValid(); iter->next())
  11140. {
  11141. Owned<IConstLocalFileUpload> upload(iter->get());
  11142. switch(upload->queryType())
  11143. {
  11144. case UploadTypeWUResult:
  11145. case UploadTypeWUResultCsv:
  11146. case UploadTypeWUResultXml:
  11147. upload->getDestination(dest);
  11148. result.setown(getResultByName(dest.str()));
  11149. if(!result)
  11150. return true;
  11151. break;
  11152. default:
  11153. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  11154. }
  11155. }
  11156. return false;
  11157. }
  11158. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  11159. {
  11160. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  11161. CriticalBlock block(crit);
  11162. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  11163. if(!s)
  11164. s = p->addPropTree("LocalFileUploads");
  11165. unsigned id = s->numChildren();
  11166. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  11167. s->addPropTree("LocalFileUpload", upload->getTree());
  11168. return id;
  11169. }
  11170. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  11171. {
  11172. CriticalBlock block(crit);
  11173. str.set(p->queryProp("Tracing/AbortBy"));
  11174. return str;
  11175. }
  11176. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  11177. {
  11178. CriticalBlock block(crit);
  11179. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  11180. }
  11181. #if 0
  11182. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  11183. {
  11184. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  11185. unsigned deps = 0;
  11186. Owned<IWorkflowDependencyIterator> diter;
  11187. switch(cwf->queryWfid())
  11188. {
  11189. case 1:
  11190. assertex(!cwf->isScheduled());
  11191. assertex(cwf->queryType() == WFTypeNormal);
  11192. assertex(cwf->queryState() == WFStateNull);
  11193. diter.setown(cwf->getDependencies());
  11194. for(diter->first(); diter->isValid(); diter->next())
  11195. deps++;
  11196. assertex(deps==0);
  11197. okay[0] = true;
  11198. break;
  11199. case 2:
  11200. assertex(!cwf->isScheduled());
  11201. assertex(cwf->queryType() == WFTypeRecovery);
  11202. assertex(cwf->queryState() == WFStateSkip);
  11203. okay[1] = true;
  11204. break;
  11205. case 3:
  11206. assertex(cwf->queryContingencyFor() == 4);
  11207. okay[2] = true;
  11208. break;
  11209. case 4:
  11210. assertex(cwf->isScheduled());
  11211. assertex(cwf->queryType() == WFTypeNormal);
  11212. assertex(cwf->queryState() == WFStateReqd);
  11213. assertex(cwf->querySuccess() == 0);
  11214. assertex(cwf->queryFailure() == 3);
  11215. assertex(cwf->queryRecovery() == 2);
  11216. assertex(cwf->queryRetriesAllowed() == 10);
  11217. assertex(cwf->queryRetriesRemaining() == 10);
  11218. diter.setown(cwf->getDependencies());
  11219. for(diter->first(); diter->isValid(); diter->next())
  11220. {
  11221. dep[diter->query()-1] = true;
  11222. deps++;
  11223. }
  11224. assertex(deps==2);
  11225. assertex(dep[0]);
  11226. assertex(dep[1]);
  11227. okay[3] = true;
  11228. break;
  11229. case 5:
  11230. assertex(cwf->isScheduled());
  11231. assertex(!cwf->isScheduledNow());
  11232. assertex(cwf->querySchedulePriority() == 75);
  11233. assertex(cwf->queryScheduleCount() == 5);
  11234. assertex(cwf->queryScheduleCountRemaining() == 5);
  11235. okay[4] = true;
  11236. break;
  11237. case 6:
  11238. assertex(cwf->isScheduled());
  11239. assertex(!cwf->isScheduledNow());
  11240. assertex(cwf->querySchedulePriority() == 25);
  11241. assertex(!cwf->hasScheduleCount());
  11242. okay[5] = true;
  11243. break;
  11244. default:
  11245. assertex(!"unknown wfid in test");
  11246. }
  11247. }
  11248. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  11249. {
  11250. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  11251. switch(rwf->queryWfid())
  11252. {
  11253. case 1:
  11254. case 2:
  11255. case 3:
  11256. okay[rwf->queryWfid()-1] = true;
  11257. break;
  11258. case 4:
  11259. {
  11260. unsigned tries = 0;
  11261. while(rwf->testAndDecRetries())
  11262. tries++;
  11263. assertex(tries == 10);
  11264. assertex(rwf->queryRetriesRemaining() == 0);
  11265. rwf->setState(WFStateFail);
  11266. assertex(rwf->queryState() == WFStateFail);
  11267. rwf->reset();
  11268. assertex(rwf->queryRetriesRemaining() == 10);
  11269. assertex(rwf->queryState() == WFStateReqd);
  11270. }
  11271. okay[3] = true;
  11272. break;
  11273. case 5:
  11274. {
  11275. assertex(rwf->queryScheduleCountRemaining() == 5);
  11276. unsigned count = 0;
  11277. do count++; while(rwf->decAndTestScheduleCountRemaining());
  11278. assertex(count == 5);
  11279. assertex(rwf->queryScheduleCountRemaining() == 0);
  11280. rwf->reset();
  11281. assertex(rwf->queryScheduleCountRemaining() == 5);
  11282. }
  11283. okay[4] = true;
  11284. break;
  11285. case 6:
  11286. {
  11287. assertex(!rwf->hasScheduleCount());
  11288. unsigned count;
  11289. for(count=0; count<20; count++)
  11290. assertex(rwf->decAndTestScheduleCountRemaining());
  11291. }
  11292. okay[5] = true;
  11293. break;
  11294. default:
  11295. assertex(!"unknown wfid in test");
  11296. }
  11297. }
  11298. void testWorkflow()
  11299. {
  11300. DBGLOG("workunit.cpp : testWorkflow");
  11301. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  11302. Owned<IWorkflowItem> wf;
  11303. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  11304. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  11305. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  11306. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  11307. wf->setScheduledNow();
  11308. wf->addDependency(1);
  11309. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  11310. wf->setScheduledOn("test", "foo*");
  11311. wf->setSchedulePriority(75);
  11312. wf->setScheduleCount(5);
  11313. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  11314. wf->setScheduledOn("test", "bar*");
  11315. wf->setSchedulePriority(25);
  11316. unsigned const n = 6;
  11317. bool okay[n];
  11318. bool dep[n];
  11319. unsigned i;
  11320. for(i=0; i<n; i++)
  11321. okay[i] = dep[i] = 0;
  11322. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  11323. for(citer->first(); citer->isValid(); citer->next())
  11324. testConstWorkflow(citer->query(), okay, dep);
  11325. for(i=0; i<n; i++)
  11326. {
  11327. assertex(okay[i]);
  11328. okay[i] = false;
  11329. }
  11330. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  11331. for(miter->first(); miter->isValid(); miter->next())
  11332. {
  11333. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  11334. testRuntimeWorkflow(rwf, okay);
  11335. }
  11336. for(i=0; i<n; i++)
  11337. {
  11338. assertex(okay[i]);
  11339. okay[i] = dep[i] = false;
  11340. }
  11341. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  11342. unsigned wfid;
  11343. for(wfid = 1; array->isValid(wfid); wfid++)
  11344. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  11345. for(i=0; i<n; i++)
  11346. {
  11347. assertex(okay[i]);
  11348. okay[i] = false;
  11349. }
  11350. for(wfid = 1; array->isValid(wfid); wfid++)
  11351. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  11352. for(i=0; i<n; i++)
  11353. {
  11354. assertex(okay[i]);
  11355. okay[i] = false;
  11356. }
  11357. }
  11358. #endif
  11359. //------------------------------------------------------------------------------------------
  11360. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, bool returnOnWaitState)
  11361. {
  11362. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, returnOnWaitState);
  11363. }
  11364. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, bool returnOnWaitState)
  11365. {
  11366. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  11367. return waitForWorkUnitToComplete(wuid, timeout, returnOnWaitState);
  11368. return WUStateUnknown;
  11369. }
  11370. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  11371. {
  11372. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, true))
  11373. {
  11374. case WUStateCompiled:
  11375. case WUStateCompleted:
  11376. case WUStateWait:
  11377. case WUStateUploadingFiles:
  11378. return true;
  11379. default:
  11380. return false;
  11381. }
  11382. }
  11383. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  11384. {
  11385. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  11386. return waitForWorkUnitToCompile(wuid, timeout);
  11387. return false;
  11388. }
  11389. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  11390. {
  11391. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  11392. {
  11393. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  11394. SCMStringBuffer ip;
  11395. unsigned port;
  11396. try
  11397. {
  11398. port = wu->getDebugAgentListenerPort();
  11399. wu->getDebugAgentListenerIP(ip);
  11400. SocketEndpoint debugEP(ip.str(), port);
  11401. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  11402. unsigned len = (size32_t)strlen(command);
  11403. unsigned revlen = len;
  11404. _WINREV(revlen);
  11405. socket->write(&revlen, sizeof(revlen));
  11406. socket->write(command, len);
  11407. for (;;)
  11408. {
  11409. socket->read(&len, sizeof(len));
  11410. _WINREV(len);
  11411. if (len == 0)
  11412. break;
  11413. if (len & 0x80000000)
  11414. {
  11415. throwUnexpected();
  11416. }
  11417. char * mem = (char*) response.reserve(len);
  11418. socket->read(mem, len);
  11419. }
  11420. return true;
  11421. }
  11422. catch (IException *E)
  11423. {
  11424. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  11425. EXCLOG(E, msg.str());
  11426. throw;
  11427. }
  11428. }
  11429. return false;
  11430. }
  11431. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  11432. {
  11433. TypeInfoArray types;
  11434. StringAttrArray names;
  11435. r->getSchema(types, names, NULL);
  11436. if (types.ordinality()==1)
  11437. type.set(&types.item(0));
  11438. }
  11439. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  11440. {
  11441. if (!r->isResultScalar())
  11442. return false;
  11443. if (!curVal.hasChildren())
  11444. return true;
  11445. getSimpleResultType(r, type);
  11446. return type && type->isScalar();
  11447. }
  11448. void updateSuppliedXmlParams(IWorkUnit * w)
  11449. {
  11450. Owned<const IPropertyTree> params = w->getXmlParams();
  11451. if (!params)
  11452. return;
  11453. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  11454. ForEach(*elems)
  11455. {
  11456. IPropertyTree & curVal = elems->query();
  11457. const char *name = curVal.queryName();
  11458. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  11459. if (r)
  11460. {
  11461. Owned<ITypeInfo> type;
  11462. StringBuffer s;
  11463. if (isSuppliedParamScalar(r, curVal, type))
  11464. {
  11465. curVal.getProp(".", s);
  11466. r->setResultXML(s);
  11467. r->setResultStatus(ResultStatusSupplied);
  11468. }
  11469. else
  11470. {
  11471. toXML(&curVal, s);
  11472. if (!type)
  11473. getSimpleResultType(r, type);
  11474. bool isSet = (type && type->getTypeCode()==type_set);
  11475. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  11476. }
  11477. }
  11478. else
  11479. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11480. }
  11481. }
  11482. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11483. {
  11484. switch ((int)sequence)
  11485. {
  11486. case ResultSequenceStored:
  11487. return w->updateVariableByName(name);
  11488. case ResultSequencePersist:
  11489. return w->updateGlobalByName(name);
  11490. case ResultSequenceInternal:
  11491. case ResultSequenceOnce:
  11492. return w->updateTemporaryByName(name);
  11493. default:
  11494. return w->updateResultBySequence(sequence);
  11495. }
  11496. }
  11497. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11498. {
  11499. switch ((int)sequence)
  11500. {
  11501. case ResultSequenceStored:
  11502. return w->getVariableByName(name);
  11503. case ResultSequencePersist:
  11504. return w->getGlobalByName(name);
  11505. case ResultSequenceInternal:
  11506. case ResultSequenceOnce:
  11507. return w->getTemporaryByName(name);
  11508. default:
  11509. if (name && name[0])
  11510. return w->getResultByName(name);//name takes precedence over sequence
  11511. else
  11512. return w->getResultBySequence(sequence);
  11513. }
  11514. }
  11515. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11516. {
  11517. if (wuid) {
  11518. char prefchar;
  11519. unsigned year,month,day,hour,min,sec;
  11520. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11521. time.set(year, month, day, hour, min, sec, 0, true);
  11522. // time.setDate(year, month, day);
  11523. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11524. return true;
  11525. }
  11526. }
  11527. return false;
  11528. }
  11529. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11530. {
  11531. return (WUState) getEnum(state, states);
  11532. }
  11533. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11534. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11535. {
  11536. public:
  11537. CWorkflowScheduleConnection(char const * wuid)
  11538. {
  11539. basexpath.append("/WorkflowSchedule/").append(wuid);
  11540. flagxpath.append(basexpath.str()).append("/Active");
  11541. }
  11542. IMPLEMENT_IINTERFACE;
  11543. virtual void lock()
  11544. {
  11545. LOG(MCschedconn, "Locking base schedule connection");
  11546. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11547. if(!baseconn)
  11548. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11549. }
  11550. virtual void unlock()
  11551. {
  11552. LOG(MCschedconn, "Unlocking base schedule connection");
  11553. baseconn.clear();
  11554. }
  11555. virtual void setActive()
  11556. {
  11557. LOG(MCschedconn, "Setting active flag in schedule connection");
  11558. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11559. if(!flagconn)
  11560. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11561. }
  11562. virtual void resetActive()
  11563. {
  11564. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11565. flagconn.clear();
  11566. }
  11567. virtual bool queryActive()
  11568. {
  11569. return baseconn->queryRoot()->hasProp("Active");
  11570. }
  11571. virtual bool pull(IWorkflowItemArray * workflow)
  11572. {
  11573. assertex(baseconn);
  11574. Owned<IPropertyTree> root = baseconn->getRoot();
  11575. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11576. if(!eventQueue) return false;
  11577. if(!eventQueue->hasProp("Item")) return false;
  11578. {
  11579. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11580. Owned<IPropertyTree> eventItem;
  11581. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11582. Owned<IRuntimeWorkflowItem> wfItem;
  11583. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11584. {
  11585. eventItem.setown(&eventItems->get());
  11586. const char * eventName = eventItem->queryProp("@name");
  11587. const char * eventText = eventItem->queryProp("@text");
  11588. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11589. {
  11590. wfItem.setown(wfItems->get());
  11591. if(wfItem->queryState() != WFStateWait)
  11592. continue;
  11593. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11594. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11595. continue;
  11596. wfItem->setEvent(eventName, eventText);
  11597. wfItem->setState(WFStateReqd);
  11598. resetDependentsState(workflow, *wfItem);
  11599. }
  11600. }
  11601. }
  11602. bool more;
  11603. do
  11604. more = eventQueue->removeProp("Item");
  11605. while(more);
  11606. return true;
  11607. }
  11608. virtual void push(char const * name, char const * text)
  11609. {
  11610. assertex(baseconn);
  11611. Owned<IPropertyTree> root = baseconn->getRoot();
  11612. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11613. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11614. eventItem->setProp("@name", name);
  11615. eventItem->setProp("@text", text);
  11616. }
  11617. virtual void remove()
  11618. {
  11619. if (baseconn)
  11620. {
  11621. baseconn->close(true);
  11622. baseconn.clear();
  11623. }
  11624. }
  11625. private:
  11626. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11627. {
  11628. if (wfid)
  11629. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11630. }
  11631. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11632. {
  11633. switch(item.queryState())
  11634. {
  11635. case WFStateDone:
  11636. case WFStateFail:
  11637. {
  11638. item.setState(WFStateNull);
  11639. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11640. resetDependentsState(workflow, item);
  11641. break;
  11642. }
  11643. }
  11644. }
  11645. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11646. {
  11647. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11648. for(iter->first(); iter->isValid(); iter->next())
  11649. {
  11650. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11651. resetItemStateAndDependents(workflow, dep);
  11652. }
  11653. }
  11654. private:
  11655. StringBuffer basexpath;
  11656. StringBuffer flagxpath;
  11657. Owned<IRemoteConnection> baseconn;
  11658. Owned<IRemoteConnection> flagconn;
  11659. };
  11660. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11661. {
  11662. return new CWorkflowScheduleConnection(wuid);
  11663. }
  11664. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11665. {
  11666. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11667. }
  11668. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11669. {
  11670. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11671. }
  11672. 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)
  11673. {
  11674. Owned<IWUException> we = wu->createException();
  11675. we->setSeverity(severity);
  11676. we->setExceptionMessage(text);
  11677. if (source)
  11678. we->setExceptionSource(source);
  11679. if (code)
  11680. we->setExceptionCode(code);
  11681. if (filename)
  11682. we->setExceptionFileName(filename);
  11683. if (lineno)
  11684. {
  11685. we->setExceptionLineNo(lineno);
  11686. if (column)
  11687. we->setExceptionColumn(lineno);
  11688. }
  11689. if (activity)
  11690. we->setActivityId(activity);
  11691. }
  11692. const char * skipLeadingXml(const char * text)
  11693. {
  11694. if (!text)
  11695. return NULL;
  11696. //skip utf8 BOM, probably excessive
  11697. if (memcmp(text, UTF8_BOM, 3) == 0)
  11698. text += 3;
  11699. for (;;)
  11700. {
  11701. if (isspace(*text))
  11702. text++;
  11703. else if (text[0] == '<' && text[1] == '?')
  11704. {
  11705. text += 2;
  11706. for (;;)
  11707. {
  11708. if (!*text) break;
  11709. if (text[0] == '?' && text[1] == '>')
  11710. {
  11711. text += 2;
  11712. break;
  11713. }
  11714. text++;
  11715. }
  11716. }
  11717. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11718. {
  11719. text += 4;
  11720. for (;;)
  11721. {
  11722. if (!*text) break;
  11723. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11724. {
  11725. text += 3;
  11726. break;
  11727. }
  11728. text++;
  11729. }
  11730. }
  11731. else
  11732. break;
  11733. }
  11734. return text;
  11735. }
  11736. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11737. {
  11738. text = skipLeadingXml(text);
  11739. if (!text)
  11740. return false;
  11741. const char * archivePrefix = "<Archive";
  11742. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11743. }
  11744. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11745. {
  11746. text = skipLeadingXml(text);
  11747. if (!text)
  11748. return false;
  11749. const char * manifestPrefix = "<Manifest";
  11750. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11751. }
  11752. //------------------------------------------------------------------------------
  11753. // Named Alias helper function
  11754. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11755. {
  11756. StringBuffer xpath;
  11757. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11758. return queryRegistry->getPropTree(xpath);
  11759. }
  11760. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11761. {
  11762. StringBuffer xpath;
  11763. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11764. return queryRegistry->getPropTree(xpath);
  11765. }
  11766. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11767. {
  11768. StringBuffer lcId(id);
  11769. lcId.toLowerCase();
  11770. StringBuffer xpath;
  11771. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11772. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11773. ForEach(*iter)
  11774. {
  11775. queryRegistry->removeProp(xpath.str());
  11776. }
  11777. }
  11778. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11779. {
  11780. StringBuffer lcName(name);
  11781. lcName.toLowerCase();
  11782. StringBuffer xpath;
  11783. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11784. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11785. unsigned seq = 1;
  11786. ForEach(*iter)
  11787. {
  11788. IPropertyTree &item = iter->query();
  11789. const char *thisWuid = item.queryProp("@wuid");
  11790. if (strieq(wuid, thisWuid))
  11791. return &item;
  11792. unsigned thisSeq = item.getPropInt("@seq");
  11793. if (thisSeq >= seq)
  11794. seq = thisSeq + 1;
  11795. }
  11796. StringBuffer id;
  11797. id.append(lcName).append(".").append(seq);
  11798. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11799. newEntry->setProp("@name", lcName);
  11800. newEntry->setProp("@wuid", wuid);
  11801. newEntry->setProp("@dll", dll);
  11802. newEntry->setProp("@id", id);
  11803. newEntry->setPropInt("@seq", seq);
  11804. if (library)
  11805. newEntry->setPropBool("@isLibrary", true);
  11806. if (userid && *userid)
  11807. newEntry->setProp("@publishedBy", userid);
  11808. if (snapshot && *snapshot)
  11809. newEntry->setProp("@snapshot", snapshot);
  11810. return queryRegistry->addPropTree("Query", newEntry);
  11811. }
  11812. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11813. {
  11814. StringBuffer lcId(id);
  11815. lcId.toLowerCase();
  11816. clearAliases(queryRegistry, lcId);
  11817. StringBuffer xpath;
  11818. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11819. queryRegistry->removeProp(xpath);
  11820. }
  11821. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11822. {
  11823. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11824. if (!match)
  11825. return;
  11826. clearAliases(queryRegistry, match->queryProp("@id"));
  11827. queryRegistry->removeTree(match);
  11828. }
  11829. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11830. {
  11831. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11832. if (!match)
  11833. return;
  11834. clearAliases(queryRegistry, match->queryProp("@id"));
  11835. queryRegistry->removeTree(match);
  11836. }
  11837. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11838. {
  11839. clearAliases(queryRegistry, id);
  11840. }
  11841. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11842. {
  11843. StringBuffer lcName(name);
  11844. lcName.toLowerCase();
  11845. StringBuffer xpath;
  11846. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11847. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11848. if (!match)
  11849. {
  11850. match = queryRegistry->addPropTree("Alias");
  11851. match->setProp("@name", lcName);
  11852. }
  11853. match->setProp("@id", value);
  11854. }
  11855. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11856. {
  11857. if (!queryRegistry || !queryid)
  11858. return NULL;
  11859. StringBuffer xpath;
  11860. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11861. return queryRegistry->getPropTree(xpath);
  11862. }
  11863. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11864. {
  11865. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11866. return getQueryById(queryRegistry, queryid);
  11867. }
  11868. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11869. {
  11870. if (!queryRegistry || !alias)
  11871. return NULL;
  11872. StringBuffer xpath;
  11873. unsigned cnt = 0;
  11874. StringBuffer lc(alias);
  11875. const char * search = lc.toLowerCase().str();
  11876. for (;;)
  11877. {
  11878. xpath.set("Alias[@name='").append(search).append("']/@id");
  11879. const char * queryId = queryRegistry->queryProp(xpath);
  11880. if (!queryId)
  11881. break;
  11882. //Check for too many alias indirections.
  11883. if (cnt++ > 10)
  11884. return NULL;
  11885. search = lc.set(queryId).toLowerCase().str();
  11886. }
  11887. return getQueryById(queryRegistry, search);
  11888. }
  11889. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11890. {
  11891. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11892. return resolveQueryAlias(queryRegistry, alias);
  11893. }
  11894. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11895. {
  11896. StringBuffer lcId(id);
  11897. lcId.toLowerCase();
  11898. StringBuffer xpath;
  11899. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11900. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11901. if (tree)
  11902. {
  11903. if (tree->getPropBool("@suspended", false) == suspend)
  11904. return;
  11905. if (suspend)
  11906. {
  11907. tree->addPropBool("@suspended", true);
  11908. if (userid && *userid)
  11909. tree->addProp("@suspendedBy", userid);
  11910. }
  11911. else
  11912. {
  11913. tree->removeProp("@suspended");
  11914. tree->removeProp("@suspendedBy");
  11915. }
  11916. }
  11917. else
  11918. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11919. }
  11920. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11921. {
  11922. if (queryComment)
  11923. {
  11924. StringBuffer lcId(id);
  11925. lcId.toLowerCase();
  11926. StringBuffer xpath;
  11927. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11928. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11929. if (tree)
  11930. tree->setProp("@queryComment", queryComment);
  11931. else
  11932. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11933. }
  11934. }
  11935. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11936. {
  11937. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11938. if (conn)
  11939. return conn->getRoot();
  11940. else
  11941. return NULL;
  11942. }
  11943. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11944. {
  11945. if (!queryTree || !libraries)
  11946. return;
  11947. if (queryTree->hasProp("@libCount")) //already added
  11948. return;
  11949. unsigned libCount=0;
  11950. ForEach(*libraries)
  11951. {
  11952. IConstWULibrary &library = libraries->query();
  11953. SCMStringBuffer libname;
  11954. if (!library.getName(libname).length())
  11955. continue;
  11956. queryTree->addProp("Library", libname.str());
  11957. libCount++;
  11958. }
  11959. queryTree->setPropInt("@libCount", libCount);
  11960. }
  11961. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11962. {
  11963. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11964. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11965. }
  11966. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11967. {
  11968. //Only lock the branch for the target we're interested in.
  11969. StringBuffer xpath;
  11970. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11971. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11972. if (conn)
  11973. return conn->getRoot();
  11974. if (readonly)
  11975. return NULL;
  11976. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11977. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11978. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11979. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11980. if (conn)
  11981. return conn->getRoot();
  11982. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11983. if (!conn)
  11984. throwUnexpected();
  11985. IPropertyTree * root = conn->queryRoot();
  11986. root->setProp("@id",wsEclId);
  11987. conn->commit();
  11988. return LINK(root);
  11989. }
  11990. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11991. {
  11992. StringBuffer xpath;
  11993. StringBuffer lcName(name);
  11994. lcName.toLowerCase();
  11995. // see if "name" already exists
  11996. xpath.append("Package[@id='").append(name).append("']");
  11997. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11998. if (pkgTree)
  11999. {
  12000. if (overWrite)
  12001. packageRegistry->removeTree(pkgTree);
  12002. else
  12003. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  12004. }
  12005. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  12006. tree->setProp("@id", lcName);
  12007. return tree;
  12008. }
  12009. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  12010. {
  12011. StringBuffer lcId(id);
  12012. lcId.toLowerCase();
  12013. StringBuffer xpath;
  12014. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  12015. packageRegistry->removeProp(xpath);
  12016. }
  12017. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  12018. {
  12019. //Only lock the branch for the target we're interested in.
  12020. StringBuffer xpath;
  12021. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  12022. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12023. if (conn)
  12024. return conn->getRoot();
  12025. if (readonly)
  12026. return NULL;
  12027. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  12028. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  12029. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  12030. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  12031. if (conn)
  12032. return conn->getRoot();
  12033. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  12034. if (!conn)
  12035. throwUnexpected();
  12036. IPropertyTree* root = conn->queryRoot();
  12037. root->setProp("@id",wsEclId);
  12038. conn->commit();
  12039. return LINK(root);
  12040. }
  12041. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  12042. {
  12043. StringBuffer cleanQueryName;
  12044. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  12045. SCMStringBuffer dllName;
  12046. Owned<IConstWUQuery> q = workunit->getQuery();
  12047. q->getQueryDllName(dllName);
  12048. if (!dllName.length())
  12049. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  12050. StringBuffer currentTargetClusterType;
  12051. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  12052. SCMStringBuffer targetClusterType;
  12053. workunit->getDebugValue("targetclustertype", targetClusterType);
  12054. SCMStringBuffer snapshot;
  12055. workunit->getSnapshot(snapshot);
  12056. if (currentTargetClusterType.length() < 1)
  12057. {
  12058. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  12059. }
  12060. else
  12061. {
  12062. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  12063. {
  12064. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  12065. }
  12066. }
  12067. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  12068. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  12069. checkAddLibrariesToQueryEntry(newEntry, libraries);
  12070. newQueryId.append(newEntry->queryProp("@id"));
  12071. workunit->setIsQueryService(true); //will check querysets before delete
  12072. workunit->commit();
  12073. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  12074. }
  12075. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  12076. {
  12077. StringBuffer cleanQueryName;
  12078. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  12079. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  12080. {
  12081. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  12082. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  12083. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  12084. {
  12085. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  12086. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  12087. else
  12088. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  12089. }
  12090. }
  12091. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  12092. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  12093. }
  12094. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  12095. {
  12096. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  12097. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  12098. }
  12099. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  12100. {
  12101. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12102. StringBuffer xpath;
  12103. xpath.appendf("Alias[@name='%s']", alias);
  12104. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  12105. return queryRegistry->removeTree(t);
  12106. }
  12107. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  12108. {
  12109. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  12110. setQueryAlias(queryRegistry, alias, id);
  12111. }
  12112. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  12113. {
  12114. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12115. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  12116. }
  12117. void deleteQuerySetQuery(const char *querySetName, const char *id)
  12118. {
  12119. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12120. removeNamedQuery(queryRegistry, id);
  12121. }
  12122. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  12123. {
  12124. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12125. clearAliases(queryRegistry, id);
  12126. }
  12127. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  12128. {
  12129. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12130. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  12131. }
  12132. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  12133. {
  12134. if (!queryRegistry)
  12135. return NULL;
  12136. StringBuffer xpath;
  12137. xpath.appendf("Query[@wuid='%s']", wuid);
  12138. if (queryName && *queryName)
  12139. xpath.appendf("[@name='%s']", queryName);
  12140. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  12141. if (q)
  12142. {
  12143. id.set(q->queryProp("@id"));
  12144. }
  12145. return id.str();
  12146. }
  12147. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  12148. {
  12149. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12150. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  12151. }
  12152. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  12153. {
  12154. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  12155. ForEach(*wulibraries)
  12156. {
  12157. SCMStringBuffer libname;
  12158. IConstWULibrary &wulibrary = wulibraries->query();
  12159. wulibrary.getName(libname);
  12160. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  12161. continue;
  12162. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  12163. if (query && query->getPropBool("@isLibrary"))
  12164. {
  12165. const char *wuid = query->queryProp("@wuid");
  12166. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  12167. if (libcw)
  12168. {
  12169. names.appendUniq(libname.str());
  12170. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  12171. continue;
  12172. }
  12173. }
  12174. unresolved.appendUniq(libname.str());
  12175. }
  12176. }
  12177. bool looksLikeAWuid(const char * wuid, const char firstChar)
  12178. {
  12179. if (!wuid)
  12180. return false;
  12181. if (wuid[0] != firstChar)
  12182. return false;
  12183. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  12184. return false;
  12185. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  12186. return false;
  12187. return (wuid[9]=='-');
  12188. }
  12189. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  12190. {
  12191. IPropertyTree * module = archive;
  12192. const char * dot = strrchr(path, '.');
  12193. StringBuffer xpath;
  12194. if (dot)
  12195. {
  12196. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  12197. module = archive->queryPropTree(xpath);
  12198. path = dot+1;
  12199. }
  12200. else
  12201. module = archive->queryPropTree("Module[@key='']");
  12202. if (!module)
  12203. return NULL;
  12204. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  12205. return module->queryPropTree(xpath);
  12206. }
  12207. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  12208. {
  12209. StringBuffer hostname;
  12210. queryHostIP().getIpText(hostname);
  12211. StringBuffer fullPathname;
  12212. makeAbsolutePath(name, fullPathname);
  12213. query->addAssociatedFile(type, fullPathname, hostname, description, crc, minActivity, maxActivity);
  12214. }
  12215. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  12216. {
  12217. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12218. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  12219. if(workunit)
  12220. workunit->deschedule();
  12221. else
  12222. doDescheduleWorkkunit(wuid);
  12223. }
  12224. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  12225. {
  12226. StringBuffer scopestr;
  12227. if (wfid && scope && *scope)
  12228. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12229. else
  12230. scopestr.set(scope);
  12231. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  12232. }
  12233. class WuTimingUpdater : implements ITimeReportInfo
  12234. {
  12235. public:
  12236. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  12237. : wu(_wu), scopeType(_scopeType), kind(_kind)
  12238. { }
  12239. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  12240. {
  12241. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  12242. }
  12243. protected:
  12244. IWorkUnit * wu;
  12245. StatisticScopeType scopeType;
  12246. StatisticKind kind;
  12247. };
  12248. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  12249. {
  12250. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  12251. timer->report(target);
  12252. }
  12253. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  12254. {
  12255. WuTimingUpdater target(wu, scopeType, kind);
  12256. timer->report(target);
  12257. }
  12258. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  12259. {
  12260. StringBuffer scopestr;
  12261. if (wfid && scope && *scope)
  12262. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12263. else
  12264. scopestr.set(scope);
  12265. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  12266. }
  12267. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  12268. {
  12269. SimpleReferenceAggregator aggregator(search, result);
  12270. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  12271. ForEach(*it)
  12272. it->playProperties(aggregator);
  12273. }
  12274. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  12275. {
  12276. public:
  12277. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  12278. virtual void beginScope(const StatsScopeId & id)
  12279. {
  12280. prevLenStack.append(scope.length());
  12281. if (scope.length())
  12282. scope.append(":");
  12283. id.getScopeText(scope);
  12284. scopeTypeStack.append(id.queryScopeType());
  12285. }
  12286. virtual void beginSubGraphScope(unsigned id)
  12287. {
  12288. StatsScopeId scopeId(SSTsubgraph, id);
  12289. beginScope(scopeId);
  12290. }
  12291. virtual void beginActivityScope(unsigned id)
  12292. {
  12293. StatsScopeId scopeId(SSTactivity, id);
  12294. beginScope(scopeId);
  12295. }
  12296. virtual void beginEdgeScope(unsigned id, unsigned oid)
  12297. {
  12298. StatsScopeId scopeId(SSTedge, id, oid);
  12299. beginScope(scopeId);
  12300. }
  12301. virtual void beginChildGraphScope(unsigned id)
  12302. {
  12303. StatsScopeId scopeId(SSTchildgraph, id);
  12304. beginScope(scopeId);
  12305. }
  12306. virtual void endScope()
  12307. {
  12308. scope.setLength(prevLenStack.popGet());
  12309. scopeTypeStack.pop();
  12310. }
  12311. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  12312. {
  12313. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12314. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  12315. }
  12316. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  12317. {
  12318. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12319. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  12320. }
  12321. virtual IStatisticCollection * getResult()
  12322. {
  12323. return NULL;
  12324. }
  12325. protected:
  12326. Linked<IWorkUnit> wu;
  12327. StringBuffer scope;
  12328. UnsignedArray prevLenStack;
  12329. UnsignedArray scopeTypeStack;
  12330. };
  12331. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  12332. {
  12333. return new GlobalStatisticGatherer(wu);
  12334. }
  12335. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  12336. {
  12337. if (!wuid || !*wuid)
  12338. return NULL;
  12339. VStringBuffer path("/GraphProgress/%s", wuid);
  12340. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12341. if (conn)
  12342. return conn->getRoot();
  12343. else
  12344. return NULL;
  12345. }
  12346. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  12347. {
  12348. ErrorSeverity wuSeverity = SeverityInformation;
  12349. ErrorSeverity severity = error->getSeverity();
  12350. switch (severity)
  12351. {
  12352. case SeverityIgnore:
  12353. return;
  12354. case SeverityInformation:
  12355. break;
  12356. case SeverityWarning:
  12357. wuSeverity = SeverityWarning;
  12358. break;
  12359. case SeverityError:
  12360. case SeverityFatal:
  12361. wuSeverity = SeverityError;
  12362. break;
  12363. }
  12364. Owned<IWUException> exception = wu->createException();
  12365. exception->setSeverity(wuSeverity);
  12366. StringBuffer msg;
  12367. exception->setExceptionCode(error->errorCode());
  12368. exception->setExceptionMessage(error->errorMessage(msg).str());
  12369. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  12370. exception->setExceptionSource(source);
  12371. exception->setExceptionFileName(error->getFilename());
  12372. exception->setExceptionLineNo(error->getLine());
  12373. exception->setExceptionColumn(error->getColumn());
  12374. if (removeTimeStamp)
  12375. exception->setTimeStamp(nullptr);
  12376. if (error->getActivity())
  12377. exception->setActivityId(error->getActivity());
  12378. if (error->queryScope())
  12379. exception->setScope(error->queryScope());
  12380. }
  12381. IError * WorkUnitErrorReceiver::mapError(IError * error)
  12382. {
  12383. return LINK(error);
  12384. }
  12385. void WorkUnitErrorReceiver::report(IError* eclError)
  12386. {
  12387. addWorkunitException(wu, eclError, removeTimeStamp);
  12388. }
  12389. size32_t WorkUnitErrorReceiver::errCount()
  12390. {
  12391. unsigned count = 0;
  12392. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12393. ForEach(*exceptions)
  12394. if (exceptions->query().getSeverity() == SeverityError)
  12395. count++;
  12396. return count;
  12397. }
  12398. size32_t WorkUnitErrorReceiver::warnCount()
  12399. {
  12400. unsigned count = 0;
  12401. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12402. ForEach(*exceptions)
  12403. if (exceptions->query().getSeverity() == SeverityWarning)
  12404. count++;
  12405. return count;
  12406. }
  12407. bool isValidPriorityValue(const char *priority)
  12408. {
  12409. if (isEmptyString(priority))
  12410. return false;
  12411. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  12412. return true;
  12413. return false;
  12414. }
  12415. bool isValidMemoryValue(const char *memoryUnit)
  12416. {
  12417. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  12418. return false;
  12419. while (isdigit(*++memoryUnit));
  12420. if (!*memoryUnit)
  12421. return true;
  12422. switch (toupper(*memoryUnit++))
  12423. {
  12424. case 'E':
  12425. case 'P':
  12426. case 'T':
  12427. case 'G':
  12428. case 'M':
  12429. case 'K':
  12430. if (!*memoryUnit || strieq("B", memoryUnit))
  12431. return true;
  12432. break;
  12433. case 'B':
  12434. if (!*memoryUnit)
  12435. return true;
  12436. break;
  12437. }
  12438. return false;
  12439. }