workunit.cpp 444 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762
  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. if (wfid)
  162. {
  163. StatsScopeId rootScopeId(SSTworkflow,wfid);
  164. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  165. collector->beginScope(graphScopeId);
  166. }
  167. else
  168. {
  169. collector.setown(createStatisticsGatherer(_creatorType, _creator, graphScopeId));
  170. }
  171. }
  172. void CWuGraphStats::beforeDispose()
  173. {
  174. Owned<IStatisticCollection> stats = collector->getResult();
  175. MemoryBuffer compressed;
  176. {
  177. MemoryBuffer serialized;
  178. serializeStatisticCollection(serialized, stats);
  179. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  180. }
  181. unsigned minActivity = 0;
  182. unsigned maxActivity = 0;
  183. stats->getMinMaxActivity(minActivity, maxActivity);
  184. StringBuffer tag;
  185. tag.append("sg").append(id);
  186. //Replace the particular subgraph statistics added by this creator
  187. StringBuffer qualified(tag);
  188. qualified.append("[@creator='").append(creator).append("']");
  189. progress->removeProp(qualified);
  190. IPropertyTree * subgraph = progress->addPropTree(tag);
  191. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  192. subgraph->setProp("@creator", creator);
  193. subgraph->setPropInt("@minActivity", minActivity);
  194. subgraph->setPropInt("@maxActivity", maxActivity);
  195. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  196. if (!progress->getPropBool("@stats", false))
  197. progress->setPropBool("@stats", true);
  198. }
  199. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  200. {
  201. return *collector;
  202. }
  203. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  204. {
  205. public:
  206. IMPLEMENT_IINTERFACE;
  207. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  208. {
  209. if (!progress)
  210. progress.setown(createPTree());
  211. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  212. }
  213. virtual IPropertyTree * getProgressTree()
  214. {
  215. if (progress->getPropBool("@stats"))
  216. return createProcessTreeFromStats(); // Should we cache that?
  217. return LINK(progress);
  218. }
  219. virtual unsigned queryFormatVersion()
  220. {
  221. return formatVersion;
  222. }
  223. protected:
  224. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  225. {
  226. formatVersion = PROGRESS_FORMAT_V;
  227. }
  228. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  229. {
  230. StringBuffer formattedValue;
  231. unsigned numStats = collection.getNumStatistics();
  232. for (unsigned i=0; i < numStats; i++)
  233. {
  234. StatisticKind kind;
  235. unsigned __int64 value;
  236. collection.getStatistic(kind, value, i);
  237. formatStatistic(formattedValue.clear(), value, kind);
  238. target->setProp(queryTreeTag(kind), formattedValue);
  239. }
  240. }
  241. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  242. {
  243. expandStats(target, *collection);
  244. StringBuffer scopeName;
  245. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL, false);
  246. ForEach(*activityIter)
  247. {
  248. IStatisticCollection & cur = activityIter->query();
  249. cur.getScope(scopeName.clear());
  250. const char * id = scopeName.str();
  251. const char * tag;
  252. IPropertyTree * curTarget = target;
  253. switch (cur.queryScopeType())
  254. {
  255. case SSTedge:
  256. tag = "edge";
  257. id += strlen(EdgeScopePrefix);
  258. break;
  259. case SSTactivity:
  260. tag = "node";
  261. id += strlen(ActivityScopePrefix);
  262. break;
  263. case SSTsubgraph:
  264. //All subgraphs are added a root elements in the progress tree
  265. curTarget = rootTarget;
  266. tag = "node";
  267. id += strlen(SubGraphScopePrefix);
  268. break;
  269. case SSTchildgraph:
  270. case SSTworkflow:
  271. case SSTgraph:
  272. // SSTworkflow and SSTgraph may be safely ignored. They are not required to produce the statistics.
  273. continue;
  274. case SSTfunction:
  275. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  276. continue;
  277. default:
  278. throwUnexpected();
  279. }
  280. IPropertyTree * next = curTarget->addPropTree(tag);
  281. next->setProp("@id", id);
  282. expandProcessTreeFromStats(rootTarget, next, &cur);
  283. }
  284. }
  285. IPropertyTree * createProcessTreeFromStats()
  286. {
  287. MemoryBuffer compressed;
  288. MemoryBuffer serialized;
  289. Owned<IPropertyTree> progressTree = createPTree();
  290. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  291. ForEach(*iter)
  292. {
  293. IPropertyTree & curSubGraph = iter->query();
  294. curSubGraph.getPropBin("Stats", compressed.clear());
  295. //Protect against updates that delete the stats while we are iterating
  296. if (compressed.length())
  297. {
  298. decompressToBuffer(serialized.clear(), compressed);
  299. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  300. expandProcessTreeFromStats(progressTree, progressTree, collection);
  301. }
  302. }
  303. return progressTree.getClear();
  304. }
  305. protected:
  306. Linked<IPropertyTree> progress;
  307. StringAttr wuid, graphName;
  308. unsigned formatVersion;
  309. };
  310. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  311. {
  312. return new CConstGraphProgress(_wuid, _graphName, _progress);
  313. }
  314. //--------------------------------------------------------------------------------------------------------------------
  315. /*
  316. * Create a user friendly description a scope/stats combination. Only currently used for elapsed time for root subgraphs
  317. */
  318. static void createDefaultDescription(StringBuffer & description, StatisticKind kind, StatisticScopeType scopeType, const char * scope)
  319. {
  320. switch (kind)
  321. {
  322. case StTimeElapsed:
  323. {
  324. if (scopeType != SSTsubgraph)
  325. break;
  326. //Create a default description for a root subgraph
  327. const char * colon = strchr(scope, ':');
  328. if (!colon)
  329. break;
  330. const char * subgraph = colon+1;
  331. //Check for nested subgraph
  332. if (strchr(subgraph, ':'))
  333. break;
  334. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  335. StringAttr graphname;
  336. graphname.set(scope, colon - scope);
  337. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  338. formatGraphTimerLabel(description, graphname, 0, subId);
  339. return;
  340. }
  341. }
  342. describeScope(description, scope);
  343. }
  344. /* Represents a single statistic */
  345. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  346. {
  347. public:
  348. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  349. {
  350. if (!description && createDefault)
  351. {
  352. StringBuffer desc;
  353. createDefaultDescription(desc, kind, scopeType, scope);
  354. str.set(desc);
  355. return str;
  356. }
  357. str.set(description);
  358. return str;
  359. }
  360. virtual IStringVal & getCreator(IStringVal & str) const
  361. {
  362. str.set(creator);
  363. return str;
  364. }
  365. virtual const char * queryScope() const
  366. {
  367. return scope;
  368. }
  369. virtual IStringVal & getFormattedValue(IStringVal & str) const
  370. {
  371. StringBuffer formatted;
  372. formatStatistic(formatted, value, measure);
  373. str.set(formatted);
  374. return str;
  375. }
  376. virtual StatisticMeasure getMeasure() const
  377. {
  378. return measure;
  379. }
  380. virtual StatisticKind getKind() const
  381. {
  382. return kind;
  383. }
  384. virtual StatisticCreatorType getCreatorType() const
  385. {
  386. return creatorType;
  387. }
  388. virtual StatisticScopeType getScopeType() const
  389. {
  390. return scopeType;
  391. }
  392. virtual unsigned __int64 getValue() const
  393. {
  394. return value;
  395. }
  396. virtual unsigned __int64 getCount() const
  397. {
  398. return count;
  399. }
  400. virtual unsigned __int64 getMax() const
  401. {
  402. return max;
  403. }
  404. virtual unsigned __int64 getTimestamp() const
  405. {
  406. return timeStamp;
  407. }
  408. public:
  409. StringBuffer creator;
  410. StringBuffer description;
  411. StringBuffer scope;
  412. StatisticMeasure measure;
  413. StatisticKind kind;
  414. StatisticCreatorType creatorType;
  415. StatisticScopeType scopeType;
  416. unsigned __int64 value;
  417. unsigned __int64 count;
  418. unsigned __int64 max;
  419. unsigned __int64 timeStamp;
  420. };
  421. //---------------------------------------------------------------------------------------------------------------------
  422. /*
  423. * The following compare functions are used to ensure that comparison are consistent with
  424. * compareScopeName() in jstats. This ensures that the scope iterators from different sources
  425. * are processed in a consistent order
  426. */
  427. static int compareGraphNode(IInterface * const *ll, IInterface * const *rr)
  428. {
  429. IPropertyTree *l = (IPropertyTree *) *ll;
  430. IPropertyTree *r = (IPropertyTree *) *rr;
  431. const char * lname = l->queryName();
  432. const char * rname = r->queryName();
  433. return compareScopeName(lname, rname);
  434. }
  435. static int compareSubGraphStatsNode(IInterface * const *ll, IInterface * const *rr)
  436. {
  437. IPropertyTree *l = (IPropertyTree *) *ll;
  438. IPropertyTree *r = (IPropertyTree *) *rr;
  439. return compareScopeName(l->queryName(), r->queryName());
  440. }
  441. static int compareSubGraphNode(IInterface * const *ll, IInterface * const *rr)
  442. {
  443. IPropertyTree *l = (IPropertyTree *) *ll;
  444. IPropertyTree *r = (IPropertyTree *) *rr;
  445. return l->getPropInt("@id") - r->getPropInt("@id");
  446. }
  447. static int compareActivityNode(IInterface * const *ll, IInterface * const *rr)
  448. {
  449. IPropertyTree *l = (IPropertyTree *) *ll;
  450. IPropertyTree *r = (IPropertyTree *) *rr;
  451. return l->getPropInt("@id") - r->getPropInt("@id");
  452. }
  453. static int compareEdgeNode(IInterface * const *ll, IInterface * const *rr)
  454. {
  455. IPropertyTree *l = (IPropertyTree *) *ll;
  456. IPropertyTree *r = (IPropertyTree *) *rr;
  457. //MORE: Edge needs more work
  458. const char * leftId = l->queryProp("@id");
  459. const char * rightId = r->queryProp("@id");
  460. unsigned leftAc = atoi(leftId);
  461. unsigned rightAc = atoi(rightId);
  462. if (leftAc != rightAc)
  463. return (int)(leftAc - rightAc);
  464. const char * leftSep = strchr(leftId, '_');
  465. const char * rightSep = strchr(rightId, '_');
  466. assertex(leftSep && rightSep);
  467. return atoi(leftSep+1) - atoi(rightSep+1);
  468. }
  469. //---------------------------------------------------------------------------------------------------------------------
  470. /*
  471. * A class for implementing a scope iterator that walks through graph progress information
  472. */
  473. class CConstGraphProgressScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  474. {
  475. public:
  476. CConstGraphProgressScopeIterator(const char * wuid, const ScopeFilter & _filter, __uint64 _minVersion) : filter(_filter), minVersion(_minVersion)
  477. {
  478. //Examine the filter, and determine if we only need to look at a single graph/subgraph
  479. StringAttr singleGraph;
  480. const StringArray & scopesToMatch = filter.queryScopes();
  481. if (scopesToMatch)
  482. {
  483. bool seenGraph = false;
  484. bool seenSubGraph = false;
  485. ForEachItemIn(iScope, scopesToMatch)
  486. {
  487. StringArray ids;
  488. ids.appendList(scopesToMatch.item(iScope), ":");
  489. ForEachItemIn(i, ids)
  490. {
  491. const char * curId = ids.item(i);
  492. StatsScopeId id(curId);
  493. switch (id.queryScopeType())
  494. {
  495. case SSTgraph:
  496. if (seenGraph)
  497. {
  498. if (singleGraph && !streq(singleGraph, curId))
  499. singleGraph.clear();
  500. }
  501. else
  502. {
  503. if (!id.isWildcard())
  504. singleGraph.set(curId);
  505. seenGraph = true;
  506. }
  507. break;
  508. case SSTsubgraph:
  509. if (seenSubGraph)
  510. {
  511. if (singleSubGraph && !streq(singleSubGraph, curId))
  512. singleSubGraph.clear();
  513. }
  514. else
  515. {
  516. if (!id.isWildcard())
  517. singleSubGraph.set(curId);
  518. seenSubGraph = true;
  519. }
  520. break;
  521. }
  522. }
  523. }
  524. }
  525. rootPath.append("/GraphProgress/").append(wuid).append('/');
  526. if (singleGraph)
  527. rootPath.append(singleGraph).append("/");
  528. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  529. if (daliClientActive())
  530. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  531. if (conn && !singleGraph)
  532. {
  533. graphIter.setown(conn->queryRoot()->getElements("*"));
  534. graphIter.setown(createSortedIterator(*graphIter, compareGraphNode));
  535. }
  536. valid = false;
  537. }
  538. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IConstWUScopeIterator>)
  539. virtual bool first()
  540. {
  541. valid = false;
  542. if (!conn)
  543. return false;
  544. if (graphIter && !graphIter->first())
  545. return false;
  546. if (!firstSubGraph())
  547. {
  548. if (!nextGraph())
  549. return false;
  550. }
  551. valid = true;
  552. return true;
  553. }
  554. virtual bool next()
  555. {
  556. if (!nextChildScope())
  557. {
  558. if (!nextSubGraph())
  559. {
  560. if (!nextGraph())
  561. {
  562. valid = false;
  563. return false;
  564. }
  565. }
  566. }
  567. return true;
  568. }
  569. virtual bool nextSibling() override
  570. {
  571. if (collections.ordinality() == 0)
  572. return false;
  573. assertex(childIterators.ordinality() < collections.ordinality());
  574. collections.pop();
  575. //next will call childIterator.next() - walking the next sibling
  576. return next();
  577. }
  578. virtual bool nextParent() override
  579. {
  580. if (collections.ordinality() == 0)
  581. return false;
  582. assertex(childIterators.ordinality() < collections.ordinality());
  583. collections.pop();
  584. if (collections.ordinality() == 0)
  585. return false;
  586. //Finish with this node - so next will move onto the sibling of the parent node.
  587. finishCollection();
  588. return next();
  589. }
  590. virtual bool isValid()
  591. {
  592. return valid;
  593. }
  594. protected:
  595. bool firstSubGraph()
  596. {
  597. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  598. const char * xpath = "sg*";
  599. StringBuffer childXpath;
  600. if (singleSubGraph)
  601. {
  602. childXpath.append(singleSubGraph);
  603. xpath = childXpath.str();
  604. }
  605. subgraphIter.setown(graphNode.getElements(xpath));
  606. if (subgraphIter)
  607. {
  608. if (!singleSubGraph)
  609. subgraphIter.setown(createSortedIterator(*subgraphIter, compareSubGraphStatsNode));
  610. }
  611. else
  612. subgraphIter.setown(graphNode.getElements("sg0"));
  613. if (!subgraphIter->first())
  614. return false;
  615. if (firstStat())
  616. return true;
  617. return nextSubGraph();
  618. }
  619. bool nextSubGraph()
  620. {
  621. for (;;)
  622. {
  623. if (!subgraphIter->next())
  624. return false;
  625. if (firstStat())
  626. return true;
  627. }
  628. }
  629. bool nextGraph()
  630. {
  631. if (!graphIter)
  632. return false;
  633. for (;;)
  634. {
  635. if (!graphIter->next())
  636. return false;
  637. if (firstSubGraph())
  638. return true;
  639. }
  640. }
  641. bool firstStat()
  642. {
  643. IPropertyTree & curSubGraph = subgraphIter->query();
  644. if (!checkSubGraph())
  645. return false;
  646. curSubGraph.getPropBin("Stats", compressed.clear());
  647. //Don't crash on old format progress...
  648. if (compressed.length() == 0)
  649. return false;
  650. decompressToBuffer(serialized.clear(), compressed);
  651. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  652. statsIterator.timeStamp = collection->queryWhenCreated();
  653. if (!beginCollection(*collection))
  654. return false;
  655. // When workflow is root element, it is just a container. Ignore the workflow element here
  656. // as WorkUnitStatisticsScopeIterator will produce workflow scope - don't want duplicates.
  657. // (Note: workflow element never contains stats).
  658. if (collections.tos().queryScopeType() == SSTworkflow)
  659. {
  660. if (!next())
  661. return false;
  662. }
  663. //The root element of a collection is a graph - but it is only there to nest the subgraphs in.
  664. //Do not iterate it as a separate element - unless it has some stats.
  665. IStatisticCollection & curCollection = collections.tos();
  666. if ((curCollection.queryScopeType() != SSTgraph) || (curCollection.getNumStatistics() != 0))
  667. return true;
  668. return next();
  669. }
  670. bool beginCollection(IStatisticCollection & collection)
  671. {
  672. collections.append(OLINK(collection));
  673. curScopeType = collection.queryScopeType();
  674. collection.getFullScope(curScopeName.clear());
  675. ScopeCompare result = filter.compare(curScopeName);
  676. if (result & SCequal)
  677. return true;
  678. //If this scope cannot be the parent of a match then discard it.
  679. if (!(result & SCparent))
  680. collections.pop();
  681. //walk the next element
  682. return nextChildScope();
  683. }
  684. bool nextChildScope()
  685. {
  686. for (;;)
  687. {
  688. if (collections.ordinality() == 0)
  689. return false;
  690. IStatisticCollection * curCollection = &collections.tos();
  691. if (childIterators.ordinality() < collections.ordinality())
  692. {
  693. ScopeCompare result = filter.compare(curScopeName);
  694. //Do not walk children scopes if it is unrelated
  695. if (result & SCparent)
  696. {
  697. //Start iterating the children for the current collection
  698. childIterators.append(curCollection->getScopes(NULL, true));
  699. if (!childIterators.tos().first())
  700. {
  701. finishCollection();
  702. continue;
  703. }
  704. }
  705. else
  706. {
  707. //Don't walk the child scopes
  708. collections.pop();
  709. continue;
  710. }
  711. }
  712. else if (!childIterators.tos().next())
  713. {
  714. finishCollection();
  715. continue;
  716. }
  717. if (beginCollection(childIterators.tos().query()))
  718. return true;
  719. }
  720. }
  721. void finishCollection()
  722. {
  723. collections.pop();
  724. childIterators.pop();
  725. }
  726. bool checkSubGraph()
  727. {
  728. IPropertyTree & curSubGraph = subgraphIter->query();
  729. StatisticCreatorType creatorType = queryCreatorType(curSubGraph.queryProp("@c"), SCTnone);
  730. const char * creator = curSubGraph.queryProp("@creator");
  731. //MORE: Check minVersion and allow early filtering
  732. //MORE: Potentially filter by creator type??
  733. // if (!filter->matches(creatorType, creator, SSTall, NULL, SMeasureAll, StKindAll, AnyStatisticValue))
  734. // return false;
  735. statsIterator.creatorType = creatorType;
  736. statsIterator.creator.set(creator);
  737. return true;
  738. }
  739. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  740. {
  741. if ((whichProperties & PTstatistics))
  742. {
  743. /*
  744. MORE: Code from the statsIterator class should be inlined here - code will be much simpler
  745. but it currently needs an implementation of the IConstWUStatistic 3rd parameter
  746. IStatisticCollection & collection = collections.tos();
  747. ForEachItemIn(i, collection)
  748. {
  749. StatisticKind kind;
  750. unsigned __int64 value;
  751. collection->getStatistic(kind, value, i);
  752. visitor.noteStatistic(kind, value, *this);
  753. }
  754. */
  755. statsIterator.reset(curScopeName, curScopeType, collections.tos());
  756. ForEach(statsIterator)
  757. statsIterator.play(visitor);
  758. }
  759. }
  760. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  761. {
  762. return collections.tos().getStatistic(kind, value);
  763. }
  764. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  765. {
  766. return nullptr;
  767. }
  768. virtual const char * queryHint(const char * kind) const override
  769. {
  770. return nullptr;
  771. }
  772. virtual const char * queryScope() const override
  773. {
  774. return curScopeName;
  775. }
  776. virtual StatisticScopeType getScopeType() const override
  777. {
  778. return curScopeType;
  779. }
  780. private:
  781. class ScopeStatisticsIterator : public CInterfaceOf<IConstWUStatistic>
  782. {
  783. friend class CConstGraphProgressScopeIterator; // cleaner if this was removed + setScope() functions added.
  784. public:
  785. void reset(const char * _scopeName, StatisticScopeType _scopeType, IStatisticCollection & _collection)
  786. {
  787. scope.set(_scopeName);
  788. scopeType = _scopeType;
  789. collection = &_collection;
  790. numStats = collection->getNumStatistics();
  791. }
  792. // interface IConstWUStatisticIterator
  793. IConstWUStatistic & query()
  794. {
  795. return *this;
  796. }
  797. bool first()
  798. {
  799. curStatIndex = 0;
  800. if (curStatIndex >= numStats)
  801. return false;
  802. collection->getStatistic(kind, value, curStatIndex);
  803. //MORE: Allow filtering:
  804. /*
  805. * if (filter && !filter->matches(SCTall, NULL, SSTall, NULL, queryMeasure(kind), kind, value))
  806. continue;
  807. */
  808. return true;
  809. }
  810. bool next()
  811. {
  812. for (;;)
  813. {
  814. ++curStatIndex;
  815. if (curStatIndex >= numStats)
  816. return false;
  817. collection->getStatistic(kind, value, curStatIndex);
  818. //MORE: Allow stats filtering
  819. return true;
  820. }
  821. }
  822. bool isValid()
  823. {
  824. return curStatIndex < numStats;
  825. }
  826. //interface IConstWUStatistic
  827. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const override
  828. {
  829. if (createDefault)
  830. {
  831. StringBuffer description;
  832. createDefaultDescription(description, kind, scopeType, scope);
  833. str.set(description);
  834. }
  835. return str;
  836. }
  837. virtual IStringVal & getCreator(IStringVal & str) const override
  838. {
  839. str.set(creator);
  840. return str;
  841. }
  842. virtual const char * queryScope() const override
  843. {
  844. return scope;
  845. }
  846. virtual IStringVal & getFormattedValue(IStringVal & str) const override
  847. {
  848. StringBuffer formatted;
  849. formatStatistic(formatted, value, kind);
  850. str.set(formatted);
  851. return str;
  852. }
  853. virtual StatisticMeasure getMeasure() const override
  854. {
  855. return queryMeasure(kind);
  856. }
  857. virtual StatisticKind getKind() const override
  858. {
  859. return kind;
  860. }
  861. virtual StatisticCreatorType getCreatorType() const override
  862. {
  863. return creatorType;
  864. }
  865. virtual StatisticScopeType getScopeType() const override
  866. {
  867. return scopeType;
  868. }
  869. virtual unsigned __int64 getValue() const override
  870. {
  871. return value;
  872. }
  873. virtual unsigned __int64 getCount() const override
  874. {
  875. return 1;
  876. }
  877. virtual unsigned __int64 getMax() const override
  878. {
  879. return 0;
  880. }
  881. virtual unsigned __int64 getTimestamp() const override
  882. {
  883. return timeStamp;
  884. }
  885. void play(IWuScopeVisitor & visitor)
  886. {
  887. visitor.noteStatistic(kind, value, *this);
  888. }
  889. protected:
  890. IStatisticCollection * collection = nullptr;
  891. StringBuffer creator;
  892. StringBuffer scope;
  893. StatisticKind kind;
  894. StatisticCreatorType creatorType;
  895. StatisticScopeType scopeType;
  896. unsigned __int64 value = 0;
  897. unsigned __int64 timeStamp;
  898. unsigned curStatIndex = 0;
  899. unsigned numStats = 0;
  900. } statsIterator;
  901. Owned<IRemoteConnection> conn;
  902. StringBuffer curScopeName;
  903. StatisticScopeType curScopeType = SSTnone;
  904. __uint64 minVersion;
  905. const ScopeFilter & filter;
  906. StringBuffer rootPath;
  907. StringAttr singleSubGraph;
  908. Owned<IPropertyTreeIterator> graphIter;
  909. Owned<IPropertyTreeIterator> subgraphIter;
  910. IArrayOf<IStatisticCollection> collections;
  911. IArrayOf<IStatisticCollectionIterator> childIterators; // Iterator(n) through collections(n) - created once iterating children
  912. MemoryBuffer compressed;
  913. MemoryBuffer serialized;
  914. bool valid;
  915. };
  916. int compareNoteScopeOrder(IConstWUException & left, IConstWUException & right)
  917. {
  918. return compareScopeName(left.queryScope(), right.queryScope());
  919. }
  920. int compareNoteScopeOrder(IInterface * const * left, IInterface * const * right)
  921. {
  922. return compareNoteScopeOrder(*static_cast<IConstWUException *>(*left), *static_cast<IConstWUException *>(*right));
  923. }
  924. class NotesIterator : public CInterfaceOf<IConstWUScopeIterator>
  925. {
  926. public:
  927. NotesIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter)
  928. {
  929. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  930. ForEach(*exceptions)
  931. {
  932. IConstWUException & exception = exceptions->query();
  933. if (exception.queryScope()!=nullptr)
  934. notes.append(OLINK(exception));
  935. }
  936. notes.sort(compareNoteScopeOrder);
  937. }
  938. virtual bool first() override
  939. {
  940. baseIndex = 0;
  941. return updateCurrent();
  942. }
  943. virtual bool next() override
  944. {
  945. baseIndex += numCurrentScope;
  946. return updateCurrent();
  947. }
  948. virtual bool isValid() override
  949. {
  950. return notes.isItem(baseIndex);
  951. }
  952. virtual bool nextSibling() override
  953. {
  954. //Search until the current scope is not a child of the previous scope
  955. StringBuffer savedScope(queryScope());
  956. for (;;)
  957. {
  958. if (!next())
  959. return false;
  960. if (compareScopes(queryScope(), savedScope) != SCchild)
  961. return true;
  962. }
  963. }
  964. virtual bool nextParent() override
  965. {
  966. //Search until the current scope is not a child of the previous parent scope
  967. StringBuffer parentScope;
  968. if (getParentScope(parentScope, queryScope()))
  969. {
  970. for (;;)
  971. {
  972. if (!next())
  973. return false;
  974. if (compareScopes(queryScope(), parentScope) != SCchild)
  975. return true;
  976. }
  977. }
  978. else
  979. {
  980. finish();
  981. return false;
  982. }
  983. }
  984. virtual const char * queryScope() const override
  985. {
  986. return notes.item(baseIndex).queryScope();
  987. }
  988. virtual StatisticScopeType getScopeType() const override
  989. {
  990. const char * tail = queryScopeTail(queryScope());
  991. StatsScopeId id(tail);
  992. return id.queryScopeType();
  993. }
  994. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) override
  995. {
  996. if (whichProperties & PTnotes)
  997. {
  998. for (unsigned i=0; i < numCurrentScope; i++)
  999. {
  1000. IConstWUException & cur = notes.item(baseIndex + i);
  1001. visitor.noteException(cur);
  1002. }
  1003. }
  1004. }
  1005. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1006. {
  1007. return false;
  1008. }
  1009. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1010. {
  1011. return nullptr;
  1012. }
  1013. virtual const char * queryHint(const char * kind) const override
  1014. {
  1015. return nullptr;
  1016. }
  1017. private:
  1018. bool updateCurrent()
  1019. {
  1020. if (!notes.isItem(baseIndex))
  1021. return false;
  1022. // set numCurrentScope to number of notes in the current scope
  1023. unsigned next = baseIndex+1;
  1024. while (next < notes.ordinality())
  1025. {
  1026. if (compareNoteScopeOrder(notes.item(baseIndex), notes.item(next)) != 0)
  1027. break;
  1028. next++;
  1029. }
  1030. numCurrentScope = (next - baseIndex);
  1031. return true;
  1032. }
  1033. void finish()
  1034. {
  1035. baseIndex = notes.ordinality();
  1036. }
  1037. unsigned baseIndex = 0;
  1038. unsigned numCurrentScope = 0;
  1039. IArrayOf<IConstWUException> notes;
  1040. };
  1041. int compareStatisticScopes(IConstWUStatistic & left, IConstWUStatistic & right)
  1042. {
  1043. return compareScopeName(left.queryScope(), right.queryScope());
  1044. }
  1045. int compareStatisticScopes(IInterface * const * left, IInterface * const * right)
  1046. {
  1047. return compareStatisticScopes(*static_cast<IConstWUStatistic *>(*left), *static_cast<IConstWUStatistic *>(*right));
  1048. }
  1049. /*
  1050. * An implementation of IConstWUScopeIterator for global workunit statistics.
  1051. */
  1052. class WorkUnitStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1053. {
  1054. public:
  1055. WorkUnitStatisticsScopeIterator(const IArrayOf<IConstWUStatistic> & _statistics, const ScopeFilter & _filter)
  1056. {
  1057. ForEachItemIn(i, _statistics)
  1058. {
  1059. IConstWUStatistic & cur = _statistics.item(i);
  1060. if (_filter.compare(cur.queryScope()) & SCequal)
  1061. statistics.append(OLINK(cur));
  1062. }
  1063. statistics.sort(compareStatisticScopes);
  1064. }
  1065. virtual bool first() override
  1066. {
  1067. curIndex = 0;
  1068. return initScope();
  1069. }
  1070. virtual bool next() override
  1071. {
  1072. curIndex += numStatistics;
  1073. return initScope();
  1074. }
  1075. virtual bool nextSibling() override
  1076. {
  1077. //Search until the current scope is not a child of the previous scope
  1078. StringBuffer savedScope(queryScope());
  1079. for (;;)
  1080. {
  1081. if (!next())
  1082. return false;
  1083. if (compareScopes(queryScope(), savedScope) != SCchild)
  1084. return true;
  1085. }
  1086. }
  1087. virtual bool nextParent() override
  1088. {
  1089. //Search until the current scope is not a child of the previous parent scope
  1090. StringBuffer parentScope;
  1091. if (getParentScope(parentScope, queryScope()))
  1092. {
  1093. for (;;)
  1094. {
  1095. if (!next())
  1096. return false;
  1097. if (compareScopes(queryScope(), parentScope) != SCchild)
  1098. return true;
  1099. }
  1100. }
  1101. else
  1102. {
  1103. finish();
  1104. return false;
  1105. }
  1106. }
  1107. virtual bool isValid() override
  1108. {
  1109. return statistics.isItem(curIndex);
  1110. }
  1111. virtual const char * queryScope() const override
  1112. {
  1113. return statistics.item(curIndex).queryScope();
  1114. }
  1115. virtual StatisticScopeType getScopeType() const override
  1116. {
  1117. return statistics.item(curIndex).getScopeType();
  1118. }
  1119. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1120. {
  1121. if (whichProperties & PTstatistics)
  1122. {
  1123. for (unsigned i=0; i < numStatistics; i++)
  1124. {
  1125. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1126. visitor.noteStatistic(cur.getKind(), cur.getValue(), cur);
  1127. }
  1128. }
  1129. }
  1130. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1131. {
  1132. for (unsigned i=0; i < numStatistics; i++)
  1133. {
  1134. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1135. if (cur.getKind() == kind)
  1136. {
  1137. value = cur.getValue();
  1138. return true;
  1139. }
  1140. }
  1141. return false;
  1142. }
  1143. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1144. {
  1145. return nullptr;
  1146. }
  1147. virtual const char * queryHint(const char * kind) const
  1148. {
  1149. return nullptr;
  1150. }
  1151. protected:
  1152. inline IConstWUStatistic & queryStatistic(unsigned i)
  1153. {
  1154. return statistics.item(curIndex + i);
  1155. }
  1156. bool initScope()
  1157. {
  1158. if (!statistics.isItem(curIndex))
  1159. return false;
  1160. unsigned next = curIndex+1;
  1161. while (next < statistics.ordinality())
  1162. {
  1163. if (compareStatisticScopes(statistics.item(curIndex), statistics.item(next)) != 0)
  1164. break;
  1165. next++;
  1166. }
  1167. numStatistics = (next - curIndex);
  1168. return true;
  1169. }
  1170. void finish()
  1171. {
  1172. curIndex = statistics.ordinality();
  1173. }
  1174. protected:
  1175. IArrayOf<IConstWUStatistic> statistics;
  1176. unsigned curIndex = 0;
  1177. unsigned numStatistics = 1;
  1178. };
  1179. /*
  1180. * An implementation of IConstWUScopeIterator for the query graphs.
  1181. */
  1182. class GraphScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1183. {
  1184. private:
  1185. //This uses a state machine - this enumeration contains the different states.
  1186. enum State
  1187. {
  1188. //Following are the states which represent valid scopes
  1189. SGraph,
  1190. SChildGraph,
  1191. SSubGraph,
  1192. SEdge,
  1193. SActivity,
  1194. //The following are internal states.
  1195. SGraphFirstEdge,
  1196. SGraphFirstSubGraph,
  1197. SGraphFirst,
  1198. SGraphEnd,
  1199. SGraphNext,
  1200. SSubGraphFirstEdge,
  1201. SSubGraphFirstActivity,
  1202. SSubGraphEnd,
  1203. SSubGraphNext,
  1204. SEdgeNext,
  1205. SEdgeEnd,
  1206. SActivityNext,
  1207. SActivityEnd,
  1208. SChildGraphFirstEdge,
  1209. SChildGraphFirstSubGraph,
  1210. SChildGraphFirst,
  1211. SChildGraphNext,
  1212. SChildGraphEnd,
  1213. SDone
  1214. };
  1215. State state = SDone;
  1216. State nextState = SDone;
  1217. public:
  1218. GraphScopeIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter) : graphIter(&wu->getGraphs(GraphTypeAny)), filter(_filter)
  1219. {
  1220. }
  1221. virtual bool first() override
  1222. {
  1223. state = SGraphFirst;
  1224. return nextScope();
  1225. }
  1226. virtual bool next() override
  1227. {
  1228. if (!selectNext())
  1229. return false;
  1230. return nextScope();
  1231. }
  1232. virtual bool nextSibling() override
  1233. {
  1234. if (!selectNextSibling())
  1235. return false;
  1236. return nextScope();
  1237. }
  1238. virtual bool nextParent() override
  1239. {
  1240. if (!selectNextParent())
  1241. return false;
  1242. return nextScope();
  1243. }
  1244. virtual bool isValid() override
  1245. {
  1246. return graphIter->isValid();
  1247. }
  1248. virtual const char * queryScope() const override
  1249. {
  1250. return curScopeName.str();
  1251. }
  1252. virtual StatisticScopeType getScopeType() const override
  1253. {
  1254. return scopeType;
  1255. }
  1256. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1257. {
  1258. switch (scopeType)
  1259. {
  1260. case SSTgraph:
  1261. return;
  1262. }
  1263. IPropertyTree & cur = treeIters.tos().query();
  1264. switch (scopeType)
  1265. {
  1266. case SSTgraph:
  1267. break;
  1268. case SSTsubgraph:
  1269. break;
  1270. case SSTactivity:
  1271. {
  1272. if (whichProperties & PTattributes)
  1273. {
  1274. playAttribute(visitor, WaLabel);
  1275. Owned<IPropertyTreeIterator> attrs = cur.getElements("att");
  1276. ForEach(*attrs)
  1277. {
  1278. IPropertyTree & cur = attrs->query();
  1279. WuAttr attr = queryGraphChildAttToWuAttr(cur.queryProp("@name"));
  1280. if (attr != WaNone)
  1281. visitor.noteAttribute(attr, cur.queryProp("@value"));
  1282. }
  1283. }
  1284. if (whichProperties & PThints)
  1285. {
  1286. Owned<IPropertyTreeIterator> hints = cur.getElements("hint");
  1287. ForEach(*hints)
  1288. {
  1289. IPropertyTree & cur = hints->query();
  1290. visitor.noteHint(cur.queryProp("@name"), cur.queryProp("@value"));
  1291. }
  1292. }
  1293. break;
  1294. }
  1295. case SSTedge:
  1296. if (whichProperties & PTattributes)
  1297. {
  1298. //MORE This will eventually need to walk the attributes and map the names.
  1299. //Need to be careful if they need to be mapped differently depending on the context.
  1300. playAttribute(visitor, WaLabel);
  1301. playAttribute(visitor, WaIdSource);
  1302. playAttribute(visitor, WaIdTarget);
  1303. playAttribute(visitor, WaSourceIndex);
  1304. playAttribute(visitor, WaTargetIndex);
  1305. playAttribute(visitor, WaIsDependency);
  1306. }
  1307. break;
  1308. }
  1309. }
  1310. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1311. {
  1312. return false;
  1313. }
  1314. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1315. {
  1316. if (!treeIters.ordinality())
  1317. return nullptr;
  1318. //MORE - check that the attribute is value for the current scope type (to prevent defaults being returned)
  1319. return queryAttributeValue(treeIters.tos().query(), attr, scratchpad);
  1320. }
  1321. virtual const char * queryHint(const char * kind) const override
  1322. {
  1323. //MORE: Needs to be implemented!
  1324. return nullptr;
  1325. }
  1326. private:
  1327. void playAttribute(IWuScopeVisitor & visitor, WuAttr kind)
  1328. {
  1329. StringBuffer scratchpad;
  1330. const char * value = queryAttributeValue(treeIters.tos().query(), kind, scratchpad);
  1331. if (value)
  1332. visitor.noteAttribute(kind, value);
  1333. }
  1334. void pushIterator(IPropertyTreeIterator * iter, State state)
  1335. {
  1336. treeIters.append(*LINK(iter));
  1337. stateStack.append(state);
  1338. }
  1339. State popIterator()
  1340. {
  1341. treeIters.pop();
  1342. return (State)stateStack.popGet();
  1343. }
  1344. void pushScope(const char * id)
  1345. {
  1346. scopeLengths.append(curScopeName.length());
  1347. curScopeName.append(":").append(id);
  1348. }
  1349. void popScope()
  1350. {
  1351. curScopeName.setLength(scopeLengths.popGet());
  1352. }
  1353. bool doNextScope()
  1354. {
  1355. for(;;)
  1356. {
  1357. switch (state)
  1358. {
  1359. case SGraph:
  1360. {
  1361. IConstWUGraph & graph = graphIter->query();
  1362. unsigned wfid = graph.getWfid();
  1363. curScopeName.clear();
  1364. if (wfid != 0)
  1365. curScopeName.append(WorkflowScopePrefix).append(wfid).append(':');
  1366. graph.getName(StringBufferAdaptor(curScopeName));
  1367. scopeType = SSTgraph;
  1368. return true;
  1369. }
  1370. case SSubGraph:
  1371. scopeId.set(SubGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1372. pushScope(scopeId);
  1373. scopeType = SSTsubgraph;
  1374. return true;
  1375. case SEdge:
  1376. scopeId.set(EdgeScopePrefix).append(treeIters.tos().query().queryProp("@id"));
  1377. pushScope(scopeId);
  1378. scopeType = SSTedge;
  1379. return true;
  1380. case SActivity:
  1381. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph)
  1382. {
  1383. state = SActivityNext;
  1384. break;
  1385. }
  1386. scopeId.set(ActivityScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1387. pushScope(scopeId);
  1388. scopeType = SSTactivity;
  1389. return true;
  1390. case SChildGraph:
  1391. {
  1392. unsigned numIters = treeIters.ordinality();
  1393. //This should really be implemented by a filter on the node - but it would require _kind/_parentActivity to move to the node tag
  1394. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1395. {
  1396. state = SChildGraphNext;
  1397. break;
  1398. }
  1399. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1400. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1401. if (parentId != parentActivityId)
  1402. {
  1403. state = SChildGraphNext;
  1404. break;
  1405. }
  1406. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1407. pushScope(scopeId);
  1408. scopeType = SSTchildgraph;
  1409. return true;
  1410. }
  1411. //Graph iteration
  1412. case SGraphFirst:
  1413. if (!graphIter->first())
  1414. state = SDone;
  1415. else
  1416. state = SGraph;
  1417. break;
  1418. case SGraphEnd:
  1419. state = SGraphNext;
  1420. break;
  1421. case SGraphNext:
  1422. if (!graphIter->next())
  1423. state = SDone;
  1424. else
  1425. state = SGraph;
  1426. break;
  1427. //Edge iteration
  1428. case SGraphFirstEdge:
  1429. {
  1430. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1431. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1432. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1433. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1434. if (treeIter && treeIter->first())
  1435. {
  1436. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1437. treeIter->first();
  1438. pushIterator(treeIter, SGraphFirstSubGraph);
  1439. state = SEdge;
  1440. }
  1441. else
  1442. state = SGraphFirstSubGraph;
  1443. break;
  1444. }
  1445. case SChildGraphFirstEdge:
  1446. {
  1447. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1448. if (treeIter && treeIter->first())
  1449. {
  1450. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1451. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1452. state = SEdge;
  1453. }
  1454. else
  1455. state = SChildGraphFirstSubGraph;
  1456. break;
  1457. }
  1458. case SEdgeEnd:
  1459. popScope();
  1460. state = SEdgeNext;
  1461. break;
  1462. case SEdgeNext:
  1463. if (treeIters.tos().next())
  1464. state = SEdge;
  1465. else
  1466. state = popIterator();
  1467. break;
  1468. //Subgraph iteration
  1469. case SGraphFirstSubGraph:
  1470. {
  1471. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1472. if (treeIter && treeIter->first())
  1473. {
  1474. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1475. treeIter->first();
  1476. pushIterator(treeIter, SGraphNext);
  1477. state = SSubGraph;
  1478. }
  1479. else
  1480. state = SGraphNext;
  1481. break;
  1482. }
  1483. case SChildGraphFirstSubGraph:
  1484. {
  1485. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1486. if (treeIter && treeIter->first())
  1487. {
  1488. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1489. pushIterator(treeIter, SChildGraphEnd);
  1490. state = SSubGraph;
  1491. }
  1492. else
  1493. state = SChildGraphEnd;
  1494. break;
  1495. }
  1496. case SSubGraphFirstEdge:
  1497. {
  1498. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1499. if (treeIter && treeIter->first())
  1500. {
  1501. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1502. pushIterator(treeIter, SSubGraphFirstActivity);
  1503. state = SEdge;
  1504. }
  1505. else
  1506. state = SSubGraphFirstActivity;
  1507. break;
  1508. }
  1509. case SSubGraphFirstActivity:
  1510. {
  1511. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1512. if (treeIter && treeIter->first())
  1513. {
  1514. treeIter.setown(createSortedIterator(*treeIter, compareActivityNode));
  1515. pushIterator(treeIter, SSubGraphEnd);
  1516. state = SActivity;
  1517. }
  1518. else
  1519. state = SSubGraphEnd;
  1520. break;
  1521. }
  1522. case SSubGraphEnd:
  1523. popScope();
  1524. state = SSubGraphNext;
  1525. break;
  1526. case SChildGraphEnd:
  1527. popScope();
  1528. state = SChildGraphNext;
  1529. break;
  1530. case SSubGraphNext:
  1531. if (treeIters.tos().next())
  1532. state = SSubGraph;
  1533. else
  1534. state = popIterator();
  1535. break;
  1536. case SActivityEnd:
  1537. popScope();
  1538. state = SActivityNext;
  1539. break;
  1540. case SActivityNext:
  1541. if (treeIters.tos().next())
  1542. state = SActivity;
  1543. else
  1544. state = popIterator();
  1545. break;
  1546. case SChildGraphNext:
  1547. if (treeIters.tos().next())
  1548. state = SChildGraph;
  1549. else
  1550. state = popIterator();
  1551. break;
  1552. case SChildGraphFirst:
  1553. {
  1554. unsigned numIters = treeIters.ordinality();
  1555. IPropertyTreeIterator & graphIter = treeIters.item(numIters-2);
  1556. Owned<IPropertyTreeIterator> treeIter = graphIter.query().getElements("att/graph/node");
  1557. //Really want to filter by <att name="_parentActivity" value="<parentid>">
  1558. if (treeIter && treeIter->first())
  1559. {
  1560. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1561. pushIterator(treeIter, SActivityEnd);
  1562. state = SChildGraph;
  1563. }
  1564. else
  1565. state = SActivityEnd;
  1566. break;
  1567. }
  1568. case SDone:
  1569. return false;
  1570. default:
  1571. throwUnexpected();
  1572. }
  1573. }
  1574. }
  1575. bool nextScope()
  1576. {
  1577. for(;;)
  1578. {
  1579. if (!doNextScope())
  1580. return false;
  1581. ScopeCompare cmp = filter.compare(curScopeName);
  1582. if (cmp & SCequal)
  1583. return true;
  1584. //MORE: Optimize next based on result of compare
  1585. if (!selectNext())
  1586. return false;
  1587. }
  1588. }
  1589. bool selectNext()
  1590. {
  1591. switch (state)
  1592. {
  1593. case SGraph:
  1594. state = SGraphFirstEdge;
  1595. break;
  1596. case SChildGraph:
  1597. state = SChildGraphFirstEdge;
  1598. break;
  1599. case SSubGraph:
  1600. state = SSubGraphFirstEdge;
  1601. break;
  1602. case SEdge:
  1603. state = SEdgeEnd;
  1604. break;
  1605. case SActivity:
  1606. state = SChildGraphFirst;
  1607. break;
  1608. case SDone:
  1609. return false;
  1610. default:
  1611. throwUnexpected();
  1612. }
  1613. return true;
  1614. }
  1615. bool selectNextSibling()
  1616. {
  1617. switch (state)
  1618. {
  1619. case SGraph:
  1620. state = SGraphEnd;
  1621. break;
  1622. case SChildGraph:
  1623. state = SChildGraphEnd;
  1624. break;
  1625. case SSubGraph:
  1626. state = SSubGraphEnd;
  1627. break;
  1628. case SEdge:
  1629. state = SEdgeEnd;
  1630. break;
  1631. case SActivity:
  1632. state = SActivityEnd;
  1633. break;
  1634. case SDone:
  1635. return false;
  1636. default:
  1637. throwUnexpected();
  1638. }
  1639. return true;
  1640. }
  1641. bool selectNextParent()
  1642. {
  1643. switch (state)
  1644. {
  1645. case SGraph:
  1646. state = SDone;
  1647. break;
  1648. case SChildGraph:
  1649. case SSubGraph:
  1650. case SEdge:
  1651. case SActivity:
  1652. popScope();
  1653. state = popIterator();
  1654. break;
  1655. case SDone:
  1656. return false;
  1657. default:
  1658. throwUnexpected();
  1659. }
  1660. return true;
  1661. }
  1662. protected:
  1663. const ScopeFilter & filter;
  1664. Owned<IConstWUGraphIterator> graphIter;
  1665. Owned<IPropertyTree> curGraph;
  1666. IArrayOf<IPropertyTreeIterator> treeIters;
  1667. UnsignedArray scopeLengths;
  1668. UnsignedArray stateStack;
  1669. StringBuffer curScopeName;
  1670. StringBuffer scopeId;
  1671. StatisticScopeType scopeType = SSTnone;
  1672. };
  1673. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1674. {
  1675. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1676. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1677. return left->queryWfid() - right->queryWfid();
  1678. }
  1679. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1680. /*
  1681. * An implementation of IConstWUScopeIterator for the workflow information.
  1682. */
  1683. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1684. {
  1685. public:
  1686. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1687. {
  1688. ForEach(*wfIter)
  1689. workflow.append(*LINK(wfIter->query()));
  1690. workflow.sort(compareWorkflow);
  1691. }
  1692. virtual bool first() override
  1693. {
  1694. if (workflow.empty())
  1695. return false;
  1696. curWorkflow = 0;
  1697. return initWorkflowItem();
  1698. }
  1699. virtual bool next() override
  1700. {
  1701. if (!workflow.isItem(++curWorkflow))
  1702. return false;
  1703. return initWorkflowItem();
  1704. }
  1705. virtual bool nextSibling() override
  1706. {
  1707. return next();
  1708. }
  1709. virtual bool nextParent() override
  1710. {
  1711. curWorkflow = NotFound;
  1712. return false;
  1713. }
  1714. virtual bool isValid() override
  1715. {
  1716. return workflow.isItem(curWorkflow);
  1717. }
  1718. virtual const char * queryScope() const override
  1719. {
  1720. return curScope.str();
  1721. }
  1722. virtual StatisticScopeType getScopeType() const override
  1723. {
  1724. return SSTworkflow;
  1725. }
  1726. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1727. {
  1728. if (whichProperties & PTattributes)
  1729. {
  1730. {
  1731. StringBuffer scratchpad;
  1732. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1733. ForEach(*depends)
  1734. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1735. }
  1736. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1737. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1738. }
  1739. }
  1740. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1741. {
  1742. return false;
  1743. }
  1744. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1745. {
  1746. auto wf = &workflow.item(curWorkflow);
  1747. StringBufferAdaptor adaptor(scratchpad);
  1748. switch (attr)
  1749. {
  1750. case WaIdDependencyList:
  1751. {
  1752. bool first = true;
  1753. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1754. ForEach(*depends)
  1755. {
  1756. if (first)
  1757. scratchpad.append("[");
  1758. else
  1759. scratchpad.append(",");
  1760. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1761. first = false;
  1762. }
  1763. if (first)
  1764. return nullptr;
  1765. scratchpad.append("]");
  1766. return scratchpad.str();
  1767. }
  1768. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1769. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1770. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1771. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1772. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1773. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1774. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1775. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1776. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1777. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1778. case WaState: return queryWorkflowStateText(wf->queryState());
  1779. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1780. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1781. /*
  1782. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1783. virtual bool isScheduledNow() const = 0;
  1784. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1785. virtual unsigned querySchedulePriority() const = 0;
  1786. virtual bool hasScheduleCount() const = 0;
  1787. virtual unsigned queryScheduleCount() const = 0;
  1788. virtual unsigned queryRetriesAllowed() const = 0;
  1789. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1790. virtual bool queryPersistRefresh() const = 0;
  1791. virtual unsigned queryScheduleCountRemaining() const = 0;
  1792. virtual unsigned queryRetriesRemaining() const = 0;
  1793. virtual int queryFailCode() const = 0;
  1794. virtual const char * queryFailMessage() const = 0;
  1795. virtual const char * queryEventName() const = 0;
  1796. virtual const char * queryEventExtra() const = 0;
  1797. */
  1798. }
  1799. return nullptr;
  1800. }
  1801. virtual const char * queryHint(const char * kind) const
  1802. {
  1803. return nullptr;
  1804. }
  1805. protected:
  1806. bool initWorkflowItem()
  1807. {
  1808. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1809. return true;
  1810. }
  1811. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1812. {
  1813. return scratchpad.clear().append(prefix).append(value).str();
  1814. }
  1815. const char * queryOptString(IStringVal & value) const
  1816. {
  1817. const char * text = value.str();
  1818. if (!text || !*text)
  1819. return nullptr;
  1820. return text;
  1821. }
  1822. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1823. {
  1824. if (!value)
  1825. return nullptr;
  1826. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1827. }
  1828. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1829. {
  1830. StringBuffer scratchpad;
  1831. for (auto attr : attrs)
  1832. {
  1833. const char * value = queryAttribute(attr, scratchpad.clear());
  1834. if (value)
  1835. visitor.noteAttribute(attr, value);
  1836. }
  1837. }
  1838. protected:
  1839. IArrayOf<IConstWorkflowItem> workflow;
  1840. unsigned curWorkflow = 0;
  1841. StringBuffer curScope;
  1842. };
  1843. /*
  1844. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1845. */
  1846. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1847. {
  1848. class VisitorMapper : implements IWuScopeVisitor
  1849. {
  1850. public:
  1851. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1852. filter(_filter), visitor(_visitor)
  1853. {}
  1854. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1855. {
  1856. if (filter.includeStatistic(kind))
  1857. visitor.noteStatistic(kind, value, extra);
  1858. }
  1859. virtual void noteAttribute(WuAttr attr, const char * value) override
  1860. {
  1861. if (filter.includeAttribute(attr))
  1862. visitor.noteAttribute(attr, value);
  1863. }
  1864. virtual void noteHint(const char * kind, const char * value) override
  1865. {
  1866. if (filter.includeHint(kind))
  1867. visitor.noteHint(kind, value);
  1868. }
  1869. virtual void noteException(IConstWUException & exception) override
  1870. {
  1871. visitor.noteException(exception);
  1872. }
  1873. protected:
  1874. const WuScopeFilter & filter;
  1875. IWuScopeVisitor & visitor;
  1876. };
  1877. public:
  1878. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1879. {
  1880. }
  1881. void addIter(IConstWUScopeIterator * iter)
  1882. {
  1883. if (iter)
  1884. {
  1885. iters.append(OLINK(*iter));
  1886. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1887. }
  1888. }
  1889. virtual bool first() override
  1890. {
  1891. activeIterMask = 0;
  1892. ForEachItemIn(i, iters)
  1893. {
  1894. if (iters.item(i).first())
  1895. activeIterMask |= (1U << i);
  1896. }
  1897. return findNextScope();
  1898. }
  1899. virtual bool next() override
  1900. {
  1901. selectNext();
  1902. return findNextScope();
  1903. }
  1904. virtual bool nextSibling() override
  1905. {
  1906. selectNextSibling();
  1907. return findNextScope();
  1908. }
  1909. virtual bool nextParent() override
  1910. {
  1911. selectNextParent();
  1912. return findNextScope();
  1913. }
  1914. virtual bool isValid() override
  1915. {
  1916. return (activeIterMask != 0);
  1917. }
  1918. virtual const char * queryScope() const override
  1919. {
  1920. return iters.item(firstMatchIter).queryScope();
  1921. }
  1922. virtual StatisticScopeType getScopeType() const override
  1923. {
  1924. return iters.item(firstMatchIter).getScopeType();
  1925. }
  1926. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1927. {
  1928. VisitorMapper mappedVisitor(filter, visitor);
  1929. whichProperties &= filter.properties;
  1930. ForEachItemIn(i, iters)
  1931. {
  1932. if (iterMatchesCurrentScope(i))
  1933. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1934. }
  1935. }
  1936. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1937. {
  1938. ForEachItemIn(i, iters)
  1939. {
  1940. if (iterMatchesCurrentScope(i))
  1941. {
  1942. if (iters.item(i).getStat(kind, value))
  1943. return true;
  1944. }
  1945. }
  1946. return false;
  1947. }
  1948. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1949. {
  1950. ForEachItemIn(i, iters)
  1951. {
  1952. if (iterMatchesCurrentScope(i))
  1953. {
  1954. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1955. if (value)
  1956. return value;
  1957. }
  1958. }
  1959. return nullptr;
  1960. }
  1961. virtual const char * queryHint(const char * kind) const override
  1962. {
  1963. ForEachItemIn(i, iters)
  1964. {
  1965. if (iterMatchesCurrentScope(i))
  1966. {
  1967. const char * value = iters.item(i).queryHint(kind);
  1968. if (value)
  1969. return value;
  1970. }
  1971. }
  1972. return nullptr;
  1973. }
  1974. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  1975. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  1976. protected:
  1977. //Calculate which iterators contain the scope that should come next
  1978. bool findNextScope()
  1979. {
  1980. for(;;)
  1981. {
  1982. if (activeIterMask == 0)
  1983. return false;
  1984. unsigned mask = 0;
  1985. const char * scope = nullptr;
  1986. ForEachItemIn(i, iters)
  1987. {
  1988. if (isAlive(i))
  1989. {
  1990. const char * iterScope = iters.item(i).queryScope();
  1991. if (mask)
  1992. {
  1993. int compare = compareScopeName(scope, iterScope);
  1994. if (compare == 0)
  1995. {
  1996. mask |= (1U << i);
  1997. }
  1998. else if (compare > 0)
  1999. {
  2000. scope = iterScope;
  2001. mask = (1U << i);
  2002. firstMatchIter = i;
  2003. }
  2004. }
  2005. else
  2006. {
  2007. scope = iterScope;
  2008. mask = (1U << i);
  2009. firstMatchIter = i;
  2010. }
  2011. }
  2012. }
  2013. matchIterMask = mask;
  2014. while (activeScopes)
  2015. {
  2016. const char * activeScope = activeScopes.tos();
  2017. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2018. if (compareScopes(scope, activeScope) & SCchild)
  2019. break;
  2020. activeScopes.pop();
  2021. }
  2022. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2023. bool include = false;
  2024. if (activeScopes)
  2025. {
  2026. const char * activeScope = activeScopes.tos();
  2027. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2028. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2029. if (nesting <= filter.include.nestedDepth)
  2030. include = true;
  2031. }
  2032. //Check to see if this is a new match
  2033. if (filter.compareMatchScopes(scope) & SCequal)
  2034. {
  2035. if (!include)
  2036. include = filter.include.matchedScope;
  2037. //Only add it to the list of active scopes if it can match child elements
  2038. if (filter.include.nestedDepth != 0)
  2039. activeScopes.append(scope);
  2040. }
  2041. if (include)
  2042. {
  2043. if (!filter.includeScope(scope))
  2044. include = false;
  2045. else if (filter.requiredStats.size())
  2046. {
  2047. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2048. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2049. {
  2050. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2051. unsigned __int64 value;
  2052. if (getStat(cur.queryKind(), value))
  2053. {
  2054. if (!cur.matches(value))
  2055. include = false;
  2056. }
  2057. else
  2058. include = false;
  2059. }
  2060. }
  2061. }
  2062. if (include)
  2063. return true;
  2064. //MORE: Optimize based on filter.compareScope()
  2065. selectNext();
  2066. }
  2067. }
  2068. void checkScopeOrder(unsigned input, const char * prevScope)
  2069. {
  2070. if (isAlive(input))
  2071. {
  2072. const char * curScope = iters.item(input).queryScope();
  2073. int compare = compareScopeName(prevScope, curScope);
  2074. if (compare >= 0)
  2075. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2076. }
  2077. }
  2078. void selectNext()
  2079. {
  2080. ForEachItemIn(i, iters)
  2081. {
  2082. if (iterMatchesCurrentScope(i))
  2083. {
  2084. #ifdef _DEBUG
  2085. StringBuffer prevScope(iters.item(i).queryScope());
  2086. #endif
  2087. if (!iters.item(i).next())
  2088. activeIterMask &= ~(1U << i);
  2089. #ifdef _DEBUG
  2090. checkScopeOrder(i, prevScope);
  2091. #endif
  2092. }
  2093. }
  2094. }
  2095. void selectNextSibling()
  2096. {
  2097. ForEachItemIn(i, iters)
  2098. {
  2099. if (iterMatchesCurrentScope(i))
  2100. {
  2101. #ifdef _DEBUG
  2102. StringBuffer prevScope(iters.item(i).queryScope());
  2103. #endif
  2104. if (!iters.item(i).nextSibling())
  2105. activeIterMask &= ~(1U << i);
  2106. #ifdef _DEBUG
  2107. checkScopeOrder(i, prevScope);
  2108. #endif
  2109. }
  2110. }
  2111. }
  2112. void selectNextParent()
  2113. {
  2114. ForEachItemIn(i, iters)
  2115. {
  2116. if (iterMatchesCurrentScope(i))
  2117. {
  2118. #ifdef _DEBUG
  2119. StringBuffer prevScope(iters.item(i).queryScope());
  2120. #endif
  2121. if (!iters.item(i).nextParent())
  2122. activeIterMask &= ~(1U << i);
  2123. #ifdef _DEBUG
  2124. checkScopeOrder(i, prevScope);
  2125. #endif
  2126. }
  2127. }
  2128. }
  2129. protected:
  2130. const WuScopeFilter & filter;
  2131. IArrayOf<IConstWUScopeIterator> iters;
  2132. unsigned curIter = 0;
  2133. unsigned firstMatchIter = 0;
  2134. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2135. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2136. StringArray activeScopes;
  2137. };
  2138. //---------------------------------------------------------------------------------------------------------------------
  2139. class AggregateFilter
  2140. {
  2141. public:
  2142. AggregateFilter(StatisticKind _search) : search(_search) {}
  2143. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2144. {
  2145. return (kind == search);
  2146. }
  2147. protected:
  2148. StatisticKind search;
  2149. //MORE: Allow filtering by scope?
  2150. };
  2151. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2152. {
  2153. public:
  2154. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2155. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2156. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2157. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2158. protected:
  2159. AggregateFilter filter;
  2160. };
  2161. class SimpleAggregator : public StatisticAggregator
  2162. {
  2163. public:
  2164. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2165. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2166. {
  2167. if (filter.matches(kind, value, extra))
  2168. summary.noteValue(value);
  2169. }
  2170. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2171. //with a noteAggregate(value, variant, value, grouping)?
  2172. protected:
  2173. StatsAggregation summary;
  2174. };
  2175. class SimpleReferenceAggregator : public StatisticAggregator
  2176. {
  2177. public:
  2178. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2179. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2180. {
  2181. if (filter.matches(kind, value, extra))
  2182. summary.noteValue(value);
  2183. }
  2184. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2185. //with a noteAggregate(value, variant, value, grouping)?
  2186. protected:
  2187. StatsAggregation & summary;
  2188. };
  2189. class GroupedAggregator : public StatisticAggregator
  2190. {
  2191. public:
  2192. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2193. {
  2194. if (filter.matches(kind, value, extra))
  2195. {
  2196. StatsAggregation & match = summary; // look up in hash table.
  2197. match.noteValue(value);
  2198. }
  2199. }
  2200. protected:
  2201. //HashTable of (possible groupings->summary)
  2202. StatsAggregation summary;
  2203. };
  2204. class CompoundAggregator : implements StatisticAggregator
  2205. {
  2206. public:
  2207. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2208. {
  2209. ForEachItemIn(i, aggregators)
  2210. aggregators.item(i).noteStatistic(kind, value, extra);
  2211. }
  2212. protected:
  2213. IArrayOf<StatisticAggregator> aggregators;
  2214. };
  2215. //To calculate aggregates, create a scope iterator, and an instance of a StatisticAggregator, and play the attributes through the interface
  2216. //---------------------------------------------------------------------------------------------------------------------
  2217. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2218. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2219. {
  2220. const char * start = finger;
  2221. if (!*start)
  2222. return false;
  2223. const char * cur = start;
  2224. const char * bra = nullptr;
  2225. const char * end = nullptr;
  2226. unsigned braDepth = 0;
  2227. char next;
  2228. arg.clear();
  2229. for (;;)
  2230. {
  2231. next = *cur;
  2232. if (!next || ((next == ',') && (braDepth == 0)))
  2233. break;
  2234. switch (next)
  2235. {
  2236. case '[':
  2237. if (braDepth == 0)
  2238. {
  2239. if (bra)
  2240. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2241. bra = cur;
  2242. }
  2243. braDepth++;
  2244. break;
  2245. case ']':
  2246. if (braDepth > 0)
  2247. {
  2248. if (--braDepth == 0)
  2249. {
  2250. end = cur;
  2251. arg.append(cur - (bra+1), bra+1);
  2252. }
  2253. }
  2254. break;
  2255. }
  2256. cur++;
  2257. }
  2258. if (braDepth != 0)
  2259. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2260. option.clear();
  2261. if (bra)
  2262. {
  2263. if (cur != end+1)
  2264. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2265. option.append(bra-start, start);
  2266. }
  2267. else
  2268. option.append(cur-start, start);
  2269. if (next)
  2270. finger = cur+1;
  2271. else
  2272. finger = cur;
  2273. return true;
  2274. }
  2275. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2276. {
  2277. if (start == end)
  2278. return dft;
  2279. char * next;
  2280. unsigned value = (unsigned)strtoll(start, &next, 10);
  2281. if (next != end)
  2282. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2283. return value;
  2284. }
  2285. static unsigned readValue(const char * start, const char * type)
  2286. {
  2287. if (*start == '\0')
  2288. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2289. char * next;
  2290. unsigned value = (unsigned)strtoll(start, &next, 10);
  2291. if (*next != '\0')
  2292. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2293. return value;
  2294. }
  2295. /*
  2296. Scope service matching Syntax: * indicates
  2297. Which items are matched:
  2298. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2299. depth[n | low..high] - range of depths to search for a match
  2300. source[global|stats|graph|all]* - which sources to search within the workunit
  2301. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2302. Which items are include in the results:
  2303. matched[true|false] - are the matched scopes returned?
  2304. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2305. includetype[<scope-type>] - which scope types should be included?
  2306. Which properties of the items are returned:
  2307. properties[statistics|hints|attributes|scope|all]
  2308. statistic[<statistic-kind>|none|all] - include statistic
  2309. attribute[<attribute-name>|none|all] - include attribute
  2310. hint[<hint-name>] - include hint
  2311. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2312. measure[<measure>] - all statistics with a particular measure
  2313. version[<version>] - minimum version to return
  2314. */
  2315. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2316. //Some of the following contains aliases for the same option e.g. stat and statistic
  2317. static constexpr EnumMapping filterOptions[] = {
  2318. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2319. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2320. { FOmatched, "matched" }, { FOnested, "nested" },
  2321. { FOinclude, "include" }, { FOinclude, "includetype" },
  2322. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2323. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2324. { FOproperty, "prop" }, { FOproperty, "property" },
  2325. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2326. static constexpr EnumMapping sourceMappings[] = {
  2327. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2328. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2329. static constexpr EnumMapping propertyMappings[] = {
  2330. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2331. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2332. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2333. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2334. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2335. WuScopeFilter::WuScopeFilter(const char * filter)
  2336. {
  2337. addFilter(filter);
  2338. finishedFilter();
  2339. }
  2340. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2341. {
  2342. if (!filter)
  2343. return *this;
  2344. StringBuffer option;
  2345. StringBuffer arg;
  2346. while (extractOption(filter, option, arg))
  2347. {
  2348. switch (getEnum(option, filterOptions, FOunknown))
  2349. {
  2350. case FOscope:
  2351. addScope(arg);
  2352. break;
  2353. case FOstype:
  2354. addScopeType(arg);
  2355. break;
  2356. case FOid:
  2357. addId(arg);
  2358. break;
  2359. case FOdepth:
  2360. {
  2361. //Allow depth[n], depth[a,b] or depth[a..b]
  2362. const char * comma = strchr(arg, ',');
  2363. const char * dotdot = strstr(arg, "..");
  2364. if (comma)
  2365. {
  2366. unsigned low = readOptValue(arg, comma, 0, "depth");
  2367. if (comma[1])
  2368. {
  2369. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2370. }
  2371. else
  2372. scopeFilter.setDepth(low, UINT_MAX);
  2373. }
  2374. else if (dotdot)
  2375. {
  2376. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2377. if (dotdot[2])
  2378. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2379. else
  2380. scopeFilter.setDepth(low, UINT_MAX);
  2381. }
  2382. else
  2383. {
  2384. scopeFilter.setDepth(readValue(arg, "depth"));
  2385. }
  2386. break;
  2387. }
  2388. case FOsource:
  2389. addSource(arg);
  2390. break;
  2391. case FOwhere: // where[stat<op>value]
  2392. addRequiredStat(arg);
  2393. break;
  2394. case FOmatched:
  2395. setIncludeMatch(strToBool(arg));
  2396. break;
  2397. case FOnested:
  2398. if (strieq(arg, "all"))
  2399. setIncludeNesting(UINT_MAX);
  2400. else if (isdigit(*arg))
  2401. setIncludeNesting(atoi(arg));
  2402. else
  2403. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2404. break;
  2405. case FOinclude:
  2406. setIncludeScopeType(arg);
  2407. break;
  2408. case FOproperties:
  2409. {
  2410. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2411. if (prop == PTunknown)
  2412. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2413. addOutputProperties(prop);
  2414. break;
  2415. }
  2416. case FOstatistic:
  2417. addOutputStatistic(arg);
  2418. break;
  2419. case FOattribute:
  2420. addOutputAttribute(arg);
  2421. break;
  2422. case FOhint:
  2423. addOutputHint(arg);
  2424. break;
  2425. case FOproperty:
  2426. addOutput(arg);
  2427. break;
  2428. case FOmeasure:
  2429. setMeasure(arg);
  2430. break;
  2431. case FOversion:
  2432. if (isdigit(*arg))
  2433. minVersion = atoi64(arg);
  2434. else
  2435. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2436. break;
  2437. default:
  2438. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2439. }
  2440. }
  2441. return *this;
  2442. }
  2443. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2444. {
  2445. if (scope)
  2446. {
  2447. validateScope(scope);
  2448. scopeFilter.addScope(scope);
  2449. }
  2450. return *this;
  2451. }
  2452. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2453. {
  2454. if (scopeType)
  2455. {
  2456. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2457. if (sst == SSTmax)
  2458. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2459. scopeFilter.addScopeType(sst);
  2460. }
  2461. return *this;
  2462. }
  2463. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2464. {
  2465. validateScopeId(id);
  2466. scopeFilter.addId(id);
  2467. return *this;
  2468. }
  2469. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2470. {
  2471. WuAttr attr = queryWuAttribute(prop, WaNone);
  2472. if (attr != WaNone)
  2473. {
  2474. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2475. if (singleKindAttr != WaNone)
  2476. addOutputAttribute(singleKindAttr);
  2477. else
  2478. addOutputAttribute(attr);
  2479. } else if (queryStatisticKind(prop, StMax) != StMax)
  2480. addOutputStatistic(prop);
  2481. else
  2482. addOutputHint(prop);
  2483. return *this;
  2484. }
  2485. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2486. {
  2487. if (!prop)
  2488. return *this;
  2489. StatisticKind kind = queryStatisticKind(prop, StMax);
  2490. if (kind == StMax)
  2491. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2492. return addOutputStatistic(kind);
  2493. }
  2494. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2495. {
  2496. if (stat != StKindNone)
  2497. {
  2498. if (stat != StKindAll)
  2499. desiredStats.append(stat);
  2500. else
  2501. desiredStats.kill();
  2502. properties |= PTstatistics;
  2503. }
  2504. else
  2505. properties &= ~PTstatistics;
  2506. return *this;
  2507. }
  2508. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2509. {
  2510. if (!prop)
  2511. return *this;
  2512. WuAttr attr = queryWuAttribute(prop, WaMax);
  2513. if (attr == WaMax)
  2514. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2515. return addOutputAttribute(attr);
  2516. }
  2517. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2518. {
  2519. if (attr != WaNone)
  2520. {
  2521. if (attr != WaAll)
  2522. desiredAttrs.append(attr);
  2523. else
  2524. desiredAttrs.kill();
  2525. properties |= PTattributes;
  2526. }
  2527. else
  2528. properties &= ~PTattributes;
  2529. return *this;
  2530. }
  2531. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2532. {
  2533. if (strieq(prop, "none"))
  2534. {
  2535. desiredHints.kill();
  2536. properties &= ~PThints;
  2537. }
  2538. else
  2539. {
  2540. if (!strieq(prop, "all"))
  2541. desiredHints.append(prop);
  2542. else
  2543. desiredHints.kill();
  2544. properties |= PThints;
  2545. }
  2546. return *this;
  2547. }
  2548. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2549. {
  2550. include.matchedScope = value;
  2551. return *this;
  2552. }
  2553. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2554. {
  2555. include.nestedDepth = depth;
  2556. return *this;
  2557. }
  2558. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2559. {
  2560. if (scopeType)
  2561. {
  2562. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2563. if (sst == SSTmax)
  2564. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2565. include.scopeTypes.append(sst);
  2566. }
  2567. return *this;
  2568. }
  2569. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2570. {
  2571. if (measure)
  2572. {
  2573. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2574. if (desiredMeasure == SMeasureNone)
  2575. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2576. properties |= PTstatistics;
  2577. }
  2578. return *this;
  2579. }
  2580. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2581. {
  2582. if (properties == PTnone)
  2583. properties = mask;
  2584. else
  2585. properties |= mask;
  2586. return *this;
  2587. }
  2588. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2589. {
  2590. requiredStats.emplace_back(statKind, lowValue, highValue);
  2591. return *this;
  2592. }
  2593. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2594. {
  2595. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2596. return *this;
  2597. }
  2598. //process a filter in one of the following forms:
  2599. // <statistic-name>
  2600. // <statistic-name> (=|<|<=|>|>=) <value>
  2601. // <statistic-name>=[<low>]..[<high>]
  2602. void WuScopeFilter::addRequiredStat(const char * filter)
  2603. {
  2604. const char * stat = filter;
  2605. const char * cur = stat;
  2606. while (isalpha(*cur))
  2607. cur++;
  2608. StringBuffer statisticName(cur-stat, stat);
  2609. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2610. if (statKind == StKindNone)
  2611. throw makeStringExceptionV(0, "Unknown statistic name '%s'", statisticName.str());
  2612. //Skip any spaces before a comparison operator.
  2613. while (*cur && isspace(*cur))
  2614. cur++;
  2615. //Save the operator, and skip over any non digits.
  2616. const char * op = cur;
  2617. switch (*op)
  2618. {
  2619. case '=':
  2620. cur++;
  2621. break;
  2622. case '<':
  2623. case '>':
  2624. if (op[1] == '=')
  2625. cur += 2;
  2626. else
  2627. cur++;
  2628. break;
  2629. case '\0':
  2630. break;
  2631. default:
  2632. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2633. }
  2634. const char * next;
  2635. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2636. stat_type lowValue = 0;
  2637. stat_type highValue = MaxStatisticValue;
  2638. switch (op[0])
  2639. {
  2640. case '=':
  2641. {
  2642. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2643. if (next[0] == ',')
  2644. {
  2645. lowValue = value;
  2646. next++;
  2647. if (*next != '\0')
  2648. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2649. }
  2650. else if (strncmp(next, "..", 2) == 0)
  2651. {
  2652. lowValue = value;
  2653. next += 2;
  2654. if (*next != '\0')
  2655. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2656. }
  2657. else
  2658. {
  2659. lowValue = value;
  2660. highValue = value;
  2661. }
  2662. break;
  2663. }
  2664. case '<':
  2665. if (op[1] == '=')
  2666. highValue = value;
  2667. else
  2668. highValue = value-1;
  2669. break;
  2670. case '>':
  2671. if (op[1] == '=')
  2672. lowValue = value;
  2673. else
  2674. lowValue = value+1;
  2675. break;
  2676. }
  2677. if (*next)
  2678. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2679. requiredStats.emplace_back(statKind, lowValue, highValue);
  2680. }
  2681. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2682. {
  2683. WuScopeSourceFlags mask = querySource(source);
  2684. if (mask == SSFunknown)
  2685. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2686. if (!mask)
  2687. sourceFlags = mask;
  2688. else
  2689. sourceFlags |= mask;
  2690. return *this;
  2691. }
  2692. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2693. {
  2694. scopeFilter.setDepth(low, high);
  2695. return *this;
  2696. }
  2697. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2698. {
  2699. //If there is a post filter on the scopeType, then check if it matches
  2700. if (include.scopeTypes.ordinality() == 1)
  2701. return (include.scopeTypes.item(0) == scopeType);
  2702. //If filter doesn't match nested items, then check if the scope filter matches.
  2703. if (include.nestedDepth == 0)
  2704. {
  2705. if (scopeFilter.matchOnly(scopeType))
  2706. return true;
  2707. }
  2708. return false;
  2709. }
  2710. //Called once the filter has been updated to optimize the filter
  2711. void WuScopeFilter::finishedFilter()
  2712. {
  2713. scopeFilter.finishedFilter();
  2714. assertex(!optimized);
  2715. optimized = true;
  2716. if ((include.nestedDepth == 0) && !include.matchedScope)
  2717. include.nestedDepth = UINT_MAX;
  2718. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2719. if (scopeFilter.canAlwaysPreFilter())
  2720. preFilterScope = true;
  2721. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2722. if (!sourceFlags)
  2723. {
  2724. sourceFlags = SSFsearchAll;
  2725. //Use the other options to reduce the number of elements that are searched.
  2726. //If not interested in scopes on their own then...
  2727. if (!(properties & PTscope))
  2728. {
  2729. //Global stats and graph stats only contain stats => remove if not interested in them
  2730. if (!(properties & PTstatistics))
  2731. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2732. //graph, workflow only contains attributes and hints => remove if not interested
  2733. if (!(properties & (PTattributes|PThints)))
  2734. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2735. }
  2736. if (!(properties & PTnotes))
  2737. sourceFlags &= ~SSFsearchExceptions;
  2738. }
  2739. //Optimize sources if they haven't been explicitly specified
  2740. //Most of the following are dependent on internal knowledge of the way that information is represented
  2741. if (matchOnly(SSTworkflow))
  2742. {
  2743. //Workflow is not nested within a graph
  2744. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2745. setDepth(1, 1);
  2746. }
  2747. else if (matchOnly(SSTgraph))
  2748. {
  2749. //Graph starts are stored globally, not in the graph stats.
  2750. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2751. if (!(properties & (PTattributes|PThints)))
  2752. sourceFlags &= ~(SSFsearchGraph);
  2753. setDepth(2, 2);
  2754. }
  2755. else if (matchOnly(SSTsubgraph))
  2756. {
  2757. sourceFlags &= ~(SSFsearchWorkflow);
  2758. }
  2759. else if (matchOnly(SSTcompilestage))
  2760. {
  2761. //compile stages are not stored in the graph
  2762. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2763. }
  2764. else if (matchOnly(SSTactivity))
  2765. {
  2766. //information about activities is not stored globally
  2767. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2768. }
  2769. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2770. if (include.nestedDepth == 0)
  2771. {
  2772. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2773. sourceFlags &= ~(SSFsearchGraphStats);
  2774. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2775. {
  2776. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2777. //then do not include the subgraph timings
  2778. if (desiredStats.ordinality())
  2779. {
  2780. bool needGraphStats = false;
  2781. ForEachItemIn(i, desiredStats)
  2782. {
  2783. unsigned stat = desiredStats.item(i);
  2784. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2785. needGraphStats = true;
  2786. }
  2787. if (!needGraphStats)
  2788. {
  2789. sourceFlags &= ~(SSFsearchGraphStats);
  2790. if (matchOnly(SSTsubgraph))
  2791. sourceFlags &= SSFsearchGlobalStats;
  2792. }
  2793. }
  2794. }
  2795. }
  2796. if (scopeFilter.compareDepth(1) < 0)
  2797. {
  2798. //If minimum match depth is > 1 then it will never match workflow
  2799. sourceFlags &= ~(SSFsearchWorkflow);
  2800. }
  2801. //The xml graph is never updated, so do not check it if minVersion != 0
  2802. if (minVersion != 0)
  2803. {
  2804. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2805. }
  2806. }
  2807. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2808. {
  2809. if (!(properties & PTstatistics))
  2810. return false;
  2811. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2812. return false;
  2813. if (desiredStats.empty())
  2814. return true;
  2815. return desiredStats.contains(kind);
  2816. }
  2817. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2818. {
  2819. if (!(properties & PTattributes))
  2820. return false;
  2821. if (desiredAttrs.empty())
  2822. return true;
  2823. return desiredAttrs.contains(attr);
  2824. }
  2825. bool WuScopeFilter::includeHint(const char * kind) const
  2826. {
  2827. if (!(properties & PThints))
  2828. return false;
  2829. if (desiredHints.empty())
  2830. return true;
  2831. return desiredHints.contains(kind);
  2832. }
  2833. bool WuScopeFilter::includeScope(const char * scope) const
  2834. {
  2835. if (include.scopeTypes)
  2836. {
  2837. const char * tail = queryScopeTail(scope);
  2838. StatsScopeId id(tail);
  2839. if (!include.scopeTypes.contains(id.queryScopeType()))
  2840. return false;
  2841. }
  2842. return true;
  2843. }
  2844. const static ScopeFilter nullScopeFilter {};
  2845. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2846. {
  2847. if (preFilterScope)
  2848. return scopeFilter;
  2849. else
  2850. return nullScopeFilter;
  2851. }
  2852. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2853. {
  2854. return scopeFilter.compare(scope);
  2855. }
  2856. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2857. {
  2858. scopeFilter.describe(out);
  2859. if (requiredStats.size())
  2860. {
  2861. out.append(",where[");
  2862. bool first = false;
  2863. for (const auto & stat : requiredStats)
  2864. {
  2865. if (!first)
  2866. out.append(",");
  2867. stat.describe(out);
  2868. first = false;
  2869. }
  2870. out.append("]");
  2871. }
  2872. {
  2873. StringBuffer sources;
  2874. for (unsigned mask=1; mask; mask *= 2)
  2875. {
  2876. if (sourceFlags & mask)
  2877. {
  2878. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2879. if (source)
  2880. sources.append(",").append(source);
  2881. }
  2882. }
  2883. if (sources)
  2884. out.append(",source[").append(sources.str()+1).append("]");
  2885. }
  2886. if (include.nestedDepth != UINT_MAX)
  2887. out.appendf(",nested[%u]", include.nestedDepth);
  2888. if (include.scopeTypes)
  2889. {
  2890. out.append(",include[");
  2891. ForEachItemIn(i, include.scopeTypes)
  2892. {
  2893. if (i)
  2894. out.append(",");
  2895. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  2896. }
  2897. out.append("]");
  2898. }
  2899. {
  2900. StringBuffer props;
  2901. if (properties == PTnone)
  2902. props.append(",none");
  2903. else if (properties == PTall)
  2904. props.append(",all");
  2905. else
  2906. {
  2907. if (properties & PTstatistics)
  2908. props.append(",stat");
  2909. if (properties & PTattributes)
  2910. props.append(",attr");
  2911. if (properties & PThints)
  2912. props.append(",hint");
  2913. if (properties & PTscope)
  2914. props.append(",scope");
  2915. if (properties & PTnotes)
  2916. props.append(",note");
  2917. }
  2918. out.append(",properties[").append(props.str()+1).append("]");
  2919. }
  2920. if (desiredStats)
  2921. {
  2922. out.append(",stat[");
  2923. ForEachItemIn(i, desiredStats)
  2924. {
  2925. if (i)
  2926. out.append(",");
  2927. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  2928. }
  2929. out.append("]");
  2930. }
  2931. if (desiredAttrs)
  2932. {
  2933. out.append(",attr[");
  2934. ForEachItemIn(i, desiredAttrs)
  2935. {
  2936. if (i)
  2937. out.append(",");
  2938. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  2939. }
  2940. out.append("]");
  2941. }
  2942. if (desiredHints)
  2943. {
  2944. out.append(",hint[");
  2945. ForEachItemIn(i, desiredHints)
  2946. {
  2947. if (i)
  2948. out.append(",");
  2949. out.append(desiredHints.item(i));
  2950. }
  2951. out.append("]");
  2952. }
  2953. if (desiredMeasure != SMeasureAll)
  2954. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  2955. if (minVersion != 0)
  2956. out.appendf(",version(%" I64F "u)", minVersion);
  2957. return out;
  2958. }
  2959. //--------------------------------------------------------------------------------------------------------------------
  2960. EnumMapping states[] = {
  2961. { WUStateUnknown, "unknown" },
  2962. { WUStateCompiled, "compiled" },
  2963. { WUStateRunning, "running" },
  2964. { WUStateCompleted, "completed" },
  2965. { WUStateFailed, "failed" },
  2966. { WUStateArchived, "archived" },
  2967. { WUStateAborting, "aborting" },
  2968. { WUStateAborted, "aborted" },
  2969. { WUStateBlocked, "blocked" },
  2970. { WUStateSubmitted, "submitted" },
  2971. { WUStateScheduled, "scheduled" },
  2972. { WUStateCompiling, "compiling" },
  2973. { WUStateWait, "wait" },
  2974. { WUStateUploadingFiles, "uploading_files" },
  2975. { WUStateDebugPaused, "debugging" },
  2976. { WUStateDebugRunning, "debug_running" },
  2977. { WUStatePaused, "paused" },
  2978. { WUStateSize, NULL }
  2979. };
  2980. EnumMapping actions[] = {
  2981. { WUActionUnknown, "unknown" },
  2982. { WUActionCompile, "compile" },
  2983. { WUActionCheck, "check" },
  2984. { WUActionRun, "run" },
  2985. { WUActionExecuteExisting, "execute" },
  2986. { WUActionPause, "pause" },
  2987. { WUActionPauseNow, "pausenow" },
  2988. { WUActionResume, "resume" },
  2989. { WUActionSize, NULL },
  2990. };
  2991. EnumMapping priorityClasses[] = {
  2992. { PriorityClassUnknown, "unknown" },
  2993. { PriorityClassLow, "low" },
  2994. { PriorityClassNormal, "normal" },
  2995. { PriorityClassHigh, "high" },
  2996. { PriorityClassSize, NULL },
  2997. };
  2998. const char * getWorkunitStateStr(WUState state)
  2999. {
  3000. dbgassertex(state < WUStateSize);
  3001. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3002. }
  3003. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3004. {
  3005. const char *defval = map->str;
  3006. while (map->str)
  3007. {
  3008. if (value==map->val)
  3009. {
  3010. p->setProp(propname, map->str);
  3011. return;
  3012. }
  3013. map++;
  3014. }
  3015. assertex(!"Unexpected value in setEnum");
  3016. p->setProp(propname, defval);
  3017. }
  3018. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3019. {
  3020. return getEnum(p->queryProp(propname),map);
  3021. }
  3022. const char * getWorkunitActionStr(WUAction action)
  3023. {
  3024. return getEnumText(action, actions);
  3025. }
  3026. WUAction getWorkunitAction(const char *actionStr)
  3027. {
  3028. return (WUAction) getEnum(actionStr, actions);
  3029. }
  3030. //==========================================================================================
  3031. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3032. {
  3033. public:
  3034. CLightweightWorkunitInfo(IPropertyTree &p)
  3035. {
  3036. wuid.set(p.queryName());
  3037. user.set(p.queryProp("@submitID"));
  3038. jobName.set(p.queryProp("@jobName"));
  3039. clusterName.set(p.queryProp("@clusterName"));
  3040. timeScheduled.set(p.queryProp("@timeScheduled"));
  3041. state = (WUState) getEnum(&p, "@state", states);
  3042. action = (WUAction) getEnum(&p, "Action", actions);
  3043. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3044. priorityLevel = calcPriorityValue(&p);
  3045. wuscope.set(p.queryProp("@scope"));
  3046. appvalues.loadBranch(&p,"Application");
  3047. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3048. _isProtected = p.getPropBool("@protected", false);
  3049. }
  3050. virtual const char *queryWuid() const { return wuid.str(); }
  3051. virtual const char *queryUser() const { return user.str(); }
  3052. virtual const char *queryJobName() const { return jobName.str(); }
  3053. virtual const char *queryClusterName() const { return clusterName.str(); }
  3054. virtual const char *queryWuScope() const { return wuscope.str(); }
  3055. virtual WUState getState() const { return state; }
  3056. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3057. virtual WUAction getAction() const { return action; }
  3058. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3059. virtual WUPriorityClass getPriority() const { return priority; }
  3060. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3061. virtual int getPriorityLevel() const { return priorityLevel; }
  3062. virtual bool isProtected() const { return _isProtected; }
  3063. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3064. {
  3065. if (timeScheduled.length())
  3066. val.setGmtString(timeScheduled.str());
  3067. return val;
  3068. }
  3069. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3070. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3071. protected:
  3072. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3073. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3074. unsigned totalThorTime;
  3075. WUState state;
  3076. WUAction action;
  3077. WUPriorityClass priority;
  3078. int priorityLevel;
  3079. bool _isProtected;
  3080. };
  3081. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3082. {
  3083. return new CLightweightWorkunitInfo(p);
  3084. }
  3085. class CDaliWuGraphStats : public CWuGraphStats
  3086. {
  3087. public:
  3088. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3089. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3090. {
  3091. }
  3092. protected:
  3093. Owned<IRemoteConnection> conn;
  3094. };
  3095. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3096. {
  3097. abortId = 0;
  3098. stateId = 0;
  3099. actionId = 0;
  3100. assertex((flags & ~SubscribeOptionAbort) == 0);
  3101. if (flags & SubscribeOptionAbort)
  3102. {
  3103. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3104. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3105. }
  3106. }
  3107. CWorkUnitWatcher::~CWorkUnitWatcher()
  3108. {
  3109. assertex(abortId==0 && stateId==0 && actionId==0);
  3110. }
  3111. void CWorkUnitWatcher::unsubscribe()
  3112. {
  3113. CriticalBlock b(crit);
  3114. if (abortId)
  3115. querySDS().unsubscribe(abortId);
  3116. if (stateId)
  3117. querySDS().unsubscribe(stateId);
  3118. if (actionId)
  3119. querySDS().unsubscribe(actionId);
  3120. abortId = 0;
  3121. stateId = 0;
  3122. actionId = 0;
  3123. }
  3124. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3125. {
  3126. CriticalBlock b(crit);
  3127. if (id==stateId)
  3128. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3129. else if (id==actionId)
  3130. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3131. else if (id==abortId)
  3132. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3133. }
  3134. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3135. {
  3136. public:
  3137. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3138. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3139. {
  3140. if (flags & SubscribeOptionState)
  3141. {
  3142. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3143. stateId = querySDS().subscribe(xpath.str(), *this);
  3144. }
  3145. if (flags & SubscribeOptionAction)
  3146. {
  3147. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3148. actionId = querySDS().subscribe(xpath.str(), *this);
  3149. }
  3150. }
  3151. };
  3152. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3153. {
  3154. CriticalBlock block(crit);
  3155. assertex(options==SubscribeOptionAbort);
  3156. if (!abortWatcher)
  3157. {
  3158. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3159. abortDirty = true;
  3160. }
  3161. }
  3162. void CPersistedWorkUnit::unsubscribe()
  3163. {
  3164. CriticalBlock block(crit);
  3165. if (abortWatcher)
  3166. {
  3167. abortWatcher->unsubscribe();
  3168. abortWatcher.clear();
  3169. }
  3170. }
  3171. bool CPersistedWorkUnit::aborting() const
  3172. {
  3173. CriticalBlock block(crit);
  3174. if (abortDirty)
  3175. {
  3176. StringBuffer apath;
  3177. apath.append("/WorkUnitAborts/").append(p->queryName());
  3178. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3179. if (acon)
  3180. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3181. else
  3182. abortState = false;
  3183. abortDirty = false;
  3184. }
  3185. return abortState;
  3186. }
  3187. class CDaliWorkUnit : public CPersistedWorkUnit
  3188. {
  3189. public:
  3190. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3191. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3192. {
  3193. loadPTree(connection->getRoot());
  3194. }
  3195. ~CDaliWorkUnit()
  3196. {
  3197. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3198. // We use the beforeDispose() in base class to help ensure this
  3199. p.clear();
  3200. }
  3201. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3202. {
  3203. Owned<IRemoteConnection> conn = getProgressConnection();
  3204. if (conn)
  3205. {
  3206. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3207. if (progress)
  3208. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3209. }
  3210. return NULL;
  3211. }
  3212. virtual WUGraphState queryGraphState(const char *graphName) const
  3213. {
  3214. Owned<IRemoteConnection> conn = getProgressConnection();
  3215. if (conn)
  3216. {
  3217. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3218. if (progress)
  3219. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3220. }
  3221. return WUGraphUnknown;
  3222. }
  3223. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3224. {
  3225. Owned<IRemoteConnection> conn = getProgressConnection();
  3226. if (conn)
  3227. {
  3228. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3229. if (progress)
  3230. {
  3231. StringBuffer path;
  3232. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3233. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3234. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3235. }
  3236. }
  3237. return WUGraphUnknown;
  3238. }
  3239. virtual void clearGraphProgress() const
  3240. {
  3241. CriticalBlock block(crit);
  3242. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3243. StringBuffer path("/GraphProgress/");
  3244. path.append(p->queryName());
  3245. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3246. if (delconn)
  3247. delconn->close(true);
  3248. }
  3249. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3250. {
  3251. Owned<IRemoteConnection> conn = getProgressConnection();
  3252. if (!conn)
  3253. return false;
  3254. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3255. if (name)
  3256. {
  3257. graphName.set(name);
  3258. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3259. return true;
  3260. }
  3261. else
  3262. return false;
  3263. }
  3264. virtual void forceReload()
  3265. {
  3266. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3267. CriticalBlock block(crit);
  3268. clearCached(true);
  3269. connection->reload();
  3270. progressConnection.clear();
  3271. abortDirty = true;
  3272. p.setown(connection->getRoot());
  3273. }
  3274. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3275. {
  3276. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3277. clearGraphProgress();
  3278. connection->close(true);
  3279. connection.clear();
  3280. }
  3281. virtual void commit()
  3282. {
  3283. CPersistedWorkUnit::commit();
  3284. if (connection)
  3285. connection->commit();
  3286. }
  3287. virtual void _lockRemote()
  3288. {
  3289. StringBuffer wuRoot;
  3290. getXPath(wuRoot, p->queryName());
  3291. if (connection)
  3292. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3293. else
  3294. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3295. if (!connection)
  3296. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3297. clearCached(true);
  3298. p.setown(connection->getRoot());
  3299. }
  3300. virtual void _unlockRemote()
  3301. {
  3302. if (connection)
  3303. {
  3304. try
  3305. {
  3306. try
  3307. {
  3308. connection->commit();
  3309. }
  3310. catch (IException *e)
  3311. {
  3312. EXCLOG(e, "Error during workunit commit");
  3313. connection->rollback();
  3314. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3315. throw;
  3316. }
  3317. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3318. }
  3319. catch (IException *E)
  3320. {
  3321. StringBuffer s;
  3322. PrintLog("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3323. throw;
  3324. }
  3325. }
  3326. }
  3327. virtual void setGraphState(const char *graphName, WUGraphState state) const
  3328. {
  3329. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName);
  3330. conn->queryRoot()->setPropInt("@_state", state);
  3331. }
  3332. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3333. {
  3334. CriticalBlock block(crit);
  3335. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3336. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3337. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3338. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3339. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3340. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3341. IPropertyTree *node = progress->queryPropTree(path.str());
  3342. if (!node)
  3343. {
  3344. node = progress->addPropTree("node");
  3345. node->setPropInt64("@id", nodeId);
  3346. }
  3347. node->setPropInt("@_state", (unsigned)state);
  3348. switch (state)
  3349. {
  3350. case WUGraphRunning:
  3351. {
  3352. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3353. running->setProp("@graph", graphName);
  3354. running->setPropInt64("@subId", nodeId);
  3355. break;
  3356. }
  3357. case WUGraphComplete:
  3358. {
  3359. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3360. break;
  3361. }
  3362. }
  3363. }
  3364. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3365. {
  3366. return new CDaliWuGraphStats(getWritableProgressConnection(graphName), creatorType, creator, _wfid, graphName, subgraph);
  3367. }
  3368. protected:
  3369. IRemoteConnection *getProgressConnection() const
  3370. {
  3371. CriticalBlock block(crit);
  3372. if (!progressConnection)
  3373. {
  3374. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3375. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3376. }
  3377. return progressConnection.getLink();
  3378. }
  3379. IRemoteConnection *getWritableProgressConnection(const char *graphName) const
  3380. {
  3381. CriticalBlock block(crit);
  3382. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3383. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3384. return querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3385. }
  3386. IPropertyTree *getGraphProgressTree() const
  3387. {
  3388. Owned<IRemoteConnection> conn = getProgressConnection();
  3389. if (conn)
  3390. {
  3391. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3392. mergePTree(tmp,conn->queryRoot());
  3393. return tmp.getClear();
  3394. }
  3395. return NULL;
  3396. }
  3397. Owned<IRemoteConnection> connection;
  3398. mutable Owned<IRemoteConnection> progressConnection;
  3399. };
  3400. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3401. {
  3402. public:
  3403. Owned<CLocalWorkUnit> c;
  3404. IMPLEMENT_IINTERFACE;
  3405. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3406. ~CLockedWorkUnit()
  3407. {
  3408. if (workUnitTraceLevel > 1)
  3409. PrintLog("Releasing locked workunit %s", queryWuid());
  3410. if (c)
  3411. c->unlockRemote();
  3412. }
  3413. virtual IConstWorkUnit * unlock()
  3414. {
  3415. c->unlockRemote();
  3416. return c.getClear();
  3417. }
  3418. virtual bool aborting() const
  3419. { return c->aborting(); }
  3420. virtual void forceReload()
  3421. { UNIMPLEMENTED; }
  3422. virtual WUAction getAction() const
  3423. { return c->getAction(); }
  3424. virtual const char *queryActionDesc() const
  3425. { return c->queryActionDesc(); }
  3426. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3427. { return c->getApplicationValue(application, propname, str); }
  3428. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3429. { return c->getApplicationValueInt(application, propname, defVal); }
  3430. virtual IConstWUAppValueIterator & getApplicationValues() const
  3431. { return c->getApplicationValues(); }
  3432. virtual bool hasWorkflow() const
  3433. { return c->hasWorkflow(); }
  3434. virtual unsigned queryEventScheduledCount() const
  3435. { return c->queryEventScheduledCount(); }
  3436. virtual IPropertyTree * queryWorkflowTree() const
  3437. { return c->queryWorkflowTree(); }
  3438. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3439. { return c->getWorkflowItems(); }
  3440. virtual IWorkflowItemArray * getWorkflowClone() const
  3441. { return c->getWorkflowClone(); }
  3442. virtual bool requiresLocalFileUpload() const
  3443. { return c->requiresLocalFileUpload(); }
  3444. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3445. { return c->getLocalFileUploads(); }
  3446. virtual bool getIsQueryService() const
  3447. { return c->getIsQueryService(); }
  3448. virtual bool getCloneable() const
  3449. { return c->getCloneable(); }
  3450. virtual IUserDescriptor * queryUserDescriptor() const
  3451. { return c->queryUserDescriptor(); }
  3452. virtual const char *queryClusterName() const
  3453. { return c->queryClusterName(); }
  3454. virtual unsigned getCodeVersion() const
  3455. { return c->getCodeVersion(); }
  3456. virtual unsigned getWuidVersion() const
  3457. { return c->getWuidVersion(); }
  3458. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3459. { c->getBuildVersion(buildVersion, eclVersion); }
  3460. virtual bool hasDebugValue(const char * propname) const
  3461. { return c->hasDebugValue(propname); }
  3462. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3463. { return c->getDebugValue(propname, str); }
  3464. virtual int getDebugValueInt(const char * propname, int defVal) const
  3465. { return c->getDebugValueInt(propname, defVal); }
  3466. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3467. { return c->getDebugValueInt64(propname, defVal); }
  3468. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3469. { return c->getDebugValueBool(propname, defVal); }
  3470. virtual IStringIterator & getDebugValues() const
  3471. { return c->getDebugValues(NULL); }
  3472. virtual IStringIterator & getDebugValues(const char *prop) const
  3473. { return c->getDebugValues(prop); }
  3474. virtual unsigned getExceptionCount() const
  3475. { return c->getExceptionCount(); }
  3476. virtual IConstWUExceptionIterator & getExceptions() const
  3477. { return c->getExceptions(); }
  3478. virtual unsigned getGraphCount() const
  3479. { return c->getGraphCount(); }
  3480. virtual unsigned getSourceFileCount() const
  3481. { return c->getSourceFileCount(); }
  3482. virtual unsigned getResultCount() const
  3483. { return c->getResultCount(); }
  3484. virtual unsigned getVariableCount() const
  3485. { return c->getVariableCount(); }
  3486. virtual unsigned getApplicationValueCount() const
  3487. { return c->getApplicationValueCount(); }
  3488. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3489. { return c->getGraphs(type); }
  3490. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3491. { return c->getGraphsMeta(type); }
  3492. virtual IConstWUGraph * getGraph(const char *name) const
  3493. { return c->getGraph(name); }
  3494. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3495. { return c->getGraphProgress(name); }
  3496. virtual const char *queryJobName() const
  3497. { return c->queryJobName(); }
  3498. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3499. { return c->getPluginByName(name); }
  3500. virtual IConstWUPluginIterator & getPlugins() const
  3501. { return c->getPlugins(); }
  3502. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3503. { return c->getLibraryByName(name); }
  3504. virtual IConstWULibraryIterator & getLibraries() const
  3505. { return c->getLibraries(); }
  3506. virtual WUPriorityClass getPriority() const
  3507. { return c->getPriority(); }
  3508. virtual const char *queryPriorityDesc() const
  3509. { return c->queryPriorityDesc(); }
  3510. virtual int getPriorityLevel() const
  3511. { return c->getPriorityLevel(); }
  3512. virtual int getPriorityValue() const
  3513. { return c->getPriorityValue(); }
  3514. virtual IConstWUQuery * getQuery() const
  3515. { return c->getQuery(); }
  3516. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3517. { return c->getWebServicesInfo(); }
  3518. virtual bool getRescheduleFlag() const
  3519. { return c->getRescheduleFlag(); }
  3520. virtual IConstWUResult * getResultByName(const char * name) const
  3521. { return c->getResultByName(name); }
  3522. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3523. { return c->getResultBySequence(seq); }
  3524. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3525. { return c->getQueryResultByName(name); }
  3526. virtual unsigned getResultLimit() const
  3527. { return c->getResultLimit(); }
  3528. virtual IConstWUResultIterator & getResults() const
  3529. { return c->getResults(); }
  3530. virtual IStringVal & getScope(IStringVal & str) const
  3531. { return c->getScope(str); }
  3532. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3533. { return c->getWorkunitDistributedAccessToken(str); }
  3534. virtual WUState getState() const
  3535. { return c->getState(); }
  3536. virtual IStringVal & getStateEx(IStringVal & str) const
  3537. { return c->getStateEx(str); }
  3538. virtual __int64 getAgentSession() const
  3539. { return c->getAgentSession(); }
  3540. virtual unsigned getAgentPID() const
  3541. { return c->getAgentPID(); }
  3542. virtual const char *queryStateDesc() const
  3543. { return c->queryStateDesc(); }
  3544. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3545. { return c->getRunningGraph(graphName, subId); }
  3546. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3547. { return c->getScopeIterator(filter); }
  3548. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3549. { return c->getStatistic(value, scope, kind); }
  3550. virtual IStringVal & getSnapshot(IStringVal & str) const
  3551. { return c->getSnapshot(str); }
  3552. virtual const char *queryUser() const
  3553. { return c->queryUser(); }
  3554. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3555. { return c->getWarningSeverity(code, defaultSeverity); }
  3556. virtual const char *queryWuScope() const
  3557. { return c->queryWuScope(); }
  3558. virtual const char *queryWuid() const
  3559. { return c->queryWuid(); }
  3560. virtual IConstWUResult * getGlobalByName(const char * name) const
  3561. { return c->getGlobalByName(name); }
  3562. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3563. { return c->getTemporaryByName(name); }
  3564. virtual IConstWUResultIterator & getTemporaries() const
  3565. { return c->getTemporaries(); }
  3566. virtual IConstWUResult * getVariableByName(const char * name) const
  3567. { return c->getVariableByName(name); }
  3568. virtual IConstWUResultIterator & getVariables() const
  3569. { return c->getVariables(); }
  3570. virtual bool isProtected() const
  3571. { return c->isProtected(); }
  3572. virtual bool isPausing() const
  3573. { return c->isPausing(); }
  3574. virtual IWorkUnit & lock()
  3575. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3576. virtual bool reload()
  3577. { UNIMPLEMENTED; }
  3578. virtual void subscribe(WUSubscribeOptions options)
  3579. { c->subscribe(options); }
  3580. virtual void requestAbort()
  3581. { c->requestAbort(); }
  3582. virtual unsigned calculateHash(unsigned prevHash)
  3583. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3584. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3585. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3586. virtual IPropertyTree *queryPTree() const
  3587. { return queryExtendedWU(c)->queryPTree(); }
  3588. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3589. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3590. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3591. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3592. virtual unsigned queryFileUsage(const char *filename) const
  3593. { return c->queryFileUsage(filename); }
  3594. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3595. { return c->getFieldUsage(); }
  3596. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3597. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3598. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3599. { return c->getTimeScheduled(val); }
  3600. virtual unsigned getDebugAgentListenerPort() const
  3601. { return c->getDebugAgentListenerPort(); }
  3602. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3603. { return c->getDebugAgentListenerIP(ip); }
  3604. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3605. { return c->getXmlParams(params, hidePasswords); }
  3606. virtual const IPropertyTree *getXmlParams() const
  3607. { return c->getXmlParams(); }
  3608. virtual unsigned __int64 getHash() const
  3609. { return c->getHash(); }
  3610. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3611. { return c->getLogs(type, instance); }
  3612. virtual IStringIterator *getProcesses(const char *type) const
  3613. { return c->getProcesses(type); }
  3614. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3615. { return c->getProcesses(type, instance); }
  3616. virtual unsigned getTotalThorTime() const
  3617. { return c->getTotalThorTime(); }
  3618. virtual WUGraphState queryGraphState(const char *graphName) const
  3619. { return c->queryGraphState(graphName); }
  3620. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3621. { return c->queryNodeState(graphName, nodeId); }
  3622. virtual void setGraphState(const char *graphName, WUGraphState state) const
  3623. { c->setGraphState(graphName, state); }
  3624. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3625. { c->setNodeState(graphName, nodeId, state); }
  3626. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3627. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3628. virtual void clearGraphProgress() const
  3629. { c->clearGraphProgress(); }
  3630. virtual IStringVal & getAbortBy(IStringVal & str) const
  3631. { return c->getAbortBy(str); }
  3632. virtual unsigned __int64 getAbortTimeStamp() const
  3633. { return c->getAbortTimeStamp(); }
  3634. virtual void clearExceptions()
  3635. { c->clearExceptions(); }
  3636. virtual void commit()
  3637. { c->commit(); }
  3638. virtual IWUException * createException()
  3639. { return c->createException(); }
  3640. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3641. { c->addProcess(type, instance, pid, log); }
  3642. virtual void protect(bool protectMode)
  3643. { c->protect(protectMode); }
  3644. virtual void setAction(WUAction action)
  3645. { c->setAction(action); }
  3646. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3647. { c->setApplicationValue(application, propname, value, overwrite); }
  3648. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3649. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3650. virtual void incEventScheduledCount()
  3651. { c->incEventScheduledCount(); }
  3652. virtual void setIsQueryService(bool value)
  3653. { c->setIsQueryService(value); }
  3654. virtual void setCloneable(bool value)
  3655. { c->setCloneable(value); }
  3656. virtual void setIsClone(bool value)
  3657. { c->setIsClone(value); }
  3658. virtual void setClusterName(const char * value)
  3659. { c->setClusterName(value); }
  3660. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3661. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3662. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3663. { c->setDebugValue(propname, value, overwrite); }
  3664. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3665. { c->setDebugValueInt(propname, value, overwrite); }
  3666. virtual void setJobName(const char * value)
  3667. { c->setJobName(value); }
  3668. virtual void setPriority(WUPriorityClass cls)
  3669. { c->setPriority(cls); }
  3670. virtual void setPriorityLevel(int level)
  3671. { c->setPriorityLevel(level); }
  3672. virtual void setRescheduleFlag(bool value)
  3673. { c->setRescheduleFlag(value); }
  3674. virtual void setResultLimit(unsigned value)
  3675. { c->setResultLimit(value); }
  3676. virtual void setState(WUState state)
  3677. { c->setState(state); }
  3678. virtual void setStateEx(const char * text)
  3679. { c->setStateEx(text); }
  3680. virtual void setAgentSession(__int64 sessionId)
  3681. { c->setAgentSession(sessionId); }
  3682. 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)
  3683. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3684. virtual void setTracingValue(const char * propname, const char * value)
  3685. { c->setTracingValue(propname, value); }
  3686. virtual void setTracingValueInt(const char * propname, int value)
  3687. { c->setTracingValueInt(propname, value); }
  3688. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3689. { c->setTracingValueInt64(propname, value); }
  3690. virtual void setUser(const char * value)
  3691. { c->setUser(value); }
  3692. virtual void setWuScope(const char * value)
  3693. { c->setWuScope(value); }
  3694. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3695. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3696. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3697. { c->syncRuntimeWorkflow(array); }
  3698. virtual IWorkflowItemIterator * updateWorkflowItems()
  3699. { return c->updateWorkflowItems(); }
  3700. virtual void resetWorkflow()
  3701. { c->resetWorkflow(); }
  3702. virtual void schedule()
  3703. { c->schedule(); }
  3704. virtual void deschedule()
  3705. { c->deschedule(); }
  3706. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3707. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3708. virtual IWUResult * updateGlobalByName(const char * name)
  3709. { return c->updateGlobalByName(name); }
  3710. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3711. { c->createGraph(name, label, type, xgmml, wfid); }
  3712. virtual IWUQuery * updateQuery()
  3713. { return c->updateQuery(); }
  3714. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3715. { return c->updateWebServicesInfo(create); }
  3716. virtual IWUPlugin * updatePluginByName(const char * name)
  3717. { return c->updatePluginByName(name); }
  3718. virtual IWULibrary * updateLibraryByName(const char * name)
  3719. { return c->updateLibraryByName(name); }
  3720. virtual IWUResult * updateResultByName(const char * name)
  3721. { return c->updateResultByName(name); }
  3722. virtual IWUResult * updateResultBySequence(unsigned seq)
  3723. { return c->updateResultBySequence(seq); }
  3724. virtual IWUResult * updateTemporaryByName(const char * name)
  3725. { return c->updateTemporaryByName(name); }
  3726. virtual IWUResult * updateVariableByName(const char * name)
  3727. { return c->updateVariableByName(name); }
  3728. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3729. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3730. virtual void noteFileRead(IDistributedFile *file)
  3731. { c->noteFileRead(file); }
  3732. virtual void noteFieldUsage(IPropertyTree * usage)
  3733. { c->noteFieldUsage(usage); }
  3734. virtual void releaseFile(const char *fileName)
  3735. { c->releaseFile(fileName); }
  3736. virtual void resetBeforeGeneration()
  3737. { c->resetBeforeGeneration(); }
  3738. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3739. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3740. virtual void deleteTemporaries()
  3741. { c->deleteTemporaries(); }
  3742. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3743. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3744. virtual IPropertyTree * getDiskUsageStats()
  3745. { return c->getDiskUsageStats(); }
  3746. virtual IPropertyTreeIterator & getFileIterator() const
  3747. { return c->getFileIterator(); }
  3748. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3749. { return c->getFilesReadIterator(); }
  3750. virtual void setSnapshot(const char * value)
  3751. { c->setSnapshot(value); }
  3752. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3753. { c->setWarningSeverity(code, severity); }
  3754. virtual void setTimeScheduled(const IJlibDateTime &val)
  3755. { c->setTimeScheduled(val); }
  3756. virtual void setDebugAgentListenerPort(unsigned port)
  3757. { c->setDebugAgentListenerPort(port); }
  3758. virtual void setDebugAgentListenerIP(const char * ip)
  3759. { c->setDebugAgentListenerIP(ip); }
  3760. virtual void setXmlParams(const char *params)
  3761. { c->setXmlParams(params); }
  3762. virtual void setXmlParams(IPropertyTree *tree)
  3763. { c->setXmlParams(tree); }
  3764. virtual void setHash(unsigned __int64 hash)
  3765. { c->setHash(hash); }
  3766. // ILocalWorkUnit - used for debugging etc
  3767. virtual void serialize(MemoryBuffer &tgt)
  3768. { c->serialize(tgt); }
  3769. virtual void deserialize(MemoryBuffer &src)
  3770. { c->deserialize(src); }
  3771. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3772. { return c->switchThorQueue(cluster,qs); }
  3773. virtual void setAllowedClusters(const char *value)
  3774. { c->setAllowedClusters(value); }
  3775. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3776. { return c->getAllowedClusters(str); }
  3777. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3778. { c->remoteCheckAccess(user,writeaccess); }
  3779. virtual void setAllowAutoQueueSwitch(bool val)
  3780. { c->setAllowAutoQueueSwitch(val); }
  3781. virtual bool getAllowAutoQueueSwitch() const
  3782. { return c->getAllowAutoQueueSwitch(); }
  3783. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3784. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3785. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3786. { c->setResultInt(name, sequence, val); }
  3787. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3788. { c->setResultUInt(name, sequence, val); }
  3789. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3790. { c->setResultReal(name, sequence, val); }
  3791. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3792. { c->setResultVarString(stepname, sequence, val); }
  3793. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3794. { c->setResultVarUnicode(stepname, sequence, val); }
  3795. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3796. { c->setResultString(stepname, sequence, len, val); }
  3797. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3798. { c->setResultData(stepname, sequence, len, val); }
  3799. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3800. { c->setResultRaw(name, sequence, len, val); }
  3801. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3802. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3803. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3804. { c->setResultUnicode(name, sequence, len, val); }
  3805. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3806. { c->setResultBool(name, sequence, val); }
  3807. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3808. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3809. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3810. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3811. };
  3812. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3813. {
  3814. Owned<IPropertyTree> p;
  3815. public:
  3816. IMPLEMENT_IINTERFACE;
  3817. CLocalWUAssociated(IPropertyTree *p);
  3818. virtual WUFileType getType() const;
  3819. virtual IStringVal & getDescription(IStringVal & ret) const;
  3820. virtual IStringVal & getIp(IStringVal & ret) const;
  3821. virtual IStringVal & getName(IStringVal & ret) const;
  3822. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3823. virtual unsigned getCrc() const;
  3824. virtual unsigned getMinActivityId() const;
  3825. virtual unsigned getMaxActivityId() const;
  3826. };
  3827. class CLocalWUQuery : implements IWUQuery, public CInterface
  3828. {
  3829. Owned<IPropertyTree> p;
  3830. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3831. mutable CriticalSection crit;
  3832. mutable bool associatedCached;
  3833. private:
  3834. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3835. void loadAssociated() const;
  3836. public:
  3837. IMPLEMENT_IINTERFACE;
  3838. CLocalWUQuery(IPropertyTree *p);
  3839. virtual WUQueryType getQueryType() const;
  3840. virtual IStringVal& getQueryText(IStringVal &str) const;
  3841. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3842. virtual IStringVal& getQueryName(IStringVal &str) const;
  3843. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3844. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3845. virtual unsigned getQueryDllCrc() const;
  3846. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3847. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3848. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3849. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3850. virtual bool isArchive() const;
  3851. virtual bool hasArchive() const
  3852. {
  3853. return p->getPropBool("@hasArchive");
  3854. }
  3855. virtual void setQueryType(WUQueryType qt);
  3856. virtual void setQueryText(const char *pstr);
  3857. virtual void setQueryName(const char *);
  3858. virtual void setQueryMainDefinition(const char * str);
  3859. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  3860. virtual void removeAssociatedFiles();
  3861. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  3862. };
  3863. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  3864. {
  3865. Owned<IPropertyTree> p;
  3866. mutable CriticalSection crit;
  3867. private:
  3868. public:
  3869. IMPLEMENT_IINTERFACE;
  3870. CLocalWUWebServicesInfo(IPropertyTree *p);
  3871. virtual IStringVal& getModuleName(IStringVal &str) const;
  3872. virtual IStringVal& getAttributeName(IStringVal &str) const;
  3873. virtual IStringVal& getDefaultName(IStringVal &str) const;
  3874. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  3875. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  3876. virtual unsigned getWebServicesCRC() const;
  3877. virtual void setModuleName(const char *);
  3878. virtual void setAttributeName(const char *);
  3879. virtual void setDefaultName(const char *);
  3880. virtual void setInfo(const char *name, const char *info);
  3881. virtual void setText(const char *name, const char *info);
  3882. virtual void setWebServicesCRC(unsigned);
  3883. };
  3884. class CLocalWUResult : implements IWUResult, public CInterface
  3885. {
  3886. friend class CLocalWorkUnit;
  3887. mutable CriticalSection crit;
  3888. Owned<IPropertyTree> p;
  3889. Owned<IProperties> xmlns;
  3890. public:
  3891. IMPLEMENT_IINTERFACE;
  3892. CLocalWUResult(IPropertyTree *props);
  3893. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  3894. virtual WUResultStatus getResultStatus() const;
  3895. virtual IStringVal& getResultName(IStringVal &str) const;
  3896. virtual int getResultSequence() const;
  3897. virtual bool isResultScalar() const;
  3898. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  3899. virtual unsigned getResultFetchSize() const;
  3900. virtual __int64 getResultTotalRowCount() const;
  3901. virtual __int64 getResultRowCount() const;
  3902. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  3903. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  3904. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  3905. virtual unsigned getResultRequestedRows() const;
  3906. virtual __int64 getResultInt() const;
  3907. virtual bool getResultBool() const;
  3908. virtual double getResultReal() const;
  3909. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  3910. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3911. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  3912. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  3913. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  3914. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3915. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3916. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  3917. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  3918. virtual __int64 getResultRowLimit() const;
  3919. virtual IStringVal& getResultFilename(IStringVal & str) const;
  3920. virtual WUResultFormat getResultFormat() const;
  3921. virtual unsigned getResultHash() const;
  3922. virtual bool getResultIsAll() const;
  3923. virtual IProperties *queryResultXmlns();
  3924. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  3925. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  3926. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  3927. // interface IWUResult
  3928. virtual void setResultStatus(WUResultStatus status);
  3929. virtual void setResultName(const char *name);
  3930. virtual void setResultSequence(unsigned seq);
  3931. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  3932. virtual void setResultScalar(bool isScalar);
  3933. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  3934. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  3935. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  3936. virtual void setResultRowCount(__int64 rows);
  3937. virtual void setResultDataset(const char *ecl, const char *defs);
  3938. virtual void setResultLogicalName(const char *logicalName);
  3939. virtual void setResultKeyField(const char * name);
  3940. virtual void setResultRequestedRows(unsigned req);
  3941. virtual void setResultRecordSizeEntry(const char * val);
  3942. virtual void setResultTransformerEntry(const char * val);
  3943. virtual void setResultInt(__int64 val);
  3944. virtual void setResultReal(double val);
  3945. virtual void setResultBool(bool val);
  3946. virtual void setResultString(const char * val, unsigned length);
  3947. virtual void setResultUnicode(const void * val, unsigned length);
  3948. virtual void setResultData(const void * val, unsigned length);
  3949. virtual void setResultDecimal(const void * val, unsigned length);
  3950. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  3951. virtual void setResultRowLimit(__int64 value);
  3952. virtual void setResultFilename(const char * name);
  3953. virtual void setResultUInt(unsigned __int64 val);
  3954. virtual void setResultIsAll(bool value);
  3955. virtual void setResultFormat(WUResultFormat format);
  3956. virtual void setResultXML(const char *val);
  3957. virtual void setResultRow(unsigned len, const void * data);
  3958. virtual void setResultXmlns(const char *prefix, const char *uri);
  3959. virtual void setResultFieldOpt(const char *name, const char *value);
  3960. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  3961. virtual IPropertyTree *queryPTree() { return p; }
  3962. };
  3963. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  3964. {
  3965. Owned<IPropertyTree> p;
  3966. public:
  3967. IMPLEMENT_IINTERFACE;
  3968. CLocalWUPlugin(IPropertyTree *p);
  3969. virtual IStringVal& getPluginName(IStringVal &str) const;
  3970. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  3971. virtual void setPluginName(const char *str);
  3972. virtual void setPluginVersion(const char *str);
  3973. };
  3974. class CLocalWULibrary : implements IWULibrary, public CInterface
  3975. {
  3976. Owned<IPropertyTree> p;
  3977. public:
  3978. IMPLEMENT_IINTERFACE;
  3979. CLocalWULibrary(IPropertyTree *p);
  3980. virtual IStringVal & getName(IStringVal & str) const;
  3981. virtual void setName(const char * str);
  3982. };
  3983. class CLocalWUException : implements IWUException, public CInterface
  3984. {
  3985. Owned<IPropertyTree> p;
  3986. public:
  3987. IMPLEMENT_IINTERFACE;
  3988. CLocalWUException(IPropertyTree *p);
  3989. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  3990. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  3991. virtual unsigned getExceptionCode() const override;
  3992. virtual ErrorSeverity getSeverity() const override;
  3993. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  3994. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  3995. virtual unsigned getExceptionLineNo() const override;
  3996. virtual unsigned getExceptionColumn() const override;
  3997. virtual unsigned getActivityId() const override;
  3998. virtual unsigned getSequence() const override;
  3999. virtual const char * queryScope() const override;
  4000. virtual unsigned getPriority() const override;
  4001. virtual void setExceptionSource(const char *str) override;
  4002. virtual void setExceptionMessage(const char *str) override;
  4003. virtual void setExceptionCode(unsigned code) override;
  4004. virtual void setSeverity(ErrorSeverity level) override;
  4005. virtual void setTimeStamp(const char * dt) override;
  4006. virtual void setExceptionFileName(const char *str) override;
  4007. virtual void setExceptionLineNo(unsigned r) override;
  4008. virtual void setExceptionColumn(unsigned c) override;
  4009. virtual void setActivityId(unsigned _id) override;
  4010. virtual void setScope(const char * _scope) override;
  4011. virtual void setPriority(unsigned _priority) override;
  4012. };
  4013. //==========================================================================================
  4014. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4015. {
  4016. switch ((int) sequence)
  4017. {
  4018. case ResultSequenceInternal:
  4019. case ResultSequenceOnce:
  4020. case ResultSequencePersist:
  4021. case ResultSequenceStored:
  4022. return true;
  4023. default:
  4024. assertex(sequence <= INT_MAX);
  4025. if ((int) sequence >= LibraryBaseSequence)
  4026. return true;
  4027. return false;
  4028. }
  4029. }
  4030. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4031. {
  4032. unsigned curTreeNum;
  4033. IArrayOf<IPropertyTree> trees;
  4034. Owned<IConstWorkUnitInfo> cur;
  4035. void setCurrent()
  4036. {
  4037. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4038. }
  4039. public:
  4040. IMPLEMENT_IINTERFACE;
  4041. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4042. {
  4043. ForEachItemIn(t, _trees)
  4044. trees.append(*LINK(&_trees.item(t)));
  4045. curTreeNum = 0;
  4046. }
  4047. bool first()
  4048. {
  4049. curTreeNum = 0;
  4050. return next();
  4051. }
  4052. bool isValid()
  4053. {
  4054. return (NULL != cur.get());
  4055. }
  4056. bool next()
  4057. {
  4058. if (curTreeNum >= trees.ordinality())
  4059. {
  4060. cur.clear();
  4061. return false;
  4062. }
  4063. setCurrent();
  4064. ++curTreeNum;
  4065. return true;
  4066. }
  4067. IConstWorkUnitInfo & query() { return *cur; }
  4068. };
  4069. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4070. {
  4071. Owned<IPropertyTree> p;
  4072. public:
  4073. IMPLEMENT_IINTERFACE;
  4074. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4075. virtual const char * queryName() const { return p->queryProp("@name"); }
  4076. };
  4077. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4078. {
  4079. public:
  4080. IMPLEMENT_IINTERFACE;
  4081. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4082. bool first() override { return iter->first(); }
  4083. bool isValid() override { return iter->isValid(); }
  4084. bool next() override { return iter->next(); }
  4085. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4086. private:
  4087. Owned<IPropertyTreeIterator> iter;
  4088. };
  4089. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4090. {
  4091. Owned<IPropertyTree> p;
  4092. public:
  4093. IMPLEMENT_IINTERFACE;
  4094. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4095. virtual const char * queryName() const { return p->queryProp("@name"); }
  4096. virtual const char * queryType() const { return p->queryProp("@type"); }
  4097. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4098. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4099. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4100. };
  4101. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4102. {
  4103. public:
  4104. IMPLEMENT_IINTERFACE;
  4105. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4106. bool first() override { return iter->first(); }
  4107. bool isValid() override { return iter->isValid(); }
  4108. bool next() override { return iter->next(); }
  4109. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4110. private:
  4111. Owned<IPropertyTreeIterator> iter;
  4112. };
  4113. //==========================================================================================
  4114. class CStringArrayIterator : implements IStringIterator, public CInterface
  4115. {
  4116. unsigned idx;
  4117. StringArray strings;
  4118. public:
  4119. IMPLEMENT_IINTERFACE;
  4120. CStringArrayIterator() { idx = 0; };
  4121. void append(const char *str) { strings.append(str); }
  4122. virtual bool first() { idx = 0; return strings.isItem(idx); }
  4123. virtual bool next() { idx ++; return strings.isItem(idx); }
  4124. virtual bool isValid() { return strings.isItem(idx); }
  4125. virtual IStringVal & str(IStringVal &s) { s.set(strings.item(idx)); return s; }
  4126. };
  4127. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4128. {
  4129. Owned<IPropertyTreeIterator> it;
  4130. public:
  4131. IMPLEMENT_IINTERFACE;
  4132. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4133. virtual bool first() { return it->first(); }
  4134. virtual bool next() { return it->next(); }
  4135. virtual bool isValid() { return it->isValid(); }
  4136. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4137. };
  4138. class CEmptyStringIterator : implements IStringIterator, public CInterface
  4139. {
  4140. public:
  4141. IMPLEMENT_IINTERFACE;
  4142. virtual bool first() { return false; }
  4143. virtual bool next() { return false; }
  4144. virtual bool isValid() { return false; }
  4145. virtual IStringVal & str(IStringVal &s) { s.clear(); return s; }
  4146. };
  4147. EnumMapping workunitSortFields[] =
  4148. {
  4149. { WUSFuser, "@submitID" },
  4150. { WUSFcluster, "@clusterName" },
  4151. { WUSFjob, "@jobName" },
  4152. { WUSFstate, "@state" },
  4153. { WUSFpriority, "@priorityClass" },
  4154. { WUSFprotected, "@protected" },
  4155. { WUSFwuid, "@" },
  4156. { WUSFecl, "Query/ShortText" },
  4157. { WUSFfileread, "FilesRead/File/@name" },
  4158. { WUSFtotalthortime, "@totalThorTime|"
  4159. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4160. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4161. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4162. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4163. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4164. },
  4165. { WUSFwuidhigh, "@" },
  4166. { WUSFwildwuid, "@" },
  4167. { WUSFappvalue, "Application" },
  4168. { WUSFfilewritten, "Files/File/@name" },
  4169. { WUSFterm, NULL }
  4170. };
  4171. extern const char *queryFilterXPath(WUSortField field)
  4172. {
  4173. return getEnumText(field, workunitSortFields);
  4174. }
  4175. EnumMapping querySortFields[] =
  4176. {
  4177. { WUQSFId, "@id" },
  4178. { WUQSFwuid, "@wuid" },
  4179. { WUQSFname, "@name" },
  4180. { WUQSFdll, "@dll" },
  4181. { WUQSFmemoryLimit, "@memoryLimit" },
  4182. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4183. { WUQSFtimeLimit, "@timeLimit" },
  4184. { WUQSFtimeLimitHi, "@timeLimit" },
  4185. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4186. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4187. { WUQSFpriority, "@priority" },
  4188. { WUQSFpriorityHi, "@priority" },
  4189. { WUQSFQuerySet, "@querySetId" },
  4190. { WUQSFActivited, "@activated" },
  4191. { WUQSFSuspendedByUser, "@suspended" },
  4192. { WUQSFLibrary, "Library"},
  4193. { WUQSFPublishedBy, "@publishedBy" },
  4194. { WUQSFterm, NULL }
  4195. };
  4196. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4197. {
  4198. StringAttr name;
  4199. public:
  4200. IMPLEMENT_IINTERFACE;
  4201. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4202. {
  4203. }
  4204. void execute()
  4205. {
  4206. PROGLOG("WU removeDll %s", name.get());
  4207. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4208. }
  4209. };
  4210. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4211. {
  4212. RemoteFilename name;
  4213. public:
  4214. IMPLEMENT_IINTERFACE;
  4215. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4216. {
  4217. SocketEndpoint ep(_ip);
  4218. name.setPath(ep, _name);
  4219. }
  4220. void execute()
  4221. {
  4222. Owned<IFile> file = createIFile(name);
  4223. PROGLOG("WU removeDll %s",file->queryFilename());
  4224. file->remove();
  4225. }
  4226. };
  4227. //==========================================================================================
  4228. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4229. {
  4230. unsigned index;
  4231. IArrayOf<IPropertyTree> trees;
  4232. public:
  4233. IMPLEMENT_IINTERFACE;
  4234. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4235. {
  4236. ForEachItemIn(t, _trees)
  4237. trees.append(*LINK(&_trees.item(t)));
  4238. index = 0;
  4239. }
  4240. ~CConstQuerySetQueryIterator()
  4241. {
  4242. trees.kill();
  4243. }
  4244. bool first()
  4245. {
  4246. index = 0;
  4247. return (trees.ordinality()!=0);
  4248. }
  4249. bool next()
  4250. {
  4251. index++;
  4252. return (index<trees.ordinality());
  4253. }
  4254. bool isValid()
  4255. {
  4256. return (index<trees.ordinality());
  4257. }
  4258. IPropertyTree &query()
  4259. {
  4260. return trees.item(index);
  4261. }
  4262. };
  4263. class CSecurityCache
  4264. {
  4265. };
  4266. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4267. {
  4268. public:
  4269. IMPLEMENT_IINTERFACE;
  4270. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4271. : ptreeIter(_ptreeIter)
  4272. {
  4273. }
  4274. bool first()
  4275. {
  4276. if (!ptreeIter->first())
  4277. {
  4278. cur.clear();
  4279. return false;
  4280. }
  4281. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4282. return true;
  4283. }
  4284. bool isValid()
  4285. {
  4286. return (NULL != cur.get());
  4287. }
  4288. bool next()
  4289. {
  4290. if (!ptreeIter->next())
  4291. {
  4292. cur.clear();
  4293. return false;
  4294. }
  4295. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4296. return true;
  4297. }
  4298. IConstWorkUnitInfo & query() { return *cur; }
  4299. private:
  4300. Owned<IConstWorkUnitInfo> cur;
  4301. Owned<IPropertyTreeIterator> ptreeIter;
  4302. };
  4303. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4304. {
  4305. public:
  4306. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4307. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4308. {
  4309. assertex(_secuser && _secmgr);
  4310. }
  4311. bool first()
  4312. {
  4313. if (!parent->first())
  4314. return false;
  4315. return getNext();
  4316. }
  4317. bool next()
  4318. {
  4319. if (!parent->next())
  4320. return false;
  4321. return getNext();
  4322. }
  4323. virtual bool isValid()
  4324. {
  4325. return parent->isValid();
  4326. }
  4327. virtual IConstWorkUnitInfo &query()
  4328. {
  4329. return parent->query();
  4330. }
  4331. private:
  4332. Owned<IConstWorkUnitIterator> parent;
  4333. MapStringTo<int> scopePermissions;
  4334. Linked<ISecManager> secmgr;
  4335. Linked<ISecUser> secuser;
  4336. bool getNext() // scan for a workunit with permissions
  4337. {
  4338. do
  4339. {
  4340. const char *scopeName = parent->query().queryWuScope();
  4341. if (!scopeName || !*scopeName || checkScope(scopeName))
  4342. return true;
  4343. } while (parent->next());
  4344. return false;
  4345. }
  4346. bool checkScope(const char *scopeName)
  4347. {
  4348. int *perms = scopePermissions.getValue(scopeName);
  4349. SecAccessFlags perm;
  4350. if (!perms)
  4351. {
  4352. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4353. scopePermissions.setValue(scopeName, perm);
  4354. }
  4355. else
  4356. perm = (SecAccessFlags)*perms;
  4357. return perm >= SecAccess_Read;
  4358. }
  4359. };
  4360. CWorkUnitFactory::CWorkUnitFactory()
  4361. {
  4362. }
  4363. CWorkUnitFactory::~CWorkUnitFactory()
  4364. {
  4365. }
  4366. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4367. {
  4368. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4369. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4370. if (scope)
  4371. 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...
  4372. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4373. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4374. ret->setDebugValue("CREATED_BY", app, true);
  4375. ret->setDebugValue("CREATED_FOR", scope, true);
  4376. return ret;
  4377. }
  4378. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4379. {
  4380. StringBuffer wuid("W");
  4381. char result[32];
  4382. time_t ltime;
  4383. time( &ltime );
  4384. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4385. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4386. wuid.append(result);
  4387. if (workUnitTraceLevel > 1)
  4388. PrintLog("createWorkUnit created %s", wuid.str());
  4389. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4390. if (workUnitTraceLevel > 1)
  4391. PrintLog("createWorkUnit created %s", ret->queryWuid());
  4392. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4393. return ret;
  4394. }
  4395. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4396. {
  4397. if (workUnitTraceLevel > 1)
  4398. PrintLog("deleteWorkUnit %s", wuid);
  4399. StringBuffer wuRoot;
  4400. getXPath(wuRoot, wuid);
  4401. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4402. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4403. return false;
  4404. if (throwException)
  4405. cw->cleanupAndDelete(true, true);
  4406. else
  4407. {
  4408. try
  4409. {
  4410. cw->cleanupAndDelete(true, true);
  4411. }
  4412. catch (IException *E)
  4413. {
  4414. StringBuffer s;
  4415. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4416. E->Release();
  4417. return false;
  4418. }
  4419. }
  4420. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4421. return true;
  4422. }
  4423. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4424. {
  4425. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4426. }
  4427. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4428. {
  4429. StringBuffer wuidStr(wuid);
  4430. wuidStr.trim();
  4431. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4432. wuidStr.setCharAt(0, 'W');
  4433. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4434. {
  4435. if (workUnitTraceLevel > 1)
  4436. PrintLog("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4437. return NULL;
  4438. }
  4439. if (workUnitTraceLevel > 1)
  4440. PrintLog("openWorkUnit %s", wuidStr.str());
  4441. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4442. if (wu)
  4443. {
  4444. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4445. return NULL; // Actually throws exception on failure, so won't reach here
  4446. return wu.getClear();
  4447. }
  4448. else
  4449. {
  4450. if (workUnitTraceLevel > 0)
  4451. PrintLog("openWorkUnit %s not found", wuidStr.str());
  4452. return NULL;
  4453. }
  4454. }
  4455. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4456. {
  4457. if (workUnitTraceLevel > 1)
  4458. PrintLog("updateWorkUnit %s", wuid);
  4459. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4460. if (wu)
  4461. {
  4462. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4463. return NULL;
  4464. return &wu->lockRemote(false);
  4465. }
  4466. else
  4467. {
  4468. if (workUnitTraceLevel > 0)
  4469. PrintLog("updateWorkUnit %s not found", wuid);
  4470. return NULL;
  4471. }
  4472. }
  4473. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4474. {
  4475. Owned<IPropertyTree> ret;
  4476. IPropertyTree * branch = from->queryPropTree(xpath);
  4477. if(branch)
  4478. {
  4479. ret.setown(createPTreeFromIPT(branch));
  4480. from->removeTree(branch);
  4481. }
  4482. return ret.getClear();
  4483. }
  4484. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4485. {
  4486. StringBuffer path(base);
  4487. addPathSepChar(path).append(wuid).append(".xml");
  4488. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4489. if (!pt)
  4490. return false;
  4491. CDateTime dt;
  4492. dt.setNow();
  4493. StringBuffer dts;
  4494. dt.getString(dts);
  4495. pt->setProp("@restoredDate", dts.str());
  4496. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4497. Owned<IPropertyTree> associatedFiles;
  4498. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4499. if (srcAssociated)
  4500. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4501. // The updating of the repo is implementation specific...
  4502. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4503. return false;
  4504. // now kludge back GeneratedDlls
  4505. if (generatedDlls)
  4506. {
  4507. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4508. for(dlls->first(); dlls->isValid(); dlls->next())
  4509. {
  4510. IPropertyTree & dll = dlls->query();
  4511. char const * name = dll.queryProp("@name");
  4512. char const * kind = dll.queryProp("@kind");
  4513. char const * location = dll.queryProp("@location");
  4514. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4515. if (!got)
  4516. {
  4517. RemoteFilename dstRfn;
  4518. dstRfn.setRemotePath(location);
  4519. StringBuffer srcPath(base);
  4520. addPathSepChar(srcPath);
  4521. dstRfn.getTail(srcPath);
  4522. OwnedIFile srcFile = createIFile(srcPath);
  4523. OwnedIFile dstFile = createIFile(dstRfn);
  4524. copyFile(dstFile, srcFile);
  4525. queryDllServer().registerDll(name, kind, location);
  4526. }
  4527. }
  4528. }
  4529. if (associatedFiles)
  4530. {
  4531. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4532. ForEach(*associated)
  4533. {
  4534. IPropertyTree &file = associated->query();
  4535. const char *filename = file.queryProp("@filename");
  4536. SocketEndpoint ep(file.queryProp("@ip"));
  4537. RemoteFilename rfn;
  4538. rfn.setPath(ep, filename);
  4539. OwnedIFile dstFile = createIFile(rfn);
  4540. StringBuffer srcPath(base), name;
  4541. addPathSepChar(srcPath);
  4542. rfn.getTail(name);
  4543. srcPath.append(name);
  4544. if (generatedDlls)
  4545. {
  4546. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4547. if (generatedDlls->hasProp(gDllPath))
  4548. continue; // generated dlls handled separately - see above
  4549. }
  4550. OwnedIFile srcFile = createIFile(srcPath);
  4551. if (srcFile->exists())
  4552. {
  4553. try
  4554. {
  4555. copyFile(dstFile, srcFile);
  4556. }
  4557. catch (IException *e)
  4558. {
  4559. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4560. EXCLOG(e, msg.str());
  4561. e->Release();
  4562. }
  4563. }
  4564. }
  4565. }
  4566. return true;
  4567. }
  4568. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4569. {
  4570. if (newLevel)
  4571. PrintLog("Setting workunit trace level to %d", newLevel);
  4572. int level = workUnitTraceLevel;
  4573. workUnitTraceLevel = newLevel;
  4574. return level;
  4575. }
  4576. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4577. {
  4578. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4579. if(!conn) return;
  4580. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4581. KeptAtomTable entries;
  4582. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4583. StringBuffer wuid;
  4584. for(iter->first(); iter->isValid(); iter->next())
  4585. {
  4586. char const * entry = iter->query().queryName();
  4587. if(!entries.find(entry))
  4588. {
  4589. entries.addAtom(entry);
  4590. ncnameUnescape(entry, wuid.clear());
  4591. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4592. if(wu && (wu->getState() == WUStateWait))
  4593. wu->setState(WUStateCompleted);
  4594. }
  4595. }
  4596. bool more;
  4597. do more = root->removeProp("*"); while(more);
  4598. }
  4599. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4600. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4601. const void *filterbuf, // (appended) string values for filters
  4602. unsigned startoffset,
  4603. unsigned maxnum,
  4604. __int64 *cachehint,
  4605. unsigned *total,
  4606. const MapStringTo<bool> *_subset)
  4607. {
  4608. struct PostFilters
  4609. {
  4610. WUQueryFilterBoolean activatedFilter;
  4611. WUQueryFilterBoolean suspendedByUserFilter;
  4612. PostFilters()
  4613. {
  4614. activatedFilter = WUQFSAll;
  4615. suspendedByUserFilter = WUQFSAll;
  4616. };
  4617. } postFilters;
  4618. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4619. {
  4620. StringAttr querySet;
  4621. StringAttr xPath;
  4622. StringAttr sortOrder;
  4623. PostFilters postFilters;
  4624. StringArray unknownAttributes;
  4625. const MapStringTo<bool> *subset;
  4626. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4627. {
  4628. const char* querySetId = querySetTree->queryProp("@id");
  4629. VStringBuffer path("Query%s", xPath.get());
  4630. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4631. ForEach(*iter)
  4632. {
  4633. IPropertyTree &query = iter->query();
  4634. bool activated = false;
  4635. const char* queryId = query.queryProp("@id");
  4636. if (queryId && *queryId)
  4637. {
  4638. if (subset)
  4639. {
  4640. VStringBuffer match("%s/%s", querySetId, queryId);
  4641. if (!subset->getValue(match))
  4642. continue;
  4643. }
  4644. VStringBuffer aliasXPath("Alias[@id='%s']", queryId);
  4645. IPropertyTree *alias = querySetTree->queryPropTree(aliasXPath.str());
  4646. if (alias)
  4647. activated = true;
  4648. }
  4649. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4650. continue;
  4651. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4652. continue;
  4653. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4654. continue;
  4655. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4656. continue;
  4657. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4658. queryWithSetId->setProp("@querySetId", querySetId);
  4659. queryWithSetId->setPropBool("@activated", activated);
  4660. }
  4661. }
  4662. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4663. {
  4664. StringBuffer querySetXPath("QuerySets");
  4665. if (!querySet.isEmpty())
  4666. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4667. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4668. if (!conn)
  4669. return NULL;
  4670. if (querySet.isEmpty())
  4671. {
  4672. Owned<IPropertyTreeIterator> querySetIter = conn->queryRoot()->getElements("*");
  4673. ForEach(*querySetIter)
  4674. populateQueryTree(&querySetIter->query(), queryTree);
  4675. }
  4676. else
  4677. populateQueryTree(conn->queryRoot(), queryTree);
  4678. return conn.getClear();
  4679. }
  4680. public:
  4681. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4682. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  4683. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  4684. {
  4685. postFilters.activatedFilter = _postFilters.activatedFilter;
  4686. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  4687. ForEachItemIn(x, _unknownAttributes)
  4688. unknownAttributes.append(_unknownAttributes.item(x));
  4689. }
  4690. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4691. {
  4692. Owned<IPropertyTree> elementTree = createPTree("Queries");
  4693. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  4694. if (!conn)
  4695. return NULL;
  4696. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  4697. if (!iter)
  4698. return NULL;
  4699. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  4700. return conn.getClear();
  4701. }
  4702. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  4703. };
  4704. StringAttr querySet;
  4705. StringBuffer xPath;
  4706. StringBuffer so;
  4707. StringArray unknownAttributes;
  4708. if (filters)
  4709. {
  4710. const char *fv = (const char *)filterbuf;
  4711. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  4712. int fmt = filters[i];
  4713. int subfmt = (fmt&0xff);
  4714. if (subfmt==WUQSFQuerySet)
  4715. querySet.set(fv);
  4716. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  4717. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  4718. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  4719. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  4720. else if (subfmt==WUQSFActivited)
  4721. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  4722. else if (subfmt==WUQSFSuspendedByUser)
  4723. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  4724. else if (!fv || !*fv)
  4725. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  4726. else {
  4727. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  4728. if (fmt&WUQSFnocase)
  4729. xPath.append('?');
  4730. if (fmt&WUQSFnumeric)
  4731. xPath.append('#');
  4732. if (fmt&WUQSFwild)
  4733. xPath.append('~');
  4734. xPath.append('"').append(fv).append("\"]");
  4735. }
  4736. fv = fv + strlen(fv)+1;
  4737. }
  4738. }
  4739. if (sortorder) {
  4740. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  4741. if (so.length())
  4742. so.append(',');
  4743. int fmt = sortorder[i];
  4744. if (fmt&WUQSFreverse)
  4745. so.append('-');
  4746. if (fmt&WUQSFnocase)
  4747. so.append('?');
  4748. if (fmt&WUQSFnumeric)
  4749. so.append('#');
  4750. so.append(getEnumText(fmt&0xff,querySortFields));
  4751. }
  4752. }
  4753. IArrayOf<IPropertyTree> results;
  4754. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  4755. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  4756. return new CConstQuerySetQueryIterator(results);
  4757. }
  4758. bool CWorkUnitFactory::isAborting(const char *wuid) const
  4759. {
  4760. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4761. try
  4762. {
  4763. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4764. if (acon)
  4765. return acon->queryRoot()->getPropInt(NULL) != 0;
  4766. }
  4767. catch (IException *E)
  4768. {
  4769. EXCLOG(E);
  4770. E->Release();
  4771. }
  4772. return false;
  4773. }
  4774. void CWorkUnitFactory::clearAborting(const char *wuid)
  4775. {
  4776. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4777. try
  4778. {
  4779. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4780. if (acon)
  4781. acon->close(true);
  4782. }
  4783. catch (IException *E)
  4784. {
  4785. EXCLOG(E);
  4786. E->Release();
  4787. }
  4788. }
  4789. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  4790. {
  4791. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  4792. bool isEcl = false;
  4793. switch (state)
  4794. {
  4795. case WUStateAborting:
  4796. state = WUStateAborted;
  4797. break;
  4798. case WUStateCompiling:
  4799. isEcl = true;
  4800. // drop into
  4801. default:
  4802. state = WUStateFailed;
  4803. }
  4804. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  4805. wu->setState(state);
  4806. Owned<IWUException> e = wu->createException();
  4807. e->setExceptionCode(isEcl ? 1001 : 1000);
  4808. e->setExceptionMessage(isEcl ? "EclServer terminated unexpectedly" : "Workunit terminated unexpectedly");
  4809. }
  4810. static CriticalSection deleteDllLock;
  4811. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  4812. MODULE_INIT(INIT_PRIORITY_STANDARD)
  4813. {
  4814. return true;
  4815. }
  4816. MODULE_EXIT()
  4817. {
  4818. CriticalBlock b(deleteDllLock);
  4819. if (deleteDllWorkQ)
  4820. ::Release(deleteDllWorkQ);
  4821. deleteDllWorkQ = nullptr;
  4822. }
  4823. static void asyncRemoveDll(const char * name)
  4824. {
  4825. CriticalBlock b(deleteDllLock);
  4826. if (!deleteDllWorkQ)
  4827. deleteDllWorkQ = createWorkQueueThread();
  4828. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  4829. }
  4830. static void asyncRemoveFile(const char * ip, const char * name)
  4831. {
  4832. CriticalBlock b(deleteDllLock);
  4833. if (!deleteDllWorkQ)
  4834. deleteDllWorkQ = createWorkQueueThread();
  4835. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  4836. }
  4837. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  4838. {
  4839. public:
  4840. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  4841. CDaliWorkUnitFactory()
  4842. {
  4843. // Assumes dali client configuration has already been done
  4844. sdsManager = &querySDS();
  4845. session = myProcessSession();
  4846. addShutdownHook(*this);
  4847. }
  4848. ~CDaliWorkUnitFactory()
  4849. {
  4850. removeShutdownHook(*this);
  4851. }
  4852. virtual bool initializeStore()
  4853. {
  4854. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  4855. }
  4856. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  4857. {
  4858. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  4859. }
  4860. virtual unsigned validateRepository(bool fixErrors)
  4861. {
  4862. return 0;
  4863. }
  4864. virtual void deleteRepository(bool recreate)
  4865. {
  4866. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4867. if (conn)
  4868. conn->close(true);
  4869. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  4870. if (conn)
  4871. conn->close(true);
  4872. }
  4873. virtual void createRepository()
  4874. {
  4875. // Nothing to do
  4876. }
  4877. virtual const char *queryStoreType() const
  4878. {
  4879. return "Dali";
  4880. }
  4881. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4882. {
  4883. StringBuffer wuRoot;
  4884. getXPath(wuRoot, wuid);
  4885. IRemoteConnection *conn;
  4886. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  4887. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4888. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  4889. conn->queryRoot()->setProp("@totalThorTime", "");
  4890. return new CDaliWorkUnit(conn, secmgr, secuser);
  4891. }
  4892. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4893. {
  4894. StringBuffer wuRoot;
  4895. getXPath(wuRoot, wuid);
  4896. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  4897. if (conn)
  4898. return new CDaliWorkUnit(conn, secmgr, secuser);
  4899. else
  4900. return NULL;
  4901. }
  4902. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  4903. {
  4904. Owned<IPTree> pt(_pt);
  4905. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  4906. StringBuffer wuRoot;
  4907. getXPath(wuRoot, wuid);
  4908. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4909. if (!conn)
  4910. {
  4911. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  4912. return false;
  4913. }
  4914. IPropertyTree *root = conn->queryRoot();
  4915. if (root->hasChildren())
  4916. {
  4917. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  4918. return false;
  4919. }
  4920. root->setPropTree(NULL, pt.getClear());
  4921. conn.clear();
  4922. // now kludge back GraphProgress
  4923. if (gprogress)
  4924. {
  4925. VStringBuffer xpath("/GraphProgress/%s", wuid);
  4926. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  4927. if (conn)
  4928. {
  4929. IPropertyTree *groot = conn->queryRoot();
  4930. if (groot->hasChildren())
  4931. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  4932. groot->setPropTree(NULL, gprogress.getClear());
  4933. }
  4934. }
  4935. return true;
  4936. }
  4937. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4938. {
  4939. StringBuffer wuRoot;
  4940. getXPath(wuRoot, wuid);
  4941. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4942. if (conn)
  4943. return new CDaliWorkUnit(conn, secmgr, secuser);
  4944. else
  4945. return NULL;
  4946. }
  4947. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  4948. {
  4949. // MORE - should it check security?
  4950. StringBuffer wuRoot;
  4951. getXPath(wuRoot, GLOBAL_WORKUNIT);
  4952. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4953. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4954. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  4955. return &cw->lockRemote(false);
  4956. }
  4957. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  4958. {
  4959. StringBuffer path("*");
  4960. if (owner && *owner)
  4961. path.append("[@submitID=?~\"").append(owner).append("\"]");
  4962. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4963. }
  4964. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4965. {
  4966. StringBuffer path("*");
  4967. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  4968. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4969. }
  4970. virtual void clientShutdown();
  4971. virtual unsigned numWorkUnits()
  4972. {
  4973. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  4974. if (!conn)
  4975. return 0;
  4976. IPropertyTree *root = conn->queryRoot();
  4977. return root->numChildren();
  4978. }
  4979. /**
  4980. * Add a filter to an xpath query, with the appropriate filter flags
  4981. */
  4982. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  4983. {
  4984. query.append('[').append(name).append('=');
  4985. if (flags & WUSFnocase)
  4986. query.append('?');
  4987. if (flags & WUSFwild)
  4988. query.append('~');
  4989. query.append('"').append(value).append("\"]");
  4990. };
  4991. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  4992. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4993. const void *filterbuf, // (appended) string values for filters
  4994. unsigned startoffset,
  4995. unsigned maxnum,
  4996. __int64 *cachehint,
  4997. unsigned *total,
  4998. ISecManager *secmgr,
  4999. ISecUser *secuser)
  5000. {
  5001. class CQueryOrFilter : public CInterface
  5002. {
  5003. unsigned flags;
  5004. StringAttr name;
  5005. StringArray values;
  5006. public:
  5007. IMPLEMENT_IINTERFACE;
  5008. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5009. : flags(_flags), name(_name)
  5010. {
  5011. values.appendListUniq(_value, "|");
  5012. };
  5013. const char* queryName() { return name.get(); };
  5014. unsigned querySearchFlags() { return flags; };
  5015. const StringArray& queryValues() const { return values; };
  5016. };
  5017. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5018. {
  5019. public:
  5020. virtual bool first() override
  5021. {
  5022. curSource = 0;
  5023. while (sources.isItem(curSource))
  5024. {
  5025. if (sources.item(curSource).first())
  5026. return true;
  5027. curSource++;
  5028. }
  5029. return false;
  5030. }
  5031. virtual bool next() override
  5032. {
  5033. if (sources.isItem(curSource))
  5034. {
  5035. if (sources.item(curSource).next())
  5036. return true;
  5037. curSource++;
  5038. while (sources.isItem(curSource))
  5039. {
  5040. if (sources.item(curSource).first())
  5041. return true;
  5042. curSource++;
  5043. }
  5044. }
  5045. return false;
  5046. }
  5047. virtual bool isValid() override
  5048. {
  5049. return sources.isItem(curSource);
  5050. }
  5051. virtual IPropertyTree & query() override
  5052. {
  5053. return sources.item(curSource).query();
  5054. }
  5055. void addSource(IPropertyTreeIterator &source)
  5056. {
  5057. sources.append(source);
  5058. }
  5059. private:
  5060. IArrayOf<IPropertyTreeIterator> sources;
  5061. unsigned curSource = 0;
  5062. };
  5063. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5064. {
  5065. StringAttr xPath;
  5066. StringAttr sortOrder;
  5067. StringAttr nameFilterLo;
  5068. StringAttr nameFilterHi;
  5069. StringArray unknownAttributes;
  5070. Owned<CQueryOrFilter> orFilter;
  5071. public:
  5072. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5073. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5074. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5075. {
  5076. ForEachItemIn(x, _unknownAttributes)
  5077. unknownAttributes.append(_unknownAttributes.item(x));
  5078. }
  5079. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5080. {
  5081. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5082. if (!conn)
  5083. return NULL;
  5084. Owned<IPropertyTreeIterator> iter;
  5085. if (!orFilter)
  5086. {
  5087. iter.setown(conn->getElements(xPath.get()));
  5088. }
  5089. else
  5090. {
  5091. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5092. bool added = false;
  5093. const char* fieldName = orFilter->queryName();
  5094. unsigned flags = orFilter->querySearchFlags();
  5095. const StringArray& values = orFilter->queryValues();
  5096. ForEachItemIn(i, values)
  5097. {
  5098. StringBuffer path(xPath.get());
  5099. const char* value = values.item(i);
  5100. if (!isEmptyString(value))
  5101. {
  5102. appendFilterToQueryString(path, flags, fieldName, value);
  5103. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5104. if (itr)
  5105. {
  5106. multi->addSource(*itr);
  5107. added = true;
  5108. }
  5109. }
  5110. }
  5111. if (added)
  5112. iter.setown(multi.getClear());
  5113. }
  5114. if (!iter)
  5115. return NULL;
  5116. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5117. return conn.getClear();
  5118. }
  5119. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5120. };
  5121. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5122. {
  5123. UniqueScopes done;
  5124. ISecManager *secmgr;
  5125. ISecUser *secuser;
  5126. CriticalSection crit;
  5127. public:
  5128. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5129. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5130. {
  5131. secmgr = _secmgr;
  5132. secuser = _secuser;
  5133. }
  5134. bool isOK(IPropertyTree &tree)
  5135. {
  5136. const char *scopename = tree.queryProp("@scope");
  5137. if (!scopename||!*scopename)
  5138. return true;
  5139. {
  5140. CriticalBlock block(crit);
  5141. const bool *b = done.getValue(scopename);
  5142. if (b)
  5143. return *b;
  5144. }
  5145. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5146. {
  5147. // conceivably could have already been checked and added, but ok.
  5148. CriticalBlock block(crit);
  5149. done.setValue(scopename,ret);
  5150. }
  5151. return ret;
  5152. }
  5153. };
  5154. Owned<CQueryOrFilter> orFilter;
  5155. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5156. StringBuffer query;
  5157. StringBuffer so;
  5158. StringAttr namefilter("*");
  5159. StringAttr namefilterlo;
  5160. StringAttr namefilterhi;
  5161. StringArray unknownAttributes;
  5162. if (filters)
  5163. {
  5164. const char *fv = (const char *) filterbuf;
  5165. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5166. {
  5167. assertex(fv);
  5168. int fmt = filters[i];
  5169. int subfmt = (fmt&0xff);
  5170. if (subfmt==WUSFwuid)
  5171. namefilterlo.set(fv);
  5172. else if (subfmt==WUSFwuidhigh)
  5173. namefilterhi.set(fv);
  5174. else if (subfmt==WUSFwildwuid)
  5175. namefilter.set(fv);
  5176. else if (subfmt==WUSFappvalue)
  5177. {
  5178. const char *app = fv;
  5179. fv = fv + strlen(fv)+1;
  5180. query.append("[Application/").append(app);
  5181. if (*fv)
  5182. query.append("=?~\"").append(fv).append('\"');
  5183. query.append("]");
  5184. }
  5185. else if (!*fv)
  5186. {
  5187. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5188. if (subfmt==WUSFtotalthortime)
  5189. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5190. }
  5191. else
  5192. {
  5193. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5194. if (!strchr(fv, '|'))
  5195. appendFilterToQueryString(query, fmt, fieldName, fv);
  5196. else if (orFilter)
  5197. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5198. else
  5199. {
  5200. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5201. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5202. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5203. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5204. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5205. }
  5206. }
  5207. fv = fv + strlen(fv)+1;
  5208. }
  5209. }
  5210. if ((sortorder&0xff)==WUSFtotalthortime)
  5211. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5212. query.insert(0, namefilter.get());
  5213. if (sortorder)
  5214. {
  5215. if (so.length())
  5216. so.append(',');
  5217. if (sortorder & WUSFreverse)
  5218. so.append('-');
  5219. if (sortorder & WUSFnocase)
  5220. so.append('?');
  5221. if (sortorder & WUSFnumeric)
  5222. so.append('#');
  5223. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5224. }
  5225. IArrayOf<IPropertyTree> results;
  5226. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5227. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5228. return new CConstWUArrayIterator(results);
  5229. }
  5230. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  5231. {
  5232. WUState ret = WUStateUnknown;
  5233. StringBuffer wuRoot;
  5234. getXPath(wuRoot, wuid);
  5235. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5236. if (timeout == 0) //no need to subscribe
  5237. {
  5238. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5239. switch (ret)
  5240. {
  5241. case WUStateCompiled:
  5242. case WUStateUploadingFiles:
  5243. if (!compiled)
  5244. break;
  5245. //fall through
  5246. case WUStateCompleted:
  5247. case WUStateFailed:
  5248. case WUStateAborted:
  5249. return ret;
  5250. case WUStateWait:
  5251. if(returnOnWaitState)
  5252. return ret;
  5253. default:
  5254. break;
  5255. }
  5256. return WUStateUnknown;
  5257. }
  5258. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5259. LocalIAbortHandler abortHandler(*waiter);
  5260. if (conn)
  5261. {
  5262. SessionId agent = -1;
  5263. bool agentSessionStopped = false;
  5264. unsigned start = msTick();
  5265. for (;;)
  5266. {
  5267. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5268. switch (ret)
  5269. {
  5270. case WUStateCompiled:
  5271. case WUStateUploadingFiles:
  5272. if (!compiled)
  5273. break;
  5274. // fall into
  5275. case WUStateCompleted:
  5276. case WUStateFailed:
  5277. case WUStateAborted:
  5278. return ret;
  5279. case WUStateWait:
  5280. if(returnOnWaitState)
  5281. {
  5282. return ret;
  5283. }
  5284. break;
  5285. case WUStateCompiling:
  5286. case WUStateRunning:
  5287. case WUStateDebugPaused:
  5288. case WUStateDebugRunning:
  5289. case WUStateBlocked:
  5290. case WUStateAborting:
  5291. if (agentSessionStopped)
  5292. {
  5293. reportAbnormalTermination(wuid, ret, agent);
  5294. return ret;
  5295. }
  5296. if (queryDaliServerVersion().compare("2.1")>=0)
  5297. {
  5298. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5299. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5300. {
  5301. agentSessionStopped = true;
  5302. conn->reload();
  5303. continue;
  5304. }
  5305. }
  5306. break;
  5307. }
  5308. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5309. unsigned waited = msTick() - start;
  5310. if (timeout==-1 || waited + 20000 < timeout)
  5311. {
  5312. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5313. if (waiter->isAborted())
  5314. {
  5315. ret = WUStateUnknown; // MORE - throw an exception?
  5316. break;
  5317. }
  5318. }
  5319. else if (waited > timeout || !waiter->wait(timeout-waited))
  5320. {
  5321. ret = WUStateUnknown; // MORE - throw an exception?
  5322. break;
  5323. }
  5324. conn->reload();
  5325. }
  5326. }
  5327. return ret;
  5328. }
  5329. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5330. {
  5331. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5332. LocalIAbortHandler abortHandler(*waiter);
  5333. WUAction ret = WUActionUnknown;
  5334. StringBuffer wuRoot;
  5335. getXPath(wuRoot, wuid);
  5336. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5337. if (conn)
  5338. {
  5339. unsigned start = msTick();
  5340. for (;;)
  5341. {
  5342. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5343. if (ret != original)
  5344. break;
  5345. unsigned waited = msTick() - start;
  5346. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5347. if (waiter->isAborted())
  5348. {
  5349. ret = WUActionUnknown; // MORE - throw an exception?
  5350. break;
  5351. }
  5352. conn->reload();
  5353. }
  5354. }
  5355. waiter->unsubscribe();
  5356. return ret;
  5357. }
  5358. protected:
  5359. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5360. {
  5361. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5362. if (conn)
  5363. {
  5364. CDaliVersion serverVersionNeeded("3.2");
  5365. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5366. conn->queryRoot()->getElements(xpath) :
  5367. conn->getElements(xpath));
  5368. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5369. }
  5370. else
  5371. return NULL;
  5372. }
  5373. ISDSManager *sdsManager;
  5374. SessionId session;
  5375. };
  5376. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5377. {
  5378. if (secmgr)
  5379. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5380. else
  5381. return iter;
  5382. }
  5383. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5384. {
  5385. if (secmgr)
  5386. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5387. else
  5388. return new CConstWUIterator(iter);
  5389. }
  5390. static CriticalSection factoryCrit;
  5391. static Owned<IWorkUnitFactory> factory;
  5392. void CDaliWorkUnitFactory::clientShutdown()
  5393. {
  5394. CriticalBlock b(factoryCrit);
  5395. factory.clear();
  5396. }
  5397. void clientShutdownWorkUnit()
  5398. {
  5399. CriticalBlock b(factoryCrit);
  5400. factory.clear();
  5401. }
  5402. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5403. {
  5404. CriticalBlock b(factoryCrit);
  5405. factory.setown(_factory);
  5406. }
  5407. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5408. {
  5409. if (!factory)
  5410. {
  5411. CriticalBlock b(factoryCrit);
  5412. 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.
  5413. {
  5414. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5415. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5416. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5417. IPropertyTree *pluginInfo = NULL;
  5418. if (env)
  5419. {
  5420. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5421. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5422. if (daliInfo)
  5423. {
  5424. const char *daliName = daliInfo->queryProp("@name");
  5425. if (daliName)
  5426. {
  5427. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5428. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5429. }
  5430. if (!pluginInfo)
  5431. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5432. }
  5433. }
  5434. if (pluginInfo && !forceDali)
  5435. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5436. else
  5437. factory.setown(new CDaliWorkUnitFactory());
  5438. }
  5439. }
  5440. return factory.getLink();
  5441. }
  5442. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5443. {
  5444. if (!factory)
  5445. {
  5446. CriticalBlock b(factoryCrit);
  5447. 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.
  5448. factory.setown(new CDaliWorkUnitFactory());
  5449. }
  5450. return factory.getLink();
  5451. }
  5452. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5453. // They can still be supplied if you want...
  5454. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5455. {
  5456. public:
  5457. IMPLEMENT_IINTERFACE;
  5458. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5459. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5460. {
  5461. }
  5462. virtual bool initializeStore()
  5463. {
  5464. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5465. }
  5466. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5467. {
  5468. return baseFactory->getWatcher(subscriber, options, wuid);
  5469. }
  5470. virtual unsigned validateRepository(bool fix)
  5471. {
  5472. return baseFactory->validateRepository(fix);
  5473. }
  5474. virtual void deleteRepository(bool recreate)
  5475. {
  5476. return baseFactory->deleteRepository(recreate);
  5477. }
  5478. virtual void createRepository()
  5479. {
  5480. return baseFactory->createRepository();
  5481. }
  5482. virtual const char *queryStoreType() const
  5483. {
  5484. return baseFactory->queryStoreType();
  5485. }
  5486. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5487. {
  5488. return baseFactory->getUniqueValues(field, prefix, result);
  5489. }
  5490. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5491. {
  5492. if (!secMgr) secMgr = defaultSecMgr.get();
  5493. if (!secUser) secUser = defaultSecUser.get();
  5494. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5495. }
  5496. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5497. {
  5498. if (!secMgr) secMgr = defaultSecMgr.get();
  5499. if (!secUser) secUser = defaultSecUser.get();
  5500. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5501. }
  5502. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5503. {
  5504. if (!secMgr) secMgr = defaultSecMgr.get();
  5505. if (!secUser) secUser = defaultSecUser.get();
  5506. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5507. }
  5508. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5509. {
  5510. if (!secMgr) secMgr = defaultSecMgr.get();
  5511. if (!secUser) secUser = defaultSecUser.get();
  5512. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5513. }
  5514. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5515. {
  5516. if (!secMgr) secMgr = defaultSecMgr.get();
  5517. if (!secUser) secUser = defaultSecUser.get();
  5518. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5519. }
  5520. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5521. {
  5522. if (!secMgr) secMgr = defaultSecMgr.get();
  5523. if (!secUser) secUser = defaultSecUser.get();
  5524. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5525. }
  5526. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5527. {
  5528. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5529. }
  5530. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5531. {
  5532. if (!secMgr) secMgr = defaultSecMgr.get();
  5533. if (!secUser) secUser = defaultSecUser.get();
  5534. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5535. }
  5536. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5537. {
  5538. if (!secMgr) secMgr = defaultSecMgr.get();
  5539. if (!secUser) secUser = defaultSecUser.get();
  5540. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5541. }
  5542. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5543. {
  5544. if (!secMgr) secMgr = defaultSecMgr.get();
  5545. if (!secUser) secUser = defaultSecUser.get();
  5546. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5547. }
  5548. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5549. {
  5550. if (!secMgr) secMgr = defaultSecMgr.get();
  5551. if (!secUser) secUser = defaultSecUser.get();
  5552. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5553. }
  5554. virtual int setTracingLevel(int newLevel)
  5555. {
  5556. return baseFactory->setTracingLevel(newLevel);
  5557. }
  5558. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5559. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5560. const void *filterbuf, // (appended) string values for filters
  5561. unsigned startoffset,
  5562. unsigned maxnum,
  5563. __int64 *cachehint,
  5564. unsigned *total,
  5565. ISecManager *secMgr, ISecUser *secUser)
  5566. {
  5567. if (!secMgr) secMgr = defaultSecMgr.get();
  5568. if (!secUser) secUser = defaultSecUser.get();
  5569. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5570. }
  5571. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5572. WUQuerySortField *filters,
  5573. const void *filterbuf,
  5574. unsigned startoffset,
  5575. unsigned maxnum,
  5576. __int64 *cachehint,
  5577. unsigned *total,
  5578. const MapStringTo<bool> *subset)
  5579. {
  5580. // MORE - why no security?
  5581. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  5582. }
  5583. virtual unsigned numWorkUnits()
  5584. {
  5585. return baseFactory->numWorkUnits();
  5586. }
  5587. virtual bool isAborting(const char *wuid) const
  5588. {
  5589. return baseFactory->isAborting(wuid);
  5590. }
  5591. virtual void clearAborting(const char *wuid)
  5592. {
  5593. baseFactory->clearAborting(wuid);
  5594. }
  5595. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  5596. {
  5597. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, returnOnWaitState);
  5598. }
  5599. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5600. {
  5601. return baseFactory->waitForWorkUnitAction(wuid, original);
  5602. }
  5603. private:
  5604. Owned<IWorkUnitFactory> baseFactory;
  5605. Linked<ISecManager> defaultSecMgr;
  5606. Linked<ISecUser> defaultSecUser;
  5607. };
  5608. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5609. {
  5610. if (secmgr && secuser)
  5611. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5612. else
  5613. return getWorkUnitFactory();
  5614. }
  5615. //==========================================================================================
  5616. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5617. {
  5618. Owned<IPropertyTreeIterator> it;
  5619. public:
  5620. IMPLEMENT_IINTERFACE;
  5621. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5622. virtual bool first() { return it->first(); }
  5623. virtual bool next() { return it->next(); }
  5624. virtual bool isValid() { return it->isValid(); }
  5625. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5626. };
  5627. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5628. {
  5629. Owned<IPropertyTreeIterator> it;
  5630. public:
  5631. IMPLEMENT_IINTERFACE;
  5632. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5633. virtual bool first() { return it->first(); }
  5634. virtual bool next() { return it->next(); }
  5635. virtual bool isValid() { return it->isValid(); }
  5636. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5637. };
  5638. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5639. {
  5640. Owned<IPropertyTreeIterator> it;
  5641. StringAttr name;
  5642. public:
  5643. IMPLEMENT_IINTERFACE;
  5644. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  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().queryProp(name)); return s; }
  5649. };
  5650. //==========================================================================================
  5651. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5652. {
  5653. clearCached(false);
  5654. secMgr.set(secmgr);
  5655. secUser.set(secuser);
  5656. workflowIteratorCached = false;
  5657. resultsCached = false;
  5658. graphsCached = false;
  5659. temporariesCached = false;
  5660. variablesCached = false;
  5661. exceptionsCached = false;
  5662. pluginsCached = false;
  5663. librariesCached = false;
  5664. activitiesCached = false;
  5665. webServicesInfoCached = false;
  5666. roxieQueryInfoCached = false;
  5667. }
  5668. void CLocalWorkUnit::clearCached(bool clearTree)
  5669. {
  5670. query.clear();
  5671. webServicesInfo.clear();
  5672. workflowIterator.clear();
  5673. graphs.kill();
  5674. results.kill();
  5675. variables.kill();
  5676. plugins.kill();
  5677. libraries.kill();
  5678. exceptions.kill();
  5679. temporaries.kill();
  5680. statistics.kill();
  5681. appvalues.kill();
  5682. if (clearTree)
  5683. p.clear();
  5684. workflowIteratorCached = false;
  5685. resultsCached = false;
  5686. graphsCached = false;
  5687. temporariesCached = false;
  5688. variablesCached = false;
  5689. exceptionsCached = false;
  5690. pluginsCached = false;
  5691. librariesCached = false;
  5692. activitiesCached = false;
  5693. webServicesInfoCached = false;
  5694. roxieQueryInfoCached = false;
  5695. }
  5696. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  5697. {
  5698. clearCached(false);
  5699. p.setown(ptree);
  5700. }
  5701. void CLocalWorkUnit::beforeDispose()
  5702. {
  5703. try
  5704. {
  5705. unsubscribe();
  5706. clearCached(true);
  5707. userDesc.clear();
  5708. secMgr.clear();
  5709. secUser.clear();
  5710. }
  5711. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  5712. }
  5713. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  5714. {
  5715. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  5716. // Delete any related things in SDS etc that might otherwise be forgotten
  5717. if (p->getPropBool("@protected", false))
  5718. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  5719. switch (getState())
  5720. {
  5721. case WUStateAborted:
  5722. case WUStateCompleted:
  5723. case WUStateFailed:
  5724. case WUStateArchived:
  5725. break;
  5726. case WUStateCompiled:
  5727. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  5728. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5729. break;
  5730. case WUStateWait:
  5731. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  5732. default:
  5733. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5734. break;
  5735. }
  5736. if (getIsQueryService())
  5737. {
  5738. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  5739. if (registry)
  5740. {
  5741. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  5742. if (registry->hasProp(xpath.str()))
  5743. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  5744. }
  5745. }
  5746. try
  5747. {
  5748. if (deldll && !p->getPropBool("@isClone", false))
  5749. {
  5750. Owned<IConstWUQuery> q = getQuery();
  5751. if (q)
  5752. {
  5753. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5754. SCMStringBuffer name;
  5755. ForEach(*iter)
  5756. {
  5757. IConstWUAssociatedFile & cur = iter->query();
  5758. cur.getNameTail(name);
  5759. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  5760. {
  5761. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5762. if (entry.get())
  5763. asyncRemoveDll(name.str());
  5764. else
  5765. {
  5766. SCMStringBuffer ip, localPath;
  5767. cur.getName(localPath);
  5768. cur.getIp(ip);
  5769. asyncRemoveFile(ip.str(), localPath.str());
  5770. }
  5771. }
  5772. }
  5773. }
  5774. }
  5775. factory->clearAborting(queryWuid());
  5776. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  5777. }
  5778. catch(IException *E)
  5779. {
  5780. StringBuffer s;
  5781. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  5782. E->Release();
  5783. }
  5784. catch (...)
  5785. {
  5786. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  5787. }
  5788. }
  5789. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  5790. {
  5791. SCMStringBuffer strval;
  5792. val.getGmtString(strval);
  5793. p->setProp("@timescheduled",strval.str());
  5794. }
  5795. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  5796. {
  5797. StringBuffer str;
  5798. p->getProp("@timescheduled",str);
  5799. if(str.length())
  5800. val.setGmtString(str.str());
  5801. return val;
  5802. }
  5803. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  5804. {
  5805. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  5806. if (extra.length())
  5807. {
  5808. const char *bufStart = buf.str();
  5809. const char *bufPtr = bufStart+buf.length();
  5810. while (bufStart != bufPtr)
  5811. {
  5812. --bufPtr;
  5813. if (!isspace(*bufPtr))
  5814. break;
  5815. }
  5816. assertex('>' == *bufPtr);
  5817. size_t l = strlen(wuid);
  5818. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  5819. bufPtr -= l+2; // skip back over </wuid
  5820. assertex(0 == memcmp(bufPtr, "</", 2) );
  5821. assertex(0 == memcmp(bufPtr+2, wuid, l));
  5822. buf.insert(bufPtr-bufStart, extra);
  5823. }
  5824. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  5825. }
  5826. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  5827. {
  5828. CriticalBlock block(crit);
  5829. StringBuffer path(base);
  5830. if (!p)
  5831. return false;
  5832. const char *wuid = p->queryName();
  5833. if (!wuid||!*wuid)
  5834. return false;
  5835. addPathSepChar(path).append(wuid).append(".xml");
  5836. Owned<IFile> file = createIFile(path.str());
  5837. if (!file)
  5838. return false;
  5839. Owned<IFileIO> fileio = file->open(IFOcreate);
  5840. if (!fileio)
  5841. return false;
  5842. StringBuffer buf;
  5843. exportWorkUnitToXML(this, buf, false, false, true);
  5844. StringBuffer extraWorkUnitXML;
  5845. Owned<IPTree> graphProgress = getGraphProgressTree();
  5846. if (graphProgress)
  5847. {
  5848. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  5849. graphProgress.clear();
  5850. }
  5851. Owned<IConstWUQuery> q = getQuery();
  5852. if (!q)
  5853. {
  5854. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5855. return false;
  5856. if (del)
  5857. {
  5858. if (getState()==WUStateUnknown)
  5859. setState(WUStateArchived); // to allow delete
  5860. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  5861. }
  5862. return false;
  5863. }
  5864. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  5865. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5866. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  5867. ForEach(*iter)
  5868. {
  5869. IConstWUAssociatedFile & cur = iter->query();
  5870. SCMStringBuffer name;
  5871. cur.getNameTail(name);
  5872. if (name.length())
  5873. {
  5874. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5875. SCMStringBuffer curPath, curIp;
  5876. cur.getName(curPath);
  5877. cur.getIp(curIp);
  5878. SocketEndpoint curEp(curIp.str());
  5879. RemoteFilename curRfn;
  5880. curRfn.setPath(curEp, curPath.str());
  5881. StringBuffer dst(base);
  5882. addPathSepChar(dst);
  5883. curRfn.getTail(dst);
  5884. Owned<IFile> dstFile = createIFile(dst.str());
  5885. if (entry.get())
  5886. {
  5887. Owned<IException> exception;
  5888. Owned<IDllLocation> loc;
  5889. Owned<IPropertyTree> generatedDllBranch = createPTree();
  5890. generatedDllBranch->setProp("@name", entry->queryName());
  5891. generatedDllBranch->setProp("@kind", entry->queryKind());
  5892. if (exportAssociatedFiles)
  5893. {
  5894. try
  5895. {
  5896. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  5897. }
  5898. catch(IException * e)
  5899. {
  5900. exception.setown(e);
  5901. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  5902. }
  5903. RemoteFilename filename;
  5904. loc->getDllFilename(filename);
  5905. if (!exception)
  5906. {
  5907. Owned<IFile> srcfile = createIFile(filename);
  5908. try
  5909. {
  5910. if (dstFile->exists())
  5911. {
  5912. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  5913. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  5914. // still want to delete if already archived but there are source file copies
  5915. }
  5916. else
  5917. copyFile(dstFile, srcfile);
  5918. }
  5919. catch(IException * e)
  5920. {
  5921. exception.setown(e);
  5922. }
  5923. }
  5924. if (exception)
  5925. {
  5926. if (ignoredllerrors)
  5927. {
  5928. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  5929. //copy failed, so don't delete the registered dll files
  5930. deleteExclusions.append(name.str());
  5931. }
  5932. else
  5933. throw exception.getClear();
  5934. }
  5935. }
  5936. // Record Associated path to restore back to
  5937. StringBuffer restorePath;
  5938. curRfn.getRemotePath(restorePath);
  5939. generatedDllBranch->setProp("@location", restorePath.str());
  5940. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  5941. }
  5942. else if (exportAssociatedFiles) // no generated dll entry
  5943. {
  5944. Owned<IFile> srcFile = createIFile(curRfn);
  5945. try
  5946. {
  5947. copyFile(dstFile, srcFile);
  5948. }
  5949. catch (IException *e)
  5950. {
  5951. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  5952. EXCLOG(e, msg.str());
  5953. e->Release();
  5954. deleteExclusions.append(name.str());
  5955. }
  5956. }
  5957. }
  5958. }
  5959. iter.clear();
  5960. if (generatedDlls->numChildren())
  5961. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  5962. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5963. return false;
  5964. if (del)
  5965. {
  5966. //setState(WUStateArchived); // this isn't useful as about to delete it!
  5967. q.clear();
  5968. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  5969. }
  5970. return true;
  5971. }
  5972. void CLocalWorkUnit::loadXML(const char *xml)
  5973. {
  5974. CriticalBlock block(crit);
  5975. clearCached(true);
  5976. assertex(xml);
  5977. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  5978. }
  5979. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  5980. {
  5981. CriticalBlock block(crit);
  5982. StringBuffer x;
  5983. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  5984. }
  5985. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  5986. {
  5987. CriticalBlock block(crit);
  5988. StringAttr value;
  5989. src.read(value);
  5990. loadXML(value);
  5991. }
  5992. void CLocalWorkUnit::requestAbort()
  5993. {
  5994. CriticalBlock block(crit);
  5995. abortWorkUnit(p->queryName());
  5996. }
  5997. void CLocalWorkUnit::unlockRemote()
  5998. {
  5999. CriticalBlock block(crit);
  6000. locked.unlock();
  6001. _unlockRemote();
  6002. }
  6003. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6004. {
  6005. if (secMgr)
  6006. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6007. locked.lock();
  6008. CriticalBlock block(crit);
  6009. if (commit)
  6010. {
  6011. try
  6012. {
  6013. _lockRemote();
  6014. }
  6015. catch (IException *E)
  6016. {
  6017. StringBuffer s;
  6018. PrintLog("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6019. locked.unlock();
  6020. throw;
  6021. }
  6022. }
  6023. return *new CLockedWorkUnit(LINK(this));
  6024. }
  6025. void CLocalWorkUnit::commit()
  6026. {
  6027. // Nothing to do if not backed by a persistent store
  6028. }
  6029. IWorkUnit& CLocalWorkUnit::lock()
  6030. {
  6031. return lockRemote(true);
  6032. }
  6033. const char *CLocalWorkUnit::queryWuid() const
  6034. {
  6035. CriticalBlock block(crit);
  6036. return p->queryName();
  6037. }
  6038. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6039. {
  6040. CriticalBlock block(crit);
  6041. return p->getPropInt("@DebugListenerPort", 0);
  6042. }
  6043. unsigned CLocalWorkUnit::getTotalThorTime() const
  6044. {
  6045. CriticalBlock block(crit);
  6046. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6047. }
  6048. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6049. {
  6050. CriticalBlock block(crit);
  6051. p->setPropInt("@DebugListenerPort", port);
  6052. }
  6053. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6054. {
  6055. CriticalBlock block(crit);
  6056. ip.set(p->queryProp("@DebugListenerIP"));
  6057. return ip;
  6058. }
  6059. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6060. {
  6061. CriticalBlock block(crit);
  6062. p->setProp("@DebugListenerIP", ip);
  6063. }
  6064. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6065. {
  6066. CriticalBlock block(crit);
  6067. datoken.set(p->queryProp("@distributedAccessToken"));
  6068. return datoken;
  6069. }
  6070. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6071. {
  6072. CriticalBlock block(crit);
  6073. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6074. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6075. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6076. if (pDSM && pDSM->isDigiSignerConfigured())
  6077. {
  6078. datoken.append(pDSM->queryKeyName()).append(';');
  6079. StringBuffer b64Signature;
  6080. if (pDSM->digiSign(b64Signature, datoken))
  6081. {
  6082. datoken.append(b64Signature.str());
  6083. }
  6084. else
  6085. {
  6086. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6087. return false;
  6088. }
  6089. }
  6090. else
  6091. {
  6092. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6093. datoken.append(";");
  6094. }
  6095. p->setProp("@distributedAccessToken", datoken);
  6096. return true;
  6097. }
  6098. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6099. {
  6100. // Only implemented in derived classes
  6101. return false;
  6102. }
  6103. void CLocalWorkUnit::setJobName(const char *value)
  6104. {
  6105. CriticalBlock block(crit);
  6106. p->setProp("@jobName", value);
  6107. }
  6108. const char *CLocalWorkUnit::queryJobName() const
  6109. {
  6110. CriticalBlock block(crit);
  6111. const char *ret = p->queryProp("@jobName");
  6112. if (!ret)
  6113. ret = "";
  6114. return ret;
  6115. }
  6116. void CLocalWorkUnit::setClusterName(const char *value)
  6117. {
  6118. CriticalBlock block(crit);
  6119. p->setProp("@clusterName", value);
  6120. }
  6121. const char *CLocalWorkUnit::queryClusterName() const
  6122. {
  6123. CriticalBlock block(crit);
  6124. const char *ret = p->queryProp("@clusterName");
  6125. if (!ret)
  6126. ret = "";
  6127. return ret;
  6128. }
  6129. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6130. {
  6131. setDebugValue("allowedclusters",value, true);
  6132. }
  6133. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6134. {
  6135. CriticalBlock block(crit);
  6136. getDebugValue("allowedclusters",str);
  6137. if (str.length()!=0)
  6138. return str;
  6139. str.set(p->queryProp("@clusterName"));
  6140. return str;
  6141. }
  6142. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6143. {
  6144. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6145. }
  6146. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6147. {
  6148. CriticalBlock block(crit);
  6149. return getDebugValueBool("allowautoqueueswitch",false);
  6150. }
  6151. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6152. {
  6153. StringBuffer suffix;
  6154. if (name && *name)
  6155. setApplicationValue("LibraryModule", "name", name, true);
  6156. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6157. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6158. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6159. }
  6160. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6161. {
  6162. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6163. if (writeaccess)
  6164. auditflags |= DALI_LDAP_WRITE_WANTED;
  6165. SecAccessFlags perm = SecAccess_Full;
  6166. const char *scopename = p->queryProp("@scope");
  6167. if (scopename&&*scopename) {
  6168. if (!user)
  6169. user = queryUserDescriptor();
  6170. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6171. if (perm<0) {
  6172. if (perm == SecAccess_Unavailable)
  6173. perm = SecAccess_Full;
  6174. else
  6175. perm = SecAccess_None;
  6176. }
  6177. }
  6178. if (!HASREADPERMISSION(perm))
  6179. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6180. if (writeaccess && !HASWRITEPERMISSION(perm))
  6181. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6182. }
  6183. void CLocalWorkUnit::setUser(const char * value)
  6184. {
  6185. CriticalBlock block(crit);
  6186. p->setProp("@submitID", value);
  6187. }
  6188. const char *CLocalWorkUnit::queryUser() const
  6189. {
  6190. CriticalBlock block(crit);
  6191. const char *ret = p->queryProp("@submitID");
  6192. if (!ret)
  6193. ret = "";
  6194. return ret;
  6195. }
  6196. void CLocalWorkUnit::setWuScope(const char * value)
  6197. {
  6198. if (value && *value)
  6199. {
  6200. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6201. {
  6202. CriticalBlock block(crit);
  6203. p->setProp("@scope", value);
  6204. }
  6205. }
  6206. }
  6207. const char *CLocalWorkUnit::queryWuScope() const
  6208. {
  6209. CriticalBlock block(crit);
  6210. const char *ret = p->queryProp("@scope");
  6211. if (!ret)
  6212. ret = "";
  6213. return ret;
  6214. }
  6215. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6216. {
  6217. CriticalBlock block(crit);
  6218. setEnum(p, "@priorityClass", cls, priorityClasses);
  6219. }
  6220. WUPriorityClass CLocalWorkUnit::getPriority() const
  6221. {
  6222. CriticalBlock block(crit);
  6223. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6224. }
  6225. const char *CLocalWorkUnit::queryPriorityDesc() const
  6226. {
  6227. return getEnumText(getPriority(), priorityClasses);
  6228. }
  6229. void CLocalWorkUnit::setState(WUState value)
  6230. {
  6231. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6232. {
  6233. if (factory)
  6234. factory->clearAborting(queryWuid());
  6235. }
  6236. CriticalBlock block(crit);
  6237. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6238. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6239. if (getDebugValueBool("monitorWorkunit", false))
  6240. {
  6241. switch(value)
  6242. {
  6243. case WUStateAborted:
  6244. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6245. break;
  6246. case WUStateCompleted:
  6247. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6248. break;
  6249. case WUStateFailed:
  6250. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6251. break;
  6252. }
  6253. }
  6254. p->removeProp("@stateEx");
  6255. }
  6256. void CLocalWorkUnit::setStateEx(const char * text)
  6257. {
  6258. CriticalBlock block(crit);
  6259. p->setProp("@stateEx", text);
  6260. }
  6261. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6262. {
  6263. CriticalBlock block(crit);
  6264. p->setPropInt64("@agentSession", sessionId);
  6265. }
  6266. bool CLocalWorkUnit::getIsQueryService() const
  6267. {
  6268. CriticalBlock block(crit);
  6269. return p->getPropBool("@isQueryService", false);
  6270. }
  6271. void CLocalWorkUnit::setIsQueryService(bool value)
  6272. {
  6273. CriticalBlock block(crit);
  6274. p->setPropBool("@isQueryService", value);
  6275. }
  6276. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6277. {
  6278. if (queryDaliServerVersion().compare("2.1")<0)
  6279. return;
  6280. switch(state)
  6281. {
  6282. case WUStateRunning:
  6283. case WUStateDebugPaused:
  6284. case WUStateDebugRunning:
  6285. case WUStateBlocked:
  6286. case WUStateAborting:
  6287. case WUStateCompiling:
  6288. case WUStatePaused:
  6289. {
  6290. SessionId agent = getAgentSession();
  6291. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6292. {
  6293. forceReload();
  6294. state = (WUState) getEnum(p, "@state", states);
  6295. bool isecl=state==WUStateCompiling;
  6296. if (aborting())
  6297. state = WUStateAborted;
  6298. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6299. state = WUStateFailed;
  6300. else
  6301. return;
  6302. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6303. Owned<IWorkUnit> w = &lock();
  6304. w->setState(state);
  6305. Owned<IWUException> e = w->createException();
  6306. WUAction action = w->getAction();
  6307. switch (action)
  6308. {
  6309. case WUActionPause:
  6310. case WUActionPauseNow:
  6311. case WUActionResume:
  6312. w->setAction(WUActionUnknown);
  6313. }
  6314. if(isecl)
  6315. {
  6316. e->setExceptionCode(1001);
  6317. e->setExceptionMessage("EclServer terminated unexpectedly");
  6318. }
  6319. else
  6320. {
  6321. e->setExceptionCode(1000);
  6322. e->setExceptionMessage("Workunit terminated unexpectedly");
  6323. }
  6324. }
  6325. }
  6326. }
  6327. }
  6328. WUState CLocalWorkUnit::getState() const
  6329. {
  6330. CriticalBlock block(crit);
  6331. WUState state = (WUState) getEnum(p, "@state", states);
  6332. switch (state)
  6333. {
  6334. case WUStateRunning:
  6335. case WUStateDebugPaused:
  6336. case WUStateDebugRunning:
  6337. case WUStateBlocked:
  6338. case WUStateCompiling:
  6339. if (aborting())
  6340. state = WUStateAborting;
  6341. break;
  6342. case WUStateSubmitted:
  6343. if (aborting())
  6344. state = WUStateAborted;
  6345. break;
  6346. }
  6347. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6348. return state;
  6349. }
  6350. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6351. {
  6352. CriticalBlock block(crit);
  6353. str.set(p->queryProp("@stateEx"));
  6354. return str;
  6355. }
  6356. __int64 CLocalWorkUnit::getAgentSession() const
  6357. {
  6358. CriticalBlock block(crit);
  6359. return p->getPropInt64("@agentSession", -1);
  6360. }
  6361. unsigned CLocalWorkUnit::getAgentPID() const
  6362. {
  6363. CriticalBlock block(crit);
  6364. return p->getPropInt("@agentPID", -1);
  6365. }
  6366. const char * CLocalWorkUnit::queryStateDesc() const
  6367. {
  6368. // MORE - not sure about this - may prefer a separate interface
  6369. CriticalBlock block(crit);
  6370. try
  6371. {
  6372. return getEnumText(getState(), states);
  6373. }
  6374. catch (...)
  6375. {
  6376. return "???";
  6377. }
  6378. }
  6379. void CLocalWorkUnit::setAction(WUAction value)
  6380. {
  6381. CriticalBlock block(crit);
  6382. setEnum(p, "Action", value, actions);
  6383. }
  6384. WUAction CLocalWorkUnit::getAction() const
  6385. {
  6386. CriticalBlock block(crit);
  6387. return (WUAction) getEnum(p, "Action", actions);
  6388. }
  6389. const char *CLocalWorkUnit::queryActionDesc() const
  6390. {
  6391. CriticalBlock block(crit);
  6392. return p->queryProp("Action");
  6393. }
  6394. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6395. {
  6396. CriticalBlock block(crit);
  6397. StringBuffer prop("Application/");
  6398. prop.append(app).append('/').append(propname);
  6399. str.set(p->queryProp(prop.str()));
  6400. return str;
  6401. }
  6402. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6403. {
  6404. CriticalBlock block(crit);
  6405. StringBuffer prop("Application/");
  6406. prop.append(app).append('/').append(propname);
  6407. return p->getPropInt(prop.str(), defVal);
  6408. }
  6409. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6410. {
  6411. CriticalBlock block(crit);
  6412. appvalues.load(p,"Application/*");
  6413. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6414. }
  6415. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6416. {
  6417. CriticalBlock block(crit);
  6418. StringBuffer prop("Application/");
  6419. prop.append(app).append('/').append(propname);
  6420. if (overwrite || !p->hasProp(prop.str()))
  6421. {
  6422. StringBuffer sp;
  6423. p->setProp(sp.append("Application").str(), "");
  6424. p->setProp(sp.append('/').append(app).str(), "");
  6425. p->setProp(prop.str(), value);
  6426. }
  6427. }
  6428. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6429. {
  6430. VStringBuffer s("%d", value);
  6431. setApplicationValue(app, propname, s, overwrite);
  6432. }
  6433. void CLocalWorkUnit::setPriorityLevel(int level)
  6434. {
  6435. CriticalBlock block(crit);
  6436. p->setPropInt("PriorityFlag", level);
  6437. }
  6438. int CLocalWorkUnit::getPriorityLevel() const
  6439. {
  6440. CriticalBlock block(crit);
  6441. return p->getPropInt("PriorityFlag");
  6442. }
  6443. int calcPriorityValue(const IPropertyTree * p)
  6444. {
  6445. int priority = p->getPropInt("PriorityFlag");
  6446. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6447. {
  6448. case PriorityClassLow:
  6449. priority -= 100;
  6450. break;
  6451. case PriorityClassHigh:
  6452. priority += 100;
  6453. break;
  6454. }
  6455. return priority;
  6456. }
  6457. int CLocalWorkUnit::getPriorityValue() const
  6458. {
  6459. CriticalBlock block(crit);
  6460. return calcPriorityValue(p);
  6461. }
  6462. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6463. {
  6464. CriticalBlock block(crit);
  6465. p->setPropInt("RescheduleFlag", (int) value);
  6466. }
  6467. bool CLocalWorkUnit::getRescheduleFlag() const
  6468. {
  6469. CriticalBlock block(crit);
  6470. return p->getPropInt("RescheduleFlag") != 0;
  6471. }
  6472. class NullIStringIterator : implements IStringIterator, public CInterface
  6473. {
  6474. public:
  6475. IMPLEMENT_IINTERFACE;
  6476. bool first() { return false; }
  6477. bool next() { return false; }
  6478. bool isValid() { return false; }
  6479. IStringVal & str(IStringVal & str) { return str; }
  6480. };
  6481. ClusterType getClusterType(const char * platform, ClusterType dft)
  6482. {
  6483. if (stricmp(platform, "thor") == 0)
  6484. return ThorLCRCluster;
  6485. if (stricmp(platform, "thorlcr") == 0)
  6486. return ThorLCRCluster;
  6487. if (stricmp(platform, "hthor") == 0)
  6488. return HThorCluster;
  6489. if (stricmp(platform, "roxie") == 0)
  6490. return RoxieCluster;
  6491. return dft;
  6492. }
  6493. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6494. {
  6495. switch (clusterType)
  6496. {
  6497. case ThorLCRCluster:
  6498. if (lcrSensitive)
  6499. return "thorlcr";
  6500. return "thor";
  6501. case RoxieCluster:
  6502. return "roxie";
  6503. case HThorCluster:
  6504. return "hthor";
  6505. }
  6506. throwUnexpected();
  6507. }
  6508. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6509. {
  6510. if (!isWorkunitDAToken(distributedAccessToken))
  6511. {
  6512. DBGLOG("Not a valid workunit distributed access token");
  6513. return false;
  6514. }
  6515. //Extract the string between [ and ]
  6516. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6517. StringBuffer tokenValues;
  6518. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6519. StringArray nameValues;
  6520. nameValues.appendList(tokenValues.str(), ",",true);
  6521. if (user || wuid)
  6522. {
  6523. for (int x = 0; x < nameValues.ordinality(); x++)
  6524. {
  6525. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6526. user->append(nameValues[x] + 2);
  6527. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6528. wuid->append(nameValues[x] + 2);
  6529. }
  6530. }
  6531. if (privKey)
  6532. {
  6533. const char * finger = pEndBracket;
  6534. ++finger;
  6535. while (*finger && *finger != ';')
  6536. privKey->append(1, finger++);
  6537. }
  6538. return true;
  6539. }
  6540. //Verifies the given signed workunit distributed access token was created
  6541. //and signed by the given wuid and user, and that the workunit is still active
  6542. //Returns:
  6543. // 0 : Success, token is valid and workunit is active
  6544. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6545. // 2 : Workunit not active
  6546. // Throws if unable to open workunit
  6547. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6548. {
  6549. if (isEmptyString(daToken))
  6550. {
  6551. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6552. return wuTokenInvalid;
  6553. }
  6554. StringBuffer tokWuid;
  6555. StringBuffer tokUser;
  6556. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6557. {
  6558. //Not a valid workunit distributed access token
  6559. return wuTokenInvalid;
  6560. }
  6561. //Validate signature
  6562. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6563. if (pDSM && pDSM->isDigiVerifierConfigured())
  6564. {
  6565. const char * finger;
  6566. StringBuffer token;//receives copy of everything up until signature
  6567. for (finger = daToken; *finger && *finger != ';'; finger++)
  6568. token.append(1, finger);
  6569. token.append(1, finger);//append ;
  6570. StringBuffer sig(++finger);
  6571. if (!pDSM->digiVerify(sig, token))
  6572. {
  6573. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6574. return wuTokenInvalid;
  6575. }
  6576. }
  6577. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6578. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6579. if(!cw)
  6580. {
  6581. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6582. }
  6583. //Verify user matches
  6584. bool wuUserExist = !isEmptyString(cw->queryUser());
  6585. bool tokUserExist = !isEmptyString(tokUser.str());
  6586. bool ctxUserExist = !isEmptyString(ctxUser);
  6587. if (wuUserExist && tokUserExist)
  6588. {
  6589. //if both users are found, they must match
  6590. if (!streq(tokUser.str(), cw->queryUser()))
  6591. {
  6592. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6593. return wuTokenInvalid;//Possible Internal error
  6594. }
  6595. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6596. {
  6597. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6598. return wuTokenInvalid;
  6599. }
  6600. }
  6601. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6602. {
  6603. if (ctxUserExist)
  6604. {
  6605. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6606. return wuTokenInvalid;
  6607. }
  6608. //both users empty and no context user means if no security enabled
  6609. }
  6610. else
  6611. {
  6612. //one user found, but not the other, treat as an error
  6613. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6614. return wuTokenInvalid;
  6615. }
  6616. // no need to compare tokWuid with workunit wuid, because it will always match
  6617. bool wuActive;
  6618. switch (cw->getState())
  6619. {
  6620. case WUStateRunning:
  6621. case WUStateDebugRunning:
  6622. case WUStateBlocked:
  6623. case WUStateAborting:
  6624. case WUStateUploadingFiles:
  6625. #ifdef _DEBUG
  6626. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6627. #endif
  6628. wuActive = true;
  6629. break;
  6630. default:
  6631. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6632. wuActive = false;
  6633. break;
  6634. }
  6635. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6636. }
  6637. IPropertyTree *queryRoxieProcessTree(IPropertyTree *environment, const char *process)
  6638. {
  6639. if (!process || !*process)
  6640. return NULL;
  6641. VStringBuffer xpath("Software/RoxieCluster[@name=\"%s\"]", process);
  6642. return environment->queryPropTree(xpath.str());
  6643. }
  6644. void getRoxieProcessServers(IPropertyTree *roxie, SocketEndpointArray &endpoints)
  6645. {
  6646. if (!roxie)
  6647. return;
  6648. Owned<IPropertyTreeIterator> servers = roxie->getElements("RoxieServerProcess");
  6649. ForEach(*servers)
  6650. {
  6651. IPropertyTree &server = servers->query();
  6652. const char *netAddress = server.queryProp("@netAddress");
  6653. if (netAddress && *netAddress)
  6654. {
  6655. SocketEndpoint ep(netAddress, server.getPropInt("@port", 9876));
  6656. endpoints.append(ep);
  6657. }
  6658. }
  6659. }
  6660. void getRoxieProcessServers(const char *process, SocketEndpointArray &servers)
  6661. {
  6662. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6663. Owned<IConstEnvironment> env = factory->openEnvironment();
  6664. Owned<IPropertyTree> root = &env->getPTree();
  6665. getRoxieProcessServers(queryRoxieProcessTree(root, process), servers);
  6666. }
  6667. class CEnvironmentClusterInfo: implements IConstWUClusterInfo, public CInterface
  6668. {
  6669. StringAttr name;
  6670. StringAttr alias;
  6671. StringAttr serverQueue;
  6672. StringAttr agentQueue;
  6673. StringAttr agentName;
  6674. StringAttr roxieProcess;
  6675. SocketEndpointArray roxieServers;
  6676. StringAttr thorQueue;
  6677. StringArray thorProcesses;
  6678. StringArray primaryThorProcesses;
  6679. StringAttr prefix;
  6680. StringAttr ldapUser;
  6681. StringBuffer ldapPassword;
  6682. ClusterType platform;
  6683. unsigned clusterWidth;
  6684. unsigned roxieRedundancy;
  6685. unsigned channelsPerNode;
  6686. unsigned numberOfSlaveLogs;
  6687. int roxieReplicateOffset;
  6688. public:
  6689. IMPLEMENT_IINTERFACE;
  6690. CEnvironmentClusterInfo(const char *_name, const char *_prefix, const char *_alias, IPropertyTree *agent, IArrayOf<IPropertyTree> &thors, IPropertyTree *roxie)
  6691. : name(_name), prefix(_prefix), alias(_alias), roxieRedundancy(0), channelsPerNode(0), numberOfSlaveLogs(0), roxieReplicateOffset(1)
  6692. {
  6693. StringBuffer queue;
  6694. if (thors.ordinality())
  6695. {
  6696. thorQueue.set(getClusterThorQueueName(queue.clear(), name));
  6697. clusterWidth = 0;
  6698. bool isMultiThor = (thors.length() > 1);
  6699. ForEachItemIn(i,thors)
  6700. {
  6701. IPropertyTree &thor = thors.item(i);
  6702. const char* thorName = thor.queryProp("@name");
  6703. thorProcesses.append(thorName);
  6704. if (!isMultiThor)
  6705. primaryThorProcesses.append(thorName);
  6706. else
  6707. {
  6708. const char *nodeGroup = thor.queryProp("@nodeGroup");
  6709. if (!nodeGroup || strieq(nodeGroup, thorName))
  6710. primaryThorProcesses.append(thorName);
  6711. }
  6712. unsigned nodes = thor.getCount("ThorSlaveProcess");
  6713. if (!nodes)
  6714. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: Thor cluster can not have 0 slave processes");
  6715. unsigned slavesPerNode = thor.getPropInt("@slavesPerNode", 1);
  6716. unsigned channelsPerSlave = thor.getPropInt("@channelsPerSlave", 1);
  6717. unsigned ts = nodes * slavesPerNode * channelsPerSlave;
  6718. numberOfSlaveLogs = nodes * slavesPerNode;
  6719. if (clusterWidth && (ts!=clusterWidth))
  6720. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: mismatched thor sizes in cluster");
  6721. clusterWidth = ts;
  6722. bool islcr = !thor.getPropBool("@Legacy");
  6723. if (!islcr)
  6724. throw MakeStringException(WUERR_MismatchThorType,"CEnvironmentClusterInfo: Legacy Thor no longer supported");
  6725. }
  6726. platform = ThorLCRCluster;
  6727. }
  6728. else if (roxie)
  6729. {
  6730. roxieProcess.set(roxie->queryProp("@name"));
  6731. platform = RoxieCluster;
  6732. getRoxieProcessServers(roxie, roxieServers);
  6733. clusterWidth = roxieServers.length();
  6734. ldapUser.set(roxie->queryProp("@ldapUser"));
  6735. StringBuffer encPassword (roxie->queryProp("@ldapPassword"));
  6736. if (encPassword.length())
  6737. decrypt(ldapPassword, encPassword);
  6738. const char *redundancyMode = roxie->queryProp("@slaveConfig");
  6739. if (redundancyMode && *redundancyMode)
  6740. {
  6741. unsigned dataCopies = roxie->getPropInt("@numDataCopies", 1);
  6742. if (strieq(redundancyMode, "overloaded"))
  6743. channelsPerNode = roxie->getPropInt("@channelsPernode", 1);
  6744. else if (strieq(redundancyMode, "full redundancy"))
  6745. {
  6746. roxieRedundancy = dataCopies-1;
  6747. roxieReplicateOffset = 0;
  6748. }
  6749. else if (strieq(redundancyMode, "cyclic redundancy"))
  6750. {
  6751. roxieRedundancy = dataCopies-1;
  6752. channelsPerNode = dataCopies;
  6753. roxieReplicateOffset = roxie->getPropInt("@cyclicOffset", 1);
  6754. }
  6755. }
  6756. }
  6757. else
  6758. {
  6759. clusterWidth = 1;
  6760. platform = HThorCluster;
  6761. }
  6762. if (agent)
  6763. {
  6764. assertex(!roxie);
  6765. agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
  6766. agentName.set(agent->queryProp("@name"));
  6767. }
  6768. else if (roxie)
  6769. agentQueue.set(getClusterRoxieQueueName(queue.clear(), name));
  6770. // MORE - does this need to be conditional?
  6771. serverQueue.set(getClusterEclCCServerQueueName(queue.clear(), name));
  6772. }
  6773. IStringVal & getName(IStringVal & str) const
  6774. {
  6775. str.set(name.get());
  6776. return str;
  6777. }
  6778. const char *getAlias() const
  6779. {
  6780. return alias;
  6781. }
  6782. IStringVal & getScope(IStringVal & str) const
  6783. {
  6784. str.set(prefix.get());
  6785. return str;
  6786. }
  6787. IStringVal & getAgentQueue(IStringVal & str) const
  6788. {
  6789. str.set(agentQueue);
  6790. return str;
  6791. }
  6792. IStringVal & getAgentName(IStringVal & str) const
  6793. {
  6794. str.set(agentName);
  6795. return str;
  6796. }
  6797. virtual IStringVal & getServerQueue(IStringVal & str) const
  6798. {
  6799. str.set(serverQueue);
  6800. return str;
  6801. }
  6802. IStringVal & getThorQueue(IStringVal & str) const
  6803. {
  6804. str.set(thorQueue);
  6805. return str;
  6806. }
  6807. unsigned getSize() const
  6808. {
  6809. return clusterWidth;
  6810. }
  6811. unsigned getNumberOfSlaveLogs() const
  6812. {
  6813. return numberOfSlaveLogs;
  6814. }
  6815. virtual ClusterType getPlatform() const
  6816. {
  6817. return platform;
  6818. }
  6819. IStringVal & getRoxieProcess(IStringVal & str) const
  6820. {
  6821. str.set(roxieProcess.get());
  6822. return str;
  6823. }
  6824. const StringArray & getThorProcesses() const
  6825. {
  6826. return thorProcesses;
  6827. }
  6828. const StringArray & getPrimaryThorProcesses() const
  6829. {
  6830. return primaryThorProcesses;
  6831. }
  6832. const SocketEndpointArray & getRoxieServers() const
  6833. {
  6834. return roxieServers;
  6835. }
  6836. unsigned getRoxieRedundancy() const
  6837. {
  6838. return roxieRedundancy;
  6839. }
  6840. unsigned getChannelsPerNode() const
  6841. {
  6842. return channelsPerNode;
  6843. }
  6844. int getRoxieReplicateOffset() const
  6845. {
  6846. return roxieReplicateOffset;
  6847. }
  6848. const char *getLdapUser() const
  6849. {
  6850. return ldapUser.get();
  6851. }
  6852. virtual const char *getLdapPassword() const
  6853. {
  6854. return ldapPassword.str();
  6855. }
  6856. };
  6857. IStringVal &getProcessQueueNames(IStringVal &ret, const char *process, const char *type, const char *suffix)
  6858. {
  6859. if (process)
  6860. {
  6861. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6862. Owned<IConstEnvironment> env = factory->openEnvironment();
  6863. Owned<IPropertyTree> root = &env->getPTree();
  6864. StringBuffer queueNames;
  6865. StringBuffer xpath;
  6866. xpath.appendf("%s[@process=\"%s\"]", type, process);
  6867. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  6868. ForEach(*targets)
  6869. {
  6870. IPropertyTree &target = targets->query();
  6871. if (target.hasProp(xpath))
  6872. {
  6873. if (queueNames.length())
  6874. queueNames.append(',');
  6875. queueNames.append(target.queryProp("@name")).append(suffix);
  6876. }
  6877. }
  6878. ret.set(queueNames);
  6879. }
  6880. return ret;
  6881. }
  6882. #define ROXIE_QUEUE_EXT ".roxie"
  6883. #define THOR_QUEUE_EXT ".thor"
  6884. #define ECLCCSERVER_QUEUE_EXT ".eclserver"
  6885. #define ECLSERVER_QUEUE_EXT ECLCCSERVER_QUEUE_EXT
  6886. #define ECLSCHEDULER_QUEUE_EXT ".eclscheduler"
  6887. #define ECLAGENT_QUEUE_EXT ".agent"
  6888. extern WORKUNIT_API void getDFUServerQueueNames(StringArray &ret, const char *process)
  6889. {
  6890. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6891. Owned<IConstEnvironment> env = factory->openEnvironment();
  6892. StringBuffer xpath ("Software/DfuServerProcess");
  6893. if (!isEmptyString(process))
  6894. xpath.appendf("[@name=\"%s\"]", process);
  6895. Owned<IPropertyTree> root = &env->getPTree();
  6896. Owned<IPropertyTreeIterator> targets = root->getElements(xpath.str());
  6897. ForEach(*targets)
  6898. {
  6899. IPropertyTree &target = targets->query();
  6900. if (target.hasProp("@queue"))
  6901. ret.appendListUniq(target.queryProp("@queue"), ",");
  6902. }
  6903. return;
  6904. }
  6905. extern WORKUNIT_API IStringVal &getEclCCServerQueueNames(IStringVal &ret, const char *process)
  6906. {
  6907. return getProcessQueueNames(ret, process, "EclCCServerProcess", ECLCCSERVER_QUEUE_EXT);
  6908. }
  6909. extern WORKUNIT_API IStringVal &getEclServerQueueNames(IStringVal &ret, const char *process)
  6910. {
  6911. return getProcessQueueNames(ret, process, "EclServerProcess", ECLSERVER_QUEUE_EXT); // shares queue name with EclCCServer
  6912. }
  6913. extern WORKUNIT_API IStringVal &getEclSchedulerQueueNames(IStringVal &ret, const char *process)
  6914. {
  6915. return getProcessQueueNames(ret, process, "EclSchedulerProcess", ECLSCHEDULER_QUEUE_EXT); // Shares deployment/config with EclCCServer
  6916. }
  6917. extern WORKUNIT_API IStringVal &getAgentQueueNames(IStringVal &ret, const char *process)
  6918. {
  6919. return getProcessQueueNames(ret, process, "EclAgentProcess", ECLAGENT_QUEUE_EXT);
  6920. }
  6921. extern WORKUNIT_API IStringVal &getRoxieQueueNames(IStringVal &ret, const char *process)
  6922. {
  6923. return getProcessQueueNames(ret, process, "RoxieCluster", ROXIE_QUEUE_EXT);
  6924. }
  6925. extern WORKUNIT_API IStringVal &getThorQueueNames(IStringVal &ret, const char *process)
  6926. {
  6927. return getProcessQueueNames(ret, process, "ThorCluster", THOR_QUEUE_EXT);
  6928. }
  6929. extern WORKUNIT_API StringBuffer &getClusterThorQueueName(StringBuffer &ret, const char *cluster)
  6930. {
  6931. return ret.append(cluster).append(THOR_QUEUE_EXT);
  6932. }
  6933. extern WORKUNIT_API StringBuffer &getClusterThorGroupName(StringBuffer &ret, const char *cluster)
  6934. {
  6935. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6936. Owned<IConstEnvironment> env = factory->openEnvironment();
  6937. Owned<IPropertyTree> root = &env->getPTree();
  6938. StringBuffer path;
  6939. path.append("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6940. IPropertyTree * child = root->queryPropTree(path);
  6941. if (child)
  6942. getClusterGroupName(*child, ret);
  6943. return ret;
  6944. }
  6945. extern WORKUNIT_API StringBuffer &getClusterGroupName(StringBuffer &ret, const char *cluster)
  6946. {
  6947. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6948. Owned<IConstEnvironment> env = factory->openEnvironment();
  6949. Owned<IPropertyTree> root = &env->getPTree();
  6950. StringBuffer path;
  6951. path.set("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6952. IPropertyTree * child = root->queryPropTree(path);
  6953. if (child)
  6954. {
  6955. return getClusterGroupName(*child, ret);
  6956. }
  6957. path.set("Software/RoxieCluster[@name=\"").append(cluster).append("\"]");
  6958. child = root->queryPropTree(path);
  6959. if (child)
  6960. {
  6961. return getClusterGroupName(*child, ret);
  6962. }
  6963. path.set("Software/EclAgentProcess[@name=\"").append(cluster).append("\"]");
  6964. child = root->queryPropTree(path);
  6965. if (child)
  6966. {
  6967. return ret.setf("hthor__%s", cluster);
  6968. }
  6969. return ret;
  6970. }
  6971. extern WORKUNIT_API ClusterType getClusterTypeByClusterName(const char *cluster)
  6972. {
  6973. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  6974. Owned<IConstEnvironment> env = factory->openEnvironment();
  6975. Owned<IPropertyTree> root = &env->getPTree();
  6976. StringBuffer path;
  6977. path.set("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  6978. if (root->hasProp(path))
  6979. return ThorLCRCluster;
  6980. path.set("Software/RoxieCluster[@name=\"").append(cluster).append("\"]");
  6981. if (root->hasProp(path))
  6982. return RoxieCluster;
  6983. path.set("Software/EclAgentProcess[@name=\"").append(cluster).append("\"]");
  6984. if (root->hasProp(path))
  6985. return HThorCluster;
  6986. return NoCluster;
  6987. }
  6988. extern WORKUNIT_API StringBuffer &getClusterRoxieQueueName(StringBuffer &ret, const char *cluster)
  6989. {
  6990. return ret.append(cluster).append(ROXIE_QUEUE_EXT);
  6991. }
  6992. extern WORKUNIT_API StringBuffer &getClusterEclCCServerQueueName(StringBuffer &ret, const char *cluster)
  6993. {
  6994. return ret.append(cluster).append(ECLCCSERVER_QUEUE_EXT);
  6995. }
  6996. extern WORKUNIT_API StringBuffer &getClusterEclServerQueueName(StringBuffer &ret, const char *cluster)
  6997. {
  6998. return ret.append(cluster).append(ECLSERVER_QUEUE_EXT);
  6999. }
  7000. extern WORKUNIT_API StringBuffer &getClusterEclAgentQueueName(StringBuffer &ret, const char *cluster)
  7001. {
  7002. return ret.append(cluster).append(ECLAGENT_QUEUE_EXT);
  7003. }
  7004. extern WORKUNIT_API IStringIterator *getTargetClusters(const char *processType, const char *processName)
  7005. {
  7006. Owned<CStringArrayIterator> ret = new CStringArrayIterator;
  7007. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7008. Owned<IConstEnvironment> env = factory->openEnvironment();
  7009. Owned<IPropertyTree> root = &env->getPTree();
  7010. StringBuffer xpath;
  7011. xpath.appendf("%s", processType ? processType : "*");
  7012. if (processName && *processName)
  7013. xpath.appendf("[@process=\"%s\"]", processName);
  7014. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  7015. ForEach(*targets)
  7016. {
  7017. IPropertyTree &target = targets->query();
  7018. if (target.hasProp(xpath))
  7019. {
  7020. ret->append(target.queryProp("@name"));
  7021. }
  7022. }
  7023. return ret.getClear();
  7024. }
  7025. extern WORKUNIT_API bool isProcessCluster(const char *process)
  7026. {
  7027. if (!process || !*process)
  7028. return false;
  7029. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7030. Owned<IConstEnvironment> env = factory->openEnvironment();
  7031. Owned<IPropertyTree> root = &env->getPTree();
  7032. VStringBuffer xpath("Software/*Cluster[@name=\"%s\"]", process);
  7033. return root->hasProp(xpath.str());
  7034. }
  7035. extern WORKUNIT_API bool isProcessCluster(const char *remoteDali, const char *process)
  7036. {
  7037. if (!remoteDali || !*remoteDali)
  7038. return isProcessCluster(process);
  7039. if (!process || !*process)
  7040. return false;
  7041. Owned<INode> remote = createINode(remoteDali, 7070);
  7042. if (!remote)
  7043. return false;
  7044. //Cannot use getEnvironmentFactory() since it is using a remotedali
  7045. VStringBuffer xpath("Environment/Software/*Cluster[@name=\"%s\"]/@name", process);
  7046. try
  7047. {
  7048. Owned<IPropertyTreeIterator> clusters = querySDS().getElementsRaw(xpath, remote, 1000*60*1);
  7049. return clusters->first();
  7050. }
  7051. catch (IException *E)
  7052. {
  7053. StringBuffer msg;
  7054. E->errorMessage(msg);
  7055. DBGLOG("Exception validating cluster %s/%s: %s", remoteDali, xpath.str(), msg.str());
  7056. E->Release();
  7057. }
  7058. return true;
  7059. }
  7060. IConstWUClusterInfo* getTargetClusterInfo(IPropertyTree *environment, IPropertyTree *cluster)
  7061. {
  7062. const char *clustname = cluster->queryProp("@name");
  7063. // MORE - at the moment configenf specifies eclagent and thor queues by (in effect) placing an 'example' thor or eclagent in the topology
  7064. // that uses the queue that will be used.
  7065. // We should and I hope will change that, at which point the code below gets simpler
  7066. StringBuffer prefix(cluster->queryProp("@prefix"));
  7067. prefix.toLowerCase();
  7068. StringBuffer xpath;
  7069. StringBuffer querySetName;
  7070. IPropertyTree *agent = NULL;
  7071. const char *agentName = cluster->queryProp("EclAgentProcess/@process");
  7072. if (agentName)
  7073. {
  7074. xpath.clear().appendf("Software/EclAgentProcess[@name=\"%s\"]", agentName);
  7075. agent = environment->queryPropTree(xpath.str());
  7076. }
  7077. Owned<IPropertyTreeIterator> ti = cluster->getElements("ThorCluster");
  7078. IArrayOf<IPropertyTree> thors;
  7079. ForEach(*ti)
  7080. {
  7081. const char *thorName = ti->query().queryProp("@process");
  7082. if (thorName)
  7083. {
  7084. xpath.clear().appendf("Software/ThorCluster[@name=\"%s\"]", thorName);
  7085. thors.append(*environment->getPropTree(xpath.str()));
  7086. }
  7087. }
  7088. const char *roxieName = cluster->queryProp("RoxieCluster/@process");
  7089. return new CEnvironmentClusterInfo(clustname, prefix, cluster->queryProp("@alias"), agent, thors, queryRoxieProcessTree(environment, roxieName));
  7090. }
  7091. IPropertyTree* getTopologyCluster(Owned<IPropertyTree> &envRoot, const char *clustname)
  7092. {
  7093. if (!clustname || !*clustname)
  7094. return NULL;
  7095. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7096. Owned<IConstEnvironment> env = factory->openEnvironment();
  7097. envRoot.setown(&env->getPTree());
  7098. StringBuffer xpath;
  7099. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  7100. return envRoot->getPropTree(xpath.str());
  7101. }
  7102. bool validateTargetClusterName(const char *clustname)
  7103. {
  7104. Owned<IPropertyTree> envRoot;
  7105. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  7106. return (cluster.get()!=NULL);
  7107. }
  7108. IConstWUClusterInfo* getTargetClusterInfo(const char *clustname)
  7109. {
  7110. Owned<IPropertyTree> envRoot;
  7111. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  7112. if (!cluster)
  7113. return NULL;
  7114. return getTargetClusterInfo(envRoot, cluster);
  7115. }
  7116. unsigned getEnvironmentClusterInfo(CConstWUClusterInfoArray &clusters)
  7117. {
  7118. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7119. Owned<IConstEnvironment> env = factory->openEnvironment();
  7120. Owned<IPropertyTree> root = &env->getPTree();
  7121. return getEnvironmentClusterInfo(root, clusters);
  7122. }
  7123. unsigned getEnvironmentClusterInfo(IPropertyTree* environmentRoot, CConstWUClusterInfoArray &clusters)
  7124. {
  7125. if (!environmentRoot)
  7126. return 0;
  7127. Owned<IPropertyTreeIterator> clusterIter = environmentRoot->getElements("Software/Topology/Cluster");
  7128. ForEach(*clusterIter)
  7129. {
  7130. IPropertyTree &node = clusterIter->query();
  7131. Owned<IConstWUClusterInfo> cluster = getTargetClusterInfo(environmentRoot, &node);
  7132. clusters.append(*cluster.getClear());
  7133. }
  7134. return clusters.ordinality();
  7135. }
  7136. const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name)
  7137. {
  7138. if (!clustname)
  7139. return NULL;
  7140. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7141. Owned<IConstEnvironment> env = factory->openEnvironment();
  7142. Owned<IPropertyTree> root = &env->getPTree();
  7143. StringBuffer xpath;
  7144. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  7145. Owned<IPropertyTree> cluster = root->getPropTree(xpath.str());
  7146. if (!cluster)
  7147. return NULL;
  7148. StringBuffer xpath1;
  7149. xpath1.appendf("%s/@process", processType);
  7150. name.append(cluster->queryProp(xpath1.str()));
  7151. return name.str();
  7152. }
  7153. unsigned getEnvironmentThorClusterNames(StringArray &thorNames, StringArray &groupNames, StringArray &targetNames, StringArray &queueNames)
  7154. {
  7155. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7156. Owned<IConstEnvironment> env = factory->openEnvironment();
  7157. Owned<IPropertyTree> root = &env->getPTree();
  7158. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  7159. ForEach(*allTargets)
  7160. {
  7161. IPropertyTree &target = allTargets->query();
  7162. const char *targetName = target.queryProp("@name");
  7163. if (targetName && *targetName)
  7164. {
  7165. Owned<IPropertyTreeIterator> thorClusters = target.getElements("ThorCluster");
  7166. ForEach(*thorClusters)
  7167. {
  7168. const char *thorName = thorClusters->query().queryProp("@process");
  7169. VStringBuffer query("Software/ThorCluster[@name=\"%s\"]",thorName);
  7170. IPropertyTree *thorCluster = root->queryPropTree(query.str());
  7171. if (thorCluster)
  7172. {
  7173. const char *groupName = thorCluster->queryProp("@nodeGroup");
  7174. if (!groupName||!*groupName)
  7175. groupName = thorName;
  7176. thorNames.append(thorName);
  7177. groupNames.append(groupName);
  7178. targetNames.append(targetName);
  7179. StringBuffer queueName(targetName);
  7180. queueNames.append(queueName.append(THOR_QUEUE_EXT));
  7181. }
  7182. }
  7183. }
  7184. }
  7185. return thorNames.ordinality();
  7186. }
  7187. unsigned getEnvironmentHThorClusterNames(StringArray &eclAgentNames, StringArray &groupNames, StringArray &targetNames)
  7188. {
  7189. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  7190. Owned<IConstEnvironment> env = factory->openEnvironment();
  7191. Owned<IPropertyTree> root = &env->getPTree();
  7192. Owned<IPropertyTreeIterator> allEclAgents = root->getElements("Software/EclAgentProcess");
  7193. ForEach(*allEclAgents)
  7194. {
  7195. IPropertyTree &eclAgent = allEclAgents->query();
  7196. const char *eclAgentName = eclAgent.queryProp("@name");
  7197. if (eclAgentName && *eclAgentName)
  7198. {
  7199. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  7200. ForEach(*allTargets)
  7201. {
  7202. IPropertyTree &target = allTargets->query();
  7203. const char *targetName = target.queryProp("@name");
  7204. if (targetName && *targetName)
  7205. {
  7206. StringBuffer xpath;
  7207. xpath.appendf("EclAgentProcess[@process=\"%s\"]", eclAgentName);
  7208. if (target.hasProp(xpath) && !target.hasProp("ThorCluster"))
  7209. {
  7210. StringBuffer groupName("hthor__");
  7211. groupName.append(eclAgentName);
  7212. groupNames.append(groupName);
  7213. eclAgentNames.append(eclAgentName);
  7214. targetNames.append(targetName);
  7215. }
  7216. }
  7217. }
  7218. }
  7219. }
  7220. return eclAgentNames.ordinality();
  7221. }
  7222. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  7223. {
  7224. CriticalBlock block(crit);
  7225. if (p->hasProp("Debug/ForceScope"))
  7226. {
  7227. StringBuffer prefix(p->queryProp("Debug/ForceScope"));
  7228. str.set(prefix.toLowerCase().str());
  7229. }
  7230. else
  7231. {
  7232. Owned <IConstWUClusterInfo> ci = getTargetClusterInfo(p->queryProp("@clusterName"));
  7233. if (ci)
  7234. ci->getScope(str);
  7235. else
  7236. str.clear();
  7237. }
  7238. return str;
  7239. }
  7240. //Queries
  7241. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  7242. {
  7243. CriticalBlock block(crit);
  7244. p->setPropInt("@codeVersion", codeVersion);
  7245. p->setProp("@buildVersion", buildVersion);
  7246. p->setProp("@eclVersion", eclVersion);
  7247. }
  7248. unsigned CLocalWorkUnit::getCodeVersion() const
  7249. {
  7250. CriticalBlock block(crit);
  7251. return p->getPropInt("@codeVersion");
  7252. }
  7253. unsigned CLocalWorkUnit::getWuidVersion() const
  7254. {
  7255. CriticalBlock block(crit);
  7256. return p->getPropInt("@wuidVersion");
  7257. }
  7258. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  7259. {
  7260. CriticalBlock block(crit);
  7261. buildVersion.set(p->queryProp("@buildVersion"));
  7262. eclVersion.set(p->queryProp("@eclVersion"));
  7263. }
  7264. void CLocalWorkUnit::setCloneable(bool value)
  7265. {
  7266. CriticalBlock block(crit);
  7267. p->setPropInt("@cloneable", value);
  7268. }
  7269. void CLocalWorkUnit::setIsClone(bool value)
  7270. {
  7271. CriticalBlock block(crit);
  7272. p->setPropInt("@isClone", value);
  7273. }
  7274. bool CLocalWorkUnit::getCloneable() const
  7275. {
  7276. CriticalBlock block(crit);
  7277. return p->getPropBool("@cloneable", false);
  7278. }
  7279. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  7280. {
  7281. CriticalBlock block(crit);
  7282. if (!userDesc)
  7283. {
  7284. userDesc.setown(createUserDescriptor());
  7285. SCMStringBuffer token;
  7286. getWorkunitDistributedAccessToken(token);
  7287. userDesc->set(queryUser(), token.str());//use token as password
  7288. }
  7289. return userDesc;
  7290. }
  7291. bool CLocalWorkUnit::isProtected() const
  7292. {
  7293. CriticalBlock block(crit);
  7294. return p->getPropBool("@protected", false);
  7295. }
  7296. bool CLocalWorkUnit::isPausing() const
  7297. {
  7298. CriticalBlock block(crit);
  7299. if (WUActionPause == getAction())
  7300. {
  7301. switch (getState())
  7302. {
  7303. case WUStateRunning:
  7304. case WUStateAborting:
  7305. return true;
  7306. }
  7307. }
  7308. return false;
  7309. }
  7310. void CLocalWorkUnit::protect(bool protectMode)
  7311. {
  7312. CriticalBlock block(crit);
  7313. p->setPropBool("@protected", protectMode);
  7314. }
  7315. void CLocalWorkUnit::setResultLimit(unsigned value)
  7316. {
  7317. CriticalBlock block(crit);
  7318. p->setPropInt("resultLimit", value);
  7319. }
  7320. unsigned CLocalWorkUnit::getResultLimit() const
  7321. {
  7322. CriticalBlock block(crit);
  7323. return p->getPropInt("resultLimit");
  7324. }
  7325. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  7326. {
  7327. CriticalBlock block(crit);
  7328. str.set(p->queryProp("SNAPSHOT"));
  7329. return str;
  7330. }
  7331. void CLocalWorkUnit::setSnapshot(const char * val)
  7332. {
  7333. CriticalBlock block(crit);
  7334. p->setProp("SNAPSHOT", val);
  7335. }
  7336. const static EnumMapping warningSeverityMap[] =
  7337. {
  7338. { SeverityInformation, "info" },
  7339. { SeverityWarning, "warning" },
  7340. { SeverityError, "error" },
  7341. { SeverityAlert, "alert" },
  7342. { SeverityIgnore, "ignore" },
  7343. { SeverityFatal, "fatal" },
  7344. { SeverityUnknown, NULL }
  7345. };
  7346. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  7347. {
  7348. StringBuffer xpath;
  7349. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7350. CriticalBlock block(crit);
  7351. IPropertyTree * mapping = p->queryPropTree(xpath);
  7352. if (mapping)
  7353. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  7354. return defaultSeverity;
  7355. }
  7356. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  7357. {
  7358. StringBuffer xpath;
  7359. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  7360. CriticalBlock block(crit);
  7361. IPropertyTree * mapping = p->queryPropTree(xpath);
  7362. if (!mapping)
  7363. {
  7364. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  7365. mapping = onWarnings->addPropTree("OnWarning");
  7366. mapping->setPropInt("@code", code);
  7367. }
  7368. setEnum(mapping, "@severity", severity, warningSeverityMap);
  7369. }
  7370. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  7371. {
  7372. IPropertyTree *l = (IPropertyTree *) *ll;
  7373. IPropertyTree *r = (IPropertyTree *) *rr;
  7374. return stricmp(l->queryName(), r->queryName());
  7375. };
  7376. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  7377. {
  7378. // Any other values in the WU that could affect generated code should be crc'ed here
  7379. IPropertyTree *tree = p->queryBranch("Debug");
  7380. if (tree)
  7381. {
  7382. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  7383. ICopyArrayOf<IPropertyTree> subs;
  7384. for(sub->first(); sub->isValid(); sub->next())
  7385. subs.append(sub->query());
  7386. subs.sort(comparePropTrees);
  7387. ForEachItemIn(idx, subs)
  7388. {
  7389. const char *name = subs.item(idx).queryName();
  7390. const char *val = subs.item(idx).queryProp(NULL);
  7391. crc = crc32(name, (size32_t)strlen(name), crc);
  7392. if (val)
  7393. crc = crc32(val, (size32_t)strlen(val), crc);
  7394. }
  7395. }
  7396. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  7397. for (plugins->first();plugins->isValid();plugins->next())
  7398. {
  7399. IConstWUPlugin &thisplugin = plugins->query();
  7400. SCMStringBuffer version;
  7401. thisplugin.getPluginVersion(version);
  7402. crc = crc32(version.str(), version.length(), crc);
  7403. }
  7404. return crc;
  7405. }
  7406. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7407. {
  7408. if (!to->hasProp(xpath) && from->hasProp(xpath))
  7409. to->setProp(xpath, from->queryProp(xpath));
  7410. }
  7411. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7412. {
  7413. if (from->hasProp(xpath))
  7414. to->setProp(xpath, from->queryProp(xpath));
  7415. }
  7416. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  7417. {
  7418. IPropertyTree * match = from->getBranch(xpath);
  7419. if (match)
  7420. to->setPropTree(xpath, match);
  7421. }
  7422. IPropertyTree *CLocalWorkUnit::queryPTree() const
  7423. {
  7424. return p;
  7425. }
  7426. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  7427. {
  7428. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  7429. if (!from)
  7430. {
  7431. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  7432. if (!fl)
  7433. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  7434. from = fl->c;
  7435. }
  7436. // Need to copy the query, the results, and the graphs from the cached query.
  7437. // The cache is made before the query is executed so there is no need to clear them.
  7438. if (!cached->getCloneable())
  7439. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  7440. const IPropertyTree * fromP = from->p;
  7441. IPropertyTree *pt;
  7442. CriticalBlock block(crit);
  7443. clearCached(false);
  7444. query.clear();
  7445. updateProp(p, fromP, "@jobName");
  7446. copyTree(p, fromP, "Query");
  7447. pt = fromP->getBranch("Application/LibraryModule");
  7448. if (pt)
  7449. {
  7450. ensurePTree(p, "Application");
  7451. p->setPropTree("Application/LibraryModule", pt);
  7452. }
  7453. pt = fromP->queryBranch("Debug");
  7454. if (pt)
  7455. {
  7456. IPropertyTree *curDebug = p->queryPropTree("Debug");
  7457. if (curDebug)
  7458. {
  7459. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  7460. ForEach(*elems)
  7461. {
  7462. IPropertyTree *elem = &elems->query();
  7463. if (!curDebug->hasProp(elem->queryName()))
  7464. curDebug->setPropTree(elem->queryName(),LINK(elem));
  7465. }
  7466. }
  7467. else
  7468. p->setPropTree("Debug", LINK(pt));
  7469. }
  7470. copyTree(p, fromP, "OnWarnings");
  7471. copyTree(p, fromP, "Plugins");
  7472. copyTree(p, fromP, "Libraries");
  7473. copyTree(p, fromP, "Results");
  7474. copyTree(p, fromP, "Graphs");
  7475. copyTree(p, fromP, "Workflow");
  7476. copyTree(p, fromP, "WebServicesInfo");
  7477. if (copyStats)
  7478. {
  7479. // Merge timing info from both branches
  7480. pt = fromP->getBranch("Statistics");
  7481. if (pt)
  7482. {
  7483. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  7484. mergePTree(tgtStatistics, pt);
  7485. pt->Release();
  7486. }
  7487. }
  7488. updateProp(p, fromP, "@clusterName");
  7489. updateProp(p, fromP, "allowedclusters");
  7490. updateProp(p, fromP, "@submitID");
  7491. updateProp(p, fromP, "SNAPSHOT");
  7492. setProp(p, fromP, "@eventScheduledCount");
  7493. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  7494. if (all)
  7495. {
  7496. setProp(p, fromP, "PriorityFlag");
  7497. setProp(p, fromP, "@priorityClass");
  7498. setProp(p, fromP, "@protected");
  7499. setProp(p, fromP, "@clusterName");
  7500. updateProp(p, fromP, "@scope");
  7501. }
  7502. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  7503. pt = fromP->getBranch("Variables");
  7504. if (pt)
  7505. {
  7506. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  7507. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  7508. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  7509. {
  7510. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  7511. const char *name = ptSrcVariable->queryProp("@name");
  7512. assertex(name);
  7513. StringBuffer xpath;
  7514. xpath.append("Variable[@name='").append(name).append("']");
  7515. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  7516. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  7517. merged->removeProp("Value"); // except value and status
  7518. merged->setProp("@status", "undefined");
  7519. if (!merged->getPropBool("@isScalar"))
  7520. merged->removeProp("totalRowCount");
  7521. merged->removeProp("rowCount");
  7522. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  7523. if (ptTgtVariable)
  7524. {
  7525. // copy status and Value from what is already set in target
  7526. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  7527. MemoryBuffer value;
  7528. if (ptTgtVariable->getPropBin("Value", value))
  7529. merged->setPropBin("Value", value.length(), value.toByteArray());
  7530. ptTgtVariable->removeProp(xpath.str());
  7531. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  7532. }
  7533. ptTgtVariables->addPropTree("Variable", merged);
  7534. }
  7535. pt->Release();
  7536. }
  7537. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  7538. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  7539. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  7540. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  7541. p->setProp("@hash", fromP->queryProp("@hash"));
  7542. p->setPropBool("@cloneable", true);
  7543. p->setPropBool("@isClone", true);
  7544. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  7545. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  7546. ForEach(*results)
  7547. {
  7548. CLocalWUResult result(LINK(&results->query()));
  7549. result.setResultStatus(ResultStatusUndefined);
  7550. }
  7551. copyTree(p, fromP, "usedsources"); // field usage
  7552. }
  7553. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7554. {
  7555. StringBuffer lower;
  7556. lower.append(propname).toLowerCase();
  7557. CriticalBlock block(crit);
  7558. StringBuffer prop("Debug/");
  7559. return p->hasProp(prop.append(lower));
  7560. }
  7561. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7562. {
  7563. StringBuffer lower;
  7564. lower.append(propname).toLowerCase();
  7565. CriticalBlock block(crit);
  7566. StringBuffer prop("Debug/");
  7567. str.set(p->queryProp(prop.append(lower).str()));
  7568. return str;
  7569. }
  7570. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7571. {
  7572. return getDebugValues(NULL);
  7573. }
  7574. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7575. {
  7576. CriticalBlock block(crit);
  7577. StringBuffer path("Debug/");
  7578. if (prop)
  7579. {
  7580. StringBuffer lower;
  7581. lower.append(prop).toLowerCase();
  7582. path.append(lower);
  7583. }
  7584. else
  7585. path.append("*");
  7586. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7587. }
  7588. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7589. {
  7590. StringBuffer lower;
  7591. lower.append(propname).toLowerCase();
  7592. CriticalBlock block(crit);
  7593. StringBuffer prop("Debug/");
  7594. prop.append(lower);
  7595. return p->getPropInt(prop.str(), defVal);
  7596. }
  7597. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7598. {
  7599. StringBuffer lower;
  7600. lower.append(propname).toLowerCase();
  7601. CriticalBlock block(crit);
  7602. StringBuffer prop("Debug/");
  7603. prop.append(lower);
  7604. return p->getPropInt64(prop.str(), defVal);
  7605. }
  7606. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7607. {
  7608. StringBuffer lower;
  7609. lower.append(propname).toLowerCase();
  7610. CriticalBlock block(crit);
  7611. StringBuffer prop("Debug/");
  7612. prop.append(lower);
  7613. return p->getPropBool(prop.str(), defVal);
  7614. }
  7615. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7616. {
  7617. VStringBuffer xpath("Process/%s/", type);
  7618. if (instance)
  7619. xpath.append(instance);
  7620. else
  7621. xpath.append("*");
  7622. CriticalBlock block(crit);
  7623. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7624. {
  7625. // NB: instance unused
  7626. if (streq("EclAgent", type))
  7627. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7628. else if (streq("Thor", type))
  7629. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7630. VStringBuffer xpath("Debug/%s", type);
  7631. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7632. }
  7633. else
  7634. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7635. }
  7636. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7637. {
  7638. VStringBuffer xpath("Process/%s/", type);
  7639. if (instance)
  7640. xpath.append(instance);
  7641. else
  7642. xpath.append("*");
  7643. CriticalBlock block(crit);
  7644. return p->getElements(xpath.str());
  7645. }
  7646. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7647. {
  7648. VStringBuffer xpath("Process/%s/*", type);
  7649. CriticalBlock block(crit);
  7650. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7651. }
  7652. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7653. {
  7654. VStringBuffer processType("Process/%s", type);
  7655. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7656. if (log)
  7657. xpath.appendf("[@log=\"%s\"]", log);
  7658. CriticalBlock block(crit);
  7659. if (!p->hasProp(xpath))
  7660. {
  7661. IPropertyTree *node = ensurePTree(p, processType.str());
  7662. node = node->addPropTree(instance);
  7663. node->setProp("@log", log);
  7664. node->setPropInt("@pid", pid);
  7665. }
  7666. }
  7667. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7668. {
  7669. StringBuffer lower;
  7670. lower.append(propname).toLowerCase();
  7671. CriticalBlock block(crit);
  7672. StringBuffer prop("Debug/");
  7673. prop.append(lower);
  7674. if (overwrite || !p->hasProp(prop.str()))
  7675. {
  7676. // MORE - not sure this line should be needed....
  7677. p->setProp("Debug", "");
  7678. p->setProp(prop.str(), value);
  7679. }
  7680. }
  7681. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7682. {
  7683. StringBuffer lower;
  7684. lower.append(propname).toLowerCase();
  7685. CriticalBlock block(crit);
  7686. StringBuffer prop("Debug/");
  7687. prop.append(lower);
  7688. if (overwrite || !p->hasProp(prop.str()))
  7689. {
  7690. // MORE - not sure this line should be needed....
  7691. p->setProp("Debug", "");
  7692. p->setPropInt(prop.str(), value);
  7693. }
  7694. }
  7695. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7696. {
  7697. CriticalBlock block(crit);
  7698. // MORE - not sure this line should be needed....
  7699. p->setProp("Tracing", "");
  7700. StringBuffer prop("Tracing/");
  7701. p->setProp(prop.append(propname).str(), value);
  7702. }
  7703. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7704. {
  7705. CriticalBlock block(crit);
  7706. StringBuffer prop("Tracing/");
  7707. p->setPropInt(prop.append(propname).str(), value);
  7708. }
  7709. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7710. {
  7711. CriticalBlock block(crit);
  7712. VStringBuffer prop("Tracing/%s", propname);
  7713. p->setPropInt64(prop.str(), value);
  7714. }
  7715. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7716. {
  7717. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7718. CriticalBlock block(crit);
  7719. if (!query)
  7720. {
  7721. IPropertyTree *s = p->getPropTree("Query");
  7722. if (s)
  7723. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7724. }
  7725. return query.getLink();
  7726. }
  7727. IWUQuery* CLocalWorkUnit::updateQuery()
  7728. {
  7729. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7730. CriticalBlock block(crit);
  7731. if (!query)
  7732. {
  7733. IPropertyTree *s = p->queryPropTree("Query");
  7734. if (!s)
  7735. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7736. s->Link();
  7737. query.setown(new CLocalWUQuery(s));
  7738. }
  7739. return query.getLink();
  7740. }
  7741. void CLocalWorkUnit::loadPlugins() const
  7742. {
  7743. CriticalBlock block(crit);
  7744. if (!pluginsCached)
  7745. {
  7746. assertex(plugins.length() == 0);
  7747. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7748. for (r->first(); r->isValid(); r->next())
  7749. {
  7750. IPropertyTree *rp = &r->query();
  7751. rp->Link();
  7752. plugins.append(*new CLocalWUPlugin(rp));
  7753. }
  7754. pluginsCached = true;
  7755. }
  7756. }
  7757. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7758. {
  7759. CriticalBlock block(crit);
  7760. loadPlugins();
  7761. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7762. }
  7763. void CLocalWorkUnit::loadLibraries() const
  7764. {
  7765. CriticalBlock block(crit);
  7766. if (!librariesCached)
  7767. {
  7768. assertex(libraries.length() == 0);
  7769. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7770. ForEach(*r)
  7771. {
  7772. IPropertyTree *rp = &r->query();
  7773. rp->Link();
  7774. libraries.append(*new CLocalWULibrary(rp));
  7775. }
  7776. librariesCached = true;
  7777. }
  7778. }
  7779. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7780. {
  7781. CriticalBlock block(crit);
  7782. loadLibraries();
  7783. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7784. }
  7785. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7786. {
  7787. CriticalBlock block(crit);
  7788. loadLibraries();
  7789. ForEachItemIn(idx, libraries)
  7790. {
  7791. SCMStringBuffer name;
  7792. IConstWULibrary &cur = libraries.item(idx);
  7793. cur.getName(name);
  7794. if (stricmp(name.str(), search)==0)
  7795. return &OLINK(cur);
  7796. }
  7797. return NULL;
  7798. }
  7799. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7800. {
  7801. str.append("Graph ").append(graphName);
  7802. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7803. else if (subId) str.append(" - id(").append(subId).append(")");
  7804. return str;
  7805. }
  7806. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7807. {
  7808. if (wfid)
  7809. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7810. str.append(graphName);
  7811. if (subId) str.append(":sg").append(subId);
  7812. return str;
  7813. }
  7814. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7815. {
  7816. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7817. unsigned len = (size32_t)strlen(label);
  7818. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7819. return false;
  7820. graphNum = 0;
  7821. subGraphNum = 0;
  7822. subId = 0;
  7823. const char *finger = label+6;
  7824. const char *finger2 = strchr(finger, '-');
  7825. if (NULL == finger2) // just graphName
  7826. graphName.set(finger);
  7827. else
  7828. {
  7829. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7830. finger = finger2+2; // skip '-' and space
  7831. finger2 = strchr(finger, ' ');
  7832. if (finger2)
  7833. {
  7834. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7835. finger = finger2+2; // skip space and '('
  7836. finger2 = strchr(finger, ')');
  7837. if (finger2)
  7838. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7839. }
  7840. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7841. {
  7842. finger += 3;
  7843. finger2 = strchr(finger, ')');
  7844. if (finger2)
  7845. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7846. }
  7847. }
  7848. if (graphName && !memicmp(graphName, "graph", 5))
  7849. graphNum = atoi(graphName + 5);
  7850. return true;
  7851. }
  7852. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7853. {
  7854. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7855. return false;
  7856. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7857. subGraphId = 0;
  7858. const char * colon = strchr(scope, ':');
  7859. if (!colon)
  7860. {
  7861. graphName.set(scope);
  7862. return true;
  7863. }
  7864. const char * subgraph = colon+1;
  7865. graphName.set(scope, (size32_t)(colon - scope));
  7866. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7867. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7868. return true;
  7869. }
  7870. 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)
  7871. {
  7872. if (!scope) scope = GLOBAL_SCOPE;
  7873. const char * kindName = queryStatisticName(kind);
  7874. StatisticMeasure measure = queryMeasure(kind);
  7875. //creator. scope and name must all be present, and must not contain semi colons.
  7876. assertex(creator && scope);
  7877. CriticalBlock block(crit);
  7878. IPropertyTree * stats = p->queryPropTree("Statistics");
  7879. if (!stats)
  7880. stats = p->addPropTree("Statistics");
  7881. IPropertyTree * statTree = NULL;
  7882. if (mergeAction != StatsMergeAppend)
  7883. {
  7884. StringBuffer xpath;
  7885. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7886. statTree = stats->queryPropTree(xpath.str());
  7887. }
  7888. if (!statTree)
  7889. {
  7890. statTree = stats->addPropTree("Statistic");
  7891. statTree->setProp("@creator", creator);
  7892. statTree->setProp("@scope", scope);
  7893. statTree->setProp("@kind", kindName);
  7894. //These items are primarily here to facilitate filtering.
  7895. statTree->setProp("@unit", queryMeasureName(measure));
  7896. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7897. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7898. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7899. if (optDescription)
  7900. statTree->setProp("@desc", optDescription);
  7901. if (statistics.cached)
  7902. statistics.append(LINK(statTree));
  7903. mergeAction = StatsMergeAppend;
  7904. }
  7905. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7906. {
  7907. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7908. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7909. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7910. if (oldMax < oldValue)
  7911. oldMax = oldValue;
  7912. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7913. statTree->setPropInt64("@count", count + oldCount);
  7914. if (maxValue > oldMax)
  7915. statTree->setPropInt64("@max", maxValue);
  7916. }
  7917. else
  7918. {
  7919. statTree->setPropInt64("@value", value);
  7920. statTree->setPropInt64("@count", count);
  7921. if (maxValue)
  7922. statTree->setPropInt64("@max", maxValue);
  7923. else
  7924. statTree->removeProp("@max");
  7925. }
  7926. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7927. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7928. {
  7929. _loadStatistics();
  7930. stat_type totalTime = 0;
  7931. ForEachItemIn(i, statistics)
  7932. {
  7933. IConstWUStatistic & cur = statistics.item(i);
  7934. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7935. totalTime += cur.getValue();
  7936. }
  7937. StringBuffer t;
  7938. formatTimeCollatable(t, totalTime, false);
  7939. p->setProp("@totalThorTime", t);
  7940. }
  7941. }
  7942. void CLocalWorkUnit::_loadStatistics() const
  7943. {
  7944. statistics.load(p,"Statistics/*");
  7945. }
  7946. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7947. {
  7948. //MORE: Optimize this....
  7949. WuScopeFilter filter;
  7950. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7951. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7952. if (stats->first())
  7953. return stats->getStat(kind, value);
  7954. return false;
  7955. }
  7956. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7957. {
  7958. assertex(filter.isOptimized());
  7959. WuScopeSourceFlags sources = filter.sourceFlags;
  7960. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7961. if (sources & SSFsearchGlobalStats)
  7962. {
  7963. {
  7964. CriticalBlock block(crit);
  7965. statistics.loadBranch(p,"Statistics");
  7966. }
  7967. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7968. compoundIter->addIter(localStats);
  7969. }
  7970. if (sources & SSFsearchGraphStats)
  7971. {
  7972. const char * wuid = p->queryName();
  7973. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7974. compoundIter->addIter(scopeIter);
  7975. }
  7976. if (sources & SSFsearchGraph)
  7977. {
  7978. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7979. compoundIter->addIter(graphIter);
  7980. }
  7981. if (sources & SSFsearchWorkflow)
  7982. {
  7983. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7984. if (iter)
  7985. {
  7986. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7987. compoundIter->addIter(workflowIter);
  7988. }
  7989. }
  7990. if (sources & SSFsearchExceptions)
  7991. {
  7992. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7993. compoundIter->addIter(notesIter);
  7994. }
  7995. return *compoundIter.getClear();
  7996. }
  7997. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7998. {
  7999. CriticalBlock block(crit);
  8000. IConstWUPlugin *existing = getPluginByName(qname);
  8001. if (existing)
  8002. return (IWUPlugin *) existing;
  8003. if (!plugins.length())
  8004. p->addPropTree("Plugins");
  8005. IPropertyTree *pl = p->queryPropTree("Plugins");
  8006. IPropertyTree *s = pl->addPropTree("Plugin");
  8007. s->Link();
  8008. IWUPlugin* q = new CLocalWUPlugin(s);
  8009. q->Link();
  8010. plugins.append(*q);
  8011. q->setPluginName(qname);
  8012. return q;
  8013. }
  8014. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  8015. {
  8016. CriticalBlock block(crit);
  8017. loadPlugins();
  8018. ForEachItemIn(idx, plugins)
  8019. {
  8020. SCMStringBuffer name;
  8021. IConstWUPlugin &cur = plugins.item(idx);
  8022. cur.getPluginName(name);
  8023. if (stricmp(name.str(), qname)==0)
  8024. {
  8025. cur.Link();
  8026. return &cur;
  8027. }
  8028. }
  8029. return NULL;
  8030. }
  8031. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  8032. {
  8033. CriticalBlock block(crit);
  8034. IConstWULibrary *existing = getLibraryByName(qname);
  8035. if (existing)
  8036. return (IWULibrary *) existing;
  8037. if (!libraries.length())
  8038. p->addPropTree("Libraries");
  8039. IPropertyTree *pl = p->queryPropTree("Libraries");
  8040. IPropertyTree *s = pl->addPropTree("Library");
  8041. s->Link();
  8042. IWULibrary* q = new CLocalWULibrary(s);
  8043. q->Link();
  8044. libraries.append(*q);
  8045. q->setName(qname);
  8046. return q;
  8047. }
  8048. void CLocalWorkUnit::_loadExceptions() const
  8049. {
  8050. assertex(exceptions.length() == 0);
  8051. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  8052. for (r->first(); r->isValid(); r->next())
  8053. {
  8054. IPropertyTree *rp = &r->query();
  8055. rp->Link();
  8056. exceptions.append(*new CLocalWUException(rp));
  8057. }
  8058. }
  8059. void CLocalWorkUnit::loadExceptions() const
  8060. {
  8061. CriticalBlock block(crit);
  8062. if (!exceptionsCached)
  8063. {
  8064. _loadExceptions();
  8065. exceptionsCached = true;
  8066. }
  8067. }
  8068. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  8069. {
  8070. CriticalBlock block(crit);
  8071. loadExceptions();
  8072. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  8073. }
  8074. unsigned CLocalWorkUnit::getExceptionCount() const
  8075. {
  8076. CriticalBlock block(crit);
  8077. loadExceptions();
  8078. return exceptions.length();
  8079. }
  8080. void CLocalWorkUnit::clearExceptions()
  8081. {
  8082. CriticalBlock block(crit);
  8083. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8084. loadExceptions();
  8085. ForEachItemInRev(idx, exceptions)
  8086. {
  8087. IWUException &e = exceptions.item(idx);
  8088. SCMStringBuffer s;
  8089. e.getExceptionSource(s);
  8090. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  8091. break;
  8092. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  8093. p->removeProp(xpath);
  8094. exceptions.remove(idx);
  8095. }
  8096. if (exceptions.length() == 0)
  8097. p->removeProp("Exceptions");
  8098. }
  8099. IWUException* CLocalWorkUnit::createException()
  8100. {
  8101. CriticalBlock block(crit);
  8102. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8103. loadExceptions();
  8104. if (!exceptions.length())
  8105. p->addPropTree("Exceptions");
  8106. IPropertyTree *r = p->queryPropTree("Exceptions");
  8107. IPropertyTree *s = r->addPropTree("Exception");
  8108. s->setPropInt("@sequence", exceptions.ordinality());
  8109. IWUException* q = new CLocalWUException(LINK(s));
  8110. exceptions.append(*LINK(q));
  8111. Owned<IJlibDateTime> now = createDateTimeNow();
  8112. SCMStringBuffer temp;
  8113. now->getString(temp);
  8114. q->setTimeStamp(temp.str());
  8115. return q;
  8116. }
  8117. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  8118. {
  8119. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8120. CriticalBlock block(crit);
  8121. if (!webServicesInfoCached)
  8122. {
  8123. assertex(!webServicesInfo);
  8124. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  8125. if (s)
  8126. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  8127. webServicesInfoCached = true;
  8128. }
  8129. return webServicesInfo.getLink();
  8130. }
  8131. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  8132. {
  8133. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8134. CriticalBlock block(crit);
  8135. if (!webServicesInfoCached)
  8136. {
  8137. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  8138. if (!s)
  8139. {
  8140. if (create)
  8141. s = p->addPropTree("WebServicesInfo");
  8142. else
  8143. return NULL;
  8144. }
  8145. s->Link();
  8146. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  8147. webServicesInfoCached = true;
  8148. }
  8149. return webServicesInfo.getLink();
  8150. }
  8151. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  8152. {
  8153. CLocalWUResult *l = (CLocalWUResult *) *ll;
  8154. CLocalWUResult *r = (CLocalWUResult *) *rr;
  8155. return l->getResultSequence() - r->getResultSequence();
  8156. }
  8157. void CLocalWorkUnit::_loadResults() const
  8158. {
  8159. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  8160. for (r->first(); r->isValid(); r->next())
  8161. {
  8162. IPropertyTree *rp = &r->query();
  8163. rp->Link();
  8164. results.append(*new CLocalWUResult(rp));
  8165. }
  8166. }
  8167. void CLocalWorkUnit::loadResults() const
  8168. {
  8169. if (!resultsCached)
  8170. {
  8171. assertex(results.length() == 0);
  8172. _loadResults();
  8173. results.sort(compareResults);
  8174. resultsCached = true;
  8175. }
  8176. }
  8177. void CLocalWorkUnit::_loadVariables() const
  8178. {
  8179. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  8180. for (r->first(); r->isValid(); r->next())
  8181. {
  8182. IPropertyTree *rp = &r->query();
  8183. rp->Link();
  8184. variables.append(*new CLocalWUResult(rp));
  8185. }
  8186. }
  8187. void CLocalWorkUnit::loadVariables() const
  8188. {
  8189. if (!variablesCached)
  8190. {
  8191. assertex(variables.length() == 0);
  8192. _loadVariables();
  8193. variablesCached = true;
  8194. }
  8195. }
  8196. void CLocalWorkUnit::_loadTemporaries() const
  8197. {
  8198. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  8199. for (r->first(); r->isValid(); r->next())
  8200. {
  8201. IPropertyTree *rp = &r->query();
  8202. rp->Link();
  8203. temporaries.append(*new CLocalWUResult(rp));
  8204. }
  8205. }
  8206. void CLocalWorkUnit::loadTemporaries() const
  8207. {
  8208. if (!temporariesCached)
  8209. {
  8210. assertex(temporaries.length() == 0);
  8211. _loadTemporaries();
  8212. temporariesCached = true;
  8213. }
  8214. }
  8215. void CLocalWorkUnit::deleteTemporaries()
  8216. {
  8217. CriticalBlock block(crit);
  8218. if (temporariesCached)
  8219. {
  8220. temporaries.kill();
  8221. temporariesCached = false;
  8222. }
  8223. p->removeProp("Temporaries");
  8224. }
  8225. IWUResult* CLocalWorkUnit::createResult()
  8226. {
  8227. CriticalBlock block(crit);
  8228. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8229. loadResults();
  8230. if (!results.length())
  8231. p->addPropTree("Results");
  8232. IPropertyTree *r = p->queryPropTree("Results");
  8233. IPropertyTree *s = r->addPropTree("Result");
  8234. s->Link();
  8235. IWUResult* q = new CLocalWUResult(s);
  8236. q->Link();
  8237. results.append(*q);
  8238. return q;
  8239. }
  8240. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  8241. {
  8242. CriticalBlock block(crit);
  8243. IConstWUResult *existing = getResultByName(qname);
  8244. if (existing)
  8245. return (IWUResult *) existing;
  8246. IWUResult* q = createResult();
  8247. q->setResultName(qname);
  8248. return q;
  8249. }
  8250. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  8251. {
  8252. CriticalBlock block(crit);
  8253. IConstWUResult *existing = getResultBySequence(seq);
  8254. if (existing)
  8255. return (IWUResult *) existing;
  8256. IWUResult* q = createResult();
  8257. q->setResultSequence(seq);
  8258. return q;
  8259. }
  8260. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  8261. {
  8262. CriticalBlock block(crit);
  8263. loadResults();
  8264. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  8265. }
  8266. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  8267. {
  8268. CriticalBlock block(crit);
  8269. loadResults();
  8270. ForEachItemIn(idx, results)
  8271. {
  8272. SCMStringBuffer name;
  8273. IConstWUResult &cur = results.item(idx);
  8274. cur.getResultName(name);
  8275. if (stricmp(name.str(), qname)==0)
  8276. {
  8277. cur.Link();
  8278. return &cur;
  8279. }
  8280. }
  8281. return NULL;
  8282. }
  8283. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  8284. {
  8285. CriticalBlock block(crit);
  8286. loadResults();
  8287. ForEachItemIn(idx, results)
  8288. {
  8289. IConstWUResult &cur = results.item(idx);
  8290. if (!isSpecialResultSequence(cur.getResultSequence()))
  8291. {
  8292. SCMStringBuffer name;
  8293. cur.getResultName(name);
  8294. if (stricmp(name.str(), qname)==0)
  8295. {
  8296. cur.Link();
  8297. return &cur;
  8298. }
  8299. }
  8300. }
  8301. return NULL;
  8302. }
  8303. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  8304. {
  8305. CriticalBlock block(crit);
  8306. loadResults();
  8307. ForEachItemIn(idx, results)
  8308. {
  8309. IConstWUResult &cur = results.item(idx);
  8310. if (cur.getResultSequence() == seq)
  8311. {
  8312. cur.Link();
  8313. return &cur;
  8314. }
  8315. }
  8316. return NULL;
  8317. }
  8318. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  8319. {
  8320. CriticalBlock block(crit);
  8321. loadVariables();
  8322. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  8323. }
  8324. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  8325. {
  8326. CriticalBlock block(crit);
  8327. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8328. return getVariableByName(qname);
  8329. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8330. return global->getVariableByName(qname);
  8331. }
  8332. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  8333. {
  8334. CriticalBlock block(crit);
  8335. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  8336. return updateVariableByName(qname);
  8337. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  8338. return global->updateVariableByName(qname);
  8339. }
  8340. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  8341. {
  8342. CriticalBlock block(crit);
  8343. loadVariables();
  8344. ForEachItemIn(idx, variables)
  8345. {
  8346. SCMStringBuffer name;
  8347. IConstWUResult &cur = variables.item(idx);
  8348. cur.getResultName(name);
  8349. if (stricmp(name.str(), qname)==0)
  8350. {
  8351. cur.Link();
  8352. return &cur;
  8353. }
  8354. }
  8355. return NULL;
  8356. }
  8357. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  8358. {
  8359. CriticalBlock block(crit);
  8360. loadTemporaries();
  8361. ForEachItemIn(idx, temporaries)
  8362. {
  8363. SCMStringBuffer name;
  8364. IConstWUResult &cur = temporaries.item(idx);
  8365. cur.getResultName(name);
  8366. if (stricmp(name.str(), qname)==0)
  8367. {
  8368. cur.Link();
  8369. return &cur;
  8370. }
  8371. }
  8372. return NULL;
  8373. }
  8374. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  8375. {
  8376. CriticalBlock block(crit);
  8377. loadTemporaries();
  8378. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  8379. }
  8380. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  8381. {
  8382. CriticalBlock block(crit);
  8383. IConstWUResult *existing = getTemporaryByName(qname);
  8384. if (existing)
  8385. return (IWUResult *) existing;
  8386. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  8387. IPropertyTree *s = vars->addPropTree("Variable");
  8388. s->Link();
  8389. IWUResult* q = new CLocalWUResult(s);
  8390. q->Link();
  8391. temporaries.append(*q);
  8392. q->setResultName(qname);
  8393. q->setResultSequence(ResultSequenceInternal);
  8394. return q;
  8395. }
  8396. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  8397. {
  8398. CriticalBlock block(crit);
  8399. IConstWUResult *existing = getVariableByName(qname);
  8400. if (existing)
  8401. return (IWUResult *) existing;
  8402. if (!variables.length())
  8403. p->addPropTree("Variables");
  8404. IPropertyTree *vars = p->queryPropTree("Variables");
  8405. IPropertyTree *s = vars->addPropTree("Variable");
  8406. s->Link();
  8407. IWUResult* q = new CLocalWUResult(s);
  8408. q->Link();
  8409. variables.append(*q);
  8410. q->setResultName(qname);
  8411. q->setResultSequence(ResultSequenceStored);
  8412. return q;
  8413. }
  8414. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  8415. {
  8416. CriticalBlock block(crit);
  8417. IPropertyTree *files = p->queryPropTree("Files");
  8418. if (!files) return;
  8419. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  8420. ICopyArrayOf<IPropertyTree> toRemove;
  8421. ForEach (*iter)
  8422. {
  8423. IPropertyTree &file = iter->query();
  8424. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  8425. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  8426. bool needDelete;
  8427. switch(fileKind)
  8428. {
  8429. case WUFileTemporary:
  8430. if(graph==NULL)
  8431. needDelete = true;
  8432. else
  8433. {
  8434. const char *graphOwner = file.queryProp("@graph");
  8435. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  8436. }
  8437. break;
  8438. case WUFileJobOwned:
  8439. needDelete = ((graph==NULL) && deleteJobOwned);
  8440. break;
  8441. case WUFileOwned:
  8442. needDelete = ((graph==NULL) && deleteOwned);
  8443. break;
  8444. default:
  8445. needDelete = false;
  8446. }
  8447. if(needDelete)
  8448. {
  8449. const char *name = file.queryProp("@name");
  8450. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  8451. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  8452. toRemove.append(file);
  8453. }
  8454. }
  8455. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  8456. }
  8457. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  8458. {
  8459. IDistributedSuperFile *super = file->querySuperFile();
  8460. StringBuffer fname;
  8461. file->getLogicalName(fname);
  8462. if (fname.length())
  8463. {
  8464. StringBuffer path("File[@name=\"");
  8465. path.append(fname).append("\"]");
  8466. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  8467. if (fileTree)
  8468. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  8469. else
  8470. {
  8471. StringBuffer cluster;
  8472. file->getClusterName(0,cluster);
  8473. fileTree = createPTree();
  8474. fileTree->setProp("@name", fname.str());
  8475. fileTree->setProp("@cluster", cluster.str());
  8476. fileTree->setPropInt("@useCount", 1);
  8477. fileTree = filesRead->addPropTree("File", fileTree);
  8478. }
  8479. if (super)
  8480. {
  8481. fileTree->setPropBool("@super", true);
  8482. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  8483. ForEach (*iter)
  8484. {
  8485. IDistributedFile &file = iter->query();
  8486. StringBuffer fname;
  8487. file.getLogicalName(fname);
  8488. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  8489. _noteFileRead(&file, filesRead);
  8490. }
  8491. }
  8492. }
  8493. }
  8494. void CLocalWorkUnit::_loadFilesRead() const
  8495. {
  8496. // Nothing to do
  8497. }
  8498. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  8499. {
  8500. if (file)
  8501. {
  8502. CriticalBlock block(crit);
  8503. IPropertyTree *files = p->queryPropTree("FilesRead");
  8504. if (!files)
  8505. files = p->addPropTree("FilesRead");
  8506. _noteFileRead(file, files);
  8507. }
  8508. }
  8509. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  8510. {
  8511. if (fieldUsage)
  8512. {
  8513. CriticalBlock block(crit);
  8514. p->addPropTree("usedsources", fieldUsage);
  8515. }
  8516. }
  8517. void CLocalWorkUnit::_loadFilesWritten() const
  8518. {
  8519. // Nothing to do
  8520. }
  8521. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8522. {
  8523. StringBuffer path("File[@name=\"");
  8524. path.append(fileName).append("\"]");
  8525. if (cluster)
  8526. path.append("[@cluster=\"").append(cluster).append("\"]");
  8527. IPropertyTree *file = files->queryPropTree(path.str());
  8528. if (file) files->removeTree(file);
  8529. file = createPTree();
  8530. file->setProp("@name", fileName);
  8531. if (cluster)
  8532. file->setProp("@cluster", cluster);
  8533. if (graphOwner)
  8534. file->setProp("@graph", graphOwner);
  8535. file->setPropInt("@kind", (unsigned)fileKind);
  8536. if (WUFileTemporary == fileKind)
  8537. file->setPropInt("@usageCount", usageCount);
  8538. files->addPropTree("File", file);
  8539. }
  8540. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  8541. {
  8542. CriticalBlock block(crit);
  8543. IPropertyTree *files = p->queryPropTree("Files");
  8544. if (!files)
  8545. files = p->addPropTree("Files");
  8546. if (!clusters)
  8547. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8548. else
  8549. {
  8550. ForEachItemIn(c, *clusters)
  8551. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8552. }
  8553. }
  8554. void CLocalWorkUnit::releaseFile(const char *fileName)
  8555. {
  8556. StringBuffer path("File[@name=\"");
  8557. path.append(fileName).append("\"]");
  8558. CriticalBlock block(crit);
  8559. IPropertyTree *files = p->queryPropTree("Files");
  8560. if (!files) return;
  8561. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8562. ForEach (*fiter)
  8563. {
  8564. IPropertyTree *file = &fiter->query();
  8565. unsigned usageCount = file->getPropInt("@usageCount");
  8566. if (usageCount > 1)
  8567. file->setPropInt("@usageCount", usageCount-1);
  8568. else
  8569. {
  8570. StringAttr name(file->queryProp("@name"));
  8571. files->removeTree(file);
  8572. if (!name.isEmpty()&&(1 == usageCount))
  8573. {
  8574. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8575. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8576. }
  8577. }
  8578. }
  8579. }
  8580. void CLocalWorkUnit::clearGraphProgress() const
  8581. {
  8582. }
  8583. void CLocalWorkUnit::resetBeforeGeneration()
  8584. {
  8585. CriticalBlock block(crit);
  8586. //Remove all associated files
  8587. Owned<IWUQuery> q = updateQuery();
  8588. q->removeAssociatedFiles();
  8589. //Remove any pre-existing workflow information
  8590. workflowIterator.clear();
  8591. p->removeProp("Workflow");
  8592. }
  8593. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8594. {
  8595. StringBuffer path("Files/File[@name=\"");
  8596. path.append(fileName).append("\"]/@usageCount");
  8597. CriticalBlock block(crit);
  8598. return p->getPropInt(path.str());
  8599. }
  8600. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8601. {
  8602. CriticalBlock block(crit);
  8603. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8604. if (!fieldUsageTree)
  8605. return NULL;
  8606. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8607. return new CConstWUFileUsageIterator(iter);
  8608. }
  8609. bool isFilenameResolved(StringBuffer& filename)
  8610. {
  8611. size32_t length = filename.length();
  8612. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8613. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8614. return true;
  8615. else
  8616. return false;
  8617. }
  8618. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8619. {
  8620. bool scopeLoaded = false;
  8621. SCMStringBuffer defaultScope;
  8622. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8623. if (!files)
  8624. return false; // this query was not compiled with recordFieldUsage option.
  8625. ForEach(*files)
  8626. {
  8627. Owned<IConstWUFileUsage> file = files->get();
  8628. StringBuffer filename(file->queryName());
  8629. size32_t length = filename.length();
  8630. if (length == 0)
  8631. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8632. StringBuffer normalizedFilename;
  8633. // Two cases to handle:
  8634. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8635. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8636. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8637. if (isFilenameResolved(filename))
  8638. {
  8639. // filename cannot be empty (i.e. empty single quotes '')
  8640. if (length == 2)
  8641. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8642. // Remove surrounding single quotes
  8643. StringAttr cleanFilename(filename.str()+1, length-2);
  8644. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8645. // We need to load a default scope from config and prefix the filename with it.
  8646. if (cleanFilename.str()[0] != '~')
  8647. {
  8648. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8649. if (!scopeLoaded)
  8650. {
  8651. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName);
  8652. if (!clusterInfo)
  8653. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8654. clusterInfo->getScope(defaultScope);
  8655. scopeLoaded = true;
  8656. }
  8657. normalizedFilename.append(defaultScope.str());
  8658. normalizedFilename.append(cleanFilename.str());
  8659. }
  8660. else
  8661. {
  8662. normalizedFilename.append(cleanFilename);
  8663. }
  8664. }
  8665. else
  8666. {
  8667. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8668. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8669. normalizedFilename.append(filename.str());
  8670. }
  8671. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8672. ForEach(*fields)
  8673. {
  8674. Owned<IConstWUFieldUsage> field = fields->get();
  8675. filenames.append(normalizedFilename.str());
  8676. columnnames.append(field->queryName());
  8677. }
  8678. }
  8679. return true;
  8680. }
  8681. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8682. {
  8683. return p->getPropTree("DiskUsageStats");
  8684. }
  8685. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8686. {
  8687. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8688. offset_t maxNodeUsage;
  8689. if (stats)
  8690. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8691. else
  8692. {
  8693. stats = p->addPropTree("DiskUsageStats");
  8694. maxNodeUsage = 0;
  8695. }
  8696. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8697. {
  8698. // record all details at time of max node usage.
  8699. stats->setPropInt("@minNode", _minNode);
  8700. stats->setPropInt("@maxNode", _maxNode);
  8701. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8702. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8703. stats->setPropInt64("@graphId", _graphId);
  8704. if (_avgNodeUsage)
  8705. {
  8706. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8707. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8708. stats->setPropInt("@skewHi", _skewHi);
  8709. stats->setPropInt("@skewLo", _skewLo);
  8710. }
  8711. }
  8712. }
  8713. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8714. {
  8715. CriticalBlock block(crit);
  8716. _loadFilesWritten();
  8717. return * p->getElements("Files/File");
  8718. }
  8719. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8720. {
  8721. CriticalBlock block(crit);
  8722. _loadFilesRead();
  8723. return * p->getElements("FilesRead/File");
  8724. }
  8725. //=================================================================================================
  8726. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8727. {
  8728. CriticalBlock block(crit);
  8729. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8730. return false;
  8731. Owned<IConstWUClusterInfo> newci = getTargetClusterInfo(cluster);
  8732. if (!newci)
  8733. return false;
  8734. StringBuffer currentcluster;
  8735. if (!p->getProp("@clusterName",currentcluster))
  8736. return false;
  8737. Owned<IConstWUClusterInfo> curci = getTargetClusterInfo(currentcluster.str());
  8738. if (!curci)
  8739. return false;
  8740. SCMStringBuffer curqname;
  8741. curci->getThorQueue(curqname);
  8742. const char *wuid = p->queryName();
  8743. void *qi = qs->getQ(curqname.str(),wuid);
  8744. if (!qi)
  8745. return false;
  8746. setClusterName(cluster);
  8747. SCMStringBuffer newqname;
  8748. newci->getThorQueue(newqname);
  8749. qs->putQ(newqname.str(),wuid,qi);
  8750. return true;
  8751. }
  8752. //=================================================================================================
  8753. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8754. {
  8755. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8756. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8757. ForEach(*graphIter)
  8758. {
  8759. IConstWUGraph &graph = graphIter->query();
  8760. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8761. SCMStringBuffer gName;
  8762. graph.getName(gName);
  8763. StringBuffer xpath("Graphs/Graph[@name=\"");
  8764. xpath.append(gName.s).append("\"]/xgmml");
  8765. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8766. if (xgmml) // don't know of any reason it shouldn't exist
  8767. {
  8768. xgmml->removeProp("graphBin");
  8769. xgmml->setPropTree("graph", graphTree.getClear());
  8770. }
  8771. }
  8772. return ret.getClear();
  8773. }
  8774. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8775. {
  8776. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8777. ForEach(*iter)
  8778. {
  8779. IPropertyTree &graph = iter->query();
  8780. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8781. }
  8782. }
  8783. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8784. {
  8785. if (graphsCached < (heavy ? 2 : 1))
  8786. {
  8787. graphs.kill();
  8788. _loadGraphs(heavy);
  8789. graphsCached = (heavy ? 2 : 1);
  8790. }
  8791. }
  8792. EnumMapping graphTypes[] = {
  8793. { GraphTypeAny, "unknown" },
  8794. { GraphTypeProgress, "progress" },
  8795. { GraphTypeEcl, "ECL" },
  8796. { GraphTypeActivities, "activities" },
  8797. { GraphTypeSubProgress, "subgraph" },
  8798. { GraphTypeSize, NULL },
  8799. };
  8800. WUGraphType getGraphTypeFromString(const char* type)
  8801. {
  8802. return (WUGraphType) getEnum(type, graphTypes);
  8803. }
  8804. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8805. {
  8806. wuidVersion = owner.getWuidVersion();
  8807. }
  8808. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8809. {
  8810. str.set(p->queryProp("@name"));
  8811. return str;
  8812. }
  8813. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8814. {
  8815. if (wuidVersion >= 2)
  8816. {
  8817. str.set(p->queryProp("@label"));
  8818. return str;
  8819. }
  8820. else
  8821. {
  8822. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8823. str.set(xgmml->queryProp("@label"));
  8824. return str;
  8825. }
  8826. }
  8827. WUGraphState CLocalWUGraph::getState() const
  8828. {
  8829. return owner.queryGraphState(p->queryProp("@name"));
  8830. }
  8831. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8832. {
  8833. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8834. if (xgmml)
  8835. {
  8836. StringBuffer x;
  8837. toXML(xgmml, x);
  8838. str.set(x.str());
  8839. }
  8840. return str;
  8841. }
  8842. unsigned CLocalWorkUnit::getGraphCount() const
  8843. {
  8844. CriticalBlock block(crit);
  8845. if (p->hasProp("Graphs"))
  8846. {
  8847. return p->queryPropTree("Graphs")->numChildren();
  8848. }
  8849. return 0;
  8850. }
  8851. unsigned CLocalWorkUnit::getSourceFileCount() const
  8852. {
  8853. CriticalBlock block(crit);
  8854. _loadFilesRead();
  8855. if (p->hasProp("FilesRead"))
  8856. {
  8857. return p->queryPropTree("FilesRead")->numChildren();
  8858. }
  8859. return 0;
  8860. }
  8861. unsigned CLocalWorkUnit::getResultCount() const
  8862. {
  8863. CriticalBlock block(crit);
  8864. if (p->hasProp("Results"))
  8865. {
  8866. return p->queryPropTree("Results")->numChildren();
  8867. }
  8868. return 0;
  8869. }
  8870. unsigned CLocalWorkUnit::getVariableCount() const
  8871. {
  8872. CriticalBlock block(crit);
  8873. if (p->hasProp("Variables"))
  8874. {
  8875. return p->queryPropTree("Variables")->numChildren();
  8876. }
  8877. return 0;
  8878. }
  8879. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8880. {
  8881. CriticalBlock block(crit);
  8882. if (p->hasProp("Application"))
  8883. {
  8884. return p->queryPropTree("Application")->numChildren();
  8885. }
  8886. return 0;
  8887. }
  8888. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8889. {
  8890. appendXMLOpenTag(s, name, NULL, false);
  8891. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8892. if (attrs->first())
  8893. {
  8894. unsigned attributeindent = indent + (size32_t) strlen(name);
  8895. unsigned count = attrs->count();
  8896. bool doindent = false;
  8897. ForEach(*attrs)
  8898. {
  8899. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8900. continue;
  8901. #ifndef _DEBUG
  8902. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8903. continue;
  8904. #endif
  8905. if (doindent)
  8906. s.append('\n').appendN(attributeindent, ' ');
  8907. else if (count > 3)
  8908. doindent = true;
  8909. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8910. }
  8911. }
  8912. s.append('>');
  8913. return s;
  8914. }
  8915. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8916. {
  8917. CriticalBlock block(crit);
  8918. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8919. if (!paramTree)
  8920. return str;
  8921. StringBuffer xml;
  8922. if (!hidePasswords)
  8923. toXML(paramTree, xml);
  8924. else
  8925. {
  8926. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8927. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8928. ForEach(*elems)
  8929. {
  8930. const char *paramname = elems->query().queryName();
  8931. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8932. if (p->getPropBool(xpath))
  8933. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8934. else
  8935. toXML(&elems->query(), xml, 2);
  8936. }
  8937. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8938. }
  8939. str.set(xml);
  8940. return str;
  8941. }
  8942. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8943. {
  8944. CriticalBlock block(crit);
  8945. return p->getPropTree("Parameters");
  8946. }
  8947. void CLocalWorkUnit::setXmlParams(const char *params)
  8948. {
  8949. CriticalBlock block(crit);
  8950. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8951. }
  8952. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8953. {
  8954. CriticalBlock block(crit);
  8955. p->setPropTree("Parameters", tree);
  8956. }
  8957. unsigned __int64 CLocalWorkUnit::getHash() const
  8958. {
  8959. CriticalBlock block(crit);
  8960. return p->getPropInt64("@hash");
  8961. }
  8962. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8963. {
  8964. CriticalBlock block(crit);
  8965. p->setPropInt64("@hash", hash);
  8966. }
  8967. // getGraphs / getGraphsMeta
  8968. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8969. // If a type other than any is requested, a postfilter is needed.
  8970. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8971. {
  8972. WUGraphType type;
  8973. Owned<T> base;
  8974. bool match()
  8975. {
  8976. return base->query().getType()==type;
  8977. }
  8978. public:
  8979. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8980. : base(_base), type(_type)
  8981. {
  8982. }
  8983. bool first()
  8984. {
  8985. if (!base->first())
  8986. return false;
  8987. if (match())
  8988. return true;
  8989. return next();
  8990. }
  8991. bool next()
  8992. {
  8993. while (base->next())
  8994. if (match())
  8995. return true;
  8996. return false;
  8997. }
  8998. virtual bool isValid()
  8999. {
  9000. return base->isValid();
  9001. }
  9002. U & query()
  9003. {
  9004. return base->query();
  9005. }
  9006. };
  9007. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  9008. {
  9009. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  9010. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  9011. */
  9012. CriticalBlock block(crit);
  9013. loadGraphs(false);
  9014. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  9015. if (type!=GraphTypeAny)
  9016. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  9017. return *giter;
  9018. }
  9019. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  9020. {
  9021. CriticalBlock block(crit);
  9022. loadGraphs(true);
  9023. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  9024. if (type!=GraphTypeAny)
  9025. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  9026. return *giter;
  9027. }
  9028. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  9029. {
  9030. CriticalBlock block(crit);
  9031. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  9032. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  9033. IPTree *graph = p->queryPropTree(xpath);
  9034. if (graph)
  9035. return new CLocalWUGraph(*this, LINK(graph));
  9036. return NULL;
  9037. }
  9038. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  9039. {
  9040. CriticalBlock block(crit);
  9041. if (!graphs.length())
  9042. p->addPropTree("Graphs");
  9043. IPropertyTree *r = p->queryPropTree("Graphs");
  9044. IPropertyTree *s = r->addPropTree("Graph");
  9045. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  9046. q->setName(name);
  9047. q->setLabel(label);
  9048. q->setType(type);
  9049. q->setWfid(wfid);
  9050. q->setXGMMLTree(xgmml);
  9051. graphs.append(*q);
  9052. }
  9053. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  9054. {
  9055. /* Owned<IRemoteConnection> conn = getProgressConnection();
  9056. if (conn)
  9057. {
  9058. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  9059. if (progress)
  9060. return new CConstGraphProgress(p->queryName(), graphName, progress);
  9061. }
  9062. */
  9063. return NULL;
  9064. }
  9065. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  9066. {
  9067. throwUnexpected(); // Should only be used for persisted workunits
  9068. }
  9069. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  9070. {
  9071. throwUnexpected(); // Should only be used for persisted workunits
  9072. }
  9073. void CLocalWorkUnit::setGraphState(const char *graphName, WUGraphState state) const
  9074. {
  9075. throwUnexpected(); // Should only be used for persisted workunits
  9076. }
  9077. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  9078. {
  9079. throwUnexpected(); // Should only be used for persisted workunits
  9080. }
  9081. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  9082. {
  9083. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  9084. }
  9085. void CLocalWUGraph::setName(const char *str)
  9086. {
  9087. p->setProp("@name", str);
  9088. }
  9089. void CLocalWUGraph::setLabel(const char *str)
  9090. {
  9091. p->setProp("@label", str);
  9092. }
  9093. void CLocalWUGraph::setWfid(unsigned wfid)
  9094. {
  9095. p->setPropInt("@wfid", wfid);
  9096. }
  9097. void CLocalWUGraph::setXGMML(const char *str)
  9098. {
  9099. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  9100. }
  9101. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  9102. {
  9103. assertex(strcmp(_graph->queryName(), "graph")==0);
  9104. IPropertyTree *xgmml = p->setPropTree("xgmml");
  9105. MemoryBuffer mb;
  9106. _graph->serialize(mb);
  9107. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  9108. // Cassandra workunit code actually lzw compresses the parent anyway
  9109. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  9110. graph.setown(_graph);
  9111. }
  9112. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  9113. {
  9114. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  9115. ForEach (*aIter)
  9116. {
  9117. const char *aName = aIter->queryName()+1;
  9118. if (0 != stricmp("id", aName)) // "id" reserved.
  9119. {
  9120. IPropertyTree *att = targetNode.addPropTree("att");
  9121. att->setProp("@name", aName);
  9122. att->setProp("@value", aIter->queryValue());
  9123. }
  9124. }
  9125. }
  9126. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  9127. {
  9128. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  9129. if (!graphNode) return;
  9130. unsigned nodeId = rootNode.getPropInt("@id");
  9131. StringBuffer progressNodePath("node[@id=\"");
  9132. progressNodePath.append(nodeId).append("\"]");
  9133. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  9134. if (progressNode)
  9135. {
  9136. expandAttributes(*graphNode, *progressNode);
  9137. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  9138. ForEach (*edges)
  9139. {
  9140. IPropertyTree &edge = edges->query();
  9141. StringBuffer edgePath("edge[@id=\"");
  9142. edgePath.append(edge.queryProp("@id")).append("\"]");
  9143. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  9144. if (graphEdge)
  9145. {
  9146. if (progressV < 1)
  9147. mergePTree(graphEdge, &edge);
  9148. else
  9149. { // must translate to XGMML format
  9150. expandAttributes(*graphEdge, edge);
  9151. // 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)
  9152. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  9153. ForEach (*iter)
  9154. {
  9155. IPropertyTree &t = iter->query();
  9156. IPropertyTree *att = graphEdge->addPropTree("att");
  9157. att->setProp("@name", t.queryName());
  9158. att->setProp("@value", t.queryProp(NULL));
  9159. }
  9160. }
  9161. }
  9162. }
  9163. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  9164. ForEach (*nodes)
  9165. {
  9166. IPropertyTree &node = nodes->query();
  9167. StringBuffer nodePath("node[@id=\"");
  9168. nodePath.append(node.queryProp("@id")).append("\"]");
  9169. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  9170. if (_node)
  9171. {
  9172. if (progressV < 1)
  9173. mergePTree(_node, &node);
  9174. else
  9175. { // must translate to XGMML format
  9176. expandAttributes(*_node, node);
  9177. }
  9178. }
  9179. }
  9180. }
  9181. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  9182. ForEach (*iter)
  9183. mergeProgress(iter->query(), progressTree, progressV);
  9184. }
  9185. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  9186. {
  9187. return p->getPropTree("xgmml");
  9188. }
  9189. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  9190. {
  9191. if (!graph)
  9192. {
  9193. // NB: although graphBin introduced in wuidVersion==2,
  9194. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  9195. MemoryBuffer mb;
  9196. if (p->getPropBin("xgmml/graphBin", mb))
  9197. graph.setown(createPTree(mb, ipt_lowmem));
  9198. else
  9199. graph.setown(p->getBranch("xgmml/graph"));
  9200. if (!graph)
  9201. return NULL;
  9202. }
  9203. if (!doMergeProgress)
  9204. return graph.getLink();
  9205. else
  9206. {
  9207. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  9208. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  9209. if (progress)
  9210. {
  9211. //MORE: Eventually this should directly access the new stats structure
  9212. unsigned progressV = progress->queryFormatVersion();
  9213. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  9214. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  9215. ForEach (*nodeIterator)
  9216. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  9217. }
  9218. return copy.getClear();
  9219. }
  9220. }
  9221. WUGraphType CLocalWUGraph::getType() const
  9222. {
  9223. return (WUGraphType) getEnum(p, "@type", graphTypes);
  9224. }
  9225. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  9226. {
  9227. str.set(p->queryProp("@type"));
  9228. if (!str.length())
  9229. str.set("unknown");
  9230. return str;
  9231. }
  9232. unsigned CLocalWUGraph::getWfid() const
  9233. {
  9234. return p->getPropInt("@wfid", 0);
  9235. }
  9236. void CLocalWUGraph::setType(WUGraphType _type)
  9237. {
  9238. setEnum(p, "@type", _type, graphTypes);
  9239. }
  9240. //=================================================================================================
  9241. EnumMapping queryFileTypes[] = {
  9242. { FileTypeCpp, "cpp" },
  9243. { FileTypeDll, "dll" },
  9244. { FileTypeResText, "res" },
  9245. { FileTypeHintXml, "hint" },
  9246. { FileTypeXml, "xml" },
  9247. { FileTypeLog, "log" },
  9248. { FileTypeSize, NULL },
  9249. };
  9250. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  9251. {
  9252. }
  9253. WUFileType CLocalWUAssociated::getType() const
  9254. {
  9255. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  9256. }
  9257. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  9258. {
  9259. str.set(p->queryProp("@desc"));
  9260. return str;
  9261. }
  9262. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  9263. {
  9264. str.set(p->queryProp("@ip"));
  9265. return str;
  9266. }
  9267. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  9268. {
  9269. str.set(p->queryProp("@filename"));
  9270. return str;
  9271. }
  9272. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  9273. {
  9274. str.set(pathTail(p->queryProp("@filename")));
  9275. return str;
  9276. }
  9277. unsigned CLocalWUAssociated::getCrc() const
  9278. {
  9279. return p->getPropInt("@crc", 0);
  9280. }
  9281. unsigned CLocalWUAssociated::getMinActivityId() const
  9282. {
  9283. return p->getPropInt("@minActivity", 0);
  9284. }
  9285. unsigned CLocalWUAssociated::getMaxActivityId() const
  9286. {
  9287. return p->getPropInt("@maxActivity", 0);
  9288. }
  9289. //=================================================================================================
  9290. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  9291. {
  9292. associatedCached = false;
  9293. }
  9294. EnumMapping queryTypes[] = {
  9295. { QueryTypeUnknown, "unknown" },
  9296. { QueryTypeEcl, "ECL" },
  9297. { QueryTypeSql, "SQL" },
  9298. { QueryTypeXml, "XML" },
  9299. { QueryTypeAttribute, "Attribute" },
  9300. { QueryTypeSize, NULL },
  9301. };
  9302. WUQueryType CLocalWUQuery::getQueryType() const
  9303. {
  9304. return (WUQueryType) getEnum(p, "@type", queryTypes);
  9305. }
  9306. void CLocalWUQuery::setQueryType(WUQueryType qt)
  9307. {
  9308. setEnum(p, "@type", qt, queryTypes);
  9309. }
  9310. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  9311. {
  9312. const char *text = p->queryProp("Text");
  9313. if (!text)
  9314. text = p->queryProp("ShortText");
  9315. str.set(text);
  9316. return str;
  9317. }
  9318. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  9319. {
  9320. const char * text = p->queryProp("ShortText");
  9321. if (text)
  9322. str.set(text);
  9323. else
  9324. {
  9325. text = p->queryProp("Text");
  9326. if (isArchiveQuery(text))
  9327. {
  9328. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9329. const char * path = xml->queryProp("Query/@attributePath");
  9330. if (path)
  9331. {
  9332. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9333. if (resolved)
  9334. str.set(resolved->queryProp(NULL));
  9335. }
  9336. else
  9337. str.set(xml->queryProp("Query"));
  9338. }
  9339. else
  9340. str.set(text);
  9341. }
  9342. return str;
  9343. }
  9344. bool CLocalWUQuery::isArchive() const
  9345. {
  9346. if (p->hasProp("@isArchive"))
  9347. return p->getPropBool("@isArchive");
  9348. const char *text = p->queryProp("Text");
  9349. return isArchiveQuery(text);
  9350. }
  9351. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  9352. {
  9353. str.set(p->queryProp("@name"));
  9354. return str;
  9355. }
  9356. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  9357. {
  9358. str.set(p->queryProp("@main"));
  9359. return str;
  9360. }
  9361. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  9362. {
  9363. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9364. if (entry)
  9365. entry->getNameTail(str);
  9366. return str;
  9367. }
  9368. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  9369. {
  9370. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  9371. if (entry)
  9372. entry->getName(str);
  9373. return str;
  9374. }
  9375. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  9376. {
  9377. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  9378. if (entry)
  9379. entry->getName(str);
  9380. return str;
  9381. }
  9382. unsigned CLocalWUQuery::getQueryDllCrc() const
  9383. {
  9384. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  9385. if (entry)
  9386. return entry->getCrc();
  9387. return 0;
  9388. }
  9389. void CLocalWUQuery::setQueryText(const char *text)
  9390. {
  9391. bool isArchive = isArchiveQuery(text);
  9392. if (isArchive)
  9393. {
  9394. p->setProp("Text", text);
  9395. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  9396. const char * path = xml->queryProp("Query/@attributePath");
  9397. if (path)
  9398. {
  9399. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  9400. if (resolved)
  9401. p->setProp("ShortText", resolved->queryProp(NULL));
  9402. }
  9403. else
  9404. p->setProp("ShortText", xml->queryProp("Query"));
  9405. }
  9406. else
  9407. {
  9408. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  9409. // but as long as there may be new workunits compiled by old systems, we can't
  9410. p->setProp("ShortText", text);
  9411. }
  9412. p->setPropBool("@isArchive", isArchive);
  9413. if (isArchive)
  9414. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  9415. }
  9416. void CLocalWUQuery::setQueryName(const char *qname)
  9417. {
  9418. p->setProp("@name", qname);
  9419. }
  9420. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  9421. {
  9422. p->setProp("@main", str);
  9423. }
  9424. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  9425. {
  9426. CriticalBlock block(crit);
  9427. loadAssociated();
  9428. StringBuffer xpath;
  9429. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  9430. if (p->hasProp(xpath))
  9431. return;
  9432. if (!associated.length())
  9433. p->addPropTree("Associated");
  9434. IPropertyTree *pl = p->queryPropTree("Associated");
  9435. IPropertyTree *s = pl->addPropTree("File");
  9436. setEnum(s, "@type", type, queryFileTypes);
  9437. s->setProp("@filename", name);
  9438. s->setProp("@ip", ip);
  9439. s->setProp("@desc", desc);
  9440. if (crc)
  9441. s->setPropInt("@crc", crc);
  9442. if (minActivity)
  9443. s->setPropInt("@minActivity", minActivity);
  9444. if (maxActivity)
  9445. s->setPropInt("@maxActivity", maxActivity);
  9446. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  9447. associated.append(*q);
  9448. }
  9449. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  9450. {
  9451. CriticalBlock block(crit);
  9452. associatedCached = false;
  9453. associated.kill();
  9454. StringBuffer xpath;
  9455. xpath.append("Associated/File");
  9456. if (type)
  9457. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  9458. if (name)
  9459. xpath.append("[@filename=\"").append(name).append("\"]");
  9460. if (desc)
  9461. xpath.append("[@desc=\"").append(desc).append("\"]");
  9462. p->removeProp(xpath.str());
  9463. }
  9464. void CLocalWUQuery::removeAssociatedFiles()
  9465. {
  9466. associatedCached = false;
  9467. associated.kill();
  9468. p->removeProp("Associated");
  9469. }
  9470. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  9471. {
  9472. CriticalBlock block(crit);
  9473. loadAssociated();
  9474. ForEachItemIn(idx, associated)
  9475. {
  9476. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  9477. if (cur.getType() == type)
  9478. {
  9479. if (index-- == 0)
  9480. return &OLINK(cur);
  9481. }
  9482. }
  9483. return NULL;
  9484. }
  9485. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  9486. {
  9487. const char * name = p->queryProp(propname);
  9488. if (name)
  9489. {
  9490. IPropertyTree *s = createPTree("File");
  9491. setEnum(s, "@type", type, queryFileTypes);
  9492. s->setProp("@filename", name);
  9493. if (crc)
  9494. s->setPropInt("@crc", crc);
  9495. associated.append(*new CLocalWUAssociated(s));
  9496. }
  9497. }
  9498. void CLocalWUQuery::loadAssociated() const
  9499. {
  9500. CriticalBlock block(crit);
  9501. if (!associatedCached)
  9502. {
  9503. assertex(associated.length() == 0);
  9504. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  9505. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  9506. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  9507. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  9508. for (r->first(); r->isValid(); r->next())
  9509. {
  9510. IPropertyTree *rp = &r->query();
  9511. rp->Link();
  9512. associated.append(*new CLocalWUAssociated(rp));
  9513. }
  9514. associatedCached = true;
  9515. }
  9516. }
  9517. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  9518. {
  9519. CriticalBlock block(crit);
  9520. loadAssociated();
  9521. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  9522. }
  9523. //========================================================================================
  9524. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  9525. {
  9526. }
  9527. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  9528. {
  9529. str.set(p->queryProp("@module"));
  9530. return str;
  9531. }
  9532. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  9533. {
  9534. str.set(p->queryProp("@attribute"));
  9535. return str;
  9536. }
  9537. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  9538. {
  9539. str.set(p->queryProp("@defaultName"));
  9540. return str;
  9541. }
  9542. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  9543. {
  9544. return (unsigned) p->getPropInt("@crc");
  9545. }
  9546. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  9547. {
  9548. if (!name)
  9549. {
  9550. StringBuffer ws_info;
  9551. ws_info.appendf("<%s ", p->queryName());
  9552. Owned<IAttributeIterator> attrs = p->getAttributes();
  9553. for(attrs->first(); attrs->isValid(); attrs->next())
  9554. {
  9555. const char *name = attrs->queryName()+1;
  9556. const char *value = attrs->queryValue();
  9557. ws_info.appendf("%s='%s' ", name, value);
  9558. }
  9559. ws_info.append("> \n");
  9560. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9561. ForEach(*info)
  9562. {
  9563. IPropertyTree &item = info->query();
  9564. const char *name = item.queryName();
  9565. if (name)
  9566. {
  9567. MemoryBuffer mb;
  9568. bool isbin = p->isBinary(name);
  9569. if (isbin)
  9570. {
  9571. p->getPropBin(name,mb);
  9572. if (mb.length())
  9573. {
  9574. unsigned len = 0;
  9575. mb.read(len);
  9576. StringBuffer encodedString;
  9577. StringBuffer val(len, (const char *) mb.readDirect(len));
  9578. encodeXML(val, encodedString);
  9579. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9580. }
  9581. }
  9582. else
  9583. {
  9584. StringBuffer tmp;
  9585. toXML(&item, tmp);
  9586. ws_info.append(tmp.str());
  9587. }
  9588. }
  9589. }
  9590. ws_info.appendf("</%s>", p->queryName());
  9591. str.setLen(ws_info.str(), ws_info.length());
  9592. }
  9593. else
  9594. {
  9595. MemoryBuffer mb;
  9596. p->getPropBin(name,mb);
  9597. if (mb.length())
  9598. {
  9599. unsigned len;
  9600. mb.read(len);
  9601. str.setLen((const char *) mb.readDirect(len), len);
  9602. }
  9603. }
  9604. return str;
  9605. }
  9606. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9607. {
  9608. str.set(p->queryProp(name));
  9609. return str;
  9610. }
  9611. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9612. {
  9613. p->setProp("@module", mname);
  9614. }
  9615. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9616. {
  9617. p->setProp("@attribute", aname);
  9618. }
  9619. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9620. {
  9621. p->setProp("@defaultName", dname);
  9622. }
  9623. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9624. {
  9625. p->setPropInt("@crc", crc);
  9626. }
  9627. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9628. {
  9629. MemoryBuffer m;
  9630. unsigned len = (size32_t)strlen(info);
  9631. serializeLPString(len, info, m);
  9632. p->setPropBin(name, m.length(), m.toByteArray());
  9633. }
  9634. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9635. {
  9636. p->setProp(name, info);
  9637. }
  9638. //========================================================================================
  9639. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9640. {
  9641. }
  9642. EnumMapping resultStatuses[] = {
  9643. { ResultStatusUndefined, "undefined" },
  9644. { ResultStatusCalculated, "calculated" },
  9645. { ResultStatusSupplied, "supplied" },
  9646. { ResultStatusFailed, "failed" },
  9647. { ResultStatusPartial, "partial" },
  9648. { ResultStatusSize, NULL }
  9649. };
  9650. WUResultStatus CLocalWUResult::getResultStatus() const
  9651. {
  9652. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9653. }
  9654. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9655. {
  9656. str.set(p->queryProp("@name"));
  9657. return str;
  9658. }
  9659. int CLocalWUResult::getResultSequence() const
  9660. {
  9661. return p->getPropInt("@sequence", -1);
  9662. }
  9663. bool CLocalWUResult::isResultScalar() const
  9664. {
  9665. return p->getPropInt("@isScalar", 1) != 0;
  9666. }
  9667. bool findSize(int size, IntArray &sizes)
  9668. {
  9669. ForEachItemIn(idx, sizes)
  9670. {
  9671. if (sizes.item(idx)==size)
  9672. return true;
  9673. }
  9674. return false;
  9675. }
  9676. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9677. {
  9678. MemoryBuffer schema;
  9679. p->getPropBin("SchemaRaw", schema);
  9680. if (schema.length())
  9681. {
  9682. for (;;)
  9683. {
  9684. StringAttr name;
  9685. schema.read(name);
  9686. if (*schema.readDirect(0)==type_void)
  9687. break;
  9688. names.append(*new StringAttrItem(name));
  9689. types.append(*deserializeType(schema)); // MORE - nested records!
  9690. }
  9691. schema.skip(1);
  9692. if (schema.length() != schema.getPos())
  9693. {
  9694. unsigned eclLen;
  9695. schema.read(eclLen);
  9696. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9697. if (eclText)
  9698. {
  9699. eclText->setLen(schemaData, eclLen);
  9700. if ((eclLen == 0) && names.ordinality())
  9701. {
  9702. const char * firstName = names.item(0).text;
  9703. StringBuffer temp;
  9704. temp.append("RECORD ");
  9705. types.item(0).getECLType(temp);
  9706. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9707. eclText->set(temp.str());
  9708. }
  9709. }
  9710. }
  9711. }
  9712. }
  9713. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9714. {
  9715. ForEachItemIn(idx, types)
  9716. {
  9717. StringAttrItem &name = names.item(idx);
  9718. ITypeInfo &type = types.item(idx);
  9719. unsigned size = type.getSize();
  9720. switch(type.getTypeCode())
  9721. {
  9722. case type_data:
  9723. if (size==UNKNOWN_LENGTH)
  9724. {
  9725. if (in.remaining() < sizeof(int))
  9726. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9727. in.read(size);
  9728. }
  9729. outputXmlData(size, in.readDirect(size), name.text, out);
  9730. break;
  9731. case type_string:
  9732. if (size==UNKNOWN_LENGTH)
  9733. {
  9734. if (in.remaining() < sizeof(int))
  9735. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9736. in.read(size);
  9737. }
  9738. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9739. break;
  9740. case type_varstring:
  9741. {
  9742. if (size == UNKNOWN_LENGTH)
  9743. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9744. const char * text = (const char *) in.readDirect(size);
  9745. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9746. break;
  9747. }
  9748. case type_unicode:
  9749. {
  9750. unsigned len = type.getStringLen();
  9751. if (size==UNKNOWN_LENGTH)
  9752. in.read(len);
  9753. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9754. }
  9755. break;
  9756. case type_utf8:
  9757. {
  9758. unsigned len = type.getStringLen();
  9759. if (size==UNKNOWN_LENGTH)
  9760. {
  9761. in.read(len);
  9762. size = rtlUtf8Size(len, in.readDirect(0));
  9763. }
  9764. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9765. }
  9766. break;
  9767. case type_qstring:
  9768. {
  9769. unsigned len = type.getStringLen();
  9770. if (size==UNKNOWN_LENGTH)
  9771. in.read(len);
  9772. unsigned outlen;
  9773. char *outstr;
  9774. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9775. outputXmlString(outlen, outstr, name.text, out);
  9776. free(outstr);
  9777. break;
  9778. }
  9779. case type_int:
  9780. case type_swapint:
  9781. if (type.isSigned())
  9782. {
  9783. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9784. unsigned __int64 cval8 = 0;
  9785. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9786. if (type.isSwappedEndian())
  9787. {
  9788. unsigned idx = 0;
  9789. if (raw[idx] & 0x80)
  9790. cval8 = (__int64)-1;
  9791. while (size--)
  9792. cval8 = (cval8 << 8) | raw[idx++];
  9793. }
  9794. else
  9795. {
  9796. if (raw[size-1] & 0x80)
  9797. cval8 = (__int64)-1;
  9798. while (size--)
  9799. cval8 = (cval8 << 8) | raw[size];
  9800. }
  9801. outputXmlInt((__int64) cval8, name.text, out);
  9802. }
  9803. else
  9804. {
  9805. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9806. unsigned __int64 cval8 = 0;
  9807. if (type.isSwappedEndian())
  9808. {
  9809. unsigned idx = 0;
  9810. while (size--)
  9811. cval8 = (cval8 << 8) | raw[idx++];
  9812. }
  9813. else
  9814. {
  9815. while (size--)
  9816. cval8 = (cval8 << 8) | raw[size];
  9817. }
  9818. outputXmlUInt(cval8, name.text, out);
  9819. }
  9820. break;
  9821. case type_boolean:
  9822. bool cvalb;
  9823. in.read(cvalb);
  9824. outputXmlBool(cvalb, name.text, out);
  9825. break;
  9826. case type_decimal:
  9827. if (type.isSigned())
  9828. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9829. else
  9830. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9831. break;
  9832. case type_real:
  9833. double cvald;
  9834. switch(size)
  9835. {
  9836. case 4:
  9837. float cvalf;
  9838. in.read(cvalf);
  9839. cvald = cvalf;
  9840. break;
  9841. case 8:
  9842. in.read(cvald);
  9843. break;
  9844. }
  9845. outputXmlReal(cvald, name.text, out);
  9846. break;
  9847. default:
  9848. assertex(!"unexpected type in raw record");
  9849. break;
  9850. }
  9851. }
  9852. }
  9853. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9854. {
  9855. TypeInfoArray types;
  9856. StringAttrArray names;
  9857. getSchema(types, names);
  9858. StringBuffer xml;
  9859. const char * name = p->queryProp("@name");
  9860. if (name)
  9861. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9862. else
  9863. xml.append("<Dataset>\n");
  9864. if (hidePassword && p->getPropBool("Format/@password"))
  9865. {
  9866. xml.append(" <Row>");
  9867. appendXMLTag(xml, name, "****");
  9868. xml.append("</Row>\n");
  9869. }
  9870. else if (p->hasProp("Value"))
  9871. {
  9872. MemoryBuffer raw;
  9873. p->getPropBin("Value", raw);
  9874. unsigned __int64 numrows = getResultRowCount();
  9875. while (numrows--)
  9876. {
  9877. xml.append(" <Row>");
  9878. readRow(xml, raw, types, names);
  9879. xml.append("</Row>\n");
  9880. }
  9881. }
  9882. else if (p->hasProp("xmlValue"))
  9883. {
  9884. xml.append(" <Row>");
  9885. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9886. xml.append("</Row>\n");
  9887. }
  9888. xml.append("</Dataset>\n");
  9889. str.set(xml.str());
  9890. return str;
  9891. }
  9892. IProperties *CLocalWUResult::queryResultXmlns()
  9893. {
  9894. CriticalBlock block(crit);
  9895. if (xmlns)
  9896. return xmlns;
  9897. xmlns.setown(createProperties());
  9898. Owned<IAttributeIterator> it = p->getAttributes();
  9899. unsigned prefixLen = strlen("@xmlns");
  9900. ForEach(*it)
  9901. {
  9902. const char *name = it->queryName();
  9903. if (!strncmp("@xmlns", name, prefixLen))
  9904. {
  9905. if (name[prefixLen]==':') //normal case
  9906. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9907. else if (!name[prefixLen]) //special case, unprefixed namespace
  9908. xmlns->setProp("xmlns", it->queryValue());
  9909. }
  9910. }
  9911. return xmlns;
  9912. }
  9913. unsigned CLocalWUResult::getResultFetchSize() const
  9914. {
  9915. return p->getPropInt("fetchSize", 100);
  9916. }
  9917. __int64 CLocalWUResult::getResultTotalRowCount() const
  9918. {
  9919. return p->getPropInt64("totalRowCount", -1);
  9920. }
  9921. __int64 CLocalWUResult::getResultRowCount() const
  9922. {
  9923. return p->getPropInt64("rowCount", 0);
  9924. }
  9925. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9926. {
  9927. ecl.set(p->queryProp("datasetEcl"));
  9928. defs.set(p->queryProp("datasetEclDefs"));
  9929. }
  9930. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9931. {
  9932. val.set(p->queryProp("logicalName"));
  9933. return val;
  9934. }
  9935. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9936. {
  9937. ecl.set(p->queryProp("keyField"));
  9938. return ecl;
  9939. }
  9940. unsigned CLocalWUResult::getResultRequestedRows() const
  9941. {
  9942. return p->getPropInt("requestedRows", 1);
  9943. }
  9944. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9945. {
  9946. TypeInfoArray types;
  9947. StringAttrArray names;
  9948. getSchema(types, names, &str);
  9949. return str;
  9950. }
  9951. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9952. {
  9953. str.set(p->queryProp("@recordSizeEntry"));
  9954. return str;
  9955. }
  9956. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9957. {
  9958. str.set(p->queryProp("@transformerEntry"));
  9959. return str;
  9960. }
  9961. __int64 CLocalWUResult::getResultRowLimit() const
  9962. {
  9963. return p->getPropInt64("@rowLimit");
  9964. }
  9965. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9966. {
  9967. str.set(p->queryProp("@tempFilename"));
  9968. return str;
  9969. }
  9970. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9971. {
  9972. str.clear();
  9973. if (!name || !*name)
  9974. return str;
  9975. IPropertyTree *format = p->queryPropTree("Format");
  9976. if (!format)
  9977. return str;
  9978. VStringBuffer xpath("@%s", name);
  9979. str.set(format->queryProp(xpath));
  9980. return str;
  9981. }
  9982. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9983. {
  9984. _graph.set(p->queryProp("@graph"));
  9985. _activityId = p->getPropInt("@activity", 0);
  9986. }
  9987. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9988. {
  9989. setEnum(p, "@status", status, resultStatuses);
  9990. if (status==ResultStatusUndefined)
  9991. {
  9992. p->removeProp("Value");
  9993. p->removeProp("totalRowCount");
  9994. p->removeProp("rowCount");
  9995. p->removeProp("@format");
  9996. p->removeProp("@tempFileNmae");
  9997. p->removeProp("logicalName");
  9998. }
  9999. }
  10000. void CLocalWUResult::setResultName(const char *s)
  10001. {
  10002. p->setProp("@name", s);
  10003. }
  10004. void CLocalWUResult::setResultSequence(unsigned seq)
  10005. {
  10006. p->setPropInt("@sequence", seq);
  10007. }
  10008. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  10009. {
  10010. p->setPropBin("SchemaRaw", size, schema);
  10011. }
  10012. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  10013. {
  10014. StringBuffer xpath("@xmlns");
  10015. if (prefix && *prefix)
  10016. xpath.append(':').append(prefix);
  10017. p->setProp(xpath, uri);
  10018. }
  10019. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  10020. {
  10021. if (!name || !*name)
  10022. return;
  10023. IPropertyTree *format = ensurePTree(p, "Format");
  10024. VStringBuffer xpath("@%s", name);
  10025. format->setProp(xpath, value);
  10026. }
  10027. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  10028. {
  10029. p->setProp("@graph", _graph);
  10030. p->setPropInt("@activity", _activityId);
  10031. }
  10032. void CLocalWUResult::setResultScalar(bool isScalar)
  10033. {
  10034. p->setPropInt("@isScalar", (int) isScalar);
  10035. if (isScalar)
  10036. setResultTotalRowCount(1);
  10037. }
  10038. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  10039. {
  10040. p->setPropBin("Value", len, data);
  10041. setResultStatus(ResultStatusSupplied);
  10042. setResultFormat(format);
  10043. }
  10044. void CLocalWUResult::setResultFormat(WUResultFormat format)
  10045. {
  10046. switch (format)
  10047. {
  10048. case ResultFormatXml:
  10049. p->setProp("@format","xml");
  10050. break;
  10051. case ResultFormatXmlSet:
  10052. p->setProp("@format","xmlSet");
  10053. break;
  10054. case ResultFormatCsv:
  10055. p->setProp("@format","csv");
  10056. break;
  10057. default:
  10058. p->removeProp("@format");
  10059. break;
  10060. }
  10061. }
  10062. void CLocalWUResult::setResultXML(const char *val)
  10063. {
  10064. p->setProp("xmlValue", val);
  10065. }
  10066. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  10067. {
  10068. p->appendPropBin("Value", len, data);
  10069. setResultStatus(ResultStatusPartial);
  10070. const char *existingFormat = p->queryProp("@format");
  10071. const char *formatStr = NULL;
  10072. switch (format)
  10073. {
  10074. case ResultFormatXml:
  10075. formatStr = "xml";
  10076. break;
  10077. case ResultFormatXmlSet:
  10078. formatStr = "xmlSet";
  10079. break;
  10080. case ResultFormatCsv:
  10081. formatStr = "csv";
  10082. break;
  10083. default:
  10084. p->removeProp("@format");
  10085. break;
  10086. }
  10087. if (format)
  10088. {
  10089. if (existingFormat)
  10090. {
  10091. if (0 != stricmp(formatStr, existingFormat))
  10092. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  10093. }
  10094. else
  10095. p->setProp("@format", formatStr);
  10096. }
  10097. }
  10098. void CLocalWUResult::setResultFetchSize(unsigned rows)
  10099. {
  10100. p->setPropInt("fetchSize", rows);
  10101. }
  10102. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  10103. {
  10104. p->setPropInt64("totalRowCount", rows);
  10105. }
  10106. void CLocalWUResult::setResultRowCount(__int64 rows)
  10107. {
  10108. p->setPropInt64("rowCount", rows);
  10109. }
  10110. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  10111. {
  10112. p->setProp("datasetEcl", ecl);
  10113. p->setProp("datasetEclDefs", defs);
  10114. }
  10115. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  10116. {
  10117. p->setProp("logicalName", logicalName);
  10118. }
  10119. void CLocalWUResult::setResultKeyField(const char *ecl)
  10120. {
  10121. p->setProp("keyField", ecl);
  10122. }
  10123. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  10124. {
  10125. p->setPropInt("requestedRows", rows);
  10126. }
  10127. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  10128. {
  10129. p->setProp("@recordSizeEntry", entry);
  10130. }
  10131. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  10132. {
  10133. p->setProp("@transformerEntry", entry);
  10134. }
  10135. void CLocalWUResult::setResultRowLimit(__int64 value)
  10136. {
  10137. p->setPropInt64("@rowLimit", value);
  10138. }
  10139. void CLocalWUResult::setResultFilename(const char * name)
  10140. {
  10141. p->setProp("@tempFilename", name);
  10142. }
  10143. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  10144. __int64 CLocalWUResult::getResultInt() const
  10145. {
  10146. __int64 result = 0;
  10147. MemoryBuffer s;
  10148. p->getPropBin("Value", s);
  10149. if (s.length())
  10150. s.read(result);
  10151. else
  10152. result = p->getPropInt64("xmlValue");
  10153. return result;
  10154. }
  10155. bool CLocalWUResult::getResultBool() const
  10156. {
  10157. bool result = false;
  10158. MemoryBuffer s;
  10159. p->getPropBin("Value", s);
  10160. if (s.length())
  10161. s.read(result);
  10162. else
  10163. result = p->getPropBool("xmlValue");
  10164. return result;
  10165. }
  10166. double CLocalWUResult::getResultReal() const
  10167. {
  10168. double result = 0;
  10169. MemoryBuffer s;
  10170. p->getPropBin("Value", s);
  10171. if (s.length())
  10172. s.read(result);
  10173. else
  10174. {
  10175. const char *xmlVal = p->queryProp("xmlValue");
  10176. if (xmlVal)
  10177. result = atof(xmlVal);
  10178. }
  10179. return result;
  10180. }
  10181. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  10182. {
  10183. MemoryBuffer s;
  10184. p->getPropBin("Value", s);
  10185. if (s.length())
  10186. {
  10187. assertex(s.length() == len);
  10188. s.read(len, val);
  10189. }
  10190. else
  10191. {
  10192. const char *xmlVal = p->queryProp("xmlValue");
  10193. if (xmlVal)
  10194. {
  10195. Decimal d;
  10196. d.setString(strlen(xmlVal), xmlVal);
  10197. if (isSigned)
  10198. d.getDecimal(len, precision, val);
  10199. else
  10200. d.getUDecimal(len, precision, val);
  10201. }
  10202. else
  10203. memset(val, 0, len);
  10204. }
  10205. }
  10206. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  10207. {
  10208. if (hidePassword && p->getPropBool("@password"))
  10209. {
  10210. str.set("****");
  10211. return str;
  10212. }
  10213. MemoryBuffer s;
  10214. p->getPropBin("Value", s);
  10215. if (s.length())
  10216. {
  10217. unsigned len;
  10218. s.read(len);
  10219. str.setLen((const char *) s.readDirect(len), len);
  10220. }
  10221. else
  10222. {
  10223. p->getPropBin("xmlValue", s);
  10224. if (p->isBinary("xmlValue"))
  10225. str.setLen(s.toByteArray(), s.length());
  10226. else
  10227. {
  10228. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  10229. str.set(ascii);
  10230. rtlFree(ascii);
  10231. }
  10232. }
  10233. return str;
  10234. }
  10235. WUResultFormat CLocalWUResult::getResultFormat() const
  10236. {
  10237. const char * format = p->queryProp("@format");
  10238. if (!format)
  10239. return ResultFormatRaw;
  10240. else if (strcmp(format, "xml") == 0)
  10241. return ResultFormatXml;
  10242. else if (strcmp(format, "xmlSet") == 0)
  10243. return ResultFormatXmlSet;
  10244. else if (strcmp(format, "csv") == 0)
  10245. return ResultFormatCsv;
  10246. else
  10247. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  10248. }
  10249. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10250. {
  10251. MemoryBuffer s;
  10252. p->getPropBin("Value", s);
  10253. unsigned len = s.length();
  10254. if (len)
  10255. {
  10256. WUResultFormat format = getResultFormat();
  10257. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  10258. {
  10259. if (!xmlTransformer)
  10260. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  10261. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  10262. }
  10263. else if (format == ResultFormatCsv)
  10264. {
  10265. if (!csvTransformer)
  10266. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  10267. csvTransformer->transform(data, len, s.readDirect(len), true);
  10268. }
  10269. else
  10270. data.setLen(s.readDirect(len), len);
  10271. }
  10272. else
  10273. data.clear();
  10274. return data;
  10275. }
  10276. unsigned CLocalWUResult::getResultHash() const
  10277. {
  10278. MemoryBuffer s;
  10279. p->getPropBin("Value", s);
  10280. unsigned len = s.length();
  10281. const byte * data = (const byte *)s.toByteArray();
  10282. return ~hashc(data, len, ~0);
  10283. }
  10284. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  10285. {
  10286. MemoryBuffer s;
  10287. p->getPropBin("Value", s);
  10288. if (s.length())
  10289. {
  10290. unsigned len;
  10291. s.read(len);
  10292. data.setLen(s.readDirect(len*2), len*2);
  10293. }
  10294. else
  10295. {
  10296. StringBuffer utf8;
  10297. if (p->getProp("xmlValue", utf8))
  10298. {
  10299. unsigned outlen;
  10300. UChar *out;
  10301. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  10302. data.setLen(out, outlen*2);
  10303. rtlFree(out);
  10304. }
  10305. else
  10306. data.clear();
  10307. }
  10308. return data;
  10309. }
  10310. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10311. {
  10312. WUResultFormat format = getResultFormat();
  10313. if (format == ResultFormatRaw)
  10314. {
  10315. //MORE: This should not load the whole property...
  10316. MemoryBuffer s;
  10317. p->getPropBin("Value", s);
  10318. return s.length();
  10319. }
  10320. else
  10321. {
  10322. MemoryBuffer temp;
  10323. MemoryBuffer2IDataVal adaptor(temp);
  10324. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10325. return temp.length();
  10326. }
  10327. }
  10328. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  10329. {
  10330. WUResultFormat format = getResultFormat();
  10331. if (format != ResultFormatRaw)
  10332. {
  10333. MemoryBuffer temp;
  10334. MemoryBuffer2IDataVal adaptor(temp);
  10335. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  10336. unsigned len = temp.length();
  10337. if (from > len) from = len;
  10338. if (from + length > len) length = len - from;
  10339. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  10340. return data;
  10341. }
  10342. else
  10343. {
  10344. //MORE: This should not load the whole property, and should be different from the code above...
  10345. MemoryBuffer s;
  10346. p->getPropBin("Value", s);
  10347. unsigned len = s.length();
  10348. if (from > len) from = len;
  10349. if (from + length > len) length = len - from;
  10350. data.setLen(s.readDirect(len) + from, (size32_t)length);
  10351. return data;
  10352. }
  10353. }
  10354. bool CLocalWUResult::getResultIsAll() const
  10355. {
  10356. return p->getPropBool("@isAll", false);
  10357. }
  10358. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  10359. void CLocalWUResult::setResultInt(__int64 val)
  10360. {
  10361. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  10362. MemoryBuffer m;
  10363. serializeInt8(val, m);
  10364. p->setPropBin("Value", m.length(), m.toByteArray());
  10365. setResultRowCount(1);
  10366. setResultTotalRowCount(1);
  10367. }
  10368. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  10369. {
  10370. setResultInt((__int64) val);
  10371. }
  10372. void CLocalWUResult::setResultReal(double val)
  10373. {
  10374. // Note: we always serialize scalar real results as real8, and schema must reflect this
  10375. MemoryBuffer m;
  10376. serializeReal8(val, m);
  10377. p->setPropBin("Value", m.length(), m.toByteArray());
  10378. setResultRowCount(1);
  10379. setResultTotalRowCount(1);
  10380. }
  10381. void CLocalWUResult::setResultBool(bool val)
  10382. {
  10383. MemoryBuffer m;
  10384. serializeBool(val, m);
  10385. p->setPropBin("Value", m.length(), m.toByteArray());
  10386. setResultRowCount(1);
  10387. setResultTotalRowCount(1);
  10388. }
  10389. void CLocalWUResult::setResultString(const char *val, unsigned len)
  10390. {
  10391. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10392. MemoryBuffer m;
  10393. serializeLPString(len, val, m);
  10394. p->setPropBin("Value", m.length(), m.toByteArray());
  10395. setResultRowCount(1);
  10396. setResultTotalRowCount(1);
  10397. }
  10398. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  10399. {
  10400. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  10401. MemoryBuffer m;
  10402. m.append(len).append(len*2, val);
  10403. p->setPropBin("Value", m.length(), m.toByteArray());
  10404. setResultRowCount(1);
  10405. setResultTotalRowCount(1);
  10406. }
  10407. void CLocalWUResult::setResultData(const void *val, unsigned len)
  10408. {
  10409. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  10410. MemoryBuffer m;
  10411. serializeLPString(len, (const char *)val, m);
  10412. p->setPropBin("Value", m.length(), m.toByteArray());
  10413. setResultRowCount(1);
  10414. setResultTotalRowCount(1);
  10415. }
  10416. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  10417. {
  10418. // Note: serialized as data but with length known from schema
  10419. MemoryBuffer m;
  10420. serializeFixedData(len, val, m);
  10421. p->setPropBin("Value", m.length(), m.toByteArray());
  10422. setResultRowCount(1);
  10423. setResultTotalRowCount(1);
  10424. }
  10425. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  10426. {
  10427. p->setPropBin("Value", len, data);
  10428. setResultRowCount(1);
  10429. setResultTotalRowCount(1);
  10430. setResultFormat(ResultFormatRaw);
  10431. }
  10432. void CLocalWUResult::setResultIsAll(bool value)
  10433. {
  10434. p->setPropBool("@isAll", value);
  10435. }
  10436. //==========================================================================================
  10437. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  10438. {
  10439. }
  10440. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  10441. {
  10442. str.set(p->queryProp("@dllname"));
  10443. return str;
  10444. }
  10445. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  10446. {
  10447. str.set(p->queryProp("@version"));
  10448. return str;
  10449. }
  10450. void CLocalWUPlugin::setPluginName(const char *str)
  10451. {
  10452. p->setProp("@dllname", str);
  10453. }
  10454. void CLocalWUPlugin::setPluginVersion(const char *str)
  10455. {
  10456. p->setProp("@version", str);
  10457. }
  10458. //==========================================================================================
  10459. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  10460. {
  10461. }
  10462. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  10463. {
  10464. str.set(p->queryProp("@name"));
  10465. return str;
  10466. }
  10467. void CLocalWULibrary::setName(const char *str)
  10468. {
  10469. p->setProp("@name", str);
  10470. }
  10471. //==========================================================================================
  10472. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  10473. {
  10474. }
  10475. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  10476. {
  10477. str.set(p->queryProp("@source"));
  10478. return str;
  10479. }
  10480. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  10481. {
  10482. str.set(p->queryProp(NULL));
  10483. return str;
  10484. }
  10485. unsigned CLocalWUException::getExceptionCode() const
  10486. {
  10487. return p->getPropInt("@code", 0);
  10488. }
  10489. ErrorSeverity CLocalWUException::getSeverity() const
  10490. {
  10491. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  10492. }
  10493. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  10494. {
  10495. dt.set(p->queryProp("@time"));
  10496. return dt;
  10497. }
  10498. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  10499. {
  10500. str.set(p->queryProp("@filename"));
  10501. return str;
  10502. }
  10503. unsigned CLocalWUException::getExceptionLineNo() const
  10504. {
  10505. return p->getPropInt("@row", 0);
  10506. }
  10507. unsigned CLocalWUException::getExceptionColumn() const
  10508. {
  10509. return p->getPropInt("@col", 0);
  10510. }
  10511. unsigned CLocalWUException::getActivityId() const
  10512. {
  10513. const char * scope = queryScope();
  10514. if (scope)
  10515. {
  10516. const char * colon = strrchr(scope, ':');
  10517. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  10518. return atoi(colon+1+strlen(ActivityScopePrefix));
  10519. }
  10520. return p->getPropInt("@activity", 0);
  10521. }
  10522. unsigned CLocalWUException::getSequence() const
  10523. {
  10524. return p->getPropInt("@sequence", 0);
  10525. }
  10526. const char * CLocalWUException::queryScope() const
  10527. {
  10528. return p->queryProp("@scope");
  10529. }
  10530. unsigned CLocalWUException::getPriority() const
  10531. {
  10532. return p->getPropInt("@prio", 0);
  10533. }
  10534. void CLocalWUException::setExceptionSource(const char *str)
  10535. {
  10536. p->setProp("@source", str);
  10537. }
  10538. void CLocalWUException::setExceptionMessage(const char *str)
  10539. {
  10540. p->setProp(NULL, str);
  10541. }
  10542. void CLocalWUException::setExceptionCode(unsigned code)
  10543. {
  10544. p->setPropInt("@code", code);
  10545. }
  10546. void CLocalWUException::setSeverity(ErrorSeverity level)
  10547. {
  10548. p->setPropInt("@severity", level);
  10549. }
  10550. void CLocalWUException::setTimeStamp(const char *str)
  10551. {
  10552. p->setProp("@time", str);
  10553. }
  10554. void CLocalWUException::setExceptionFileName(const char *str)
  10555. {
  10556. p->setProp("@filename", str);
  10557. }
  10558. void CLocalWUException::setExceptionLineNo(unsigned r)
  10559. {
  10560. p->setPropInt("@row", r);
  10561. }
  10562. void CLocalWUException::setExceptionColumn(unsigned c)
  10563. {
  10564. p->setPropInt("@col", c);
  10565. }
  10566. void CLocalWUException::setActivityId(unsigned _id)
  10567. {
  10568. p->setPropInt("@activity", _id);
  10569. }
  10570. void CLocalWUException::setScope(const char * _scope)
  10571. {
  10572. p->setProp("@scope", _scope);
  10573. }
  10574. void CLocalWUException::setPriority(unsigned _priority)
  10575. {
  10576. p->setPropInt("@prio", _priority);
  10577. }
  10578. //==========================================================================================
  10579. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10580. {
  10581. StringAttrBuilder propPath(prop);
  10582. propPath.append("*[").append(child).append("]");
  10583. }
  10584. const char * CLocalWUAppValue::queryApplication() const
  10585. {
  10586. return p->queryName();
  10587. }
  10588. const char * CLocalWUAppValue::queryName() const
  10589. {
  10590. IPropertyTree* val=p->queryPropTree(prop.str());
  10591. if(val)
  10592. return val->queryName();
  10593. return ""; // Should not happen in normal usage
  10594. }
  10595. const char * CLocalWUAppValue::queryValue() const
  10596. {
  10597. return p->queryProp(prop.str());
  10598. }
  10599. //==========================================================================================
  10600. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10601. {
  10602. }
  10603. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10604. {
  10605. const char * creator = p->queryProp("@creator");
  10606. str.set(creator);
  10607. return str;
  10608. }
  10609. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10610. {
  10611. const char * desc = p->queryProp("@desc");
  10612. if (desc)
  10613. {
  10614. str.set(desc); // legacy and in case it is overridden
  10615. }
  10616. else if (createDefault)
  10617. {
  10618. StatisticKind kind = getKind();
  10619. assertex(kind != StKindNone);
  10620. const char * scope = p->queryProp("@scope");
  10621. assertex(scope);
  10622. //Clean up the format of the scope when converting it to a description
  10623. StringBuffer descriptionText;
  10624. if (isGlobalScope(scope))
  10625. {
  10626. const char * creator = p->queryProp("@creator");
  10627. descriptionText.append(creator).append(":");
  10628. queryLongStatisticName(descriptionText, kind);
  10629. }
  10630. else
  10631. {
  10632. for (;;)
  10633. {
  10634. char c = *scope++;
  10635. if (!c)
  10636. break;
  10637. if (c == ':')
  10638. descriptionText.append(": ");
  10639. else
  10640. descriptionText.append(c);
  10641. }
  10642. if (kind != StTimeElapsed)
  10643. queryLongStatisticName(descriptionText.append(": "), kind);
  10644. }
  10645. str.set(descriptionText);
  10646. }
  10647. else
  10648. str.clear();
  10649. return str;
  10650. }
  10651. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10652. {
  10653. StringBuffer formatted;
  10654. formatStatistic(formatted, getValue(), getMeasure());
  10655. str.set(formatted);
  10656. return str;
  10657. }
  10658. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10659. {
  10660. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10661. }
  10662. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10663. {
  10664. return queryScopeType(p->queryProp("@s"), SSTnone);
  10665. }
  10666. StatisticKind CLocalWUStatistic::getKind() const
  10667. {
  10668. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10669. }
  10670. const char * CLocalWUStatistic::queryScope() const
  10671. {
  10672. const char * scope = p->queryProp("@scope");
  10673. if (scope && streq(scope, LEGACY_GLOBAL_SCOPE))
  10674. scope = GLOBAL_SCOPE;
  10675. return scope;
  10676. }
  10677. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10678. {
  10679. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10680. }
  10681. unsigned __int64 CLocalWUStatistic::getValue() const
  10682. {
  10683. return p->getPropInt64("@value", 0);
  10684. }
  10685. unsigned __int64 CLocalWUStatistic::getCount() const
  10686. {
  10687. return p->getPropInt64("@count", 0);
  10688. }
  10689. unsigned __int64 CLocalWUStatistic::getMax() const
  10690. {
  10691. return p->getPropInt64("@max", 0);
  10692. }
  10693. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10694. {
  10695. return p->getPropInt64("@ts", 0);
  10696. }
  10697. //==========================================================================================
  10698. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10699. {
  10700. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10701. if (xml)
  10702. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10703. else
  10704. {
  10705. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10706. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10707. cw->loadPTree(p.getClear());
  10708. }
  10709. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10710. return ret;
  10711. }
  10712. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10713. {
  10714. const char *name = p->queryName();
  10715. if (!name)
  10716. name = "__unnamed__";
  10717. StringBuffer temp;
  10718. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10719. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10720. ForEach(*elems)
  10721. {
  10722. IPropertyTree &elem = elems->query();
  10723. if (streq(elem.queryName(), "Parameters"))
  10724. {
  10725. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10726. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10727. ForEach(*params)
  10728. {
  10729. IPropertyTree &param = params->query();
  10730. const char *paramname = param.queryName();
  10731. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10732. if (p->getPropBool(xpath))
  10733. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10734. else
  10735. {
  10736. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10737. }
  10738. }
  10739. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10740. }
  10741. else if (streq(elem.queryName(), "Variables"))
  10742. {
  10743. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10744. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10745. ForEach(*vars)
  10746. {
  10747. Owned<IPropertyTree> var = LINK(&vars->query());
  10748. if (var->getPropBool("Format/@password"))
  10749. {
  10750. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10751. var->removeProp("Value");
  10752. var->removeProp("xmlValue");
  10753. }
  10754. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10755. }
  10756. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10757. }
  10758. else
  10759. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10760. }
  10761. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10762. }
  10763. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10764. {
  10765. class CAdapter : public CInterface, implements IIOStream
  10766. {
  10767. StringBuffer &out;
  10768. public:
  10769. IMPLEMENT_IINTERFACE;
  10770. CAdapter(StringBuffer &_out) : out(_out) { }
  10771. virtual void flush() { }
  10772. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10773. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10774. } adapter(str);
  10775. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10776. return str;
  10777. }
  10778. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10779. {
  10780. OwnedIFile ifile = createIFile(filename);
  10781. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10782. Owned<IIOStream> stream = createIOStream(ifileio);
  10783. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10784. }
  10785. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10786. {
  10787. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10788. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10789. if (ewu)
  10790. {
  10791. Linked<IPropertyTree> p;
  10792. if (unpack||includeProgress)
  10793. p.setown(ewu->getUnpackedTree(includeProgress));
  10794. else
  10795. p.set(ewu->queryPTree());
  10796. if (hidePasswords)
  10797. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10798. else
  10799. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10800. }
  10801. else
  10802. return str.append("Unrecognized workunit format");
  10803. }
  10804. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10805. {
  10806. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10807. if (ewu)
  10808. {
  10809. Linked<IPropertyTree> p;
  10810. if (unpack||includeProgress)
  10811. p.setown(ewu->getUnpackedTree(includeProgress));
  10812. else if (regressionTest)
  10813. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10814. else
  10815. p.set(ewu->queryPTree());
  10816. if (hidePasswords)
  10817. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10818. if (regressionTest)
  10819. {
  10820. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10821. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10822. p->removeProp("@buildVersion");
  10823. p->removeProp("@eclVersion");
  10824. p->removeProp("@hash");
  10825. //Remove statistics, and extract them to a separate file
  10826. IPropertyTree * stats = p->queryPropTree("Statistics");
  10827. if (stats)
  10828. {
  10829. StringBuffer statsFilename;
  10830. statsFilename.append(filename).append(".stats");
  10831. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10832. p->removeProp("Statistics");
  10833. }
  10834. //Now remove timestamps from exceptions
  10835. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10836. ForEach(*elems)
  10837. {
  10838. IPropertyTree &elem = elems->query();
  10839. elem.removeProp("@time");
  10840. }
  10841. }
  10842. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10843. }
  10844. else
  10845. throw makeStringException(0, "Unrecognized workunit format");
  10846. }
  10847. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10848. {
  10849. MemoryBuffer buffer;
  10850. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10851. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10852. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10853. assertex(workunit);
  10854. StringAttr clusterName(workunit->queryClusterName());
  10855. if (!clusterName.length())
  10856. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10857. workunit->commit();
  10858. workunit.clear();
  10859. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  10860. if (!clusterInfo)
  10861. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName.str());
  10862. SCMStringBuffer serverQueue;
  10863. clusterInfo->getServerQueue(serverQueue);
  10864. assertex(serverQueue.length());
  10865. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10866. if (!queue.get())
  10867. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10868. IJobQueueItem *item = createJobQueueItem(wuid);
  10869. queue->enqueue(item);
  10870. }
  10871. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10872. {
  10873. StringBuffer xpath("/WorkUnitAborts/");
  10874. xpath.append(wuid);
  10875. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10876. acon->queryRoot()->setPropInt(NULL, 1);
  10877. }
  10878. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10879. {
  10880. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10881. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10882. }
  10883. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10884. {
  10885. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10886. return;
  10887. abortWorkUnit(wuid);
  10888. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10889. if(!cw)
  10890. return;
  10891. WorkunitUpdate wu(&cw->lock());
  10892. const char *abortBy = secuser.getName();
  10893. if (abortBy && *abortBy)
  10894. wu->setTracingValue("AbortBy", abortBy);
  10895. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10896. }
  10897. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10898. {
  10899. if (secmgr && secuser)
  10900. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10901. if (secuser)
  10902. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10903. submitWorkUnit(wuid, "", "");
  10904. }
  10905. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10906. {
  10907. if (secmgr && secuser)
  10908. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10909. abortWorkUnit(wuid);
  10910. }
  10911. bool CLocalWorkUnit::hasWorkflow() const
  10912. {
  10913. return p->hasProp("Workflow");
  10914. }
  10915. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10916. {
  10917. CriticalBlock block(crit);
  10918. if (p->hasProp("@eventScheduledCount"))
  10919. return p->getPropInt("@eventScheduledCount", 0);
  10920. else
  10921. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10922. }
  10923. void CLocalWorkUnit::incEventScheduledCount()
  10924. {
  10925. CriticalBlock block(crit);
  10926. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10927. }
  10928. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10929. {
  10930. CriticalBlock block(crit);
  10931. return p->queryPropTree("Workflow");
  10932. }
  10933. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10934. {
  10935. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10936. CriticalBlock block(crit);
  10937. if(!workflowIteratorCached)
  10938. {
  10939. assertex(!workflowIterator);
  10940. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10941. if(s)
  10942. workflowIterator.setown(createWorkflowItemIterator(s));
  10943. workflowIteratorCached = true;
  10944. }
  10945. return workflowIterator.getLink();
  10946. }
  10947. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10948. {
  10949. unsigned count = 0;
  10950. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10951. for(iter->first(); iter->isValid(); iter->next())
  10952. count++;
  10953. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10954. for(iter->first(); iter->isValid(); iter->next())
  10955. array->addClone(iter->query());
  10956. return array.getLink();
  10957. }
  10958. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10959. {
  10960. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10961. CriticalBlock block(crit);
  10962. workflowIterator.clear();
  10963. workflowIteratorCached = false;
  10964. IPropertyTree * s = p->queryPropTree("Workflow");
  10965. if(!s)
  10966. s = p->addPropTree("Workflow");
  10967. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10968. }
  10969. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10970. {
  10971. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10972. CriticalBlock block(crit);
  10973. if(!workflowIterator)
  10974. {
  10975. IPropertyTree * s = p->queryPropTree("Workflow");
  10976. if(!s)
  10977. s = p->addPropTree("Workflow");
  10978. workflowIterator.setown(createWorkflowItemIterator(s));
  10979. workflowIteratorCached = true;
  10980. }
  10981. return workflowIterator.getLink();
  10982. }
  10983. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10984. {
  10985. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10986. Owned<IWorkflowItem> item;
  10987. for(iter->first(); iter->isValid(); iter->next())
  10988. {
  10989. item.setown(iter->get());
  10990. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10991. }
  10992. workflowIterator.clear();
  10993. workflowIteratorCached = false;
  10994. }
  10995. void CLocalWorkUnit::resetWorkflow()
  10996. {
  10997. if (hasWorkflow())
  10998. {
  10999. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  11000. Owned<IWorkflowItem> wf;
  11001. for(iter->first(); iter->isValid(); iter->next())
  11002. {
  11003. wf.setown(iter->get());
  11004. wf->reset();
  11005. }
  11006. workflowIterator.clear();
  11007. workflowIteratorCached = false;
  11008. }
  11009. }
  11010. void CLocalWorkUnit::schedule()
  11011. {
  11012. CriticalBlock block(crit);
  11013. if(queryEventScheduledCount() == 0) return;
  11014. switch(getState())
  11015. {
  11016. case WUStateCompleted:
  11017. setState(WUStateWait);
  11018. break;
  11019. case WUStateFailed:
  11020. case WUStateArchived:
  11021. case WUStateAborting:
  11022. case WUStateAborted:
  11023. case WUStateScheduled:
  11024. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  11025. }
  11026. StringBuffer rootPath;
  11027. rootPath.append("/Schedule/").append(queryClusterName());
  11028. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11029. Owned<IPropertyTree> root = conn->getRoot();
  11030. if(!root->hasChildren())
  11031. {
  11032. StringBuffer addPath;
  11033. addPath.append("/Schedulers/").append(queryClusterName());
  11034. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11035. }
  11036. char const * wuid = p->queryName();
  11037. StringBuffer xpath("*/*/");
  11038. ncnameEscape(wuid, xpath);
  11039. bool more;
  11040. do more = root->removeProp(xpath.str()); while(more);
  11041. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  11042. Owned<IWorkflowEvent> event;
  11043. Owned<IPropertyTree> branch1, branch2;
  11044. for(iter->first(); iter->isValid(); iter->next())
  11045. {
  11046. event.setown(iter->query()->getScheduleEvent());
  11047. if(!event) continue;
  11048. ncnameEscape(event->queryName(), xpath.clear());
  11049. ensurePTree(root, xpath.str());
  11050. branch1.setown(root->getPropTree(xpath.str()));
  11051. ncnameEscape(event->queryText(), xpath.clear());
  11052. ensurePTree(branch1, xpath.str());
  11053. branch2.setown(branch1->getPropTree(xpath.str()));
  11054. ncnameEscape(wuid, xpath.clear());
  11055. ensurePTree(branch2, xpath.str());
  11056. }
  11057. }
  11058. void CLocalWorkUnit::deschedule()
  11059. {
  11060. if(queryEventScheduledCount() == 0) return;
  11061. if(getState() == WUStateWait)
  11062. setState(WUStateCompleted);
  11063. doDescheduleWorkkunit(p->queryName());
  11064. }
  11065. EnumMapping localFileUploadTypes[] = {
  11066. { UploadTypeFileSpray, "FileSpray" },
  11067. { UploadTypeWUResult, "WUResult" },
  11068. { UploadTypeWUResultCsv, "WUResultCsv" },
  11069. { UploadTypeWUResultXml, "WUResultXml" },
  11070. { UploadTypeSize, NULL }
  11071. };
  11072. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  11073. {
  11074. public:
  11075. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  11076. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  11077. {
  11078. tree.setown(createPTree());
  11079. tree->setPropInt("@id", id);
  11080. setEnum(tree, "@type", type, localFileUploadTypes);
  11081. tree->setProp("@source", source);
  11082. tree->setProp("@destination", destination);
  11083. if (eventTag)
  11084. tree->setProp("@eventTag", eventTag);
  11085. }
  11086. IMPLEMENT_IINTERFACE;
  11087. IPropertyTree * getTree() { return tree.getLink(); }
  11088. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  11089. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  11090. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  11091. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  11092. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  11093. private:
  11094. Owned<IPropertyTree> tree;
  11095. };
  11096. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  11097. {
  11098. public:
  11099. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  11100. IMPLEMENT_IINTERFACE;
  11101. bool first() { return iter->first(); }
  11102. bool isValid() { return iter->isValid(); }
  11103. bool next() { return iter->next(); }
  11104. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  11105. private:
  11106. Owned<IPropertyTree> tree;
  11107. Owned<IPropertyTreeIterator> iter;
  11108. };
  11109. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  11110. {
  11111. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  11112. CriticalBlock block(crit);
  11113. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  11114. if(s)
  11115. return new CLocalFileUploadIterator(s.getClear());
  11116. else
  11117. return NULL;
  11118. }
  11119. bool CLocalWorkUnit::requiresLocalFileUpload() const
  11120. {
  11121. SCMStringBuffer dest;
  11122. Owned<IConstWUResult> result;
  11123. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  11124. if(!iter)
  11125. return false;
  11126. for(iter->first(); iter->isValid(); iter->next())
  11127. {
  11128. Owned<IConstLocalFileUpload> upload(iter->get());
  11129. switch(upload->queryType())
  11130. {
  11131. case UploadTypeWUResult:
  11132. case UploadTypeWUResultCsv:
  11133. case UploadTypeWUResultXml:
  11134. upload->getDestination(dest);
  11135. result.setown(getResultByName(dest.str()));
  11136. if(!result)
  11137. return true;
  11138. break;
  11139. default:
  11140. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  11141. }
  11142. }
  11143. return false;
  11144. }
  11145. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  11146. {
  11147. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  11148. CriticalBlock block(crit);
  11149. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  11150. if(!s)
  11151. s = p->addPropTree("LocalFileUploads");
  11152. unsigned id = s->numChildren();
  11153. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  11154. s->addPropTree("LocalFileUpload", upload->getTree());
  11155. return id;
  11156. }
  11157. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  11158. {
  11159. CriticalBlock block(crit);
  11160. str.set(p->queryProp("Tracing/AbortBy"));
  11161. return str;
  11162. }
  11163. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  11164. {
  11165. CriticalBlock block(crit);
  11166. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  11167. }
  11168. #if 0
  11169. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  11170. {
  11171. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  11172. unsigned deps = 0;
  11173. Owned<IWorkflowDependencyIterator> diter;
  11174. switch(cwf->queryWfid())
  11175. {
  11176. case 1:
  11177. assertex(!cwf->isScheduled());
  11178. assertex(cwf->queryType() == WFTypeNormal);
  11179. assertex(cwf->queryState() == WFStateNull);
  11180. diter.setown(cwf->getDependencies());
  11181. for(diter->first(); diter->isValid(); diter->next())
  11182. deps++;
  11183. assertex(deps==0);
  11184. okay[0] = true;
  11185. break;
  11186. case 2:
  11187. assertex(!cwf->isScheduled());
  11188. assertex(cwf->queryType() == WFTypeRecovery);
  11189. assertex(cwf->queryState() == WFStateSkip);
  11190. okay[1] = true;
  11191. break;
  11192. case 3:
  11193. assertex(cwf->queryContingencyFor() == 4);
  11194. okay[2] = true;
  11195. break;
  11196. case 4:
  11197. assertex(cwf->isScheduled());
  11198. assertex(cwf->queryType() == WFTypeNormal);
  11199. assertex(cwf->queryState() == WFStateReqd);
  11200. assertex(cwf->querySuccess() == 0);
  11201. assertex(cwf->queryFailure() == 3);
  11202. assertex(cwf->queryRecovery() == 2);
  11203. assertex(cwf->queryRetriesAllowed() == 10);
  11204. assertex(cwf->queryRetriesRemaining() == 10);
  11205. diter.setown(cwf->getDependencies());
  11206. for(diter->first(); diter->isValid(); diter->next())
  11207. {
  11208. dep[diter->query()-1] = true;
  11209. deps++;
  11210. }
  11211. assertex(deps==2);
  11212. assertex(dep[0]);
  11213. assertex(dep[1]);
  11214. okay[3] = true;
  11215. break;
  11216. case 5:
  11217. assertex(cwf->isScheduled());
  11218. assertex(!cwf->isScheduledNow());
  11219. assertex(cwf->querySchedulePriority() == 75);
  11220. assertex(cwf->queryScheduleCount() == 5);
  11221. assertex(cwf->queryScheduleCountRemaining() == 5);
  11222. okay[4] = true;
  11223. break;
  11224. case 6:
  11225. assertex(cwf->isScheduled());
  11226. assertex(!cwf->isScheduledNow());
  11227. assertex(cwf->querySchedulePriority() == 25);
  11228. assertex(!cwf->hasScheduleCount());
  11229. okay[5] = true;
  11230. break;
  11231. default:
  11232. assertex(!"unknown wfid in test");
  11233. }
  11234. }
  11235. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  11236. {
  11237. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  11238. switch(rwf->queryWfid())
  11239. {
  11240. case 1:
  11241. case 2:
  11242. case 3:
  11243. okay[rwf->queryWfid()-1] = true;
  11244. break;
  11245. case 4:
  11246. {
  11247. unsigned tries = 0;
  11248. while(rwf->testAndDecRetries())
  11249. tries++;
  11250. assertex(tries == 10);
  11251. assertex(rwf->queryRetriesRemaining() == 0);
  11252. rwf->setState(WFStateFail);
  11253. assertex(rwf->queryState() == WFStateFail);
  11254. rwf->reset();
  11255. assertex(rwf->queryRetriesRemaining() == 10);
  11256. assertex(rwf->queryState() == WFStateReqd);
  11257. }
  11258. okay[3] = true;
  11259. break;
  11260. case 5:
  11261. {
  11262. assertex(rwf->queryScheduleCountRemaining() == 5);
  11263. unsigned count = 0;
  11264. do count++; while(rwf->decAndTestScheduleCountRemaining());
  11265. assertex(count == 5);
  11266. assertex(rwf->queryScheduleCountRemaining() == 0);
  11267. rwf->reset();
  11268. assertex(rwf->queryScheduleCountRemaining() == 5);
  11269. }
  11270. okay[4] = true;
  11271. break;
  11272. case 6:
  11273. {
  11274. assertex(!rwf->hasScheduleCount());
  11275. unsigned count;
  11276. for(count=0; count<20; count++)
  11277. assertex(rwf->decAndTestScheduleCountRemaining());
  11278. }
  11279. okay[5] = true;
  11280. break;
  11281. default:
  11282. assertex(!"unknown wfid in test");
  11283. }
  11284. }
  11285. void testWorkflow()
  11286. {
  11287. DBGLOG("workunit.cpp : testWorkflow");
  11288. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  11289. Owned<IWorkflowItem> wf;
  11290. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  11291. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  11292. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  11293. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  11294. wf->setScheduledNow();
  11295. wf->addDependency(1);
  11296. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  11297. wf->setScheduledOn("test", "foo*");
  11298. wf->setSchedulePriority(75);
  11299. wf->setScheduleCount(5);
  11300. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  11301. wf->setScheduledOn("test", "bar*");
  11302. wf->setSchedulePriority(25);
  11303. unsigned const n = 6;
  11304. bool okay[n];
  11305. bool dep[n];
  11306. unsigned i;
  11307. for(i=0; i<n; i++)
  11308. okay[i] = dep[i] = 0;
  11309. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  11310. for(citer->first(); citer->isValid(); citer->next())
  11311. testConstWorkflow(citer->query(), okay, dep);
  11312. for(i=0; i<n; i++)
  11313. {
  11314. assertex(okay[i]);
  11315. okay[i] = false;
  11316. }
  11317. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  11318. for(miter->first(); miter->isValid(); miter->next())
  11319. {
  11320. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  11321. testRuntimeWorkflow(rwf, okay);
  11322. }
  11323. for(i=0; i<n; i++)
  11324. {
  11325. assertex(okay[i]);
  11326. okay[i] = dep[i] = false;
  11327. }
  11328. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  11329. unsigned wfid;
  11330. for(wfid = 1; array->isValid(wfid); wfid++)
  11331. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  11332. for(i=0; i<n; i++)
  11333. {
  11334. assertex(okay[i]);
  11335. okay[i] = false;
  11336. }
  11337. for(wfid = 1; array->isValid(wfid); wfid++)
  11338. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  11339. for(i=0; i<n; i++)
  11340. {
  11341. assertex(okay[i]);
  11342. okay[i] = false;
  11343. }
  11344. }
  11345. #endif
  11346. //------------------------------------------------------------------------------------------
  11347. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, bool returnOnWaitState)
  11348. {
  11349. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, returnOnWaitState);
  11350. }
  11351. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, bool returnOnWaitState)
  11352. {
  11353. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  11354. return waitForWorkUnitToComplete(wuid, timeout, returnOnWaitState);
  11355. return WUStateUnknown;
  11356. }
  11357. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  11358. {
  11359. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, true))
  11360. {
  11361. case WUStateCompiled:
  11362. case WUStateCompleted:
  11363. case WUStateWait:
  11364. case WUStateUploadingFiles:
  11365. return true;
  11366. default:
  11367. return false;
  11368. }
  11369. }
  11370. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  11371. {
  11372. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  11373. return waitForWorkUnitToCompile(wuid, timeout);
  11374. return false;
  11375. }
  11376. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  11377. {
  11378. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  11379. {
  11380. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  11381. SCMStringBuffer ip;
  11382. unsigned port;
  11383. try
  11384. {
  11385. port = wu->getDebugAgentListenerPort();
  11386. wu->getDebugAgentListenerIP(ip);
  11387. SocketEndpoint debugEP(ip.str(), port);
  11388. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  11389. unsigned len = (size32_t)strlen(command);
  11390. unsigned revlen = len;
  11391. _WINREV(revlen);
  11392. socket->write(&revlen, sizeof(revlen));
  11393. socket->write(command, len);
  11394. for (;;)
  11395. {
  11396. socket->read(&len, sizeof(len));
  11397. _WINREV(len);
  11398. if (len == 0)
  11399. break;
  11400. if (len & 0x80000000)
  11401. {
  11402. throwUnexpected();
  11403. }
  11404. char * mem = (char*) response.reserve(len);
  11405. socket->read(mem, len);
  11406. }
  11407. return true;
  11408. }
  11409. catch (IException *E)
  11410. {
  11411. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  11412. EXCLOG(E, msg.str());
  11413. throw;
  11414. }
  11415. }
  11416. return false;
  11417. }
  11418. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  11419. {
  11420. TypeInfoArray types;
  11421. StringAttrArray names;
  11422. r->getSchema(types, names, NULL);
  11423. if (types.ordinality()==1)
  11424. type.set(&types.item(0));
  11425. }
  11426. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  11427. {
  11428. if (!r->isResultScalar())
  11429. return false;
  11430. if (!curVal.hasChildren())
  11431. return true;
  11432. getSimpleResultType(r, type);
  11433. return type && type->isScalar();
  11434. }
  11435. void updateSuppliedXmlParams(IWorkUnit * w)
  11436. {
  11437. Owned<const IPropertyTree> params = w->getXmlParams();
  11438. if (!params)
  11439. return;
  11440. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  11441. ForEach(*elems)
  11442. {
  11443. IPropertyTree & curVal = elems->query();
  11444. const char *name = curVal.queryName();
  11445. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  11446. if (r)
  11447. {
  11448. Owned<ITypeInfo> type;
  11449. StringBuffer s;
  11450. if (isSuppliedParamScalar(r, curVal, type))
  11451. {
  11452. curVal.getProp(".", s);
  11453. r->setResultXML(s);
  11454. r->setResultStatus(ResultStatusSupplied);
  11455. }
  11456. else
  11457. {
  11458. toXML(&curVal, s);
  11459. if (!type)
  11460. getSimpleResultType(r, type);
  11461. bool isSet = (type && type->getTypeCode()==type_set);
  11462. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  11463. }
  11464. }
  11465. else
  11466. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  11467. }
  11468. }
  11469. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  11470. {
  11471. switch ((int)sequence)
  11472. {
  11473. case ResultSequenceStored:
  11474. return w->updateVariableByName(name);
  11475. case ResultSequencePersist:
  11476. return w->updateGlobalByName(name);
  11477. case ResultSequenceInternal:
  11478. case ResultSequenceOnce:
  11479. return w->updateTemporaryByName(name);
  11480. default:
  11481. return w->updateResultBySequence(sequence);
  11482. }
  11483. }
  11484. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  11485. {
  11486. switch ((int)sequence)
  11487. {
  11488. case ResultSequenceStored:
  11489. return w->getVariableByName(name);
  11490. case ResultSequencePersist:
  11491. return w->getGlobalByName(name);
  11492. case ResultSequenceInternal:
  11493. case ResultSequenceOnce:
  11494. return w->getTemporaryByName(name);
  11495. default:
  11496. if (name && name[0])
  11497. return w->getResultByName(name);//name takes precedence over sequence
  11498. else
  11499. return w->getResultBySequence(sequence);
  11500. }
  11501. }
  11502. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  11503. {
  11504. if (wuid) {
  11505. char prefchar;
  11506. unsigned year,month,day,hour,min,sec;
  11507. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  11508. time.set(year, month, day, hour, min, sec, 0, true);
  11509. // time.setDate(year, month, day);
  11510. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  11511. return true;
  11512. }
  11513. }
  11514. return false;
  11515. }
  11516. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  11517. {
  11518. return (WUState) getEnum(state, states);
  11519. }
  11520. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  11521. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  11522. {
  11523. public:
  11524. CWorkflowScheduleConnection(char const * wuid)
  11525. {
  11526. basexpath.append("/WorkflowSchedule/").append(wuid);
  11527. flagxpath.append(basexpath.str()).append("/Active");
  11528. }
  11529. IMPLEMENT_IINTERFACE;
  11530. virtual void lock()
  11531. {
  11532. LOG(MCschedconn, "Locking base schedule connection");
  11533. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  11534. if(!baseconn)
  11535. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  11536. }
  11537. virtual void unlock()
  11538. {
  11539. LOG(MCschedconn, "Unlocking base schedule connection");
  11540. baseconn.clear();
  11541. }
  11542. virtual void setActive()
  11543. {
  11544. LOG(MCschedconn, "Setting active flag in schedule connection");
  11545. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  11546. if(!flagconn)
  11547. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  11548. }
  11549. virtual void resetActive()
  11550. {
  11551. LOG(MCschedconn, "Resetting active flag in schedule connection");
  11552. flagconn.clear();
  11553. }
  11554. virtual bool queryActive()
  11555. {
  11556. return baseconn->queryRoot()->hasProp("Active");
  11557. }
  11558. virtual bool pull(IWorkflowItemArray * workflow)
  11559. {
  11560. assertex(baseconn);
  11561. Owned<IPropertyTree> root = baseconn->getRoot();
  11562. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11563. if(!eventQueue) return false;
  11564. if(!eventQueue->hasProp("Item")) return false;
  11565. {
  11566. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11567. Owned<IPropertyTree> eventItem;
  11568. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11569. Owned<IRuntimeWorkflowItem> wfItem;
  11570. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11571. {
  11572. eventItem.setown(&eventItems->get());
  11573. const char * eventName = eventItem->queryProp("@name");
  11574. const char * eventText = eventItem->queryProp("@text");
  11575. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11576. {
  11577. wfItem.setown(wfItems->get());
  11578. if(wfItem->queryState() != WFStateWait)
  11579. continue;
  11580. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11581. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11582. continue;
  11583. wfItem->setEvent(eventName, eventText);
  11584. wfItem->setState(WFStateReqd);
  11585. resetDependentsState(workflow, *wfItem);
  11586. }
  11587. }
  11588. }
  11589. bool more;
  11590. do
  11591. more = eventQueue->removeProp("Item");
  11592. while(more);
  11593. return true;
  11594. }
  11595. virtual void push(char const * name, char const * text)
  11596. {
  11597. assertex(baseconn);
  11598. Owned<IPropertyTree> root = baseconn->getRoot();
  11599. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11600. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11601. eventItem->setProp("@name", name);
  11602. eventItem->setProp("@text", text);
  11603. }
  11604. virtual void remove()
  11605. {
  11606. if (baseconn)
  11607. {
  11608. baseconn->close(true);
  11609. baseconn.clear();
  11610. }
  11611. }
  11612. private:
  11613. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11614. {
  11615. if (wfid)
  11616. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11617. }
  11618. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11619. {
  11620. switch(item.queryState())
  11621. {
  11622. case WFStateDone:
  11623. case WFStateFail:
  11624. {
  11625. item.setState(WFStateNull);
  11626. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11627. resetDependentsState(workflow, item);
  11628. break;
  11629. }
  11630. }
  11631. }
  11632. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11633. {
  11634. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11635. for(iter->first(); iter->isValid(); iter->next())
  11636. {
  11637. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11638. resetItemStateAndDependents(workflow, dep);
  11639. }
  11640. }
  11641. private:
  11642. StringBuffer basexpath;
  11643. StringBuffer flagxpath;
  11644. Owned<IRemoteConnection> baseconn;
  11645. Owned<IRemoteConnection> flagconn;
  11646. };
  11647. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11648. {
  11649. return new CWorkflowScheduleConnection(wuid);
  11650. }
  11651. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11652. {
  11653. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11654. }
  11655. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11656. {
  11657. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11658. }
  11659. 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)
  11660. {
  11661. Owned<IWUException> we = wu->createException();
  11662. we->setSeverity(severity);
  11663. we->setExceptionMessage(text);
  11664. if (source)
  11665. we->setExceptionSource(source);
  11666. if (code)
  11667. we->setExceptionCode(code);
  11668. if (filename)
  11669. we->setExceptionFileName(filename);
  11670. if (lineno)
  11671. {
  11672. we->setExceptionLineNo(lineno);
  11673. if (column)
  11674. we->setExceptionColumn(lineno);
  11675. }
  11676. if (activity)
  11677. we->setActivityId(activity);
  11678. }
  11679. const char * skipLeadingXml(const char * text)
  11680. {
  11681. if (!text)
  11682. return NULL;
  11683. //skip utf8 BOM, probably excessive
  11684. if (memcmp(text, UTF8_BOM, 3) == 0)
  11685. text += 3;
  11686. for (;;)
  11687. {
  11688. if (isspace(*text))
  11689. text++;
  11690. else if (text[0] == '<' && text[1] == '?')
  11691. {
  11692. text += 2;
  11693. for (;;)
  11694. {
  11695. if (!*text) break;
  11696. if (text[0] == '?' && text[1] == '>')
  11697. {
  11698. text += 2;
  11699. break;
  11700. }
  11701. text++;
  11702. }
  11703. }
  11704. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11705. {
  11706. text += 4;
  11707. for (;;)
  11708. {
  11709. if (!*text) break;
  11710. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11711. {
  11712. text += 3;
  11713. break;
  11714. }
  11715. text++;
  11716. }
  11717. }
  11718. else
  11719. break;
  11720. }
  11721. return text;
  11722. }
  11723. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11724. {
  11725. text = skipLeadingXml(text);
  11726. if (!text)
  11727. return false;
  11728. const char * archivePrefix = "<Archive";
  11729. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11730. }
  11731. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11732. {
  11733. text = skipLeadingXml(text);
  11734. if (!text)
  11735. return false;
  11736. const char * manifestPrefix = "<Manifest";
  11737. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11738. }
  11739. //------------------------------------------------------------------------------
  11740. // Named Alias helper function
  11741. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11742. {
  11743. StringBuffer xpath;
  11744. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11745. return queryRegistry->getPropTree(xpath);
  11746. }
  11747. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11748. {
  11749. StringBuffer xpath;
  11750. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11751. return queryRegistry->getPropTree(xpath);
  11752. }
  11753. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11754. {
  11755. StringBuffer lcId(id);
  11756. lcId.toLowerCase();
  11757. StringBuffer xpath;
  11758. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11759. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11760. ForEach(*iter)
  11761. {
  11762. queryRegistry->removeProp(xpath.str());
  11763. }
  11764. }
  11765. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11766. {
  11767. StringBuffer lcName(name);
  11768. lcName.toLowerCase();
  11769. StringBuffer xpath;
  11770. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11771. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11772. unsigned seq = 1;
  11773. ForEach(*iter)
  11774. {
  11775. IPropertyTree &item = iter->query();
  11776. const char *thisWuid = item.queryProp("@wuid");
  11777. if (strieq(wuid, thisWuid))
  11778. return &item;
  11779. unsigned thisSeq = item.getPropInt("@seq");
  11780. if (thisSeq >= seq)
  11781. seq = thisSeq + 1;
  11782. }
  11783. StringBuffer id;
  11784. id.append(lcName).append(".").append(seq);
  11785. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11786. newEntry->setProp("@name", lcName);
  11787. newEntry->setProp("@wuid", wuid);
  11788. newEntry->setProp("@dll", dll);
  11789. newEntry->setProp("@id", id);
  11790. newEntry->setPropInt("@seq", seq);
  11791. if (library)
  11792. newEntry->setPropBool("@isLibrary", true);
  11793. if (userid && *userid)
  11794. newEntry->setProp("@publishedBy", userid);
  11795. if (snapshot && *snapshot)
  11796. newEntry->setProp("@snapshot", snapshot);
  11797. return queryRegistry->addPropTree("Query", newEntry);
  11798. }
  11799. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11800. {
  11801. StringBuffer lcId(id);
  11802. lcId.toLowerCase();
  11803. clearAliases(queryRegistry, lcId);
  11804. StringBuffer xpath;
  11805. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11806. queryRegistry->removeProp(xpath);
  11807. }
  11808. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11809. {
  11810. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11811. if (!match)
  11812. return;
  11813. clearAliases(queryRegistry, match->queryProp("@id"));
  11814. queryRegistry->removeTree(match);
  11815. }
  11816. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11817. {
  11818. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11819. if (!match)
  11820. return;
  11821. clearAliases(queryRegistry, match->queryProp("@id"));
  11822. queryRegistry->removeTree(match);
  11823. }
  11824. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11825. {
  11826. clearAliases(queryRegistry, id);
  11827. }
  11828. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11829. {
  11830. StringBuffer lcName(name);
  11831. lcName.toLowerCase();
  11832. StringBuffer xpath;
  11833. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11834. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11835. if (!match)
  11836. {
  11837. match = queryRegistry->addPropTree("Alias");
  11838. match->setProp("@name", lcName);
  11839. }
  11840. match->setProp("@id", value);
  11841. }
  11842. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11843. {
  11844. if (!queryRegistry || !queryid)
  11845. return NULL;
  11846. StringBuffer xpath;
  11847. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11848. return queryRegistry->getPropTree(xpath);
  11849. }
  11850. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11851. {
  11852. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11853. return getQueryById(queryRegistry, queryid);
  11854. }
  11855. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11856. {
  11857. if (!queryRegistry || !alias)
  11858. return NULL;
  11859. StringBuffer xpath;
  11860. unsigned cnt = 0;
  11861. StringBuffer lc(alias);
  11862. const char * search = lc.toLowerCase().str();
  11863. for (;;)
  11864. {
  11865. xpath.set("Alias[@name='").append(search).append("']/@id");
  11866. const char * queryId = queryRegistry->queryProp(xpath);
  11867. if (!queryId)
  11868. break;
  11869. //Check for too many alias indirections.
  11870. if (cnt++ > 10)
  11871. return NULL;
  11872. search = lc.set(queryId).toLowerCase().str();
  11873. }
  11874. return getQueryById(queryRegistry, search);
  11875. }
  11876. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11877. {
  11878. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11879. return resolveQueryAlias(queryRegistry, alias);
  11880. }
  11881. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11882. {
  11883. StringBuffer lcId(id);
  11884. lcId.toLowerCase();
  11885. StringBuffer xpath;
  11886. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11887. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11888. if (tree)
  11889. {
  11890. if (tree->getPropBool("@suspended", false) == suspend)
  11891. return;
  11892. if (suspend)
  11893. {
  11894. tree->addPropBool("@suspended", true);
  11895. if (userid && *userid)
  11896. tree->addProp("@suspendedBy", userid);
  11897. }
  11898. else
  11899. {
  11900. tree->removeProp("@suspended");
  11901. tree->removeProp("@suspendedBy");
  11902. }
  11903. }
  11904. else
  11905. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11906. }
  11907. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11908. {
  11909. if (queryComment)
  11910. {
  11911. StringBuffer lcId(id);
  11912. lcId.toLowerCase();
  11913. StringBuffer xpath;
  11914. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11915. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11916. if (tree)
  11917. tree->setProp("@queryComment", queryComment);
  11918. else
  11919. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11920. }
  11921. }
  11922. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11923. {
  11924. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11925. if (conn)
  11926. return conn->getRoot();
  11927. else
  11928. return NULL;
  11929. }
  11930. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11931. {
  11932. if (!queryTree || !libraries)
  11933. return;
  11934. if (queryTree->hasProp("@libCount")) //already added
  11935. return;
  11936. unsigned libCount=0;
  11937. ForEach(*libraries)
  11938. {
  11939. IConstWULibrary &library = libraries->query();
  11940. SCMStringBuffer libname;
  11941. if (!library.getName(libname).length())
  11942. continue;
  11943. queryTree->addProp("Library", libname.str());
  11944. libCount++;
  11945. }
  11946. queryTree->setPropInt("@libCount", libCount);
  11947. }
  11948. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11949. {
  11950. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11951. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11952. }
  11953. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11954. {
  11955. //Only lock the branch for the target we're interested in.
  11956. StringBuffer xpath;
  11957. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11958. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11959. if (conn)
  11960. return conn->getRoot();
  11961. if (readonly)
  11962. return NULL;
  11963. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11964. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11965. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11966. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11967. if (conn)
  11968. return conn->getRoot();
  11969. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11970. if (!conn)
  11971. throwUnexpected();
  11972. IPropertyTree * root = conn->queryRoot();
  11973. root->setProp("@id",wsEclId);
  11974. conn->commit();
  11975. return LINK(root);
  11976. }
  11977. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11978. {
  11979. StringBuffer xpath;
  11980. StringBuffer lcName(name);
  11981. lcName.toLowerCase();
  11982. // see if "name" already exists
  11983. xpath.append("Package[@id='").append(name).append("']");
  11984. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11985. if (pkgTree)
  11986. {
  11987. if (overWrite)
  11988. packageRegistry->removeTree(pkgTree);
  11989. else
  11990. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11991. }
  11992. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11993. tree->setProp("@id", lcName);
  11994. return tree;
  11995. }
  11996. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11997. {
  11998. StringBuffer lcId(id);
  11999. lcId.toLowerCase();
  12000. StringBuffer xpath;
  12001. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  12002. packageRegistry->removeProp(xpath);
  12003. }
  12004. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  12005. {
  12006. //Only lock the branch for the target we're interested in.
  12007. StringBuffer xpath;
  12008. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  12009. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12010. if (conn)
  12011. return conn->getRoot();
  12012. if (readonly)
  12013. return NULL;
  12014. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  12015. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  12016. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  12017. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  12018. if (conn)
  12019. return conn->getRoot();
  12020. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  12021. if (!conn)
  12022. throwUnexpected();
  12023. IPropertyTree* root = conn->queryRoot();
  12024. root->setProp("@id",wsEclId);
  12025. conn->commit();
  12026. return LINK(root);
  12027. }
  12028. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  12029. {
  12030. StringBuffer cleanQueryName;
  12031. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  12032. SCMStringBuffer dllName;
  12033. Owned<IConstWUQuery> q = workunit->getQuery();
  12034. q->getQueryDllName(dllName);
  12035. if (!dllName.length())
  12036. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  12037. StringBuffer currentTargetClusterType;
  12038. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  12039. SCMStringBuffer targetClusterType;
  12040. workunit->getDebugValue("targetclustertype", targetClusterType);
  12041. SCMStringBuffer snapshot;
  12042. workunit->getSnapshot(snapshot);
  12043. if (currentTargetClusterType.length() < 1)
  12044. {
  12045. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  12046. }
  12047. else
  12048. {
  12049. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  12050. {
  12051. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  12052. }
  12053. }
  12054. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  12055. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  12056. checkAddLibrariesToQueryEntry(newEntry, libraries);
  12057. newQueryId.append(newEntry->queryProp("@id"));
  12058. workunit->setIsQueryService(true); //will check querysets before delete
  12059. workunit->commit();
  12060. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  12061. }
  12062. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  12063. {
  12064. StringBuffer cleanQueryName;
  12065. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  12066. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  12067. {
  12068. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  12069. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  12070. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  12071. {
  12072. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  12073. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  12074. else
  12075. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  12076. }
  12077. }
  12078. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  12079. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  12080. }
  12081. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  12082. {
  12083. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  12084. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  12085. }
  12086. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  12087. {
  12088. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12089. StringBuffer xpath;
  12090. xpath.appendf("Alias[@name='%s']", alias);
  12091. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  12092. return queryRegistry->removeTree(t);
  12093. }
  12094. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  12095. {
  12096. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  12097. setQueryAlias(queryRegistry, alias, id);
  12098. }
  12099. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  12100. {
  12101. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12102. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  12103. }
  12104. void deleteQuerySetQuery(const char *querySetName, const char *id)
  12105. {
  12106. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12107. removeNamedQuery(queryRegistry, id);
  12108. }
  12109. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  12110. {
  12111. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12112. clearAliases(queryRegistry, id);
  12113. }
  12114. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  12115. {
  12116. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12117. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  12118. }
  12119. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  12120. {
  12121. if (!queryRegistry)
  12122. return NULL;
  12123. StringBuffer xpath;
  12124. xpath.appendf("Query[@wuid='%s']", wuid);
  12125. if (queryName && *queryName)
  12126. xpath.appendf("[@name='%s']", queryName);
  12127. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  12128. if (q)
  12129. {
  12130. id.set(q->queryProp("@id"));
  12131. }
  12132. return id.str();
  12133. }
  12134. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  12135. {
  12136. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  12137. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  12138. }
  12139. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  12140. {
  12141. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  12142. ForEach(*wulibraries)
  12143. {
  12144. SCMStringBuffer libname;
  12145. IConstWULibrary &wulibrary = wulibraries->query();
  12146. wulibrary.getName(libname);
  12147. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  12148. continue;
  12149. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  12150. if (query && query->getPropBool("@isLibrary"))
  12151. {
  12152. const char *wuid = query->queryProp("@wuid");
  12153. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  12154. if (libcw)
  12155. {
  12156. names.appendUniq(libname.str());
  12157. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  12158. continue;
  12159. }
  12160. }
  12161. unresolved.appendUniq(libname.str());
  12162. }
  12163. }
  12164. bool looksLikeAWuid(const char * wuid, const char firstChar)
  12165. {
  12166. if (!wuid)
  12167. return false;
  12168. if (wuid[0] != firstChar)
  12169. return false;
  12170. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  12171. return false;
  12172. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  12173. return false;
  12174. return (wuid[9]=='-');
  12175. }
  12176. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  12177. {
  12178. IPropertyTree * module = archive;
  12179. const char * dot = strrchr(path, '.');
  12180. StringBuffer xpath;
  12181. if (dot)
  12182. {
  12183. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  12184. module = archive->queryPropTree(xpath);
  12185. path = dot+1;
  12186. }
  12187. else
  12188. module = archive->queryPropTree("Module[@key='']");
  12189. if (!module)
  12190. return NULL;
  12191. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  12192. return module->queryPropTree(xpath);
  12193. }
  12194. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  12195. {
  12196. StringBuffer hostname;
  12197. queryHostIP().getIpText(hostname);
  12198. StringBuffer fullPathname;
  12199. makeAbsolutePath(name, fullPathname);
  12200. query->addAssociatedFile(type, fullPathname, hostname, description, crc, minActivity, maxActivity);
  12201. }
  12202. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  12203. {
  12204. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  12205. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  12206. if(workunit)
  12207. workunit->deschedule();
  12208. else
  12209. doDescheduleWorkkunit(wuid);
  12210. }
  12211. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  12212. {
  12213. StringBuffer scopestr;
  12214. if (wfid && scope && *scope)
  12215. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12216. else
  12217. scopestr.set(scope);
  12218. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  12219. }
  12220. class WuTimingUpdater : implements ITimeReportInfo
  12221. {
  12222. public:
  12223. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  12224. : wu(_wu), scopeType(_scopeType), kind(_kind)
  12225. { }
  12226. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  12227. {
  12228. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  12229. }
  12230. protected:
  12231. IWorkUnit * wu;
  12232. StatisticScopeType scopeType;
  12233. StatisticKind kind;
  12234. };
  12235. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  12236. {
  12237. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  12238. timer->report(target);
  12239. }
  12240. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  12241. {
  12242. WuTimingUpdater target(wu, scopeType, kind);
  12243. timer->report(target);
  12244. }
  12245. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  12246. {
  12247. StringBuffer scopestr;
  12248. if (wfid && scope && *scope)
  12249. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  12250. else
  12251. scopestr.set(scope);
  12252. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  12253. }
  12254. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  12255. {
  12256. SimpleReferenceAggregator aggregator(search, result);
  12257. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  12258. ForEach(*it)
  12259. it->playProperties(aggregator);
  12260. }
  12261. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  12262. {
  12263. public:
  12264. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  12265. virtual void beginScope(const StatsScopeId & id)
  12266. {
  12267. prevLenStack.append(scope.length());
  12268. if (scope.length())
  12269. scope.append(":");
  12270. id.getScopeText(scope);
  12271. scopeTypeStack.append(id.queryScopeType());
  12272. }
  12273. virtual void beginSubGraphScope(unsigned id)
  12274. {
  12275. StatsScopeId scopeId(SSTsubgraph, id);
  12276. beginScope(scopeId);
  12277. }
  12278. virtual void beginActivityScope(unsigned id)
  12279. {
  12280. StatsScopeId scopeId(SSTactivity, id);
  12281. beginScope(scopeId);
  12282. }
  12283. virtual void beginEdgeScope(unsigned id, unsigned oid)
  12284. {
  12285. StatsScopeId scopeId(SSTedge, id, oid);
  12286. beginScope(scopeId);
  12287. }
  12288. virtual void beginChildGraphScope(unsigned id)
  12289. {
  12290. StatsScopeId scopeId(SSTchildgraph, id);
  12291. beginScope(scopeId);
  12292. }
  12293. virtual void endScope()
  12294. {
  12295. scope.setLength(prevLenStack.popGet());
  12296. scopeTypeStack.pop();
  12297. }
  12298. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  12299. {
  12300. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12301. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  12302. }
  12303. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  12304. {
  12305. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  12306. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  12307. }
  12308. virtual IStatisticCollection * getResult()
  12309. {
  12310. return NULL;
  12311. }
  12312. protected:
  12313. Linked<IWorkUnit> wu;
  12314. StringBuffer scope;
  12315. UnsignedArray prevLenStack;
  12316. UnsignedArray scopeTypeStack;
  12317. };
  12318. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  12319. {
  12320. return new GlobalStatisticGatherer(wu);
  12321. }
  12322. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  12323. {
  12324. if (!wuid || !*wuid)
  12325. return NULL;
  12326. VStringBuffer path("/GraphProgress/%s", wuid);
  12327. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  12328. if (conn)
  12329. return conn->getRoot();
  12330. else
  12331. return NULL;
  12332. }
  12333. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  12334. {
  12335. ErrorSeverity wuSeverity = SeverityInformation;
  12336. ErrorSeverity severity = error->getSeverity();
  12337. switch (severity)
  12338. {
  12339. case SeverityIgnore:
  12340. return;
  12341. case SeverityInformation:
  12342. break;
  12343. case SeverityWarning:
  12344. wuSeverity = SeverityWarning;
  12345. break;
  12346. case SeverityError:
  12347. case SeverityFatal:
  12348. wuSeverity = SeverityError;
  12349. break;
  12350. }
  12351. Owned<IWUException> exception = wu->createException();
  12352. exception->setSeverity(wuSeverity);
  12353. StringBuffer msg;
  12354. exception->setExceptionCode(error->errorCode());
  12355. exception->setExceptionMessage(error->errorMessage(msg).str());
  12356. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  12357. exception->setExceptionSource(source);
  12358. exception->setExceptionFileName(error->getFilename());
  12359. exception->setExceptionLineNo(error->getLine());
  12360. exception->setExceptionColumn(error->getColumn());
  12361. if (removeTimeStamp)
  12362. exception->setTimeStamp(nullptr);
  12363. if (error->getActivity())
  12364. exception->setActivityId(error->getActivity());
  12365. if (error->queryScope())
  12366. exception->setScope(error->queryScope());
  12367. }
  12368. IError * WorkUnitErrorReceiver::mapError(IError * error)
  12369. {
  12370. return LINK(error);
  12371. }
  12372. void WorkUnitErrorReceiver::report(IError* eclError)
  12373. {
  12374. addWorkunitException(wu, eclError, removeTimeStamp);
  12375. }
  12376. size32_t WorkUnitErrorReceiver::errCount()
  12377. {
  12378. unsigned count = 0;
  12379. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12380. ForEach(*exceptions)
  12381. if (exceptions->query().getSeverity() == SeverityError)
  12382. count++;
  12383. return count;
  12384. }
  12385. size32_t WorkUnitErrorReceiver::warnCount()
  12386. {
  12387. unsigned count = 0;
  12388. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  12389. ForEach(*exceptions)
  12390. if (exceptions->query().getSeverity() == SeverityWarning)
  12391. count++;
  12392. return count;
  12393. }
  12394. bool isValidPriorityValue(const char *priority)
  12395. {
  12396. if (isEmptyString(priority))
  12397. return false;
  12398. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  12399. return true;
  12400. return false;
  12401. }
  12402. bool isValidMemoryValue(const char *memoryUnit)
  12403. {
  12404. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  12405. return false;
  12406. while (isdigit(*++memoryUnit));
  12407. if (!*memoryUnit)
  12408. return true;
  12409. switch (toupper(*memoryUnit++))
  12410. {
  12411. case 'E':
  12412. case 'P':
  12413. case 'T':
  12414. case 'G':
  12415. case 'M':
  12416. case 'K':
  12417. if (!*memoryUnit || strieq("B", memoryUnit))
  12418. return true;
  12419. break;
  12420. case 'B':
  12421. if (!*memoryUnit)
  12422. return true;
  12423. break;
  12424. }
  12425. return false;
  12426. }