workunit.cpp 428 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294
  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. #ifndef _CONTAINERIZED
  44. #include "environment.hpp"
  45. #endif
  46. #include "daqueue.hpp"
  47. #include "workunit.ipp"
  48. #include "digisign.hpp"
  49. #include <list>
  50. #include <string>
  51. #include <algorithm>
  52. using namespace cryptohelper;
  53. static int workUnitTraceLevel = 1;
  54. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  55. {
  56. // MORE - can fold in the date
  57. return wuRoot.append("/WorkUnits/").append(wuid);
  58. }
  59. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  60. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  61. {
  62. #ifdef _WIN32
  63. suffix.append("W");
  64. #else
  65. suffix.append("L");
  66. #endif
  67. #ifdef __64BIT__
  68. suffix.append("64");
  69. #else
  70. suffix.append("32");
  71. #endif
  72. return suffix;
  73. }
  74. typedef MapStringTo<bool> UniqueScopes;
  75. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  76. {
  77. StringBuffer err;
  78. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  79. if (wuid)
  80. err.append(" workunit:").append(wuid);
  81. if (wuscope)
  82. err.append(" scope:").append(wuscope);
  83. //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
  84. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  85. if (log)
  86. LOG(MCuserError, "%s", err.str());
  87. if (excpt)
  88. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  89. }
  90. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  91. {
  92. if (!secmgr || !secuser)
  93. return true;
  94. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  95. if (!ret && (log || excpt))
  96. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  97. return ret;
  98. }
  99. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  100. {
  101. if (!scopes)
  102. return true;
  103. bool ret=true;
  104. if (wuscope)
  105. {
  106. Owned<ISecResource> res=scopes->getResource(wuscope);
  107. if (!res || res->getAccessFlags()<required)
  108. ret=false;
  109. }
  110. else
  111. {
  112. for (int seq=0; ret && seq<scopes->count(); seq++)
  113. {
  114. ISecResource *res=scopes->queryResource(seq);
  115. if (res && res->getAccessFlags()<required)
  116. return false;
  117. }
  118. }
  119. if (!ret && (log || excpt))
  120. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  121. return ret;
  122. }
  123. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  124. {
  125. if (!secmgr || !secuser)
  126. return true;
  127. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  128. if (!ret && (log || excpt))
  129. {
  130. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  131. }
  132. return ret;
  133. }
  134. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  135. {
  136. if (!secmgr || !secuser)
  137. return true;
  138. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  139. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  140. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw->queryWuScope())>=required;
  141. if (!ret && (log || excpt))
  142. {
  143. wuAccessError(secuser->getName(), action, cw->queryWuScope(), cw->queryWuid(), excpt, log);
  144. }
  145. return ret;
  146. }
  147. void doDescheduleWorkkunit(char const * wuid)
  148. {
  149. StringBuffer xpath;
  150. xpath.append("*/*/*/");
  151. ncnameEscape(wuid, xpath);
  152. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  153. if(!conn) return;
  154. Owned<IPropertyTree> root = conn->getRoot();
  155. bool more;
  156. do more = root->removeProp(xpath.str()); while(more);
  157. }
  158. //======================================================
  159. /*
  160. * Graph progress support
  161. */
  162. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, unsigned wfid, const char * _rootScope, unsigned _id)
  163. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  164. {
  165. StatsScopeId graphScopeId;
  166. verifyex(graphScopeId.setScopeText(_rootScope));
  167. StatsScopeId rootScopeId(SSTworkflow,wfid);
  168. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  169. collector->beginScope(graphScopeId);
  170. }
  171. void CWuGraphStats::beforeDispose()
  172. {
  173. Owned<IStatisticCollection> stats = collector->getResult();
  174. MemoryBuffer compressed;
  175. {
  176. MemoryBuffer serialized;
  177. serializeStatisticCollection(serialized, stats);
  178. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  179. }
  180. unsigned minActivity = 0;
  181. unsigned maxActivity = 0;
  182. stats->getMinMaxActivity(minActivity, maxActivity);
  183. StringBuffer tag;
  184. tag.append("sg").append(id);
  185. //Replace the particular subgraph statistics added by this creator
  186. StringBuffer qualified(tag);
  187. qualified.append("[@creator='").append(creator).append("']");
  188. progress->removeProp(qualified);
  189. IPropertyTree * subgraph = progress->addPropTree(tag);
  190. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  191. subgraph->setProp("@creator", creator);
  192. subgraph->setPropInt("@minActivity", minActivity);
  193. subgraph->setPropInt("@maxActivity", maxActivity);
  194. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  195. if (!progress->getPropBool("@stats", false))
  196. progress->setPropBool("@stats", true);
  197. }
  198. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  199. {
  200. return *collector;
  201. }
  202. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  203. {
  204. public:
  205. IMPLEMENT_IINTERFACE;
  206. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  207. {
  208. if (!progress)
  209. progress.setown(createPTree());
  210. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  211. }
  212. virtual IPropertyTree * getProgressTree()
  213. {
  214. if (progress->getPropBool("@stats"))
  215. return createProcessTreeFromStats(); // Should we cache that?
  216. return LINK(progress);
  217. }
  218. virtual unsigned queryFormatVersion()
  219. {
  220. return formatVersion;
  221. }
  222. protected:
  223. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  224. {
  225. formatVersion = PROGRESS_FORMAT_V;
  226. }
  227. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  228. {
  229. StringBuffer formattedValue;
  230. unsigned numStats = collection.getNumStatistics();
  231. for (unsigned i=0; i < numStats; i++)
  232. {
  233. StatisticKind kind;
  234. unsigned __int64 value;
  235. collection.getStatistic(kind, value, i);
  236. formatStatistic(formattedValue.clear(), value, kind);
  237. target->setProp(queryTreeTag(kind), formattedValue);
  238. }
  239. }
  240. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  241. {
  242. expandStats(target, *collection);
  243. StringBuffer scopeName;
  244. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL, false);
  245. ForEach(*activityIter)
  246. {
  247. IStatisticCollection & cur = activityIter->query();
  248. cur.getScope(scopeName.clear());
  249. const char * id = scopeName.str();
  250. const char * tag;
  251. IPropertyTree * curTarget = target;
  252. switch (cur.queryScopeType())
  253. {
  254. case SSTedge:
  255. tag = "edge";
  256. id += strlen(EdgeScopePrefix);
  257. break;
  258. case SSTactivity:
  259. tag = "node";
  260. id += strlen(ActivityScopePrefix);
  261. break;
  262. case SSTsubgraph:
  263. //All subgraphs are added a root elements in the progress tree
  264. curTarget = rootTarget;
  265. tag = "node";
  266. id += strlen(SubGraphScopePrefix);
  267. break;
  268. case SSTchildgraph:
  269. case SSTworkflow:
  270. case SSTgraph:
  271. // SSTworkflow and SSTgraph may be safely ignored. They are not required to produce the statistics.
  272. continue;
  273. case SSTfunction:
  274. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  275. continue;
  276. default:
  277. throwUnexpected();
  278. }
  279. IPropertyTree * next = curTarget->addPropTree(tag);
  280. next->setProp("@id", id);
  281. expandProcessTreeFromStats(rootTarget, next, &cur);
  282. }
  283. }
  284. IPropertyTree * createProcessTreeFromStats()
  285. {
  286. MemoryBuffer compressed;
  287. MemoryBuffer serialized;
  288. Owned<IPropertyTree> progressTree = createPTree();
  289. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  290. ForEach(*iter)
  291. {
  292. IPropertyTree & curSubGraph = iter->query();
  293. curSubGraph.getPropBin("Stats", compressed.clear());
  294. //Protect against updates that delete the stats while we are iterating
  295. if (compressed.length())
  296. {
  297. decompressToBuffer(serialized.clear(), compressed);
  298. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  299. expandProcessTreeFromStats(progressTree, progressTree, collection);
  300. }
  301. }
  302. return progressTree.getClear();
  303. }
  304. protected:
  305. Linked<IPropertyTree> progress;
  306. StringAttr wuid, graphName;
  307. unsigned formatVersion;
  308. };
  309. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  310. {
  311. return new CConstGraphProgress(_wuid, _graphName, _progress);
  312. }
  313. //--------------------------------------------------------------------------------------------------------------------
  314. /*
  315. * Create a user friendly description a scope/stats combination. Only currently used for elapsed time for root subgraphs
  316. */
  317. static void createDefaultDescription(StringBuffer & description, StatisticKind kind, StatisticScopeType scopeType, const char * scope)
  318. {
  319. switch (kind)
  320. {
  321. case StTimeElapsed:
  322. {
  323. if (scopeType != SSTsubgraph)
  324. break;
  325. //Create a default description for a root subgraph
  326. const char * colon = strchr(scope, ':');
  327. if (!colon)
  328. break;
  329. const char * subgraph = colon+1;
  330. //Check for nested subgraph
  331. if (strchr(subgraph, ':'))
  332. break;
  333. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  334. StringAttr graphname;
  335. graphname.set(scope, colon - scope);
  336. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  337. formatGraphTimerLabel(description, graphname, 0, subId);
  338. return;
  339. }
  340. }
  341. describeScope(description, scope);
  342. }
  343. /* Represents a single statistic */
  344. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  345. {
  346. public:
  347. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  348. {
  349. if (!description && createDefault)
  350. {
  351. StringBuffer desc;
  352. createDefaultDescription(desc, kind, scopeType, scope);
  353. str.set(desc);
  354. return str;
  355. }
  356. str.set(description);
  357. return str;
  358. }
  359. virtual IStringVal & getCreator(IStringVal & str) const
  360. {
  361. str.set(creator);
  362. return str;
  363. }
  364. virtual const char * queryScope() const
  365. {
  366. return scope ? scope : "";
  367. }
  368. virtual IStringVal & getFormattedValue(IStringVal & str) const
  369. {
  370. StringBuffer formatted;
  371. formatStatistic(formatted, value, measure);
  372. str.set(formatted);
  373. return str;
  374. }
  375. virtual StatisticMeasure getMeasure() const
  376. {
  377. return measure;
  378. }
  379. virtual StatisticKind getKind() const
  380. {
  381. return kind;
  382. }
  383. virtual StatisticCreatorType getCreatorType() const
  384. {
  385. return creatorType;
  386. }
  387. virtual StatisticScopeType getScopeType() const
  388. {
  389. return scopeType;
  390. }
  391. virtual unsigned __int64 getValue() const
  392. {
  393. return value;
  394. }
  395. virtual unsigned __int64 getCount() const
  396. {
  397. return count;
  398. }
  399. virtual unsigned __int64 getMax() const
  400. {
  401. return max;
  402. }
  403. virtual unsigned __int64 getTimestamp() const
  404. {
  405. return timeStamp;
  406. }
  407. public:
  408. StringBuffer creator;
  409. StringBuffer description;
  410. StringBuffer scope;
  411. StatisticMeasure measure;
  412. StatisticKind kind;
  413. StatisticCreatorType creatorType;
  414. StatisticScopeType scopeType;
  415. unsigned __int64 value;
  416. unsigned __int64 count;
  417. unsigned __int64 max;
  418. unsigned __int64 timeStamp;
  419. };
  420. //---------------------------------------------------------------------------------------------------------------------
  421. /*
  422. * The following compare functions are used to ensure that comparison are consistent with
  423. * compareScopeName() in jstats. This ensures that the scope iterators from different sources
  424. * are processed in a consistent order
  425. */
  426. static int compareGraphNode(IInterface * const *ll, IInterface * const *rr)
  427. {
  428. IPropertyTree *l = (IPropertyTree *) *ll;
  429. IPropertyTree *r = (IPropertyTree *) *rr;
  430. unsigned lwfid = l->getPropInt("@wfid");
  431. unsigned rwfid = r->getPropInt("@wfid");
  432. if (lwfid != rwfid)
  433. return lwfid > rwfid ? +1 : -1;
  434. const char * lname = l->queryName();
  435. const char * rname = r->queryName();
  436. return compareScopeName(lname, rname);
  437. }
  438. static int compareSubGraphStatsNode(IInterface * const *ll, IInterface * const *rr)
  439. {
  440. IPropertyTree *l = (IPropertyTree *) *ll;
  441. IPropertyTree *r = (IPropertyTree *) *rr;
  442. return compareScopeName(l->queryName(), r->queryName());
  443. }
  444. static int compareSubGraphNode(IInterface * const *ll, IInterface * const *rr)
  445. {
  446. IPropertyTree *l = (IPropertyTree *) *ll;
  447. IPropertyTree *r = (IPropertyTree *) *rr;
  448. return l->getPropInt("@id") - r->getPropInt("@id");
  449. }
  450. static int compareActivityNode(IInterface * const *ll, IInterface * const *rr)
  451. {
  452. IPropertyTree *l = (IPropertyTree *) *ll;
  453. IPropertyTree *r = (IPropertyTree *) *rr;
  454. return l->getPropInt("@id") - r->getPropInt("@id");
  455. }
  456. static int compareEdgeNode(IInterface * const *ll, IInterface * const *rr)
  457. {
  458. IPropertyTree *l = (IPropertyTree *) *ll;
  459. IPropertyTree *r = (IPropertyTree *) *rr;
  460. //MORE: Edge needs more work
  461. const char * leftId = l->queryProp("@id");
  462. const char * rightId = r->queryProp("@id");
  463. unsigned leftAc = atoi(leftId);
  464. unsigned rightAc = atoi(rightId);
  465. if (leftAc != rightAc)
  466. return (int)(leftAc - rightAc);
  467. const char * leftSep = strchr(leftId, '_');
  468. const char * rightSep = strchr(rightId, '_');
  469. assertex(leftSep && rightSep);
  470. return atoi(leftSep+1) - atoi(rightSep+1);
  471. }
  472. //---------------------------------------------------------------------------------------------------------------------
  473. /*
  474. * A class for implementing a scope iterator that walks through graph progress information
  475. */
  476. class CConstGraphProgressScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  477. {
  478. public:
  479. CConstGraphProgressScopeIterator(const char * wuid, const ScopeFilter & _filter, __uint64 _minVersion) : filter(_filter), minVersion(_minVersion)
  480. {
  481. //Examine the filter, and determine if we only need to look at a single graph/subgraph
  482. StringAttr singleGraph;
  483. const StringArray & scopesToMatch = filter.queryScopes();
  484. if (scopesToMatch)
  485. {
  486. bool seenGraph = false;
  487. bool seenSubGraph = false;
  488. ForEachItemIn(iScope, scopesToMatch)
  489. {
  490. StringArray ids;
  491. ids.appendList(scopesToMatch.item(iScope), ":");
  492. ForEachItemIn(i, ids)
  493. {
  494. const char * curId = ids.item(i);
  495. StatsScopeId id(curId);
  496. switch (id.queryScopeType())
  497. {
  498. case SSTgraph:
  499. if (seenGraph)
  500. {
  501. if (singleGraph && !streq(singleGraph, curId))
  502. singleGraph.clear();
  503. }
  504. else
  505. {
  506. if (!id.isWildcard())
  507. singleGraph.set(curId);
  508. seenGraph = true;
  509. }
  510. break;
  511. case SSTsubgraph:
  512. if (seenSubGraph)
  513. {
  514. if (singleSubGraph && !streq(singleSubGraph, curId))
  515. singleSubGraph.clear();
  516. }
  517. else
  518. {
  519. if (!id.isWildcard())
  520. singleSubGraph.set(curId);
  521. seenSubGraph = true;
  522. }
  523. break;
  524. }
  525. }
  526. }
  527. }
  528. rootPath.append("/GraphProgress/").append(wuid).append('/');
  529. if (singleGraph)
  530. rootPath.append(singleGraph).append("/");
  531. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  532. if (daliClientActive())
  533. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  534. if (conn && !singleGraph)
  535. {
  536. graphIter.setown(conn->queryRoot()->getElements("*"));
  537. graphIter.setown(createSortedIterator(*graphIter, compareGraphNode));
  538. }
  539. valid = false;
  540. }
  541. IMPLEMENT_IINTERFACE_USING(CInterfaceOf<IConstWUScopeIterator>)
  542. virtual bool first()
  543. {
  544. valid = false;
  545. if (!conn)
  546. return false;
  547. if (graphIter && !graphIter->first())
  548. return false;
  549. if (!firstSubGraph())
  550. {
  551. if (!nextGraph())
  552. return false;
  553. }
  554. valid = true;
  555. return true;
  556. }
  557. virtual bool next()
  558. {
  559. if (!nextChildScope())
  560. {
  561. if (!nextSubGraph())
  562. {
  563. if (!nextGraph())
  564. {
  565. valid = false;
  566. return false;
  567. }
  568. }
  569. }
  570. return true;
  571. }
  572. virtual bool nextSibling() override
  573. {
  574. if (collections.ordinality() == 0)
  575. return false;
  576. assertex(childIterators.ordinality() < collections.ordinality());
  577. collections.pop();
  578. //next will call childIterator.next() - walking the next sibling
  579. return next();
  580. }
  581. virtual bool nextParent() override
  582. {
  583. if (collections.ordinality() == 0)
  584. return false;
  585. assertex(childIterators.ordinality() < collections.ordinality());
  586. collections.pop();
  587. if (collections.ordinality() == 0)
  588. return false;
  589. //Finish with this node - so next will move onto the sibling of the parent node.
  590. finishCollection();
  591. return next();
  592. }
  593. virtual bool isValid()
  594. {
  595. return valid;
  596. }
  597. protected:
  598. bool firstSubGraph()
  599. {
  600. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  601. const char * xpath = "sg*";
  602. StringBuffer childXpath;
  603. if (singleSubGraph)
  604. {
  605. childXpath.append(singleSubGraph);
  606. xpath = childXpath.str();
  607. }
  608. subgraphIter.setown(graphNode.getElements(xpath));
  609. if (subgraphIter)
  610. {
  611. if (!singleSubGraph)
  612. subgraphIter.setown(createSortedIterator(*subgraphIter, compareSubGraphStatsNode));
  613. }
  614. else
  615. subgraphIter.setown(graphNode.getElements("sg0"));
  616. if (!subgraphIter->first())
  617. return false;
  618. if (firstStat())
  619. return true;
  620. return nextSubGraph();
  621. }
  622. bool nextSubGraph()
  623. {
  624. for (;;)
  625. {
  626. if (!subgraphIter->next())
  627. return false;
  628. if (firstStat())
  629. return true;
  630. }
  631. }
  632. bool nextGraph()
  633. {
  634. if (!graphIter)
  635. return false;
  636. for (;;)
  637. {
  638. if (!graphIter->next())
  639. return false;
  640. if (firstSubGraph())
  641. return true;
  642. }
  643. }
  644. bool firstStat()
  645. {
  646. IPropertyTree & curSubGraph = subgraphIter->query();
  647. if (!checkSubGraph())
  648. return false;
  649. curSubGraph.getPropBin("Stats", compressed.clear());
  650. //Don't crash on old format progress...
  651. if (compressed.length() == 0)
  652. return false;
  653. decompressToBuffer(serialized.clear(), compressed);
  654. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  655. statsIterator.timeStamp = collection->queryWhenCreated();
  656. if (!beginCollection(*collection))
  657. return false;
  658. // When workflow is root element, it is just a container. Ignore the workflow element here
  659. // as WorkUnitStatisticsScopeIterator will produce workflow scope - don't want duplicates.
  660. // (Note: workflow element never contains stats).
  661. if (collections.tos().queryScopeType() == SSTworkflow)
  662. {
  663. if (!next())
  664. return false;
  665. }
  666. //The root element of a collection is a graph - but it is only there to nest the subgraphs in.
  667. //Do not iterate it as a separate element - unless it has some stats.
  668. IStatisticCollection & curCollection = collections.tos();
  669. if ((curCollection.queryScopeType() != SSTgraph) || (curCollection.getNumStatistics() != 0))
  670. return true;
  671. return next();
  672. }
  673. bool beginCollection(IStatisticCollection & collection)
  674. {
  675. collections.append(OLINK(collection));
  676. curScopeType = collection.queryScopeType();
  677. collection.getFullScope(curScopeName.clear());
  678. ScopeCompare result = filter.compare(curScopeName);
  679. if (result & SCequal)
  680. return true;
  681. //If this scope cannot be the parent of a match then discard it.
  682. if (!(result & SCparent))
  683. collections.pop();
  684. //walk the next element
  685. return nextChildScope();
  686. }
  687. bool nextChildScope()
  688. {
  689. for (;;)
  690. {
  691. if (collections.ordinality() == 0)
  692. return false;
  693. IStatisticCollection * curCollection = &collections.tos();
  694. if (childIterators.ordinality() < collections.ordinality())
  695. {
  696. ScopeCompare result = filter.compare(curScopeName);
  697. //Do not walk children scopes if it is unrelated
  698. if (result & SCparent)
  699. {
  700. //Start iterating the children for the current collection
  701. childIterators.append(curCollection->getScopes(NULL, true));
  702. if (!childIterators.tos().first())
  703. {
  704. finishCollection();
  705. continue;
  706. }
  707. }
  708. else
  709. {
  710. //Don't walk the child scopes
  711. collections.pop();
  712. continue;
  713. }
  714. }
  715. else if (!childIterators.tos().next())
  716. {
  717. finishCollection();
  718. continue;
  719. }
  720. if (beginCollection(childIterators.tos().query()))
  721. return true;
  722. }
  723. }
  724. void finishCollection()
  725. {
  726. collections.pop();
  727. childIterators.pop();
  728. }
  729. bool checkSubGraph()
  730. {
  731. IPropertyTree & curSubGraph = subgraphIter->query();
  732. StatisticCreatorType creatorType = queryCreatorType(curSubGraph.queryProp("@c"), SCTnone);
  733. const char * creator = curSubGraph.queryProp("@creator");
  734. //MORE: Check minVersion and allow early filtering
  735. //MORE: Potentially filter by creator type??
  736. // if (!filter->matches(creatorType, creator, SSTall, NULL, SMeasureAll, StKindAll, AnyStatisticValue))
  737. // return false;
  738. statsIterator.creatorType = creatorType;
  739. statsIterator.creator.set(creator);
  740. return true;
  741. }
  742. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  743. {
  744. if ((whichProperties & PTstatistics))
  745. {
  746. /*
  747. MORE: Code from the statsIterator class should be inlined here - code will be much simpler
  748. but it currently needs an implementation of the IConstWUStatistic 3rd parameter
  749. IStatisticCollection & collection = collections.tos();
  750. ForEachItemIn(i, collection)
  751. {
  752. StatisticKind kind;
  753. unsigned __int64 value;
  754. collection->getStatistic(kind, value, i);
  755. visitor.noteStatistic(kind, value, *this);
  756. }
  757. */
  758. statsIterator.reset(curScopeName, curScopeType, collections.tos());
  759. ForEach(statsIterator)
  760. statsIterator.play(visitor);
  761. }
  762. }
  763. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  764. {
  765. return collections.tos().getStatistic(kind, value);
  766. }
  767. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  768. {
  769. return nullptr;
  770. }
  771. virtual const char * queryHint(const char * kind) const override
  772. {
  773. return nullptr;
  774. }
  775. virtual const char * queryScope() const override
  776. {
  777. return curScopeName;
  778. }
  779. virtual StatisticScopeType getScopeType() const override
  780. {
  781. return curScopeType;
  782. }
  783. private:
  784. class ScopeStatisticsIterator : public CInterfaceOf<IConstWUStatistic>
  785. {
  786. friend class CConstGraphProgressScopeIterator; // cleaner if this was removed + setScope() functions added.
  787. public:
  788. void reset(const char * _scopeName, StatisticScopeType _scopeType, IStatisticCollection & _collection)
  789. {
  790. scope.set(_scopeName);
  791. scopeType = _scopeType;
  792. collection = &_collection;
  793. numStats = collection->getNumStatistics();
  794. }
  795. // interface IConstWUStatisticIterator
  796. IConstWUStatistic & query()
  797. {
  798. return *this;
  799. }
  800. bool first()
  801. {
  802. curStatIndex = 0;
  803. if (curStatIndex >= numStats)
  804. return false;
  805. collection->getStatistic(kind, value, curStatIndex);
  806. //MORE: Allow filtering:
  807. /*
  808. * if (filter && !filter->matches(SCTall, NULL, SSTall, NULL, queryMeasure(kind), kind, value))
  809. continue;
  810. */
  811. return true;
  812. }
  813. bool next()
  814. {
  815. for (;;)
  816. {
  817. ++curStatIndex;
  818. if (curStatIndex >= numStats)
  819. return false;
  820. collection->getStatistic(kind, value, curStatIndex);
  821. //MORE: Allow stats filtering
  822. return true;
  823. }
  824. }
  825. bool isValid()
  826. {
  827. return curStatIndex < numStats;
  828. }
  829. //interface IConstWUStatistic
  830. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const override
  831. {
  832. if (createDefault)
  833. {
  834. StringBuffer description;
  835. createDefaultDescription(description, kind, scopeType, scope);
  836. str.set(description);
  837. }
  838. return str;
  839. }
  840. virtual IStringVal & getCreator(IStringVal & str) const override
  841. {
  842. str.set(creator);
  843. return str;
  844. }
  845. virtual const char * queryScope() const override
  846. {
  847. return scope;
  848. }
  849. virtual IStringVal & getFormattedValue(IStringVal & str) const override
  850. {
  851. StringBuffer formatted;
  852. formatStatistic(formatted, value, kind);
  853. str.set(formatted);
  854. return str;
  855. }
  856. virtual StatisticMeasure getMeasure() const override
  857. {
  858. return queryMeasure(kind);
  859. }
  860. virtual StatisticKind getKind() const override
  861. {
  862. return kind;
  863. }
  864. virtual StatisticCreatorType getCreatorType() const override
  865. {
  866. return creatorType;
  867. }
  868. virtual StatisticScopeType getScopeType() const override
  869. {
  870. return scopeType;
  871. }
  872. virtual unsigned __int64 getValue() const override
  873. {
  874. return value;
  875. }
  876. virtual unsigned __int64 getCount() const override
  877. {
  878. return 1;
  879. }
  880. virtual unsigned __int64 getMax() const override
  881. {
  882. return 0;
  883. }
  884. virtual unsigned __int64 getTimestamp() const override
  885. {
  886. return timeStamp;
  887. }
  888. void play(IWuScopeVisitor & visitor)
  889. {
  890. visitor.noteStatistic(kind, value, *this);
  891. }
  892. protected:
  893. IStatisticCollection * collection = nullptr;
  894. StringBuffer creator;
  895. StringBuffer scope;
  896. StatisticKind kind;
  897. StatisticCreatorType creatorType;
  898. StatisticScopeType scopeType;
  899. unsigned __int64 value = 0;
  900. unsigned __int64 timeStamp;
  901. unsigned curStatIndex = 0;
  902. unsigned numStats = 0;
  903. } statsIterator;
  904. Owned<IRemoteConnection> conn;
  905. StringBuffer curScopeName;
  906. StatisticScopeType curScopeType = SSTnone;
  907. __uint64 minVersion;
  908. const ScopeFilter & filter;
  909. StringBuffer rootPath;
  910. StringAttr singleSubGraph;
  911. Owned<IPropertyTreeIterator> graphIter;
  912. Owned<IPropertyTreeIterator> subgraphIter;
  913. IArrayOf<IStatisticCollection> collections;
  914. IArrayOf<IStatisticCollectionIterator> childIterators; // Iterator(n) through collections(n) - created once iterating children
  915. MemoryBuffer compressed;
  916. MemoryBuffer serialized;
  917. bool valid;
  918. };
  919. int compareNoteScopeOrder(IConstWUException & left, IConstWUException & right)
  920. {
  921. return compareScopeName(left.queryScope(), right.queryScope());
  922. }
  923. int compareNoteScopeOrder(IInterface * const * left, IInterface * const * right)
  924. {
  925. return compareNoteScopeOrder(*static_cast<IConstWUException *>(*left), *static_cast<IConstWUException *>(*right));
  926. }
  927. class NotesIterator : public CInterfaceOf<IConstWUScopeIterator>
  928. {
  929. public:
  930. NotesIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter)
  931. {
  932. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  933. ForEach(*exceptions)
  934. {
  935. IConstWUException & exception = exceptions->query();
  936. if (exception.queryScope()!=nullptr)
  937. notes.append(OLINK(exception));
  938. }
  939. notes.sort(compareNoteScopeOrder);
  940. }
  941. virtual bool first() override
  942. {
  943. baseIndex = 0;
  944. return updateCurrent();
  945. }
  946. virtual bool next() override
  947. {
  948. baseIndex += numCurrentScope;
  949. return updateCurrent();
  950. }
  951. virtual bool isValid() override
  952. {
  953. return notes.isItem(baseIndex);
  954. }
  955. virtual bool nextSibling() override
  956. {
  957. //Search until the current scope is not a child of the previous scope
  958. StringBuffer savedScope(queryScope());
  959. for (;;)
  960. {
  961. if (!next())
  962. return false;
  963. if (compareScopes(queryScope(), savedScope) != SCchild)
  964. return true;
  965. }
  966. }
  967. virtual bool nextParent() override
  968. {
  969. //Search until the current scope is not a child of the previous parent scope
  970. StringBuffer parentScope;
  971. if (getParentScope(parentScope, queryScope()))
  972. {
  973. for (;;)
  974. {
  975. if (!next())
  976. return false;
  977. if (compareScopes(queryScope(), parentScope) != SCchild)
  978. return true;
  979. }
  980. }
  981. else
  982. {
  983. finish();
  984. return false;
  985. }
  986. }
  987. virtual const char * queryScope() const override
  988. {
  989. const char * scope = notes.item(baseIndex).queryScope();
  990. return scope ? scope : "";
  991. }
  992. virtual StatisticScopeType getScopeType() const override
  993. {
  994. const char * tail = queryScopeTail(queryScope());
  995. StatsScopeId id(tail);
  996. return id.queryScopeType();
  997. }
  998. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) override
  999. {
  1000. if (whichProperties & PTnotes)
  1001. {
  1002. for (unsigned i=0; i < numCurrentScope; i++)
  1003. {
  1004. IConstWUException & cur = notes.item(baseIndex + i);
  1005. visitor.noteException(cur);
  1006. }
  1007. }
  1008. }
  1009. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1010. {
  1011. return false;
  1012. }
  1013. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1014. {
  1015. return nullptr;
  1016. }
  1017. virtual const char * queryHint(const char * kind) const override
  1018. {
  1019. return nullptr;
  1020. }
  1021. private:
  1022. bool updateCurrent()
  1023. {
  1024. if (!notes.isItem(baseIndex))
  1025. return false;
  1026. // set numCurrentScope to number of notes in the current scope
  1027. unsigned next = baseIndex+1;
  1028. while (next < notes.ordinality())
  1029. {
  1030. if (compareNoteScopeOrder(notes.item(baseIndex), notes.item(next)) != 0)
  1031. break;
  1032. next++;
  1033. }
  1034. numCurrentScope = (next - baseIndex);
  1035. return true;
  1036. }
  1037. void finish()
  1038. {
  1039. baseIndex = notes.ordinality();
  1040. }
  1041. unsigned baseIndex = 0;
  1042. unsigned numCurrentScope = 0;
  1043. IArrayOf<IConstWUException> notes;
  1044. };
  1045. int compareStatisticScopes(IConstWUStatistic & left, IConstWUStatistic & right)
  1046. {
  1047. return compareScopeName(left.queryScope(), right.queryScope());
  1048. }
  1049. int compareStatisticScopes(IInterface * const * left, IInterface * const * right)
  1050. {
  1051. return compareStatisticScopes(*static_cast<IConstWUStatistic *>(*left), *static_cast<IConstWUStatistic *>(*right));
  1052. }
  1053. /*
  1054. * An implementation of IConstWUScopeIterator for global workunit statistics.
  1055. */
  1056. class WorkUnitStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1057. {
  1058. public:
  1059. WorkUnitStatisticsScopeIterator(const IArrayOf<IConstWUStatistic> & _statistics, const ScopeFilter & _filter)
  1060. {
  1061. ForEachItemIn(i, _statistics)
  1062. {
  1063. IConstWUStatistic & cur = _statistics.item(i);
  1064. if (_filter.compare(cur.queryScope()) & SCequal)
  1065. statistics.append(OLINK(cur));
  1066. }
  1067. statistics.sort(compareStatisticScopes);
  1068. }
  1069. virtual bool first() override
  1070. {
  1071. curIndex = 0;
  1072. return initScope();
  1073. }
  1074. virtual bool next() override
  1075. {
  1076. curIndex += numStatistics;
  1077. return initScope();
  1078. }
  1079. virtual bool nextSibling() override
  1080. {
  1081. //Search until the current scope is not a child of the previous scope
  1082. StringBuffer savedScope(queryScope());
  1083. for (;;)
  1084. {
  1085. if (!next())
  1086. return false;
  1087. if (compareScopes(queryScope(), savedScope) != SCchild)
  1088. return true;
  1089. }
  1090. }
  1091. virtual bool nextParent() override
  1092. {
  1093. //Search until the current scope is not a child of the previous parent scope
  1094. StringBuffer parentScope;
  1095. if (getParentScope(parentScope, queryScope()))
  1096. {
  1097. for (;;)
  1098. {
  1099. if (!next())
  1100. return false;
  1101. if (compareScopes(queryScope(), parentScope) != SCchild)
  1102. return true;
  1103. }
  1104. }
  1105. else
  1106. {
  1107. finish();
  1108. return false;
  1109. }
  1110. }
  1111. virtual bool isValid() override
  1112. {
  1113. return statistics.isItem(curIndex);
  1114. }
  1115. virtual const char * queryScope() const override
  1116. {
  1117. return statistics.item(curIndex).queryScope();
  1118. }
  1119. virtual StatisticScopeType getScopeType() const override
  1120. {
  1121. return statistics.item(curIndex).getScopeType();
  1122. }
  1123. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1124. {
  1125. if (whichProperties & PTstatistics)
  1126. {
  1127. for (unsigned i=0; i < numStatistics; i++)
  1128. {
  1129. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1130. visitor.noteStatistic(cur.getKind(), cur.getValue(), cur);
  1131. }
  1132. }
  1133. }
  1134. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1135. {
  1136. for (unsigned i=0; i < numStatistics; i++)
  1137. {
  1138. IConstWUStatistic & cur = statistics.item(curIndex + i);
  1139. if (cur.getKind() == kind)
  1140. {
  1141. value = cur.getValue();
  1142. return true;
  1143. }
  1144. }
  1145. return false;
  1146. }
  1147. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1148. {
  1149. return nullptr;
  1150. }
  1151. virtual const char * queryHint(const char * kind) const
  1152. {
  1153. return nullptr;
  1154. }
  1155. protected:
  1156. inline IConstWUStatistic & queryStatistic(unsigned i)
  1157. {
  1158. return statistics.item(curIndex + i);
  1159. }
  1160. bool initScope()
  1161. {
  1162. if (!statistics.isItem(curIndex))
  1163. return false;
  1164. unsigned next = curIndex+1;
  1165. while (next < statistics.ordinality())
  1166. {
  1167. if (compareStatisticScopes(statistics.item(curIndex), statistics.item(next)) != 0)
  1168. break;
  1169. next++;
  1170. }
  1171. numStatistics = (next - curIndex);
  1172. return true;
  1173. }
  1174. void finish()
  1175. {
  1176. curIndex = statistics.ordinality();
  1177. }
  1178. protected:
  1179. IArrayOf<IConstWUStatistic> statistics;
  1180. unsigned curIndex = 0;
  1181. unsigned numStatistics = 1;
  1182. };
  1183. /*
  1184. * An implementation of IConstWUScopeIterator for the query graphs.
  1185. */
  1186. class GraphScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1187. {
  1188. private:
  1189. //This uses a state machine - this enumeration contains the different states.
  1190. enum State
  1191. {
  1192. //Following are the states which represent valid scopes
  1193. SGraph,
  1194. SChildGraph,
  1195. SSubGraph,
  1196. SEdge,
  1197. SActivity,
  1198. //The following are internal states.
  1199. SGraphFirstEdge,
  1200. SGraphFirstSubGraph,
  1201. SGraphFirst,
  1202. SGraphEnd,
  1203. SGraphNext,
  1204. SSubGraphFirstEdge,
  1205. SSubGraphFirstActivity,
  1206. SSubGraphEnd,
  1207. SSubGraphNext,
  1208. SEdgeNext,
  1209. SEdgeEnd,
  1210. SActivityNext,
  1211. SActivityEnd,
  1212. SChildGraphFirstEdge,
  1213. SChildGraphFirstSubGraph,
  1214. SChildGraphFirst,
  1215. SChildGraphNext,
  1216. SChildGraphEnd,
  1217. SDone
  1218. };
  1219. State state = SDone;
  1220. State nextState = SDone;
  1221. public:
  1222. GraphScopeIterator(const IConstWorkUnit * wu, const ScopeFilter & _filter) : graphIter(&wu->getGraphs(GraphTypeAny)), filter(_filter)
  1223. {
  1224. }
  1225. virtual bool first() override
  1226. {
  1227. state = SGraphFirst;
  1228. return nextScope();
  1229. }
  1230. virtual bool next() override
  1231. {
  1232. if (!selectNext())
  1233. return false;
  1234. return nextScope();
  1235. }
  1236. virtual bool nextSibling() override
  1237. {
  1238. if (!selectNextSibling())
  1239. return false;
  1240. return nextScope();
  1241. }
  1242. virtual bool nextParent() override
  1243. {
  1244. if (!selectNextParent())
  1245. return false;
  1246. return nextScope();
  1247. }
  1248. virtual bool isValid() override
  1249. {
  1250. return graphIter->isValid();
  1251. }
  1252. virtual const char * queryScope() const override
  1253. {
  1254. return curScopeName.str();
  1255. }
  1256. virtual StatisticScopeType getScopeType() const override
  1257. {
  1258. return scopeType;
  1259. }
  1260. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1261. {
  1262. switch (scopeType)
  1263. {
  1264. case SSTgraph:
  1265. return;
  1266. }
  1267. IPropertyTree & cur = treeIters.tos().query();
  1268. switch (scopeType)
  1269. {
  1270. case SSTgraph:
  1271. break;
  1272. case SSTsubgraph:
  1273. break;
  1274. case SSTactivity:
  1275. {
  1276. if (whichProperties & PTattributes)
  1277. {
  1278. playAttribute(visitor, WaLabel);
  1279. Owned<IPropertyTreeIterator> attrs = cur.getElements("att");
  1280. ForEach(*attrs)
  1281. {
  1282. IPropertyTree & cur = attrs->query();
  1283. WuAttr attr = queryGraphChildAttToWuAttr(cur.queryProp("@name"));
  1284. if (attr != WaNone)
  1285. visitor.noteAttribute(attr, cur.queryProp("@value"));
  1286. }
  1287. }
  1288. if (whichProperties & PThints)
  1289. {
  1290. Owned<IPropertyTreeIterator> hints = cur.getElements("hint");
  1291. ForEach(*hints)
  1292. {
  1293. IPropertyTree & cur = hints->query();
  1294. visitor.noteHint(cur.queryProp("@name"), cur.queryProp("@value"));
  1295. }
  1296. }
  1297. break;
  1298. }
  1299. case SSTedge:
  1300. if (whichProperties & PTattributes)
  1301. {
  1302. //MORE This will eventually need to walk the attributes and map the names.
  1303. //Need to be careful if they need to be mapped differently depending on the context.
  1304. playAttribute(visitor, WaLabel);
  1305. playAttribute(visitor, WaIdSource);
  1306. playAttribute(visitor, WaIdTarget);
  1307. playAttribute(visitor, WaSourceIndex);
  1308. playAttribute(visitor, WaTargetIndex);
  1309. playAttribute(visitor, WaIsDependency);
  1310. }
  1311. break;
  1312. }
  1313. }
  1314. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1315. {
  1316. return false;
  1317. }
  1318. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1319. {
  1320. if (!treeIters.ordinality())
  1321. return nullptr;
  1322. //MORE - check that the attribute is value for the current scope type (to prevent defaults being returned)
  1323. return queryAttributeValue(treeIters.tos().query(), attr, scratchpad);
  1324. }
  1325. virtual const char * queryHint(const char * kind) const override
  1326. {
  1327. //MORE: Needs to be implemented!
  1328. return nullptr;
  1329. }
  1330. private:
  1331. void playAttribute(IWuScopeVisitor & visitor, WuAttr kind)
  1332. {
  1333. StringBuffer scratchpad;
  1334. const char * value = queryAttributeValue(treeIters.tos().query(), kind, scratchpad);
  1335. if (value)
  1336. visitor.noteAttribute(kind, value);
  1337. }
  1338. void pushIterator(IPropertyTreeIterator * iter, State state)
  1339. {
  1340. treeIters.append(*LINK(iter));
  1341. stateStack.append(state);
  1342. }
  1343. State popIterator()
  1344. {
  1345. treeIters.pop();
  1346. return (State)stateStack.popGet();
  1347. }
  1348. void pushScope(const char * id)
  1349. {
  1350. scopeLengths.append(curScopeName.length());
  1351. curScopeName.append(":").append(id);
  1352. }
  1353. void popScope()
  1354. {
  1355. curScopeName.setLength(scopeLengths.popGet());
  1356. }
  1357. bool doNextScope()
  1358. {
  1359. for(;;)
  1360. {
  1361. switch (state)
  1362. {
  1363. case SGraph:
  1364. {
  1365. IConstWUGraph & graph = graphIter->query();
  1366. unsigned wfid = graph.getWfid();
  1367. curScopeName.clear();
  1368. if (wfid != 0)
  1369. curScopeName.append(WorkflowScopePrefix).append(wfid).append(':');
  1370. graph.getName(StringBufferAdaptor(curScopeName));
  1371. scopeType = SSTgraph;
  1372. return true;
  1373. }
  1374. case SSubGraph:
  1375. scopeId.set(SubGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1376. pushScope(scopeId);
  1377. scopeType = SSTsubgraph;
  1378. return true;
  1379. case SEdge:
  1380. scopeId.set(EdgeScopePrefix).append(treeIters.tos().query().queryProp("@id"));
  1381. pushScope(scopeId);
  1382. scopeType = SSTedge;
  1383. return true;
  1384. case SActivity:
  1385. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") == TAKsubgraph)
  1386. {
  1387. state = SActivityNext;
  1388. break;
  1389. }
  1390. scopeId.set(ActivityScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1391. pushScope(scopeId);
  1392. scopeType = SSTactivity;
  1393. return true;
  1394. case SChildGraph:
  1395. {
  1396. unsigned numIters = treeIters.ordinality();
  1397. //This should really be implemented by a filter on the node - but it would require _kind/_parentActivity to move to the node tag
  1398. if (treeIters.tos().query().getPropInt("att[@name='_kind']/@value") != TAKsubgraph)
  1399. {
  1400. state = SChildGraphNext;
  1401. break;
  1402. }
  1403. unsigned parentActivityId = treeIters.item(numIters-2).query().getPropInt("@id");
  1404. unsigned parentId = treeIters.tos().query().getPropInt("att[@name='_parentActivity']/@value");
  1405. if (parentId != parentActivityId)
  1406. {
  1407. state = SChildGraphNext;
  1408. break;
  1409. }
  1410. scopeId.set(ChildGraphScopePrefix).append(treeIters.tos().query().getPropInt("@id"));
  1411. pushScope(scopeId);
  1412. scopeType = SSTchildgraph;
  1413. return true;
  1414. }
  1415. //Graph iteration
  1416. case SGraphFirst:
  1417. if (!graphIter->first())
  1418. state = SDone;
  1419. else
  1420. state = SGraph;
  1421. break;
  1422. case SGraphEnd:
  1423. state = SGraphNext;
  1424. break;
  1425. case SGraphNext:
  1426. if (!graphIter->next())
  1427. state = SDone;
  1428. else
  1429. state = SGraph;
  1430. break;
  1431. //Edge iteration
  1432. case SGraphFirstEdge:
  1433. {
  1434. //Walk dependencies - should possibly have a different SST e.g., SSTdependency since they do not
  1435. //share many characteristics with edges - e.g. no flowing records => few/no stats.
  1436. curGraph.setown(graphIter->query().getXGMMLTree(false));
  1437. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("edge");
  1438. if (treeIter && treeIter->first())
  1439. {
  1440. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1441. treeIter->first();
  1442. pushIterator(treeIter, SGraphFirstSubGraph);
  1443. state = SEdge;
  1444. }
  1445. else
  1446. state = SGraphFirstSubGraph;
  1447. break;
  1448. }
  1449. case SChildGraphFirstEdge:
  1450. {
  1451. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1452. if (treeIter && treeIter->first())
  1453. {
  1454. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1455. pushIterator(treeIter, SChildGraphFirstSubGraph);
  1456. state = SEdge;
  1457. }
  1458. else
  1459. state = SChildGraphFirstSubGraph;
  1460. break;
  1461. }
  1462. case SEdgeEnd:
  1463. popScope();
  1464. state = SEdgeNext;
  1465. break;
  1466. case SEdgeNext:
  1467. if (treeIters.tos().next())
  1468. state = SEdge;
  1469. else
  1470. state = popIterator();
  1471. break;
  1472. //Subgraph iteration
  1473. case SGraphFirstSubGraph:
  1474. {
  1475. Owned<IPropertyTreeIterator> treeIter = curGraph->getElements("node");
  1476. if (treeIter && treeIter->first())
  1477. {
  1478. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1479. treeIter->first();
  1480. pushIterator(treeIter, SGraphNext);
  1481. state = SSubGraph;
  1482. }
  1483. else
  1484. state = SGraphNext;
  1485. break;
  1486. }
  1487. case SChildGraphFirstSubGraph:
  1488. {
  1489. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1490. if (treeIter && treeIter->first())
  1491. {
  1492. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1493. pushIterator(treeIter, SChildGraphEnd);
  1494. state = SSubGraph;
  1495. }
  1496. else
  1497. state = SChildGraphEnd;
  1498. break;
  1499. }
  1500. case SSubGraphFirstEdge:
  1501. {
  1502. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/edge");
  1503. if (treeIter && treeIter->first())
  1504. {
  1505. treeIter.setown(createSortedIterator(*treeIter, compareEdgeNode));
  1506. pushIterator(treeIter, SSubGraphFirstActivity);
  1507. state = SEdge;
  1508. }
  1509. else
  1510. state = SSubGraphFirstActivity;
  1511. break;
  1512. }
  1513. case SSubGraphFirstActivity:
  1514. {
  1515. Owned<IPropertyTreeIterator> treeIter = treeIters.tos().query().getElements("att/graph/node");
  1516. if (treeIter && treeIter->first())
  1517. {
  1518. treeIter.setown(createSortedIterator(*treeIter, compareActivityNode));
  1519. pushIterator(treeIter, SSubGraphEnd);
  1520. state = SActivity;
  1521. }
  1522. else
  1523. state = SSubGraphEnd;
  1524. break;
  1525. }
  1526. case SSubGraphEnd:
  1527. popScope();
  1528. state = SSubGraphNext;
  1529. break;
  1530. case SChildGraphEnd:
  1531. popScope();
  1532. state = SChildGraphNext;
  1533. break;
  1534. case SSubGraphNext:
  1535. if (treeIters.tos().next())
  1536. state = SSubGraph;
  1537. else
  1538. state = popIterator();
  1539. break;
  1540. case SActivityEnd:
  1541. popScope();
  1542. state = SActivityNext;
  1543. break;
  1544. case SActivityNext:
  1545. if (treeIters.tos().next())
  1546. state = SActivity;
  1547. else
  1548. state = popIterator();
  1549. break;
  1550. case SChildGraphNext:
  1551. if (treeIters.tos().next())
  1552. state = SChildGraph;
  1553. else
  1554. state = popIterator();
  1555. break;
  1556. case SChildGraphFirst:
  1557. {
  1558. unsigned numIters = treeIters.ordinality();
  1559. IPropertyTreeIterator & graphIter = treeIters.item(numIters-2);
  1560. Owned<IPropertyTreeIterator> treeIter = graphIter.query().getElements("att/graph/node");
  1561. //Really want to filter by <att name="_parentActivity" value="<parentid>">
  1562. if (treeIter && treeIter->first())
  1563. {
  1564. treeIter.setown(createSortedIterator(*treeIter, compareSubGraphNode));
  1565. pushIterator(treeIter, SActivityEnd);
  1566. state = SChildGraph;
  1567. }
  1568. else
  1569. state = SActivityEnd;
  1570. break;
  1571. }
  1572. case SDone:
  1573. return false;
  1574. default:
  1575. throwUnexpected();
  1576. }
  1577. }
  1578. }
  1579. bool nextScope()
  1580. {
  1581. for(;;)
  1582. {
  1583. if (!doNextScope())
  1584. return false;
  1585. ScopeCompare cmp = filter.compare(curScopeName);
  1586. if (cmp & SCequal)
  1587. return true;
  1588. //MORE: Optimize next based on result of compare
  1589. if (!selectNext())
  1590. return false;
  1591. }
  1592. }
  1593. bool selectNext()
  1594. {
  1595. switch (state)
  1596. {
  1597. case SGraph:
  1598. state = SGraphFirstEdge;
  1599. break;
  1600. case SChildGraph:
  1601. state = SChildGraphFirstEdge;
  1602. break;
  1603. case SSubGraph:
  1604. state = SSubGraphFirstEdge;
  1605. break;
  1606. case SEdge:
  1607. state = SEdgeEnd;
  1608. break;
  1609. case SActivity:
  1610. state = SChildGraphFirst;
  1611. break;
  1612. case SDone:
  1613. return false;
  1614. default:
  1615. throwUnexpected();
  1616. }
  1617. return true;
  1618. }
  1619. bool selectNextSibling()
  1620. {
  1621. switch (state)
  1622. {
  1623. case SGraph:
  1624. state = SGraphEnd;
  1625. break;
  1626. case SChildGraph:
  1627. state = SChildGraphEnd;
  1628. break;
  1629. case SSubGraph:
  1630. state = SSubGraphEnd;
  1631. break;
  1632. case SEdge:
  1633. state = SEdgeEnd;
  1634. break;
  1635. case SActivity:
  1636. state = SActivityEnd;
  1637. break;
  1638. case SDone:
  1639. return false;
  1640. default:
  1641. throwUnexpected();
  1642. }
  1643. return true;
  1644. }
  1645. bool selectNextParent()
  1646. {
  1647. switch (state)
  1648. {
  1649. case SGraph:
  1650. state = SDone;
  1651. break;
  1652. case SChildGraph:
  1653. case SSubGraph:
  1654. case SEdge:
  1655. case SActivity:
  1656. popScope();
  1657. state = popIterator();
  1658. break;
  1659. case SDone:
  1660. return false;
  1661. default:
  1662. throwUnexpected();
  1663. }
  1664. return true;
  1665. }
  1666. protected:
  1667. const ScopeFilter & filter;
  1668. Owned<IConstWUGraphIterator> graphIter;
  1669. Owned<IPropertyTree> curGraph;
  1670. IArrayOf<IPropertyTreeIterator> treeIters;
  1671. UnsignedArray scopeLengths;
  1672. UnsignedArray stateStack;
  1673. StringBuffer curScopeName;
  1674. StringBuffer scopeId;
  1675. StatisticScopeType scopeType = SSTnone;
  1676. };
  1677. static int compareWorkflow(IInterface * const * pLeft, IInterface * const * pRight)
  1678. {
  1679. IConstWorkflowItem * left = static_cast<IConstWorkflowItem *>(*pLeft);
  1680. IConstWorkflowItem * right = static_cast<IConstWorkflowItem *>(*pRight);
  1681. return left->queryWfid() - right->queryWfid();
  1682. }
  1683. static const char * trueToStr(bool value) { return value ? "true" : nullptr; }
  1684. /*
  1685. * An implementation of IConstWUScopeIterator for the workflow information.
  1686. */
  1687. class WorkflowStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1688. {
  1689. public:
  1690. WorkflowStatisticsScopeIterator(IConstWorkflowItemIterator * wfIter)
  1691. {
  1692. ForEach(*wfIter)
  1693. workflow.append(*LINK(wfIter->query()));
  1694. workflow.sort(compareWorkflow);
  1695. }
  1696. virtual bool first() override
  1697. {
  1698. if (workflow.empty())
  1699. return false;
  1700. curWorkflow = 0;
  1701. return initWorkflowItem();
  1702. }
  1703. virtual bool next() override
  1704. {
  1705. if (!workflow.isItem(++curWorkflow))
  1706. return false;
  1707. return initWorkflowItem();
  1708. }
  1709. virtual bool nextSibling() override
  1710. {
  1711. return next();
  1712. }
  1713. virtual bool nextParent() override
  1714. {
  1715. curWorkflow = NotFound;
  1716. return false;
  1717. }
  1718. virtual bool isValid() override
  1719. {
  1720. return workflow.isItem(curWorkflow);
  1721. }
  1722. virtual const char * queryScope() const override
  1723. {
  1724. return curScope.str();
  1725. }
  1726. virtual StatisticScopeType getScopeType() const override
  1727. {
  1728. return SSTworkflow;
  1729. }
  1730. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1731. {
  1732. if (whichProperties & PTattributes)
  1733. {
  1734. {
  1735. StringBuffer scratchpad;
  1736. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1737. ForEach(*depends)
  1738. visitor.noteAttribute(WaIdDependency, getValueText(depends->query(), scratchpad, WorkflowScopePrefix));
  1739. }
  1740. play(visitor, { WaIsScheduled, WaIdSuccess, WaIdFailure, WaIdRecovery, WaIdPersist, WaIdScheduled,
  1741. WaPersistName, WaLabel, WaMode, WaType, WaState, WaCluster, WaCriticalSection });
  1742. }
  1743. }
  1744. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1745. {
  1746. return false;
  1747. }
  1748. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1749. {
  1750. auto wf = &workflow.item(curWorkflow);
  1751. StringBufferAdaptor adaptor(scratchpad);
  1752. switch (attr)
  1753. {
  1754. case WaIdDependencyList:
  1755. {
  1756. bool first = true;
  1757. Owned<IWorkflowDependencyIterator> depends = workflow.item(curWorkflow).getDependencies();
  1758. ForEach(*depends)
  1759. {
  1760. if (first)
  1761. scratchpad.append("[");
  1762. else
  1763. scratchpad.append(",");
  1764. scratchpad.append('"').append(WorkflowScopePrefix).append(depends->query()).append('"');
  1765. first = false;
  1766. }
  1767. if (first)
  1768. return nullptr;
  1769. scratchpad.append("]");
  1770. return scratchpad.str();
  1771. }
  1772. case WaIsScheduled: return trueToStr(wf->isScheduled());
  1773. case WaIdSuccess: return getWfidText(wf->querySuccess(), scratchpad);
  1774. case WaIdFailure: return getWfidText(wf->queryFailure(), scratchpad);
  1775. case WaIdRecovery: return getWfidText(wf->queryRecovery(), scratchpad);
  1776. case WaIdPersist: return getWfidText(wf->queryPersistWfid(), scratchpad);
  1777. case WaIdScheduled: return getWfidText(wf->queryScheduledWfid(), scratchpad);
  1778. case WaPersistName: return queryOptString(wf->getPersistName(adaptor));
  1779. case WaLabel: return queryOptString(wf->getLabel(adaptor));
  1780. case WaMode: return wf->queryMode() != WFModeNormal ? queryWorkflowModeText(wf->queryMode()) : nullptr;
  1781. case WaType: return wf->queryType() != WFTypeNormal ? queryWorkflowTypeText(wf->queryType()) : nullptr;
  1782. case WaState: return queryWorkflowStateText(wf->queryState());
  1783. case WaCluster: return queryOptString(wf->queryCluster(adaptor));
  1784. case WaCriticalSection: return queryOptString(wf->getCriticalName(adaptor));
  1785. /*
  1786. The followng attributes are not generated - I'm not convinced they are very useful, but they could be added later.
  1787. virtual bool isScheduledNow() const = 0;
  1788. virtual IWorkflowEvent * getScheduleEvent() const = 0;
  1789. virtual unsigned querySchedulePriority() const = 0;
  1790. virtual bool hasScheduleCount() const = 0;
  1791. virtual unsigned queryScheduleCount() const = 0;
  1792. virtual unsigned queryRetriesAllowed() const = 0;
  1793. virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
  1794. virtual bool queryPersistRefresh() const = 0;
  1795. virtual unsigned queryScheduleCountRemaining() const = 0;
  1796. virtual unsigned queryRetriesRemaining() const = 0;
  1797. virtual int queryFailCode() const = 0;
  1798. virtual const char * queryFailMessage() const = 0;
  1799. virtual const char * queryEventName() const = 0;
  1800. virtual const char * queryEventExtra() const = 0;
  1801. */
  1802. }
  1803. return nullptr;
  1804. }
  1805. virtual const char * queryHint(const char * kind) const
  1806. {
  1807. return nullptr;
  1808. }
  1809. protected:
  1810. bool initWorkflowItem()
  1811. {
  1812. curScope.clear().append(WorkflowScopePrefix).append(workflow.item(curWorkflow).queryWfid());
  1813. return true;
  1814. }
  1815. const char * getValueText(unsigned value, StringBuffer & scratchpad, const char * prefix = nullptr) const
  1816. {
  1817. return scratchpad.clear().append(prefix).append(value).str();
  1818. }
  1819. const char * queryOptString(IStringVal & value) const
  1820. {
  1821. const char * text = value.str();
  1822. if (!text || !*text)
  1823. return nullptr;
  1824. return text;
  1825. }
  1826. const char * getWfidText(unsigned value, StringBuffer & scratchpad) const
  1827. {
  1828. if (!value)
  1829. return nullptr;
  1830. return scratchpad.clear().append(WorkflowScopePrefix).append(value).str();
  1831. }
  1832. void play(IWuScopeVisitor & visitor, const std::initializer_list<WuAttr> & attrs) const
  1833. {
  1834. StringBuffer scratchpad;
  1835. for (auto attr : attrs)
  1836. {
  1837. const char * value = queryAttribute(attr, scratchpad.clear());
  1838. if (value)
  1839. visitor.noteAttribute(attr, value);
  1840. }
  1841. }
  1842. protected:
  1843. IArrayOf<IConstWorkflowItem> workflow;
  1844. unsigned curWorkflow = 0;
  1845. StringBuffer curScope;
  1846. };
  1847. /*
  1848. * An implementation of IConstWUScopeIterator that combines results from multiple sources.
  1849. */
  1850. class CompoundStatisticsScopeIterator : public CInterfaceOf<IConstWUScopeIterator>
  1851. {
  1852. class VisitorMapper : implements IWuScopeVisitor
  1853. {
  1854. public:
  1855. VisitorMapper(const WuScopeFilter & _filter, IWuScopeVisitor & _visitor) :
  1856. filter(_filter), visitor(_visitor)
  1857. {}
  1858. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  1859. {
  1860. if (filter.includeStatistic(kind))
  1861. visitor.noteStatistic(kind, value, extra);
  1862. }
  1863. virtual void noteAttribute(WuAttr attr, const char * value) override
  1864. {
  1865. if (filter.includeAttribute(attr))
  1866. visitor.noteAttribute(attr, value);
  1867. }
  1868. virtual void noteHint(const char * kind, const char * value) override
  1869. {
  1870. if (filter.includeHint(kind))
  1871. visitor.noteHint(kind, value);
  1872. }
  1873. virtual void noteException(IConstWUException & exception) override
  1874. {
  1875. visitor.noteException(exception);
  1876. }
  1877. protected:
  1878. const WuScopeFilter & filter;
  1879. IWuScopeVisitor & visitor;
  1880. };
  1881. public:
  1882. CompoundStatisticsScopeIterator(const WuScopeFilter & _filter) : filter(_filter)
  1883. {
  1884. }
  1885. void addIter(IConstWUScopeIterator * iter)
  1886. {
  1887. if (iter)
  1888. {
  1889. iters.append(OLINK(*iter));
  1890. assertex(iters.ordinality() <= sizeof(activeIterMask)*8);
  1891. }
  1892. }
  1893. virtual bool first() override
  1894. {
  1895. activeIterMask = 0;
  1896. ForEachItemIn(i, iters)
  1897. {
  1898. if (iters.item(i).first())
  1899. activeIterMask |= (1U << i);
  1900. }
  1901. return findNextScope();
  1902. }
  1903. virtual bool next() override
  1904. {
  1905. selectNext();
  1906. return findNextScope();
  1907. }
  1908. virtual bool nextSibling() override
  1909. {
  1910. selectNextSibling();
  1911. return findNextScope();
  1912. }
  1913. virtual bool nextParent() override
  1914. {
  1915. selectNextParent();
  1916. return findNextScope();
  1917. }
  1918. virtual bool isValid() override
  1919. {
  1920. return (activeIterMask != 0);
  1921. }
  1922. virtual const char * queryScope() const override
  1923. {
  1924. return iters.item(firstMatchIter).queryScope();
  1925. }
  1926. virtual StatisticScopeType getScopeType() const override
  1927. {
  1928. return iters.item(firstMatchIter).getScopeType();
  1929. }
  1930. virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties) override
  1931. {
  1932. VisitorMapper mappedVisitor(filter, visitor);
  1933. whichProperties &= filter.properties;
  1934. ForEachItemIn(i, iters)
  1935. {
  1936. if (iterMatchesCurrentScope(i))
  1937. iters.item(i).playProperties(mappedVisitor, whichProperties);
  1938. }
  1939. }
  1940. virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const override
  1941. {
  1942. ForEachItemIn(i, iters)
  1943. {
  1944. if (iterMatchesCurrentScope(i))
  1945. {
  1946. if (iters.item(i).getStat(kind, value))
  1947. return true;
  1948. }
  1949. }
  1950. return false;
  1951. }
  1952. virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const override
  1953. {
  1954. ForEachItemIn(i, iters)
  1955. {
  1956. if (iterMatchesCurrentScope(i))
  1957. {
  1958. const char * value = iters.item(i).queryAttribute(attr, scratchpad);
  1959. if (value)
  1960. return value;
  1961. }
  1962. }
  1963. return nullptr;
  1964. }
  1965. virtual const char * queryHint(const char * kind) const override
  1966. {
  1967. ForEachItemIn(i, iters)
  1968. {
  1969. if (iterMatchesCurrentScope(i))
  1970. {
  1971. const char * value = iters.item(i).queryHint(kind);
  1972. if (value)
  1973. return value;
  1974. }
  1975. }
  1976. return nullptr;
  1977. }
  1978. inline bool iterMatchesCurrentScope(unsigned i) const { return ((1U << i) & matchIterMask) != 0; }
  1979. inline bool isAlive(unsigned i) const { return ((1U << i) & activeIterMask) != 0; }
  1980. protected:
  1981. //Calculate which iterators contain the scope that should come next
  1982. bool findNextScope()
  1983. {
  1984. for(;;)
  1985. {
  1986. if (activeIterMask == 0)
  1987. return false;
  1988. unsigned mask = 0;
  1989. const char * scope = nullptr;
  1990. ForEachItemIn(i, iters)
  1991. {
  1992. if (isAlive(i))
  1993. {
  1994. const char * iterScope = iters.item(i).queryScope();
  1995. if (mask)
  1996. {
  1997. int compare = compareScopeName(scope, iterScope);
  1998. if (compare == 0)
  1999. {
  2000. mask |= (1U << i);
  2001. }
  2002. else if (compare > 0)
  2003. {
  2004. scope = iterScope;
  2005. mask = (1U << i);
  2006. firstMatchIter = i;
  2007. }
  2008. }
  2009. else
  2010. {
  2011. scope = iterScope;
  2012. mask = (1U << i);
  2013. firstMatchIter = i;
  2014. }
  2015. }
  2016. }
  2017. matchIterMask = mask;
  2018. while (activeScopes)
  2019. {
  2020. const char * activeScope = activeScopes.tos();
  2021. //If the next scope if not a child of one of the active scopes then that active scope will no longer match.
  2022. if (compareScopes(scope, activeScope) & SCchild)
  2023. break;
  2024. activeScopes.pop();
  2025. }
  2026. //The top most scope will be the deepest. Check if the current scope is close enough to return as a match.
  2027. bool include = false;
  2028. if (activeScopes)
  2029. {
  2030. const char * activeScope = activeScopes.tos();
  2031. //code above has ensured that this scope must be a child of (and therefore deeper) than activeScope
  2032. unsigned nesting = queryScopeDepth(scope) - queryScopeDepth(activeScope);
  2033. if (nesting <= filter.include.nestedDepth)
  2034. include = true;
  2035. }
  2036. //Check to see if this is a new match
  2037. if (filter.compareMatchScopes(scope) & SCequal)
  2038. {
  2039. if (!include)
  2040. include = filter.include.matchedScope;
  2041. //Only add it to the list of active scopes if it can match child elements
  2042. if (filter.include.nestedDepth != 0)
  2043. activeScopes.append(scope);
  2044. }
  2045. if (include)
  2046. {
  2047. if (!filter.includeScope(scope))
  2048. include = false;
  2049. else if (filter.requiredStats.size())
  2050. {
  2051. //MORE: This would be cleaner as a member of filter - but it needs access to the stats.
  2052. for (unsigned iReq=0; iReq < filter.requiredStats.size(); iReq++)
  2053. {
  2054. const StatisticValueFilter & cur = filter.requiredStats[iReq];
  2055. unsigned __int64 value;
  2056. if (getStat(cur.queryKind(), value))
  2057. {
  2058. if (!cur.matches(value))
  2059. include = false;
  2060. }
  2061. else
  2062. include = false;
  2063. }
  2064. }
  2065. }
  2066. if (include)
  2067. return true;
  2068. //MORE: Optimize based on filter.compareScope()
  2069. selectNext();
  2070. }
  2071. }
  2072. void checkScopeOrder(unsigned input, const char * prevScope)
  2073. {
  2074. if (isAlive(input))
  2075. {
  2076. const char * curScope = iters.item(input).queryScope();
  2077. int compare = compareScopeName(prevScope, curScope);
  2078. if (compare >= 0)
  2079. throw MakeStringException(0, "Out of order (%u) scopes %s,%s = %d", input, prevScope, curScope, compare);
  2080. }
  2081. }
  2082. void selectNext()
  2083. {
  2084. ForEachItemIn(i, iters)
  2085. {
  2086. if (iterMatchesCurrentScope(i))
  2087. {
  2088. #ifdef _DEBUG
  2089. StringBuffer prevScope(iters.item(i).queryScope());
  2090. #endif
  2091. if (!iters.item(i).next())
  2092. activeIterMask &= ~(1U << i);
  2093. #ifdef _DEBUG
  2094. checkScopeOrder(i, prevScope);
  2095. #endif
  2096. }
  2097. }
  2098. }
  2099. void selectNextSibling()
  2100. {
  2101. ForEachItemIn(i, iters)
  2102. {
  2103. if (iterMatchesCurrentScope(i))
  2104. {
  2105. #ifdef _DEBUG
  2106. StringBuffer prevScope(iters.item(i).queryScope());
  2107. #endif
  2108. if (!iters.item(i).nextSibling())
  2109. activeIterMask &= ~(1U << i);
  2110. #ifdef _DEBUG
  2111. checkScopeOrder(i, prevScope);
  2112. #endif
  2113. }
  2114. }
  2115. }
  2116. void selectNextParent()
  2117. {
  2118. ForEachItemIn(i, iters)
  2119. {
  2120. if (iterMatchesCurrentScope(i))
  2121. {
  2122. #ifdef _DEBUG
  2123. StringBuffer prevScope(iters.item(i).queryScope());
  2124. #endif
  2125. if (!iters.item(i).nextParent())
  2126. activeIterMask &= ~(1U << i);
  2127. #ifdef _DEBUG
  2128. checkScopeOrder(i, prevScope);
  2129. #endif
  2130. }
  2131. }
  2132. }
  2133. protected:
  2134. const WuScopeFilter & filter;
  2135. IArrayOf<IConstWUScopeIterator> iters;
  2136. unsigned curIter = 0;
  2137. unsigned firstMatchIter = 0;
  2138. unsigned matchIterMask = 0; // bit set of iterators which have a valid entry for the current scope
  2139. unsigned activeIterMask = 0; // bit set of iterators which are still active
  2140. StringArray activeScopes;
  2141. };
  2142. //---------------------------------------------------------------------------------------------------------------------
  2143. class AggregateFilter
  2144. {
  2145. public:
  2146. AggregateFilter(StatisticKind _search) : search(_search) {}
  2147. inline bool matches(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) const
  2148. {
  2149. return (kind == search);
  2150. }
  2151. protected:
  2152. StatisticKind search;
  2153. //MORE: Allow filtering by scope?
  2154. };
  2155. class StatisticAggregator : public CInterfaceOf<IWuScopeVisitor>
  2156. {
  2157. public:
  2158. StatisticAggregator(StatisticKind _search) : filter(_search) {}
  2159. virtual void noteAttribute(WuAttr attr, const char * value) override { throwUnexpected(); }
  2160. virtual void noteHint(const char * kind, const char * value) override { throwUnexpected(); }
  2161. virtual void noteException(IConstWUException & exception) { throwUnexpected();}
  2162. protected:
  2163. AggregateFilter filter;
  2164. };
  2165. class SimpleAggregator : public StatisticAggregator
  2166. {
  2167. public:
  2168. SimpleAggregator(StatisticKind _search) : StatisticAggregator(_search) {}
  2169. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2170. {
  2171. if (filter.matches(kind, value, extra))
  2172. summary.noteValue(value);
  2173. }
  2174. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2175. //with a noteAggregate(value, variant, value, grouping)?
  2176. protected:
  2177. StatsAggregation summary;
  2178. };
  2179. class SimpleReferenceAggregator : public StatisticAggregator
  2180. {
  2181. public:
  2182. SimpleReferenceAggregator(StatisticKind _search, StatsAggregation & _summary) : StatisticAggregator(_search), summary(_summary) {}
  2183. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2184. {
  2185. if (filter.matches(kind, value, extra))
  2186. summary.noteValue(value);
  2187. }
  2188. //How should these be reported? Should there be a playAggregates(IWuAggregatedScopeVisitor)
  2189. //with a noteAggregate(value, variant, value, grouping)?
  2190. protected:
  2191. StatsAggregation & summary;
  2192. };
  2193. class GroupedAggregator : public StatisticAggregator
  2194. {
  2195. public:
  2196. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override
  2197. {
  2198. if (filter.matches(kind, value, extra))
  2199. {
  2200. StatsAggregation & match = summary; // look up in hash table.
  2201. match.noteValue(value);
  2202. }
  2203. }
  2204. protected:
  2205. //HashTable of (possible groupings->summary)
  2206. StatsAggregation summary;
  2207. };
  2208. class CompoundAggregator : implements StatisticAggregator
  2209. {
  2210. public:
  2211. virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra)
  2212. {
  2213. ForEachItemIn(i, aggregators)
  2214. aggregators.item(i).noteStatistic(kind, value, extra);
  2215. }
  2216. protected:
  2217. IArrayOf<StatisticAggregator> aggregators;
  2218. };
  2219. //To calculate aggregates, create a scope iterator, and an instance of a StatisticAggregator, and play the attributes through the interface
  2220. //---------------------------------------------------------------------------------------------------------------------
  2221. //Extract an argument of the format abc[def[ghi...,]],... as (abc,def[...])
  2222. static bool extractOption(const char * & finger, StringBuffer & option, StringBuffer & arg)
  2223. {
  2224. const char * start = finger;
  2225. if (!*start)
  2226. return false;
  2227. const char * cur = start;
  2228. const char * bra = nullptr;
  2229. const char * end = nullptr;
  2230. unsigned braDepth = 0;
  2231. char next;
  2232. arg.clear();
  2233. for (;;)
  2234. {
  2235. next = *cur;
  2236. if (!next || ((next == ',') && (braDepth == 0)))
  2237. break;
  2238. switch (next)
  2239. {
  2240. case '[':
  2241. if (braDepth == 0)
  2242. {
  2243. if (bra)
  2244. throw makeStringExceptionV(0, "Multiple [ in filter : %s", bra);
  2245. bra = cur;
  2246. }
  2247. braDepth++;
  2248. break;
  2249. case ']':
  2250. if (braDepth > 0)
  2251. {
  2252. if (--braDepth == 0)
  2253. {
  2254. end = cur;
  2255. arg.append(cur - (bra+1), bra+1);
  2256. }
  2257. }
  2258. break;
  2259. }
  2260. cur++;
  2261. }
  2262. if (braDepth != 0)
  2263. throw makeStringExceptionV(0, "Mismatched ] in filter : %s", start);
  2264. option.clear();
  2265. if (bra)
  2266. {
  2267. if (cur != end+1)
  2268. throw makeStringExceptionV(0, "Text follows closing bracket: %s", end);
  2269. option.append(bra-start, start);
  2270. }
  2271. else
  2272. option.append(cur-start, start);
  2273. if (next)
  2274. finger = cur+1;
  2275. else
  2276. finger = cur;
  2277. return true;
  2278. }
  2279. static unsigned readOptValue(const char * start, const char * end, unsigned dft, const char * type)
  2280. {
  2281. if (start == end)
  2282. return dft;
  2283. char * next;
  2284. unsigned value = (unsigned)strtoll(start, &next, 10);
  2285. if (next != end)
  2286. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2287. return value;
  2288. }
  2289. static unsigned readValue(const char * start, const char * type)
  2290. {
  2291. if (*start == '\0')
  2292. throw makeStringExceptionV(0, "Expected a value for the %s option", type);
  2293. char * next;
  2294. unsigned value = (unsigned)strtoll(start, &next, 10);
  2295. if (*next != '\0')
  2296. throw makeStringExceptionV(0, "Unexpected characters in %s option '%s'", type, next);
  2297. return value;
  2298. }
  2299. /*
  2300. Scope service matching Syntax: * indicates
  2301. Which items are matched:
  2302. scope[<scope-id>]* | stype[<scope-type>]* | id[<id>]* - which scopes should be matched?
  2303. depth[n | low..high] - range of depths to search for a match
  2304. source[global|stats|graph|all]* - which sources to search within the workunit
  2305. where[<statistickind> | <statistickind> (=|<|<=|>|>=) value | <statistickind>=low..high] - a statistic filter
  2306. Which items are include in the results:
  2307. matched[true|false] - are the matched scopes returned?
  2308. nested[<depth>|all] - how deep within a scope should be matched (default = 0 if matched[true], all if matched[false])
  2309. includetype[<scope-type>] - which scope types should be included?
  2310. Which properties of the items are returned:
  2311. properties[statistics|hints|attributes|scope|all]
  2312. statistic[<statistic-kind>|none|all] - include statistic
  2313. attribute[<attribute-name>|none|all] - include attribute
  2314. hint[<hint-name>] - include hint
  2315. property[<statistic-kind>|<attribute-name>|<hint-name>] - include property
  2316. measure[<measure>] - all statistics with a particular measure
  2317. version[<version>] - minimum version to return
  2318. */
  2319. enum { FOscope, FOstype, FOid, FOdepth, FOsource, FOwhere, FOmatched, FOnested, FOinclude, FOproperties, FOstatistic, FOattribute, FOhint, FOproperty, FOmeasure, FOversion, FOunknown };
  2320. //Some of the following contains aliases for the same option e.g. stat and statistic
  2321. static constexpr EnumMapping filterOptions[] = {
  2322. { FOscope, "scope" }, { FOstype, "stype" }, { FOid, "id" },
  2323. { FOdepth, "depth" }, { FOsource, "source" }, { FOwhere, "where" },
  2324. { FOmatched, "matched" }, { FOnested, "nested" },
  2325. { FOinclude, "include" }, { FOinclude, "includetype" },
  2326. { FOproperties, "props" }, { FOproperties, "properties" }, // some aliases
  2327. { FOstatistic, "stat" }, { FOstatistic, "statistic" }, { FOattribute, "attr" }, { FOattribute, "attribute" }, { FOhint, "hint" },
  2328. { FOproperty, "prop" }, { FOproperty, "property" },
  2329. { FOmeasure, "measure" }, { FOversion, "version" }, { 0, nullptr} };
  2330. static constexpr EnumMapping sourceMappings[] = {
  2331. { SSFsearchGlobalStats, "global" }, { SSFsearchGraphStats, "stats" }, { SSFsearchGraphStats, "statistics" }, { SSFsearchGraph, "graph" }, { SSFsearchExceptions, "exception" }, { SSFsearchWorkflow, "workflow" },
  2332. { (int)SSFsearchAll, "all" }, { 0, nullptr } };
  2333. static constexpr EnumMapping propertyMappings[] = {
  2334. { PTstatistics, "stat" }, { PTstatistics, "statistic" }, { PTattributes, "attr" }, { PTattributes, "attribute" }, { PThints, "hint" },{ PTnotes, "note" },
  2335. { PTstatistics, "stats" }, { PTstatistics, "statistics" }, { PTattributes, "attrs" }, { PTattributes, "attributes" }, { PThints, "hints" }, { PTnotes, "notes" },
  2336. { PTnone, "none" }, { PTscope, "scope" }, { PTall, "all" }, { 0, nullptr } };
  2337. WuScopeSourceFlags querySource(const char * source) { return (WuScopeSourceFlags)getEnum(source, sourceMappings, SSFunknown); }
  2338. const char * querySourceText(WuScopeSourceFlags source) { return getEnumText(source, sourceMappings, nullptr); }
  2339. WuScopeFilter::WuScopeFilter(const char * filter)
  2340. {
  2341. addFilter(filter);
  2342. finishedFilter();
  2343. }
  2344. WuScopeFilter & WuScopeFilter::addFilter(const char * filter)
  2345. {
  2346. if (!filter)
  2347. return *this;
  2348. StringBuffer option;
  2349. StringBuffer arg;
  2350. while (extractOption(filter, option, arg))
  2351. {
  2352. switch (getEnum(option, filterOptions, FOunknown))
  2353. {
  2354. case FOscope:
  2355. addScope(arg);
  2356. break;
  2357. case FOstype:
  2358. addScopeType(arg);
  2359. break;
  2360. case FOid:
  2361. addId(arg);
  2362. break;
  2363. case FOdepth:
  2364. {
  2365. //Allow depth[n], depth[a,b] or depth[a..b]
  2366. const char * comma = strchr(arg, ',');
  2367. const char * dotdot = strstr(arg, "..");
  2368. if (comma)
  2369. {
  2370. unsigned low = readOptValue(arg, comma, 0, "depth");
  2371. if (comma[1])
  2372. {
  2373. scopeFilter.setDepth(low, readValue(comma+1, "depth"));
  2374. }
  2375. else
  2376. scopeFilter.setDepth(low, UINT_MAX);
  2377. }
  2378. else if (dotdot)
  2379. {
  2380. unsigned low = readOptValue(arg, dotdot, 0, "depth");
  2381. if (dotdot[2])
  2382. scopeFilter.setDepth(low, readValue(dotdot+2, "depth"));
  2383. else
  2384. scopeFilter.setDepth(low, UINT_MAX);
  2385. }
  2386. else
  2387. {
  2388. scopeFilter.setDepth(readValue(arg, "depth"));
  2389. }
  2390. break;
  2391. }
  2392. case FOsource:
  2393. addSource(arg);
  2394. break;
  2395. case FOwhere: // where[stat<op>value]
  2396. addRequiredStat(arg);
  2397. break;
  2398. case FOmatched:
  2399. setIncludeMatch(strToBool(arg));
  2400. break;
  2401. case FOnested:
  2402. if (strieq(arg, "all"))
  2403. setIncludeNesting(UINT_MAX);
  2404. else if (isdigit(*arg))
  2405. setIncludeNesting(atoi(arg));
  2406. else
  2407. throw makeStringExceptionV(0, "Expected a value for the nesting depth: %s", arg.str());
  2408. break;
  2409. case FOinclude:
  2410. setIncludeScopeType(arg);
  2411. break;
  2412. case FOproperties:
  2413. {
  2414. WuPropertyTypes prop = (WuPropertyTypes)getEnum(arg, propertyMappings, PTunknown);
  2415. if (prop == PTunknown)
  2416. throw makeStringExceptionV(0, "Unexpected properties '%s'", arg.str());
  2417. addOutputProperties(prop);
  2418. break;
  2419. }
  2420. case FOstatistic:
  2421. addOutputStatistic(arg);
  2422. break;
  2423. case FOattribute:
  2424. addOutputAttribute(arg);
  2425. break;
  2426. case FOhint:
  2427. addOutputHint(arg);
  2428. break;
  2429. case FOproperty:
  2430. addOutput(arg);
  2431. break;
  2432. case FOmeasure:
  2433. setMeasure(arg);
  2434. break;
  2435. case FOversion:
  2436. if (isdigit(*arg))
  2437. minVersion = atoi64(arg);
  2438. else
  2439. throw makeStringExceptionV(0, "Expected a value for the version: %s", arg.str());
  2440. break;
  2441. default:
  2442. throw makeStringExceptionV(0, "Unrecognised filter option: %s", option.str());
  2443. }
  2444. }
  2445. return *this;
  2446. }
  2447. WuScopeFilter & WuScopeFilter::addScope(const char * scope)
  2448. {
  2449. if (scope)
  2450. {
  2451. validateScope(scope);
  2452. scopeFilter.addScope(scope);
  2453. }
  2454. return *this;
  2455. }
  2456. WuScopeFilter & WuScopeFilter::addScopeType(const char * scopeType)
  2457. {
  2458. if (scopeType)
  2459. {
  2460. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2461. if (sst == SSTmax)
  2462. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2463. scopeFilter.addScopeType(sst);
  2464. }
  2465. return *this;
  2466. }
  2467. WuScopeFilter & WuScopeFilter::addId(const char * id)
  2468. {
  2469. validateScopeId(id);
  2470. scopeFilter.addId(id);
  2471. return *this;
  2472. }
  2473. WuScopeFilter & WuScopeFilter::addOutput(const char * prop)
  2474. {
  2475. WuAttr attr = queryWuAttribute(prop, WaNone);
  2476. if (attr != WaNone)
  2477. {
  2478. WuAttr singleKindAttr = getSingleKindOfListAttribute(attr);
  2479. if (singleKindAttr != WaNone)
  2480. addOutputAttribute(singleKindAttr);
  2481. else
  2482. addOutputAttribute(attr);
  2483. } else if (queryStatisticKind(prop, StMax) != StMax)
  2484. addOutputStatistic(prop);
  2485. else
  2486. addOutputHint(prop);
  2487. return *this;
  2488. }
  2489. WuScopeFilter & WuScopeFilter::addOutputStatistic(const char * prop)
  2490. {
  2491. if (!prop)
  2492. return *this;
  2493. StatisticKind kind = queryStatisticKind(prop, StMax);
  2494. if (kind == StMax)
  2495. throw makeStringExceptionV(0, "Unrecognised statistic '%s'", prop);
  2496. return addOutputStatistic(kind);
  2497. }
  2498. WuScopeFilter & WuScopeFilter::addOutputStatistic(StatisticKind stat)
  2499. {
  2500. if (stat != StKindNone)
  2501. {
  2502. if (stat != StKindAll)
  2503. desiredStats.append(stat);
  2504. else
  2505. desiredStats.kill();
  2506. properties |= PTstatistics;
  2507. }
  2508. else
  2509. properties &= ~PTstatistics;
  2510. return *this;
  2511. }
  2512. WuScopeFilter & WuScopeFilter::addOutputAttribute(const char * prop)
  2513. {
  2514. if (!prop)
  2515. return *this;
  2516. WuAttr attr = queryWuAttribute(prop, WaMax);
  2517. if (attr == WaMax)
  2518. throw makeStringExceptionV(0, "Unrecognised attribute '%s'", prop);
  2519. return addOutputAttribute(attr);
  2520. }
  2521. WuScopeFilter & WuScopeFilter::addOutputAttribute(WuAttr attr)
  2522. {
  2523. if (attr != WaNone)
  2524. {
  2525. if (attr != WaAll)
  2526. desiredAttrs.append(attr);
  2527. else
  2528. desiredAttrs.kill();
  2529. properties |= PTattributes;
  2530. }
  2531. else
  2532. properties &= ~PTattributes;
  2533. return *this;
  2534. }
  2535. WuScopeFilter & WuScopeFilter::addOutputHint(const char * prop)
  2536. {
  2537. if (strieq(prop, "none"))
  2538. {
  2539. desiredHints.kill();
  2540. properties &= ~PThints;
  2541. }
  2542. else
  2543. {
  2544. if (!strieq(prop, "all"))
  2545. desiredHints.append(prop);
  2546. else
  2547. desiredHints.kill();
  2548. properties |= PThints;
  2549. }
  2550. return *this;
  2551. }
  2552. WuScopeFilter & WuScopeFilter::setIncludeMatch(bool value)
  2553. {
  2554. include.matchedScope = value;
  2555. return *this;
  2556. }
  2557. WuScopeFilter & WuScopeFilter::setIncludeNesting(unsigned depth)
  2558. {
  2559. include.nestedDepth = depth;
  2560. return *this;
  2561. }
  2562. WuScopeFilter & WuScopeFilter::setIncludeScopeType(const char * scopeType)
  2563. {
  2564. if (scopeType)
  2565. {
  2566. StatisticScopeType sst = queryScopeType(scopeType, SSTmax);
  2567. if (sst == SSTmax)
  2568. throw makeStringExceptionV(0, "Unrecognised scope type '%s'", scopeType);
  2569. include.scopeTypes.append(sst);
  2570. }
  2571. return *this;
  2572. }
  2573. WuScopeFilter & WuScopeFilter::setMeasure(const char * measure)
  2574. {
  2575. if (measure)
  2576. {
  2577. desiredMeasure = queryMeasure(measure, SMeasureNone);
  2578. if (desiredMeasure == SMeasureNone)
  2579. throw makeStringExceptionV(0, "Unrecognised measure '%s'", measure);
  2580. properties |= PTstatistics;
  2581. }
  2582. return *this;
  2583. }
  2584. WuScopeFilter & WuScopeFilter::addOutputProperties(WuPropertyTypes mask)
  2585. {
  2586. if (properties == PTnone)
  2587. properties = mask;
  2588. else
  2589. properties |= mask;
  2590. return *this;
  2591. }
  2592. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue)
  2593. {
  2594. requiredStats.emplace_back(statKind, lowValue, highValue);
  2595. return *this;
  2596. }
  2597. WuScopeFilter & WuScopeFilter::addRequiredStat(StatisticKind statKind)
  2598. {
  2599. requiredStats.emplace_back(statKind, 0, MaxStatisticValue);
  2600. return *this;
  2601. }
  2602. //process a filter in one of the following forms:
  2603. // <statistic-name>
  2604. // <statistic-name> (=|<|<=|>|>=) <value>
  2605. // <statistic-name>=[<low>]..[<high>]
  2606. void WuScopeFilter::addRequiredStat(const char * filter)
  2607. {
  2608. const char * stat = filter;
  2609. const char * cur = stat;
  2610. while (isalpha(*cur))
  2611. cur++;
  2612. StringBuffer statisticName(cur-stat, stat);
  2613. StatisticKind statKind = queryStatisticKind(statisticName, StKindNone);
  2614. if (statKind == StKindNone)
  2615. throw makeStringExceptionV(0, "Unknown statistic name '%s'", statisticName.str());
  2616. //Skip any spaces before a comparison operator.
  2617. while (*cur && isspace(*cur))
  2618. cur++;
  2619. //Save the operator, and skip over any non digits.
  2620. const char * op = cur;
  2621. switch (*op)
  2622. {
  2623. case '=':
  2624. cur++;
  2625. break;
  2626. case '<':
  2627. case '>':
  2628. if (op[1] == '=')
  2629. cur += 2;
  2630. else
  2631. cur++;
  2632. break;
  2633. case '\0':
  2634. break;
  2635. default:
  2636. throw makeStringExceptionV(0, "Unknown comparison '%s'", op);
  2637. }
  2638. const char * next;
  2639. stat_type value = readStatisticValue(cur, &next, queryMeasure(statKind));
  2640. stat_type lowValue = 0;
  2641. stat_type highValue = MaxStatisticValue;
  2642. switch (op[0])
  2643. {
  2644. case '=':
  2645. {
  2646. //Allow a,b or a..b to specify a range - either bound may be omitted.
  2647. if (next[0] == ',')
  2648. {
  2649. lowValue = value;
  2650. next++;
  2651. if (*next != '\0')
  2652. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2653. }
  2654. else if (strncmp(next, "..", 2) == 0)
  2655. {
  2656. lowValue = value;
  2657. next += 2;
  2658. if (*next != '\0')
  2659. highValue = readStatisticValue(next, &next, queryMeasure(statKind));
  2660. }
  2661. else
  2662. {
  2663. lowValue = value;
  2664. highValue = value;
  2665. }
  2666. break;
  2667. }
  2668. case '<':
  2669. if (op[1] == '=')
  2670. highValue = value;
  2671. else
  2672. highValue = value-1;
  2673. break;
  2674. case '>':
  2675. if (op[1] == '=')
  2676. lowValue = value;
  2677. else
  2678. lowValue = value+1;
  2679. break;
  2680. }
  2681. if (*next)
  2682. throw makeStringExceptionV(0, "Trailing characters in where '%s'", next);
  2683. requiredStats.emplace_back(statKind, lowValue, highValue);
  2684. }
  2685. WuScopeFilter & WuScopeFilter::addSource(const char * source)
  2686. {
  2687. WuScopeSourceFlags mask = querySource(source);
  2688. if (mask == SSFunknown)
  2689. throw makeStringExceptionV(0, "Unexpected source '%s'", source);
  2690. if (!mask)
  2691. sourceFlags = mask;
  2692. else
  2693. sourceFlags |= mask;
  2694. return *this;
  2695. }
  2696. WuScopeFilter & WuScopeFilter::setDepth(unsigned low, unsigned high)
  2697. {
  2698. scopeFilter.setDepth(low, high);
  2699. return *this;
  2700. }
  2701. bool WuScopeFilter::matchOnly(StatisticScopeType scopeType) const
  2702. {
  2703. //If there is a post filter on the scopeType, then check if it matches
  2704. if (include.scopeTypes.ordinality() == 1)
  2705. return (include.scopeTypes.item(0) == scopeType);
  2706. //If filter doesn't match nested items, then check if the scope filter matches.
  2707. if (include.nestedDepth == 0)
  2708. {
  2709. if (scopeFilter.matchOnly(scopeType))
  2710. return true;
  2711. }
  2712. return false;
  2713. }
  2714. //Called once the filter has been updated to optimize the filter
  2715. void WuScopeFilter::finishedFilter()
  2716. {
  2717. scopeFilter.finishedFilter();
  2718. assertex(!optimized);
  2719. optimized = true;
  2720. if ((include.nestedDepth == 0) && !include.matchedScope)
  2721. include.nestedDepth = UINT_MAX;
  2722. preFilterScope = include.matchedScope && (include.nestedDepth == 0);
  2723. if (scopeFilter.canAlwaysPreFilter())
  2724. preFilterScope = true;
  2725. //If the source flags have not been explicitly set then calculate which sources will provide the results
  2726. if (!sourceFlags)
  2727. {
  2728. sourceFlags = SSFsearchAll;
  2729. //Use the other options to reduce the number of elements that are searched.
  2730. //If not interested in scopes on their own then...
  2731. if (!(properties & PTscope))
  2732. {
  2733. //Global stats and graph stats only contain stats => remove if not interested in them
  2734. if (!(properties & PTstatistics))
  2735. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchGraphStats);
  2736. //graph, workflow only contains attributes and hints => remove if not interested
  2737. if (!(properties & (PTattributes|PThints)))
  2738. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2739. }
  2740. if (!(properties & PTnotes))
  2741. sourceFlags &= ~SSFsearchExceptions;
  2742. }
  2743. //Optimize sources if they haven't been explicitly specified
  2744. //Most of the following are dependent on internal knowledge of the way that information is represented
  2745. if (matchOnly(SSTworkflow))
  2746. {
  2747. //Workflow is not nested within a graph
  2748. sourceFlags &= ~(SSFsearchGraph|SSFsearchGraphStats);
  2749. setDepth(1, 1);
  2750. }
  2751. else if (matchOnly(SSTgraph))
  2752. {
  2753. //Graph starts are stored globally, not in the graph stats.
  2754. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchWorkflow);
  2755. if (!(properties & (PTattributes|PThints)))
  2756. sourceFlags &= ~(SSFsearchGraph);
  2757. //This should really be setDepth(2,2) but workunits prior to 7.4 did not have graph ids prefixed by the wfid
  2758. //Remove once 7.2 is a distant memory (see HPCC-22887)
  2759. setDepth(1, 2);
  2760. }
  2761. else if (matchOnly(SSTsubgraph))
  2762. {
  2763. sourceFlags &= ~(SSFsearchWorkflow);
  2764. }
  2765. else if (matchOnly(SSTcompilestage))
  2766. {
  2767. //compile stages are not stored in the graph
  2768. sourceFlags &= ~(SSFsearchGraphStats|SSFsearchGraph|SSFsearchWorkflow);
  2769. }
  2770. else if (matchOnly(SSTactivity))
  2771. {
  2772. //information about activities is not stored globally
  2773. sourceFlags &= ~(SSFsearchGlobalStats|SSFsearchWorkflow);
  2774. }
  2775. // Everything stored in the graphs stats has a depth of 3 or more - so ignore if there are not matches in that depth
  2776. if (include.nestedDepth == 0)
  2777. {
  2778. if (scopeFilter.compareDepth(3) > 0) // 3 is larger than any scope in the filter
  2779. sourceFlags &= ~(SSFsearchGraphStats);
  2780. else if (scopeFilter.compareDepth(3) == 0) // 3 matches the maximum scope in the filter
  2781. {
  2782. //Subgraph WhenStarted and TimeElapsed are stored globally. If that is all that is required
  2783. //then do not include the subgraph timings
  2784. if (desiredStats.ordinality())
  2785. {
  2786. bool needGraphStats = false;
  2787. ForEachItemIn(i, desiredStats)
  2788. {
  2789. unsigned stat = desiredStats.item(i);
  2790. if ((stat != StWhenStarted) && (stat != StTimeElapsed))
  2791. needGraphStats = true;
  2792. }
  2793. if (!needGraphStats)
  2794. {
  2795. sourceFlags &= ~(SSFsearchGraphStats);
  2796. if (matchOnly(SSTsubgraph))
  2797. sourceFlags &= SSFsearchGlobalStats;
  2798. }
  2799. }
  2800. }
  2801. }
  2802. if (scopeFilter.compareDepth(1) < 0)
  2803. {
  2804. //If minimum match depth is > 1 then it will never match workflow
  2805. sourceFlags &= ~(SSFsearchWorkflow);
  2806. }
  2807. //The xml graph is never updated, so do not check it if minVersion != 0
  2808. if (minVersion != 0)
  2809. {
  2810. sourceFlags &= ~(SSFsearchGraph|SSFsearchWorkflow);
  2811. }
  2812. }
  2813. bool WuScopeFilter::includeStatistic(StatisticKind kind) const
  2814. {
  2815. if (!(properties & PTstatistics))
  2816. return false;
  2817. if ((desiredMeasure != SMeasureAll) && (queryMeasure(kind) != desiredMeasure))
  2818. return false;
  2819. if (desiredStats.empty())
  2820. return true;
  2821. return desiredStats.contains(kind);
  2822. }
  2823. bool WuScopeFilter::includeAttribute(WuAttr attr) const
  2824. {
  2825. if (!(properties & PTattributes))
  2826. return false;
  2827. if (desiredAttrs.empty())
  2828. return true;
  2829. return desiredAttrs.contains(attr);
  2830. }
  2831. bool WuScopeFilter::includeHint(const char * kind) const
  2832. {
  2833. if (!(properties & PThints))
  2834. return false;
  2835. if (desiredHints.empty())
  2836. return true;
  2837. return desiredHints.contains(kind);
  2838. }
  2839. bool WuScopeFilter::includeScope(const char * scope) const
  2840. {
  2841. if (include.scopeTypes)
  2842. {
  2843. const char * tail = queryScopeTail(scope);
  2844. StatsScopeId id(tail);
  2845. if (!include.scopeTypes.contains(id.queryScopeType()))
  2846. return false;
  2847. }
  2848. return true;
  2849. }
  2850. const static ScopeFilter nullScopeFilter {};
  2851. const ScopeFilter & WuScopeFilter::queryIterFilter() const
  2852. {
  2853. if (preFilterScope)
  2854. return scopeFilter;
  2855. else
  2856. return nullScopeFilter;
  2857. }
  2858. ScopeCompare WuScopeFilter::compareMatchScopes(const char * scope) const
  2859. {
  2860. return scopeFilter.compare(scope);
  2861. }
  2862. StringBuffer & WuScopeFilter::describe(StringBuffer & out) const
  2863. {
  2864. scopeFilter.describe(out);
  2865. if (requiredStats.size())
  2866. {
  2867. out.append(",where[");
  2868. bool first = false;
  2869. for (const auto & stat : requiredStats)
  2870. {
  2871. if (!first)
  2872. out.append(",");
  2873. stat.describe(out);
  2874. first = false;
  2875. }
  2876. out.append("]");
  2877. }
  2878. {
  2879. StringBuffer sources;
  2880. for (unsigned mask=1; mask; mask *= 2)
  2881. {
  2882. if (sourceFlags & mask)
  2883. {
  2884. const char * source = querySourceText((WuScopeSourceFlags)mask);
  2885. if (source)
  2886. sources.append(",").append(source);
  2887. }
  2888. }
  2889. if (sources)
  2890. out.append(",source[").append(sources.str()+1).append("]");
  2891. }
  2892. if (include.nestedDepth != UINT_MAX)
  2893. out.appendf(",nested[%u]", include.nestedDepth);
  2894. if (include.scopeTypes)
  2895. {
  2896. out.append(",include[");
  2897. ForEachItemIn(i, include.scopeTypes)
  2898. {
  2899. if (i)
  2900. out.append(",");
  2901. out.append(queryScopeTypeName((StatisticScopeType)include.scopeTypes.item(i)));
  2902. }
  2903. out.append("]");
  2904. }
  2905. {
  2906. StringBuffer props;
  2907. if (properties == PTnone)
  2908. props.append(",none");
  2909. else if (properties == PTall)
  2910. props.append(",all");
  2911. else
  2912. {
  2913. if (properties & PTstatistics)
  2914. props.append(",stat");
  2915. if (properties & PTattributes)
  2916. props.append(",attr");
  2917. if (properties & PThints)
  2918. props.append(",hint");
  2919. if (properties & PTscope)
  2920. props.append(",scope");
  2921. if (properties & PTnotes)
  2922. props.append(",note");
  2923. }
  2924. out.append(",properties[").append(props.str()+1).append("]");
  2925. }
  2926. if (desiredStats)
  2927. {
  2928. out.append(",stat[");
  2929. ForEachItemIn(i, desiredStats)
  2930. {
  2931. if (i)
  2932. out.append(",");
  2933. out.append(queryStatisticName((StatisticKind)desiredStats.item(i)));
  2934. }
  2935. out.append("]");
  2936. }
  2937. if (desiredAttrs)
  2938. {
  2939. out.append(",attr[");
  2940. ForEachItemIn(i, desiredAttrs)
  2941. {
  2942. if (i)
  2943. out.append(",");
  2944. out.append(queryWuAttributeName((WuAttr)desiredAttrs.item(i)));
  2945. }
  2946. out.append("]");
  2947. }
  2948. if (desiredHints)
  2949. {
  2950. out.append(",hint[");
  2951. ForEachItemIn(i, desiredHints)
  2952. {
  2953. if (i)
  2954. out.append(",");
  2955. out.append(desiredHints.item(i));
  2956. }
  2957. out.append("]");
  2958. }
  2959. if (desiredMeasure != SMeasureAll)
  2960. out.append(",measure[").append(queryMeasureName(desiredMeasure)).append("]");
  2961. if (minVersion != 0)
  2962. out.appendf(",version(%" I64F "u)", minVersion);
  2963. return out;
  2964. }
  2965. //--------------------------------------------------------------------------------------------------------------------
  2966. EnumMapping states[] = {
  2967. { WUStateUnknown, "unknown" },
  2968. { WUStateCompiled, "compiled" },
  2969. { WUStateRunning, "running" },
  2970. { WUStateCompleted, "completed" },
  2971. { WUStateFailed, "failed" },
  2972. { WUStateArchived, "archived" },
  2973. { WUStateAborting, "aborting" },
  2974. { WUStateAborted, "aborted" },
  2975. { WUStateBlocked, "blocked" },
  2976. { WUStateSubmitted, "submitted" },
  2977. { WUStateScheduled, "scheduled" },
  2978. { WUStateCompiling, "compiling" },
  2979. { WUStateWait, "wait" },
  2980. { WUStateUploadingFiles, "uploading_files" },
  2981. { WUStateDebugPaused, "debugging" },
  2982. { WUStateDebugRunning, "debug_running" },
  2983. { WUStatePaused, "paused" },
  2984. { WUStateSize, NULL }
  2985. };
  2986. EnumMapping actions[] = {
  2987. { WUActionUnknown, "unknown" },
  2988. { WUActionCompile, "compile" },
  2989. { WUActionCheck, "check" },
  2990. { WUActionRun, "run" },
  2991. { WUActionExecuteExisting, "execute" },
  2992. { WUActionPause, "pause" },
  2993. { WUActionPauseNow, "pausenow" },
  2994. { WUActionResume, "resume" },
  2995. { WUActionSize, NULL },
  2996. };
  2997. EnumMapping priorityClasses[] = {
  2998. { PriorityClassUnknown, "unknown" },
  2999. { PriorityClassLow, "low" },
  3000. { PriorityClassNormal, "normal" },
  3001. { PriorityClassHigh, "high" },
  3002. { PriorityClassSize, NULL },
  3003. };
  3004. const char * getWorkunitStateStr(WUState state)
  3005. {
  3006. dbgassertex(state < WUStateSize);
  3007. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  3008. }
  3009. void setEnum(IPropertyTree *p, const char *propname, int value, const EnumMapping *map)
  3010. {
  3011. const char *defval = map->str;
  3012. while (map->str)
  3013. {
  3014. if (value==map->val)
  3015. {
  3016. p->setProp(propname, map->str);
  3017. return;
  3018. }
  3019. map++;
  3020. }
  3021. assertex(!"Unexpected value in setEnum");
  3022. p->setProp(propname, defval);
  3023. }
  3024. static int getEnum(const IPropertyTree *p, const char *propname, const EnumMapping *map)
  3025. {
  3026. return getEnum(p->queryProp(propname),map);
  3027. }
  3028. const char * getWorkunitActionStr(WUAction action)
  3029. {
  3030. return getEnumText(action, actions);
  3031. }
  3032. WUAction getWorkunitAction(const char *actionStr)
  3033. {
  3034. return (WUAction) getEnum(actionStr, actions);
  3035. }
  3036. //==========================================================================================
  3037. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  3038. {
  3039. public:
  3040. CLightweightWorkunitInfo(IPropertyTree &p)
  3041. {
  3042. wuid.set(p.queryName());
  3043. user.set(p.queryProp("@submitID"));
  3044. jobName.set(p.queryProp("@jobName"));
  3045. clusterName.set(p.queryProp("@clusterName"));
  3046. timeScheduled.set(p.queryProp("@timeScheduled"));
  3047. state = (WUState) getEnum(&p, "@state", states);
  3048. action = (WUAction) getEnum(&p, "Action", actions);
  3049. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  3050. priorityLevel = calcPriorityValue(&p);
  3051. wuscope.set(p.queryProp("@scope"));
  3052. appvalues.loadBranch(&p,"Application");
  3053. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  3054. _isProtected = p.getPropBool("@protected", false);
  3055. }
  3056. virtual const char *queryWuid() const { return wuid.str(); }
  3057. virtual const char *queryUser() const { return user.str(); }
  3058. virtual const char *queryJobName() const { return jobName.str(); }
  3059. virtual const char *queryClusterName() const { return clusterName.str(); }
  3060. virtual const char *queryWuScope() const { return wuscope.str(); }
  3061. virtual WUState getState() const { return state; }
  3062. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  3063. virtual WUAction getAction() const { return action; }
  3064. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  3065. virtual WUPriorityClass getPriority() const { return priority; }
  3066. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  3067. virtual int getPriorityLevel() const { return priorityLevel; }
  3068. virtual bool isProtected() const { return _isProtected; }
  3069. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  3070. {
  3071. if (timeScheduled.length())
  3072. val.setGmtString(timeScheduled.str());
  3073. return val;
  3074. }
  3075. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  3076. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  3077. protected:
  3078. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  3079. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  3080. unsigned totalThorTime;
  3081. WUState state;
  3082. WUAction action;
  3083. WUPriorityClass priority;
  3084. int priorityLevel;
  3085. bool _isProtected;
  3086. };
  3087. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  3088. {
  3089. return new CLightweightWorkunitInfo(p);
  3090. }
  3091. class CDaliWuGraphStats : public CWuGraphStats
  3092. {
  3093. public:
  3094. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, unsigned _wfid, const char * _rootScope, unsigned _id)
  3095. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _wfid, _rootScope, _id), conn(_conn)
  3096. {
  3097. }
  3098. protected:
  3099. Owned<IRemoteConnection> conn;
  3100. };
  3101. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  3102. {
  3103. abortId = 0;
  3104. stateId = 0;
  3105. actionId = 0;
  3106. assertex((flags & ~SubscribeOptionAbort) == 0);
  3107. if (flags & SubscribeOptionAbort)
  3108. {
  3109. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  3110. abortId = querySDS().subscribe(xpath.str(), *this, false, true);
  3111. }
  3112. }
  3113. CWorkUnitWatcher::~CWorkUnitWatcher()
  3114. {
  3115. assertex(abortId==0 && stateId==0 && actionId==0);
  3116. }
  3117. void CWorkUnitWatcher::unsubscribe()
  3118. {
  3119. CriticalBlock b(crit);
  3120. if (abortId)
  3121. querySDS().unsubscribe(abortId);
  3122. if (stateId)
  3123. querySDS().unsubscribe(stateId);
  3124. if (actionId)
  3125. querySDS().unsubscribe(actionId);
  3126. abortId = 0;
  3127. stateId = 0;
  3128. actionId = 0;
  3129. }
  3130. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  3131. {
  3132. CriticalBlock b(crit);
  3133. if (id==stateId)
  3134. subscriber->notify(SubscribeOptionState, valueLen, valueData);
  3135. else if (id==actionId)
  3136. subscriber->notify(SubscribeOptionAction, valueLen, valueData);
  3137. else if (id==abortId)
  3138. subscriber->notify(SubscribeOptionAbort, valueLen, valueData);
  3139. }
  3140. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  3141. {
  3142. public:
  3143. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  3144. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  3145. {
  3146. if (flags & SubscribeOptionState)
  3147. {
  3148. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  3149. stateId = querySDS().subscribe(xpath.str(), *this);
  3150. }
  3151. if (flags & SubscribeOptionAction)
  3152. {
  3153. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  3154. actionId = querySDS().subscribe(xpath.str(), *this);
  3155. }
  3156. }
  3157. };
  3158. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  3159. {
  3160. CriticalBlock block(crit);
  3161. assertex(options==SubscribeOptionAbort);
  3162. if (!abortWatcher)
  3163. {
  3164. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  3165. abortDirty = true;
  3166. }
  3167. }
  3168. void CPersistedWorkUnit::unsubscribe()
  3169. {
  3170. CriticalBlock block(crit);
  3171. if (abortWatcher)
  3172. {
  3173. abortWatcher->unsubscribe();
  3174. abortWatcher.clear();
  3175. }
  3176. }
  3177. bool CPersistedWorkUnit::aborting() const
  3178. {
  3179. CriticalBlock block(crit);
  3180. if (abortDirty)
  3181. {
  3182. StringBuffer apath;
  3183. apath.append("/WorkUnitAborts/").append(p->queryName());
  3184. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  3185. if (acon)
  3186. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  3187. else
  3188. abortState = false;
  3189. abortDirty = false;
  3190. }
  3191. return abortState;
  3192. }
  3193. class CDaliWorkUnit : public CPersistedWorkUnit
  3194. {
  3195. public:
  3196. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  3197. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  3198. {
  3199. loadPTree(connection->getRoot());
  3200. }
  3201. ~CDaliWorkUnit()
  3202. {
  3203. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  3204. // We use the beforeDispose() in base class to help ensure this
  3205. p.clear();
  3206. }
  3207. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  3208. {
  3209. Owned<IRemoteConnection> conn = getProgressConnection();
  3210. if (conn)
  3211. {
  3212. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3213. if (progress)
  3214. return new CConstGraphProgress(p->queryName(), graphName, progress);
  3215. }
  3216. return NULL;
  3217. }
  3218. virtual WUGraphState queryGraphState(const char *graphName) const
  3219. {
  3220. Owned<IRemoteConnection> conn = getProgressConnection();
  3221. if (conn)
  3222. {
  3223. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3224. if (progress)
  3225. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  3226. }
  3227. return WUGraphUnknown;
  3228. }
  3229. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3230. {
  3231. Owned<IRemoteConnection> conn = getProgressConnection();
  3232. if (conn)
  3233. {
  3234. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  3235. if (progress)
  3236. {
  3237. StringBuffer path;
  3238. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3239. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  3240. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  3241. }
  3242. }
  3243. return WUGraphUnknown;
  3244. }
  3245. virtual void clearGraphProgress() const
  3246. {
  3247. CriticalBlock block(crit);
  3248. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3249. StringBuffer path("/GraphProgress/");
  3250. path.append(p->queryName());
  3251. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  3252. if (delconn)
  3253. delconn->close(true);
  3254. }
  3255. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3256. {
  3257. Owned<IRemoteConnection> conn = getProgressConnection();
  3258. if (!conn)
  3259. return false;
  3260. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  3261. if (name)
  3262. {
  3263. graphName.set(name);
  3264. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  3265. return true;
  3266. }
  3267. else
  3268. return false;
  3269. }
  3270. virtual void forceReload()
  3271. {
  3272. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  3273. CriticalBlock block(crit);
  3274. clearCached(true);
  3275. connection->reload();
  3276. progressConnection.clear();
  3277. abortDirty = true;
  3278. p.setown(connection->getRoot());
  3279. }
  3280. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3281. {
  3282. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  3283. clearGraphProgress();
  3284. connection->close(true);
  3285. connection.clear();
  3286. }
  3287. virtual void commit()
  3288. {
  3289. CPersistedWorkUnit::commit();
  3290. if (connection)
  3291. connection->commit();
  3292. }
  3293. virtual void _lockRemote()
  3294. {
  3295. StringBuffer wuRoot;
  3296. getXPath(wuRoot, p->queryName());
  3297. if (connection)
  3298. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  3299. else
  3300. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  3301. if (!connection)
  3302. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  3303. clearCached(true);
  3304. p.setown(connection->getRoot());
  3305. }
  3306. virtual void _unlockRemote()
  3307. {
  3308. if (connection)
  3309. {
  3310. try
  3311. {
  3312. try
  3313. {
  3314. connection->commit();
  3315. }
  3316. catch (IException *e)
  3317. {
  3318. EXCLOG(e, "Error during workunit commit");
  3319. connection->rollback();
  3320. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3321. throw;
  3322. }
  3323. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  3324. }
  3325. catch (IException *E)
  3326. {
  3327. StringBuffer s;
  3328. IERRLOG("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  3329. throw;
  3330. }
  3331. }
  3332. }
  3333. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3334. {
  3335. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName, wfid);
  3336. conn->queryRoot()->setPropInt("@_state", state);
  3337. }
  3338. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3339. {
  3340. CriticalBlock block(crit);
  3341. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  3342. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3343. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3344. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  3345. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  3346. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  3347. IPropertyTree *node = progress->queryPropTree(path.str());
  3348. if (!node)
  3349. {
  3350. node = progress->addPropTree("node");
  3351. node->setPropInt64("@id", nodeId);
  3352. }
  3353. node->setPropInt("@_state", (unsigned)state);
  3354. switch (state)
  3355. {
  3356. case WUGraphRunning:
  3357. {
  3358. IPropertyTree *running = conn->queryRoot()->setPropTree("Running");
  3359. running->setProp("@graph", graphName);
  3360. running->setPropInt64("@subId", nodeId);
  3361. break;
  3362. }
  3363. case WUGraphComplete:
  3364. {
  3365. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  3366. break;
  3367. }
  3368. }
  3369. }
  3370. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3371. {
  3372. return new CDaliWuGraphStats(getWritableProgressConnection(graphName, _wfid), creatorType, creator, _wfid, graphName, subgraph);
  3373. }
  3374. protected:
  3375. IRemoteConnection *getProgressConnection() const
  3376. {
  3377. CriticalBlock block(crit);
  3378. if (!progressConnection)
  3379. {
  3380. VStringBuffer path("/GraphProgress/%s", queryWuid());
  3381. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  3382. }
  3383. return progressConnection.getLink();
  3384. }
  3385. IRemoteConnection *getWritableProgressConnection(const char *graphName, unsigned wfid) const
  3386. {
  3387. CriticalBlock block(crit);
  3388. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  3389. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  3390. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  3391. IPropertyTree * root = conn->queryRoot();
  3392. assertex(wfid);
  3393. if (!root->hasProp("@wfid"))
  3394. {
  3395. root->setPropInt("@wfid", wfid);
  3396. }
  3397. else
  3398. {
  3399. //Ideally the following code would check that the wfids are passed consistently.
  3400. //However there is an obscure problem with out of line functions being called from multiple workflow
  3401. //ids, and possibly library graphs.
  3402. //Stats for library graphs should be nested below the library call activity
  3403. //assertex(root->getPropInt("@wfid", 0) == wfid); // check that wfid is passed consistently
  3404. }
  3405. return conn.getClear();
  3406. }
  3407. IPropertyTree *getGraphProgressTree() const
  3408. {
  3409. Owned<IRemoteConnection> conn = getProgressConnection();
  3410. if (conn)
  3411. {
  3412. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  3413. mergePTree(tmp,conn->queryRoot());
  3414. return tmp.getClear();
  3415. }
  3416. return NULL;
  3417. }
  3418. Owned<IRemoteConnection> connection;
  3419. mutable Owned<IRemoteConnection> progressConnection;
  3420. };
  3421. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  3422. {
  3423. public:
  3424. Owned<CLocalWorkUnit> c;
  3425. IMPLEMENT_IINTERFACE;
  3426. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  3427. ~CLockedWorkUnit()
  3428. {
  3429. if (workUnitTraceLevel > 1)
  3430. DBGLOG("Releasing locked workunit %s", queryWuid());
  3431. if (c)
  3432. c->unlockRemote();
  3433. }
  3434. virtual IConstWorkUnit * unlock()
  3435. {
  3436. c->unlockRemote();
  3437. return c.getClear();
  3438. }
  3439. virtual bool aborting() const
  3440. { return c->aborting(); }
  3441. virtual void forceReload()
  3442. { UNIMPLEMENTED; }
  3443. virtual WUAction getAction() const
  3444. { return c->getAction(); }
  3445. virtual const char *queryActionDesc() const
  3446. { return c->queryActionDesc(); }
  3447. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  3448. { return c->getApplicationValue(application, propname, str); }
  3449. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  3450. { return c->getApplicationValueInt(application, propname, defVal); }
  3451. virtual IConstWUAppValueIterator & getApplicationValues() const
  3452. { return c->getApplicationValues(); }
  3453. virtual bool hasWorkflow() const
  3454. { return c->hasWorkflow(); }
  3455. virtual unsigned queryEventScheduledCount() const
  3456. { return c->queryEventScheduledCount(); }
  3457. virtual IPropertyTree * queryWorkflowTree() const
  3458. { return c->queryWorkflowTree(); }
  3459. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  3460. { return c->getWorkflowItems(); }
  3461. virtual IWorkflowItemArray * getWorkflowClone() const
  3462. { return c->getWorkflowClone(); }
  3463. virtual bool requiresLocalFileUpload() const
  3464. { return c->requiresLocalFileUpload(); }
  3465. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  3466. { return c->getLocalFileUploads(); }
  3467. virtual bool getIsQueryService() const
  3468. { return c->getIsQueryService(); }
  3469. virtual bool getCloneable() const
  3470. { return c->getCloneable(); }
  3471. virtual IUserDescriptor * queryUserDescriptor() const
  3472. { return c->queryUserDescriptor(); }
  3473. virtual const char *queryClusterName() const
  3474. { return c->queryClusterName(); }
  3475. virtual unsigned getCodeVersion() const
  3476. { return c->getCodeVersion(); }
  3477. virtual unsigned getWuidVersion() const
  3478. { return c->getWuidVersion(); }
  3479. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3480. { c->getBuildVersion(buildVersion, eclVersion); }
  3481. virtual bool hasDebugValue(const char * propname) const
  3482. { return c->hasDebugValue(propname); }
  3483. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  3484. { return c->getDebugValue(propname, str); }
  3485. virtual int getDebugValueInt(const char * propname, int defVal) const
  3486. { return c->getDebugValueInt(propname, defVal); }
  3487. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  3488. { return c->getDebugValueInt64(propname, defVal); }
  3489. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  3490. { return c->getDebugValueBool(propname, defVal); }
  3491. virtual IStringIterator & getDebugValues() const
  3492. { return c->getDebugValues(NULL); }
  3493. virtual IStringIterator & getDebugValues(const char *prop) const
  3494. { return c->getDebugValues(prop); }
  3495. virtual unsigned getExceptionCount() const
  3496. { return c->getExceptionCount(); }
  3497. virtual IConstWUExceptionIterator & getExceptions() const
  3498. { return c->getExceptions(); }
  3499. virtual unsigned getGraphCount() const
  3500. { return c->getGraphCount(); }
  3501. virtual unsigned getSourceFileCount() const
  3502. { return c->getSourceFileCount(); }
  3503. virtual unsigned getResultCount() const
  3504. { return c->getResultCount(); }
  3505. virtual unsigned getVariableCount() const
  3506. { return c->getVariableCount(); }
  3507. virtual unsigned getApplicationValueCount() const
  3508. { return c->getApplicationValueCount(); }
  3509. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  3510. { return c->getGraphs(type); }
  3511. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  3512. { return c->getGraphsMeta(type); }
  3513. virtual IConstWUGraph * getGraph(const char *name) const
  3514. { return c->getGraph(name); }
  3515. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  3516. { return c->getGraphProgress(name); }
  3517. virtual const char *queryJobName() const
  3518. { return c->queryJobName(); }
  3519. virtual IConstWUPlugin * getPluginByName(const char * name) const
  3520. { return c->getPluginByName(name); }
  3521. virtual IConstWUPluginIterator & getPlugins() const
  3522. { return c->getPlugins(); }
  3523. virtual IConstWULibrary* getLibraryByName(const char *name) const
  3524. { return c->getLibraryByName(name); }
  3525. virtual IConstWULibraryIterator & getLibraries() const
  3526. { return c->getLibraries(); }
  3527. virtual WUPriorityClass getPriority() const
  3528. { return c->getPriority(); }
  3529. virtual const char *queryPriorityDesc() const
  3530. { return c->queryPriorityDesc(); }
  3531. virtual int getPriorityLevel() const
  3532. { return c->getPriorityLevel(); }
  3533. virtual int getPriorityValue() const
  3534. { return c->getPriorityValue(); }
  3535. virtual IConstWUQuery * getQuery() const
  3536. { return c->getQuery(); }
  3537. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  3538. { return c->getWebServicesInfo(); }
  3539. virtual bool getRescheduleFlag() const
  3540. { return c->getRescheduleFlag(); }
  3541. virtual IConstWUResult * getResultByName(const char * name) const
  3542. { return c->getResultByName(name); }
  3543. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  3544. { return c->getResultBySequence(seq); }
  3545. virtual IConstWUResult * getQueryResultByName(const char * name) const
  3546. { return c->getQueryResultByName(name); }
  3547. virtual unsigned getResultLimit() const
  3548. { return c->getResultLimit(); }
  3549. virtual IConstWUResultIterator & getResults() const
  3550. { return c->getResults(); }
  3551. virtual IStringVal & getScope(IStringVal & str) const
  3552. { return c->getScope(str); }
  3553. virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & str) const
  3554. { return c->getWorkunitDistributedAccessToken(str); }
  3555. virtual WUState getState() const
  3556. { return c->getState(); }
  3557. virtual IStringVal & getStateEx(IStringVal & str) const
  3558. { return c->getStateEx(str); }
  3559. virtual __int64 getAgentSession() const
  3560. { return c->getAgentSession(); }
  3561. virtual unsigned getAgentPID() const
  3562. { return c->getAgentPID(); }
  3563. virtual const char *queryStateDesc() const
  3564. { return c->queryStateDesc(); }
  3565. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  3566. { return c->getRunningGraph(graphName, subId); }
  3567. virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const override
  3568. { return c->getScopeIterator(filter); }
  3569. virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const override
  3570. { return c->getStatistic(value, scope, kind); }
  3571. virtual IStringVal & getSnapshot(IStringVal & str) const
  3572. { return c->getSnapshot(str); }
  3573. virtual const char *queryUser() const
  3574. { return c->queryUser(); }
  3575. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  3576. { return c->getWarningSeverity(code, defaultSeverity); }
  3577. virtual const char *queryWuScope() const
  3578. { return c->queryWuScope(); }
  3579. virtual const char *queryWuid() const
  3580. { return c->queryWuid(); }
  3581. virtual IConstWUResult * getGlobalByName(const char * name) const
  3582. { return c->getGlobalByName(name); }
  3583. virtual IConstWUResult * getTemporaryByName(const char * name) const
  3584. { return c->getTemporaryByName(name); }
  3585. virtual IConstWUResultIterator & getTemporaries() const
  3586. { return c->getTemporaries(); }
  3587. virtual IConstWUResult * getVariableByName(const char * name) const
  3588. { return c->getVariableByName(name); }
  3589. virtual IConstWUResultIterator & getVariables() const
  3590. { return c->getVariables(); }
  3591. virtual bool isProtected() const
  3592. { return c->isProtected(); }
  3593. virtual bool isPausing() const
  3594. { return c->isPausing(); }
  3595. virtual IWorkUnit & lock()
  3596. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  3597. virtual bool reload()
  3598. { UNIMPLEMENTED; }
  3599. virtual void subscribe(WUSubscribeOptions options)
  3600. { c->subscribe(options); }
  3601. virtual void requestAbort()
  3602. { c->requestAbort(); }
  3603. virtual unsigned calculateHash(unsigned prevHash)
  3604. { return queryExtendedWU(c)->calculateHash(prevHash); }
  3605. virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  3606. { queryExtendedWU(c)->copyWorkUnit(cached, copyStats, all); }
  3607. virtual IPropertyTree *queryPTree() const
  3608. { return queryExtendedWU(c)->queryPTree(); }
  3609. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  3610. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  3611. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  3612. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  3613. virtual unsigned queryFileUsage(const char *filename) const
  3614. { return c->queryFileUsage(filename); }
  3615. virtual IConstWUFileUsageIterator * getFieldUsage() const
  3616. { return c->getFieldUsage(); }
  3617. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  3618. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  3619. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  3620. { return c->getTimeScheduled(val); }
  3621. virtual unsigned getDebugAgentListenerPort() const
  3622. { return c->getDebugAgentListenerPort(); }
  3623. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  3624. { return c->getDebugAgentListenerIP(ip); }
  3625. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  3626. { return c->getXmlParams(params, hidePasswords); }
  3627. virtual const IPropertyTree *getXmlParams() const
  3628. { return c->getXmlParams(); }
  3629. virtual unsigned __int64 getHash() const
  3630. { return c->getHash(); }
  3631. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  3632. { return c->getLogs(type, instance); }
  3633. virtual IStringIterator *getProcesses(const char *type) const
  3634. { return c->getProcesses(type); }
  3635. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  3636. { return c->getProcesses(type, instance); }
  3637. virtual unsigned getTotalThorTime() const
  3638. { return c->getTotalThorTime(); }
  3639. virtual WUGraphState queryGraphState(const char *graphName) const
  3640. { return c->queryGraphState(graphName); }
  3641. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  3642. { return c->queryNodeState(graphName, nodeId); }
  3643. virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  3644. { c->setGraphState(graphName, wfid, state); }
  3645. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  3646. { c->setNodeState(graphName, nodeId, state); }
  3647. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const override
  3648. { return c->updateStats(graphName, creatorType, creator, _wfid, subgraph); }
  3649. virtual void clearGraphProgress() const
  3650. { c->clearGraphProgress(); }
  3651. virtual IStringVal & getAbortBy(IStringVal & str) const
  3652. { return c->getAbortBy(str); }
  3653. virtual unsigned __int64 getAbortTimeStamp() const
  3654. { return c->getAbortTimeStamp(); }
  3655. virtual void clearExceptions(const char *source=nullptr)
  3656. { c->clearExceptions(source); }
  3657. virtual void commit()
  3658. { c->commit(); }
  3659. virtual IWUException * createException()
  3660. { return c->createException(); }
  3661. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  3662. { c->addProcess(type, instance, pid, log); }
  3663. virtual void protect(bool protectMode)
  3664. { c->protect(protectMode); }
  3665. virtual void setAction(WUAction action)
  3666. { c->setAction(action); }
  3667. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  3668. { c->setApplicationValue(application, propname, value, overwrite); }
  3669. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  3670. { c->setApplicationValueInt(application, propname, value, overwrite); }
  3671. virtual void incEventScheduledCount()
  3672. { c->incEventScheduledCount(); }
  3673. virtual void setIsQueryService(bool value)
  3674. { c->setIsQueryService(value); }
  3675. virtual void setCloneable(bool value)
  3676. { c->setCloneable(value); }
  3677. virtual void setIsClone(bool value)
  3678. { c->setIsClone(value); }
  3679. virtual void setClusterName(const char * value)
  3680. { c->setClusterName(value); }
  3681. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  3682. { c->setCodeVersion(version, buildVersion, eclVersion); }
  3683. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  3684. { c->setDebugValue(propname, value, overwrite); }
  3685. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  3686. { c->setDebugValueInt(propname, value, overwrite); }
  3687. virtual void setJobName(const char * value)
  3688. { c->setJobName(value); }
  3689. virtual void setPriority(WUPriorityClass cls)
  3690. { c->setPriority(cls); }
  3691. virtual void setPriorityLevel(int level)
  3692. { c->setPriorityLevel(level); }
  3693. virtual void setRescheduleFlag(bool value)
  3694. { c->setRescheduleFlag(value); }
  3695. virtual void setResultLimit(unsigned value)
  3696. { c->setResultLimit(value); }
  3697. virtual void setState(WUState state)
  3698. { c->setState(state); }
  3699. virtual void setStateEx(const char * text)
  3700. { c->setStateEx(text); }
  3701. virtual void setAgentSession(__int64 sessionId)
  3702. { c->setAgentSession(sessionId); }
  3703. 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)
  3704. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  3705. virtual void setTracingValue(const char * propname, const char * value)
  3706. { c->setTracingValue(propname, value); }
  3707. virtual void setTracingValueInt(const char * propname, int value)
  3708. { c->setTracingValueInt(propname, value); }
  3709. virtual void setTracingValueInt64(const char * propname, __int64 value)
  3710. { c->setTracingValueInt64(propname, value); }
  3711. virtual void setUser(const char * value)
  3712. { c->setUser(value); }
  3713. virtual void setWuScope(const char * value)
  3714. { c->setWuScope(value); }
  3715. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  3716. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  3717. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  3718. { c->syncRuntimeWorkflow(array); }
  3719. virtual IWorkflowItemIterator * updateWorkflowItems()
  3720. { return c->updateWorkflowItems(); }
  3721. virtual void resetWorkflow()
  3722. { c->resetWorkflow(); }
  3723. virtual void schedule()
  3724. { c->schedule(); }
  3725. virtual void deschedule()
  3726. { c->deschedule(); }
  3727. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  3728. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  3729. virtual IWUResult * updateGlobalByName(const char * name)
  3730. { return c->updateGlobalByName(name); }
  3731. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  3732. { c->createGraph(name, label, type, xgmml, wfid); }
  3733. virtual IWUQuery * updateQuery()
  3734. { return c->updateQuery(); }
  3735. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  3736. { return c->updateWebServicesInfo(create); }
  3737. virtual IWUPlugin * updatePluginByName(const char * name)
  3738. { return c->updatePluginByName(name); }
  3739. virtual IWULibrary * updateLibraryByName(const char * name)
  3740. { return c->updateLibraryByName(name); }
  3741. virtual IWUResult * updateResultByName(const char * name)
  3742. { return c->updateResultByName(name); }
  3743. virtual IWUResult * updateResultBySequence(unsigned seq)
  3744. { return c->updateResultBySequence(seq); }
  3745. virtual IWUResult * updateTemporaryByName(const char * name)
  3746. { return c->updateTemporaryByName(name); }
  3747. virtual IWUResult * updateVariableByName(const char * name)
  3748. { return c->updateVariableByName(name); }
  3749. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  3750. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  3751. virtual void noteFileRead(IDistributedFile *file)
  3752. { c->noteFileRead(file); }
  3753. virtual void noteFieldUsage(IPropertyTree * usage)
  3754. { c->noteFieldUsage(usage); }
  3755. virtual void releaseFile(const char *fileName)
  3756. { c->releaseFile(fileName); }
  3757. virtual void resetBeforeGeneration()
  3758. { c->resetBeforeGeneration(); }
  3759. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  3760. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  3761. virtual void deleteTemporaries()
  3762. { c->deleteTemporaries(); }
  3763. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  3764. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  3765. virtual IPropertyTree * getDiskUsageStats()
  3766. { return c->getDiskUsageStats(); }
  3767. virtual IPropertyTreeIterator & getFileIterator() const
  3768. { return c->getFileIterator(); }
  3769. virtual IPropertyTreeIterator & getFilesReadIterator() const
  3770. { return c->getFilesReadIterator(); }
  3771. virtual void setSnapshot(const char * value)
  3772. { c->setSnapshot(value); }
  3773. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  3774. { c->setWarningSeverity(code, severity); }
  3775. virtual void setTimeScheduled(const IJlibDateTime &val)
  3776. { c->setTimeScheduled(val); }
  3777. virtual void setDebugAgentListenerPort(unsigned port)
  3778. { c->setDebugAgentListenerPort(port); }
  3779. virtual void setDebugAgentListenerIP(const char * ip)
  3780. { c->setDebugAgentListenerIP(ip); }
  3781. virtual void setXmlParams(const char *params)
  3782. { c->setXmlParams(params); }
  3783. virtual void setXmlParams(IPropertyTree *tree)
  3784. { c->setXmlParams(tree); }
  3785. virtual void setHash(unsigned __int64 hash)
  3786. { c->setHash(hash); }
  3787. // ILocalWorkUnit - used for debugging etc
  3788. virtual void serialize(MemoryBuffer &tgt)
  3789. { c->serialize(tgt); }
  3790. virtual void deserialize(MemoryBuffer &src)
  3791. { c->deserialize(src); }
  3792. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  3793. { return c->switchThorQueue(cluster,qs); }
  3794. virtual void setAllowedClusters(const char *value)
  3795. { c->setAllowedClusters(value); }
  3796. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  3797. { return c->getAllowedClusters(str); }
  3798. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3799. { c->remoteCheckAccess(user,writeaccess); }
  3800. virtual void setAllowAutoQueueSwitch(bool val)
  3801. { c->setAllowAutoQueueSwitch(val); }
  3802. virtual bool getAllowAutoQueueSwitch() const
  3803. { return c->getAllowAutoQueueSwitch(); }
  3804. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3805. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  3806. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  3807. { c->setResultInt(name, sequence, val); }
  3808. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  3809. { c->setResultUInt(name, sequence, val); }
  3810. virtual void setResultReal(const char *name, unsigned sequence, double val)
  3811. { c->setResultReal(name, sequence, val); }
  3812. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  3813. { c->setResultVarString(stepname, sequence, val); }
  3814. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  3815. { c->setResultVarUnicode(stepname, sequence, val); }
  3816. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  3817. { c->setResultString(stepname, sequence, len, val); }
  3818. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  3819. { c->setResultData(stepname, sequence, len, val); }
  3820. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  3821. { c->setResultRaw(name, sequence, len, val); }
  3822. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  3823. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  3824. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  3825. { c->setResultUnicode(name, sequence, len, val); }
  3826. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  3827. { c->setResultBool(name, sequence, val); }
  3828. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  3829. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  3830. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  3831. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  3832. };
  3833. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  3834. {
  3835. Owned<IPropertyTree> p;
  3836. public:
  3837. IMPLEMENT_IINTERFACE;
  3838. CLocalWUAssociated(IPropertyTree *p);
  3839. virtual WUFileType getType() const;
  3840. virtual IStringVal & getDescription(IStringVal & ret) const;
  3841. virtual IStringVal & getIp(IStringVal & ret) const;
  3842. virtual IStringVal & getName(IStringVal & ret) const;
  3843. virtual IStringVal & getNameTail(IStringVal & ret) const;
  3844. virtual unsigned getCrc() const;
  3845. virtual unsigned getMinActivityId() const;
  3846. virtual unsigned getMaxActivityId() const;
  3847. };
  3848. class CLocalWUQuery : implements IWUQuery, public CInterface
  3849. {
  3850. Owned<IPropertyTree> p;
  3851. mutable IArrayOf<IConstWUAssociatedFile> associated;
  3852. mutable CriticalSection crit;
  3853. mutable bool associatedCached;
  3854. private:
  3855. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  3856. void loadAssociated() const;
  3857. public:
  3858. IMPLEMENT_IINTERFACE;
  3859. CLocalWUQuery(IPropertyTree *p);
  3860. virtual WUQueryType getQueryType() const;
  3861. virtual IStringVal& getQueryText(IStringVal &str) const;
  3862. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  3863. virtual IStringVal& getQueryName(IStringVal &str) const;
  3864. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  3865. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  3866. virtual unsigned getQueryDllCrc() const;
  3867. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  3868. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  3869. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  3870. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  3871. virtual bool isArchive() const;
  3872. virtual bool hasArchive() const
  3873. {
  3874. return p->getPropBool("@hasArchive");
  3875. }
  3876. virtual void setQueryType(WUQueryType qt);
  3877. virtual void setQueryText(const char *pstr);
  3878. virtual void setQueryName(const char *);
  3879. virtual void setQueryMainDefinition(const char * str);
  3880. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  3881. virtual void removeAssociatedFiles();
  3882. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  3883. };
  3884. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  3885. {
  3886. Owned<IPropertyTree> p;
  3887. mutable CriticalSection crit;
  3888. private:
  3889. public:
  3890. IMPLEMENT_IINTERFACE;
  3891. CLocalWUWebServicesInfo(IPropertyTree *p);
  3892. virtual IStringVal& getModuleName(IStringVal &str) const;
  3893. virtual IStringVal& getAttributeName(IStringVal &str) const;
  3894. virtual IStringVal& getDefaultName(IStringVal &str) const;
  3895. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  3896. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  3897. virtual unsigned getWebServicesCRC() const;
  3898. virtual void setModuleName(const char *);
  3899. virtual void setAttributeName(const char *);
  3900. virtual void setDefaultName(const char *);
  3901. virtual void setInfo(const char *name, const char *info);
  3902. virtual void setText(const char *name, const char *info);
  3903. virtual void setWebServicesCRC(unsigned);
  3904. };
  3905. class CLocalWUResult : implements IWUResult, public CInterface
  3906. {
  3907. friend class CLocalWorkUnit;
  3908. mutable CriticalSection crit;
  3909. Owned<IPropertyTree> p;
  3910. Owned<IProperties> xmlns;
  3911. public:
  3912. IMPLEMENT_IINTERFACE;
  3913. CLocalWUResult(IPropertyTree *props);
  3914. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  3915. virtual WUResultStatus getResultStatus() const;
  3916. virtual IStringVal& getResultName(IStringVal &str) const;
  3917. virtual int getResultSequence() const;
  3918. virtual bool isResultScalar() const;
  3919. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  3920. virtual unsigned getResultFetchSize() const;
  3921. virtual __int64 getResultTotalRowCount() const;
  3922. virtual __int64 getResultRowCount() const;
  3923. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  3924. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  3925. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  3926. virtual unsigned getResultRequestedRows() const;
  3927. virtual __int64 getResultInt() const;
  3928. virtual bool getResultBool() const;
  3929. virtual double getResultReal() const;
  3930. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  3931. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3932. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  3933. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  3934. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  3935. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3936. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  3937. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  3938. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  3939. virtual __int64 getResultRowLimit() const;
  3940. virtual IStringVal& getResultFilename(IStringVal & str) const;
  3941. virtual WUResultFormat getResultFormat() const;
  3942. virtual unsigned getResultHash() const;
  3943. virtual bool getResultIsAll() const;
  3944. virtual IProperties *queryResultXmlns();
  3945. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  3946. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  3947. virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const;
  3948. // interface IWUResult
  3949. virtual void setResultStatus(WUResultStatus status);
  3950. virtual void setResultName(const char *name);
  3951. virtual void setResultSequence(unsigned seq);
  3952. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  3953. virtual void setResultScalar(bool isScalar);
  3954. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  3955. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  3956. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  3957. virtual void setResultRowCount(__int64 rows);
  3958. virtual void setResultDataset(const char *ecl, const char *defs);
  3959. virtual void setResultLogicalName(const char *logicalName);
  3960. virtual void setResultKeyField(const char * name);
  3961. virtual void setResultRequestedRows(unsigned req);
  3962. virtual void setResultRecordSizeEntry(const char * val);
  3963. virtual void setResultTransformerEntry(const char * val);
  3964. virtual void setResultInt(__int64 val);
  3965. virtual void setResultReal(double val);
  3966. virtual void setResultBool(bool val);
  3967. virtual void setResultString(const char * val, unsigned length);
  3968. virtual void setResultUnicode(const void * val, unsigned length);
  3969. virtual void setResultData(const void * val, unsigned length);
  3970. virtual void setResultDecimal(const void * val, unsigned length);
  3971. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  3972. virtual void setResultRowLimit(__int64 value);
  3973. virtual void setResultFilename(const char * name);
  3974. virtual void setResultUInt(unsigned __int64 val);
  3975. virtual void setResultIsAll(bool value);
  3976. virtual void setResultFormat(WUResultFormat format);
  3977. virtual void setResultXML(const char *val);
  3978. virtual void setResultRow(unsigned len, const void * data);
  3979. virtual void setResultXmlns(const char *prefix, const char *uri);
  3980. virtual void setResultFieldOpt(const char *name, const char *value);
  3981. virtual void setResultWriteLocation(const char * _graph, unsigned _activityId);
  3982. virtual IPropertyTree *queryPTree() { return p; }
  3983. };
  3984. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  3985. {
  3986. Owned<IPropertyTree> p;
  3987. public:
  3988. IMPLEMENT_IINTERFACE;
  3989. CLocalWUPlugin(IPropertyTree *p);
  3990. virtual IStringVal& getPluginName(IStringVal &str) const;
  3991. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  3992. virtual void setPluginName(const char *str);
  3993. virtual void setPluginVersion(const char *str);
  3994. };
  3995. class CLocalWULibrary : implements IWULibrary, public CInterface
  3996. {
  3997. Owned<IPropertyTree> p;
  3998. public:
  3999. IMPLEMENT_IINTERFACE;
  4000. CLocalWULibrary(IPropertyTree *p);
  4001. virtual IStringVal & getName(IStringVal & str) const;
  4002. virtual void setName(const char * str);
  4003. };
  4004. class CLocalWUException : implements IWUException, public CInterface
  4005. {
  4006. Owned<IPropertyTree> p;
  4007. public:
  4008. IMPLEMENT_IINTERFACE;
  4009. CLocalWUException(IPropertyTree *p);
  4010. virtual IStringVal& getExceptionSource(IStringVal &str) const override;
  4011. virtual IStringVal& getExceptionMessage(IStringVal &str) const override;
  4012. virtual unsigned getExceptionCode() const override;
  4013. virtual ErrorSeverity getSeverity() const override;
  4014. virtual IStringVal & getTimeStamp(IStringVal & dt) const override;
  4015. virtual IStringVal & getExceptionFileName(IStringVal & str) const override;
  4016. virtual unsigned getExceptionLineNo() const override;
  4017. virtual unsigned getExceptionColumn() const override;
  4018. virtual unsigned getActivityId() const override;
  4019. virtual unsigned getSequence() const override;
  4020. virtual const char * queryScope() const override;
  4021. virtual unsigned getPriority() const override;
  4022. virtual void setExceptionSource(const char *str) override;
  4023. virtual void setExceptionMessage(const char *str) override;
  4024. virtual void setExceptionCode(unsigned code) override;
  4025. virtual void setSeverity(ErrorSeverity level) override;
  4026. virtual void setTimeStamp(const char * dt) override;
  4027. virtual void setExceptionFileName(const char *str) override;
  4028. virtual void setExceptionLineNo(unsigned r) override;
  4029. virtual void setExceptionColumn(unsigned c) override;
  4030. virtual void setActivityId(unsigned _id) override;
  4031. virtual void setScope(const char * _scope) override;
  4032. virtual void setPriority(unsigned _priority) override;
  4033. };
  4034. //==========================================================================================
  4035. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  4036. {
  4037. switch ((int) sequence)
  4038. {
  4039. case ResultSequenceInternal:
  4040. case ResultSequenceOnce:
  4041. case ResultSequencePersist:
  4042. case ResultSequenceStored:
  4043. return true;
  4044. default:
  4045. assertex(sequence <= INT_MAX);
  4046. if ((int) sequence >= LibraryBaseSequence)
  4047. return true;
  4048. return false;
  4049. }
  4050. }
  4051. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  4052. {
  4053. unsigned curTreeNum;
  4054. IArrayOf<IPropertyTree> trees;
  4055. Owned<IConstWorkUnitInfo> cur;
  4056. void setCurrent()
  4057. {
  4058. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  4059. }
  4060. public:
  4061. IMPLEMENT_IINTERFACE;
  4062. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  4063. {
  4064. ForEachItemIn(t, _trees)
  4065. trees.append(*LINK(&_trees.item(t)));
  4066. curTreeNum = 0;
  4067. }
  4068. bool first()
  4069. {
  4070. curTreeNum = 0;
  4071. return next();
  4072. }
  4073. bool isValid()
  4074. {
  4075. return (NULL != cur.get());
  4076. }
  4077. bool next()
  4078. {
  4079. if (curTreeNum >= trees.ordinality())
  4080. {
  4081. cur.clear();
  4082. return false;
  4083. }
  4084. setCurrent();
  4085. ++curTreeNum;
  4086. return true;
  4087. }
  4088. IConstWorkUnitInfo & query() { return *cur; }
  4089. };
  4090. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  4091. {
  4092. Owned<IPropertyTree> p;
  4093. public:
  4094. IMPLEMENT_IINTERFACE;
  4095. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  4096. virtual const char * queryName() const { return p->queryProp("@name"); }
  4097. };
  4098. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  4099. {
  4100. public:
  4101. IMPLEMENT_IINTERFACE;
  4102. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4103. bool first() override { return iter->first(); }
  4104. bool isValid() override { return iter->isValid(); }
  4105. bool next() override { return iter->next(); }
  4106. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  4107. private:
  4108. Owned<IPropertyTreeIterator> iter;
  4109. };
  4110. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  4111. {
  4112. Owned<IPropertyTree> p;
  4113. public:
  4114. IMPLEMENT_IINTERFACE;
  4115. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  4116. virtual const char * queryName() const { return p->queryProp("@name"); }
  4117. virtual const char * queryType() const { return p->queryProp("@type"); }
  4118. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  4119. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  4120. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  4121. };
  4122. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  4123. {
  4124. public:
  4125. IMPLEMENT_IINTERFACE;
  4126. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  4127. bool first() override { return iter->first(); }
  4128. bool isValid() override { return iter->isValid(); }
  4129. bool next() override { return iter->next(); }
  4130. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  4131. private:
  4132. Owned<IPropertyTreeIterator> iter;
  4133. };
  4134. //==========================================================================================
  4135. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  4136. {
  4137. Owned<IPropertyTreeIterator> it;
  4138. public:
  4139. IMPLEMENT_IINTERFACE;
  4140. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  4141. virtual bool first() { return it->first(); }
  4142. virtual bool next() { return it->next(); }
  4143. virtual bool isValid() { return it->isValid(); }
  4144. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  4145. };
  4146. EnumMapping workunitSortFields[] =
  4147. {
  4148. { WUSFuser, "@submitID" },
  4149. { WUSFcluster, "@clusterName" },
  4150. { WUSFjob, "@jobName" },
  4151. { WUSFstate, "@state" },
  4152. { WUSFpriority, "@priorityClass" },
  4153. { WUSFprotected, "@protected" },
  4154. { WUSFwuid, "@" },
  4155. { WUSFecl, "Query/ShortText" },
  4156. { WUSFfileread, "FilesRead/File/@name" },
  4157. { WUSFtotalthortime, "@totalThorTime|"
  4158. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  4159. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  4160. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  4161. "Statistics/Statistic[@desc='Total thor time']/@value|"
  4162. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  4163. },
  4164. { WUSFwuidhigh, "@" },
  4165. { WUSFwildwuid, "@" },
  4166. { WUSFappvalue, "Application" },
  4167. { WUSFfilewritten, "Files/File/@name" },
  4168. { WUSFterm, NULL }
  4169. };
  4170. extern const char *queryFilterXPath(WUSortField field)
  4171. {
  4172. return getEnumText(field, workunitSortFields);
  4173. }
  4174. EnumMapping querySortFields[] =
  4175. {
  4176. { WUQSFId, "@id" },
  4177. { WUQSFwuid, "@wuid" },
  4178. { WUQSFname, "@name" },
  4179. { WUQSFdll, "@dll" },
  4180. { WUQSFmemoryLimit, "@memoryLimit" },
  4181. { WUQSFmemoryLimitHi, "@memoryLimit" },
  4182. { WUQSFtimeLimit, "@timeLimit" },
  4183. { WUQSFtimeLimitHi, "@timeLimit" },
  4184. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  4185. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  4186. { WUQSFpriority, "@priority" },
  4187. { WUQSFpriorityHi, "@priority" },
  4188. { WUQSFQuerySet, "@querySetId" },
  4189. { WUQSFActivited, "@activated" },
  4190. { WUQSFSuspendedByUser, "@suspended" },
  4191. { WUQSFLibrary, "Library"},
  4192. { WUQSFPublishedBy, "@publishedBy" },
  4193. { WUQSFterm, NULL }
  4194. };
  4195. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  4196. {
  4197. StringAttr name;
  4198. public:
  4199. IMPLEMENT_IINTERFACE;
  4200. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  4201. {
  4202. }
  4203. void execute()
  4204. {
  4205. PROGLOG("WU removeDll %s", name.get());
  4206. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  4207. }
  4208. };
  4209. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  4210. {
  4211. RemoteFilename name;
  4212. public:
  4213. IMPLEMENT_IINTERFACE;
  4214. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  4215. {
  4216. SocketEndpoint ep(_ip);
  4217. name.setPath(ep, _name);
  4218. }
  4219. void execute()
  4220. {
  4221. Owned<IFile> file = createIFile(name);
  4222. PROGLOG("WU removeDll %s",file->queryFilename());
  4223. file->remove();
  4224. }
  4225. };
  4226. //==========================================================================================
  4227. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  4228. {
  4229. unsigned index;
  4230. IArrayOf<IPropertyTree> trees;
  4231. public:
  4232. IMPLEMENT_IINTERFACE;
  4233. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  4234. {
  4235. ForEachItemIn(t, _trees)
  4236. trees.append(*LINK(&_trees.item(t)));
  4237. index = 0;
  4238. }
  4239. ~CConstQuerySetQueryIterator()
  4240. {
  4241. trees.kill();
  4242. }
  4243. bool first()
  4244. {
  4245. index = 0;
  4246. return (trees.ordinality()!=0);
  4247. }
  4248. bool next()
  4249. {
  4250. index++;
  4251. return (index<trees.ordinality());
  4252. }
  4253. bool isValid()
  4254. {
  4255. return (index<trees.ordinality());
  4256. }
  4257. IPropertyTree &query()
  4258. {
  4259. return trees.item(index);
  4260. }
  4261. };
  4262. class CSecurityCache
  4263. {
  4264. };
  4265. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  4266. {
  4267. public:
  4268. IMPLEMENT_IINTERFACE;
  4269. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  4270. : ptreeIter(_ptreeIter)
  4271. {
  4272. }
  4273. bool first()
  4274. {
  4275. if (!ptreeIter->first())
  4276. {
  4277. cur.clear();
  4278. return false;
  4279. }
  4280. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4281. return true;
  4282. }
  4283. bool isValid()
  4284. {
  4285. return (NULL != cur.get());
  4286. }
  4287. bool next()
  4288. {
  4289. if (!ptreeIter->next())
  4290. {
  4291. cur.clear();
  4292. return false;
  4293. }
  4294. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  4295. return true;
  4296. }
  4297. IConstWorkUnitInfo & query() { return *cur; }
  4298. private:
  4299. Owned<IConstWorkUnitInfo> cur;
  4300. Owned<IPropertyTreeIterator> ptreeIter;
  4301. };
  4302. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  4303. {
  4304. public:
  4305. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  4306. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  4307. {
  4308. assertex(_secuser && _secmgr);
  4309. }
  4310. bool first()
  4311. {
  4312. if (!parent->first())
  4313. return false;
  4314. return getNext();
  4315. }
  4316. bool next()
  4317. {
  4318. if (!parent->next())
  4319. return false;
  4320. return getNext();
  4321. }
  4322. virtual bool isValid()
  4323. {
  4324. return parent->isValid();
  4325. }
  4326. virtual IConstWorkUnitInfo &query()
  4327. {
  4328. return parent->query();
  4329. }
  4330. private:
  4331. Owned<IConstWorkUnitIterator> parent;
  4332. MapStringTo<int> scopePermissions;
  4333. Linked<ISecManager> secmgr;
  4334. Linked<ISecUser> secuser;
  4335. bool getNext() // scan for a workunit with permissions
  4336. {
  4337. do
  4338. {
  4339. const char *scopeName = parent->query().queryWuScope();
  4340. if (!scopeName || !*scopeName || checkScope(scopeName))
  4341. return true;
  4342. } while (parent->next());
  4343. return false;
  4344. }
  4345. bool checkScope(const char *scopeName)
  4346. {
  4347. int *perms = scopePermissions.getValue(scopeName);
  4348. SecAccessFlags perm;
  4349. if (!perms)
  4350. {
  4351. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  4352. scopePermissions.setValue(scopeName, perm);
  4353. }
  4354. else
  4355. perm = (SecAccessFlags)*perms;
  4356. return perm >= SecAccess_Read;
  4357. }
  4358. };
  4359. CWorkUnitFactory::CWorkUnitFactory()
  4360. {
  4361. }
  4362. CWorkUnitFactory::~CWorkUnitFactory()
  4363. {
  4364. }
  4365. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4366. {
  4367. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  4368. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  4369. if (scope)
  4370. 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...
  4371. cw->setDistributedAccessToken(secuser ? secuser->getName() : "");//create and sign the workunit distributed access token
  4372. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  4373. ret->setDebugValue("CREATED_BY", app, true);
  4374. ret->setDebugValue("CREATED_FOR", scope, true);
  4375. return ret;
  4376. }
  4377. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  4378. {
  4379. StringBuffer wuid("W");
  4380. char result[32];
  4381. time_t ltime;
  4382. time( &ltime );
  4383. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  4384. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  4385. wuid.append(result);
  4386. if (workUnitTraceLevel > 1)
  4387. DBGLOG("createWorkUnit created %s", wuid.str());
  4388. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  4389. if (workUnitTraceLevel > 1)
  4390. DBGLOG("createWorkUnit created %s", ret->queryWuid());
  4391. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  4392. return ret;
  4393. }
  4394. bool CWorkUnitFactory::deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secmgr, ISecUser *secuser)
  4395. {
  4396. if (workUnitTraceLevel > 1)
  4397. DBGLOG("deleteWorkUnit %s", wuid);
  4398. StringBuffer wuRoot;
  4399. getXPath(wuRoot, wuid);
  4400. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  4401. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  4402. return false;
  4403. if (throwException)
  4404. cw->cleanupAndDelete(true, true);
  4405. else
  4406. {
  4407. try
  4408. {
  4409. cw->cleanupAndDelete(true, true);
  4410. }
  4411. catch (IException *E)
  4412. {
  4413. StringBuffer s;
  4414. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  4415. E->Release();
  4416. return false;
  4417. }
  4418. }
  4419. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  4420. return true;
  4421. }
  4422. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  4423. {
  4424. return deleteWorkUnitEx(wuid, false, secmgr, secuser);
  4425. }
  4426. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4427. {
  4428. StringBuffer wuidStr(wuid);
  4429. wuidStr.trim();
  4430. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  4431. wuidStr.setCharAt(0, 'W');
  4432. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  4433. {
  4434. if (workUnitTraceLevel > 1)
  4435. DBGLOG("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  4436. return NULL;
  4437. }
  4438. if (workUnitTraceLevel > 1)
  4439. DBGLOG("openWorkUnit %s", wuidStr.str());
  4440. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  4441. if (wu)
  4442. {
  4443. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  4444. return NULL; // Actually throws exception on failure, so won't reach here
  4445. return wu.getClear();
  4446. }
  4447. else
  4448. {
  4449. if (workUnitTraceLevel > 0)
  4450. IERRLOG("openWorkUnit %s not found", wuidStr.str());
  4451. return NULL;
  4452. }
  4453. }
  4454. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4455. {
  4456. if (workUnitTraceLevel > 1)
  4457. DBGLOG("updateWorkUnit %s", wuid);
  4458. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  4459. if (wu)
  4460. {
  4461. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  4462. return NULL;
  4463. return &wu->lockRemote(false);
  4464. }
  4465. else
  4466. {
  4467. if (workUnitTraceLevel > 0)
  4468. IERRLOG("updateWorkUnit %s not found", wuid);
  4469. return NULL;
  4470. }
  4471. }
  4472. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  4473. {
  4474. Owned<IPropertyTree> ret;
  4475. IPropertyTree * branch = from->queryPropTree(xpath);
  4476. if(branch)
  4477. {
  4478. ret.setown(createPTreeFromIPT(branch));
  4479. from->removeTree(branch);
  4480. }
  4481. return ret.getClear();
  4482. }
  4483. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  4484. {
  4485. StringBuffer path(base);
  4486. addPathSepChar(path).append(wuid).append(".xml");
  4487. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  4488. if (!pt)
  4489. return false;
  4490. CDateTime dt;
  4491. dt.setNow();
  4492. StringBuffer dts;
  4493. dt.getString(dts);
  4494. pt->setProp("@restoredDate", dts.str());
  4495. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  4496. Owned<IPropertyTree> associatedFiles;
  4497. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  4498. if (srcAssociated)
  4499. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  4500. // The updating of the repo is implementation specific...
  4501. if (!_restoreWorkUnit(pt.getClear(), wuid))
  4502. return false;
  4503. // now kludge back GeneratedDlls
  4504. if (generatedDlls)
  4505. {
  4506. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  4507. for(dlls->first(); dlls->isValid(); dlls->next())
  4508. {
  4509. IPropertyTree & dll = dlls->query();
  4510. char const * name = dll.queryProp("@name");
  4511. char const * kind = dll.queryProp("@kind");
  4512. char const * location = dll.queryProp("@location");
  4513. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  4514. if (!got)
  4515. {
  4516. RemoteFilename dstRfn;
  4517. dstRfn.setRemotePath(location);
  4518. StringBuffer srcPath(base);
  4519. addPathSepChar(srcPath);
  4520. dstRfn.getTail(srcPath);
  4521. OwnedIFile srcFile = createIFile(srcPath);
  4522. OwnedIFile dstFile = createIFile(dstRfn);
  4523. copyFile(dstFile, srcFile);
  4524. queryDllServer().registerDll(name, kind, location);
  4525. }
  4526. }
  4527. }
  4528. if (associatedFiles)
  4529. {
  4530. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  4531. ForEach(*associated)
  4532. {
  4533. IPropertyTree &file = associated->query();
  4534. const char *filename = file.queryProp("@filename");
  4535. SocketEndpoint ep(file.queryProp("@ip"));
  4536. RemoteFilename rfn;
  4537. rfn.setPath(ep, filename);
  4538. OwnedIFile dstFile = createIFile(rfn);
  4539. StringBuffer srcPath(base), name;
  4540. addPathSepChar(srcPath);
  4541. rfn.getTail(name);
  4542. srcPath.append(name);
  4543. if (generatedDlls)
  4544. {
  4545. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  4546. if (generatedDlls->hasProp(gDllPath))
  4547. continue; // generated dlls handled separately - see above
  4548. }
  4549. OwnedIFile srcFile = createIFile(srcPath);
  4550. if (srcFile->exists())
  4551. {
  4552. try
  4553. {
  4554. copyFile(dstFile, srcFile);
  4555. }
  4556. catch (IException *e)
  4557. {
  4558. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  4559. EXCLOG(e, msg.str());
  4560. e->Release();
  4561. }
  4562. }
  4563. }
  4564. }
  4565. return true;
  4566. }
  4567. int CWorkUnitFactory::setTracingLevel(int newLevel)
  4568. {
  4569. if (newLevel)
  4570. DBGLOG("Setting workunit trace level to %d", newLevel);
  4571. int level = workUnitTraceLevel;
  4572. workUnitTraceLevel = newLevel;
  4573. return level;
  4574. }
  4575. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4576. {
  4577. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4578. if(!conn) return;
  4579. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  4580. KeptAtomTable entries;
  4581. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  4582. StringBuffer wuid;
  4583. for(iter->first(); iter->isValid(); iter->next())
  4584. {
  4585. char const * entry = iter->query().queryName();
  4586. if(!entries.find(entry))
  4587. {
  4588. entries.addAtom(entry);
  4589. ncnameUnescape(entry, wuid.clear());
  4590. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  4591. if(wu && (wu->getState() == WUStateWait))
  4592. wu->setState(WUStateCompleted);
  4593. }
  4594. }
  4595. bool more;
  4596. do more = root->removeProp("*"); while(more);
  4597. }
  4598. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  4599. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4600. const void *filterbuf, // (appended) string values for filters
  4601. unsigned startoffset,
  4602. unsigned maxnum,
  4603. __int64 *cachehint,
  4604. unsigned *total,
  4605. const MapStringTo<bool> *_subset)
  4606. {
  4607. struct PostFilters
  4608. {
  4609. WUQueryFilterBoolean activatedFilter;
  4610. WUQueryFilterBoolean suspendedByUserFilter;
  4611. PostFilters()
  4612. {
  4613. activatedFilter = WUQFSAll;
  4614. suspendedByUserFilter = WUQFSAll;
  4615. };
  4616. } postFilters;
  4617. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  4618. {
  4619. StringAttr querySet;
  4620. StringAttr xPath;
  4621. StringAttr sortOrder;
  4622. PostFilters postFilters;
  4623. StringArray unknownAttributes;
  4624. const MapStringTo<bool> *subset;
  4625. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  4626. {
  4627. const char* querySetId = querySetTree->queryProp("@id");
  4628. VStringBuffer path("Query%s", xPath.get());
  4629. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  4630. ForEach(*iter)
  4631. {
  4632. IPropertyTree &query = iter->query();
  4633. bool activated = false;
  4634. const char* queryId = query.queryProp("@id");
  4635. if (queryId && *queryId)
  4636. {
  4637. if (subset)
  4638. {
  4639. VStringBuffer match("%s/%s", querySetId, queryId);
  4640. if (!subset->getValue(match))
  4641. continue;
  4642. }
  4643. VStringBuffer aliasXPath("Alias[@id='%s']", queryId);
  4644. IPropertyTree *alias = querySetTree->queryPropTree(aliasXPath.str());
  4645. if (alias)
  4646. activated = true;
  4647. }
  4648. if (activated && (postFilters.activatedFilter == WUQFSNo))
  4649. continue;
  4650. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  4651. continue;
  4652. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4653. continue;
  4654. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  4655. continue;
  4656. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  4657. queryWithSetId->setProp("@querySetId", querySetId);
  4658. queryWithSetId->setPropBool("@activated", activated);
  4659. }
  4660. }
  4661. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  4662. {
  4663. StringBuffer querySetXPath("QuerySets");
  4664. if (!querySet.isEmpty())
  4665. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  4666. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4667. if (!conn)
  4668. return NULL;
  4669. if (querySet.isEmpty())
  4670. {
  4671. Owned<IPropertyTreeIterator> querySetIter = conn->queryRoot()->getElements("*");
  4672. ForEach(*querySetIter)
  4673. populateQueryTree(&querySetIter->query(), queryTree);
  4674. }
  4675. else
  4676. populateQueryTree(conn->queryRoot(), queryTree);
  4677. return conn.getClear();
  4678. }
  4679. public:
  4680. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  4681. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  4682. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  4683. {
  4684. postFilters.activatedFilter = _postFilters.activatedFilter;
  4685. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  4686. ForEachItemIn(x, _unknownAttributes)
  4687. unknownAttributes.append(_unknownAttributes.item(x));
  4688. }
  4689. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  4690. {
  4691. Owned<IPropertyTree> elementTree = createPTree("Queries");
  4692. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  4693. if (!conn)
  4694. return NULL;
  4695. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  4696. if (!iter)
  4697. return NULL;
  4698. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  4699. return conn.getClear();
  4700. }
  4701. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  4702. };
  4703. StringAttr querySet;
  4704. StringBuffer xPath;
  4705. StringBuffer so;
  4706. StringArray unknownAttributes;
  4707. if (filters)
  4708. {
  4709. const char *fv = (const char *)filterbuf;
  4710. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  4711. int fmt = filters[i];
  4712. int subfmt = (fmt&0xff);
  4713. if (subfmt==WUQSFQuerySet)
  4714. querySet.set(fv);
  4715. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  4716. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  4717. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  4718. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  4719. else if (subfmt==WUQSFActivited)
  4720. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  4721. else if (subfmt==WUQSFSuspendedByUser)
  4722. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  4723. else if (!fv || !*fv)
  4724. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  4725. else {
  4726. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  4727. if (fmt&WUQSFnocase)
  4728. xPath.append('?');
  4729. if (fmt&WUQSFnumeric)
  4730. xPath.append('#');
  4731. if (fmt&WUQSFwild)
  4732. xPath.append('~');
  4733. xPath.append('"').append(fv).append("\"]");
  4734. }
  4735. fv = fv + strlen(fv)+1;
  4736. }
  4737. }
  4738. if (sortorder) {
  4739. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  4740. if (so.length())
  4741. so.append(',');
  4742. int fmt = sortorder[i];
  4743. if (fmt&WUQSFreverse)
  4744. so.append('-');
  4745. if (fmt&WUQSFnocase)
  4746. so.append('?');
  4747. if (fmt&WUQSFnumeric)
  4748. so.append('#');
  4749. so.append(getEnumText(fmt&0xff,querySortFields));
  4750. }
  4751. }
  4752. IArrayOf<IPropertyTree> results;
  4753. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  4754. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  4755. return new CConstQuerySetQueryIterator(results);
  4756. }
  4757. bool CWorkUnitFactory::isAborting(const char *wuid) const
  4758. {
  4759. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4760. try
  4761. {
  4762. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  4763. if (acon)
  4764. return acon->queryRoot()->getPropInt(NULL) != 0;
  4765. }
  4766. catch (IException *E)
  4767. {
  4768. EXCLOG(E);
  4769. E->Release();
  4770. }
  4771. return false;
  4772. }
  4773. void CWorkUnitFactory::clearAborting(const char *wuid)
  4774. {
  4775. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  4776. try
  4777. {
  4778. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4779. if (acon)
  4780. acon->close(true);
  4781. }
  4782. catch (IException *E)
  4783. {
  4784. EXCLOG(E);
  4785. E->Release();
  4786. }
  4787. }
  4788. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  4789. {
  4790. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  4791. bool isEcl = false;
  4792. switch (state)
  4793. {
  4794. case WUStateAborting:
  4795. state = WUStateAborted;
  4796. break;
  4797. case WUStateCompiling:
  4798. isEcl = true;
  4799. // drop into
  4800. default:
  4801. state = WUStateFailed;
  4802. }
  4803. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  4804. wu->setState(state);
  4805. Owned<IWUException> e = wu->createException();
  4806. e->setExceptionCode(isEcl ? 1001 : 1000);
  4807. e->setExceptionMessage(isEcl ? "EclCC terminated unexpectedly" : "Workunit terminated unexpectedly");
  4808. }
  4809. static CriticalSection deleteDllLock;
  4810. static IWorkQueueThread *deleteDllWorkQ = nullptr;
  4811. MODULE_INIT(INIT_PRIORITY_STANDARD)
  4812. {
  4813. return true;
  4814. }
  4815. MODULE_EXIT()
  4816. {
  4817. CriticalBlock b(deleteDllLock);
  4818. if (deleteDllWorkQ)
  4819. ::Release(deleteDllWorkQ);
  4820. deleteDllWorkQ = nullptr;
  4821. }
  4822. static void asyncRemoveDll(const char * name)
  4823. {
  4824. CriticalBlock b(deleteDllLock);
  4825. if (!deleteDllWorkQ)
  4826. deleteDllWorkQ = createWorkQueueThread();
  4827. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  4828. }
  4829. static void asyncRemoveFile(const char * ip, const char * name)
  4830. {
  4831. CriticalBlock b(deleteDllLock);
  4832. if (!deleteDllWorkQ)
  4833. deleteDllWorkQ = createWorkQueueThread();
  4834. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  4835. }
  4836. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  4837. {
  4838. public:
  4839. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  4840. CDaliWorkUnitFactory()
  4841. {
  4842. // Assumes dali client configuration has already been done
  4843. sdsManager = &querySDS();
  4844. session = myProcessSession();
  4845. addShutdownHook(*this);
  4846. }
  4847. ~CDaliWorkUnitFactory()
  4848. {
  4849. removeShutdownHook(*this);
  4850. }
  4851. virtual bool initializeStore()
  4852. {
  4853. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  4854. }
  4855. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  4856. {
  4857. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  4858. }
  4859. virtual unsigned validateRepository(bool fixErrors)
  4860. {
  4861. return 0;
  4862. }
  4863. virtual void deleteRepository(bool recreate)
  4864. {
  4865. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  4866. if (conn)
  4867. conn->close(true);
  4868. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  4869. if (conn)
  4870. conn->close(true);
  4871. }
  4872. virtual void createRepository()
  4873. {
  4874. // Nothing to do
  4875. }
  4876. virtual const char *queryStoreType() const
  4877. {
  4878. return "Dali";
  4879. }
  4880. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4881. {
  4882. StringBuffer wuRoot;
  4883. getXPath(wuRoot, wuid);
  4884. IRemoteConnection *conn;
  4885. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  4886. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4887. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  4888. conn->queryRoot()->setProp("@totalThorTime", "");
  4889. return new CDaliWorkUnit(conn, secmgr, secuser);
  4890. }
  4891. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4892. {
  4893. StringBuffer wuRoot;
  4894. getXPath(wuRoot, wuid);
  4895. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  4896. if (conn)
  4897. return new CDaliWorkUnit(conn, secmgr, secuser);
  4898. else
  4899. return NULL;
  4900. }
  4901. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  4902. {
  4903. Owned<IPTree> pt(_pt);
  4904. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  4905. StringBuffer wuRoot;
  4906. getXPath(wuRoot, wuid);
  4907. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4908. if (!conn)
  4909. {
  4910. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  4911. return false;
  4912. }
  4913. IPropertyTree *root = conn->queryRoot();
  4914. if (root->hasChildren())
  4915. {
  4916. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  4917. return false;
  4918. }
  4919. root->setPropTree(NULL, pt.getClear());
  4920. conn.clear();
  4921. // now kludge back GraphProgress
  4922. if (gprogress)
  4923. {
  4924. VStringBuffer xpath("/GraphProgress/%s", wuid);
  4925. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  4926. if (conn)
  4927. {
  4928. IPropertyTree *groot = conn->queryRoot();
  4929. if (groot->hasChildren())
  4930. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  4931. groot->setPropTree(NULL, gprogress.getClear());
  4932. }
  4933. }
  4934. return true;
  4935. }
  4936. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  4937. {
  4938. StringBuffer wuRoot;
  4939. getXPath(wuRoot, wuid);
  4940. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  4941. if (conn)
  4942. return new CDaliWorkUnit(conn, secmgr, secuser);
  4943. else
  4944. return NULL;
  4945. }
  4946. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  4947. {
  4948. // MORE - should it check security?
  4949. StringBuffer wuRoot;
  4950. getXPath(wuRoot, GLOBAL_WORKUNIT);
  4951. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  4952. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  4953. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  4954. return &cw->lockRemote(false);
  4955. }
  4956. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  4957. {
  4958. StringBuffer path("*");
  4959. if (owner && *owner)
  4960. path.append("[@submitID=?~\"").append(owner).append("\"]");
  4961. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4962. }
  4963. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  4964. {
  4965. StringBuffer path("*");
  4966. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  4967. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  4968. }
  4969. virtual void clientShutdown();
  4970. virtual unsigned numWorkUnits()
  4971. {
  4972. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  4973. if (!conn)
  4974. return 0;
  4975. IPropertyTree *root = conn->queryRoot();
  4976. return root->numChildren();
  4977. }
  4978. /**
  4979. * Add a filter to an xpath query, with the appropriate filter flags
  4980. */
  4981. static void appendFilterToQueryString(StringBuffer& query, int flags, const char* name, const char* value)
  4982. {
  4983. query.append('[').append(name).append('=');
  4984. if (flags & WUSFnocase)
  4985. query.append('?');
  4986. if (flags & WUSFwild)
  4987. query.append('~');
  4988. query.append('"').append(value).append("\"]");
  4989. };
  4990. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  4991. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  4992. const void *filterbuf, // (appended) string values for filters
  4993. unsigned startoffset,
  4994. unsigned maxnum,
  4995. __int64 *cachehint,
  4996. unsigned *total,
  4997. ISecManager *secmgr,
  4998. ISecUser *secuser)
  4999. {
  5000. class CQueryOrFilter : public CInterface
  5001. {
  5002. unsigned flags;
  5003. StringAttr name;
  5004. StringArray values;
  5005. public:
  5006. IMPLEMENT_IINTERFACE;
  5007. CQueryOrFilter(unsigned _flags, const char *_name, const char *_value)
  5008. : flags(_flags), name(_name)
  5009. {
  5010. values.appendListUniq(_value, "|");
  5011. };
  5012. const char* queryName() { return name.get(); };
  5013. unsigned querySearchFlags() { return flags; };
  5014. const StringArray& queryValues() const { return values; };
  5015. };
  5016. class CMultiPTreeIterator : public CInterfaceOf<IPropertyTreeIterator>
  5017. {
  5018. public:
  5019. virtual bool first() override
  5020. {
  5021. curSource = 0;
  5022. while (sources.isItem(curSource))
  5023. {
  5024. if (sources.item(curSource).first())
  5025. return true;
  5026. curSource++;
  5027. }
  5028. return false;
  5029. }
  5030. virtual bool next() override
  5031. {
  5032. if (sources.isItem(curSource))
  5033. {
  5034. if (sources.item(curSource).next())
  5035. return true;
  5036. curSource++;
  5037. while (sources.isItem(curSource))
  5038. {
  5039. if (sources.item(curSource).first())
  5040. return true;
  5041. curSource++;
  5042. }
  5043. }
  5044. return false;
  5045. }
  5046. virtual bool isValid() override
  5047. {
  5048. return sources.isItem(curSource);
  5049. }
  5050. virtual IPropertyTree & query() override
  5051. {
  5052. return sources.item(curSource).query();
  5053. }
  5054. void addSource(IPropertyTreeIterator &source)
  5055. {
  5056. sources.append(source);
  5057. }
  5058. private:
  5059. IArrayOf<IPropertyTreeIterator> sources;
  5060. unsigned curSource = 0;
  5061. };
  5062. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  5063. {
  5064. StringAttr xPath;
  5065. StringAttr sortOrder;
  5066. StringAttr nameFilterLo;
  5067. StringAttr nameFilterHi;
  5068. StringArray unknownAttributes;
  5069. Owned<CQueryOrFilter> orFilter;
  5070. public:
  5071. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5072. CWorkUnitsPager(const char* _xPath, CQueryOrFilter* _orFilter, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  5073. : xPath(_xPath), orFilter(_orFilter), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  5074. {
  5075. ForEachItemIn(x, _unknownAttributes)
  5076. unknownAttributes.append(_unknownAttributes.item(x));
  5077. }
  5078. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  5079. {
  5080. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5081. if (!conn)
  5082. return NULL;
  5083. Owned<IPropertyTreeIterator> iter;
  5084. if (!orFilter)
  5085. {
  5086. iter.setown(conn->getElements(xPath.get()));
  5087. }
  5088. else
  5089. {
  5090. Owned <CMultiPTreeIterator> multi = new CMultiPTreeIterator;
  5091. bool added = false;
  5092. const char* fieldName = orFilter->queryName();
  5093. unsigned flags = orFilter->querySearchFlags();
  5094. const StringArray& values = orFilter->queryValues();
  5095. ForEachItemIn(i, values)
  5096. {
  5097. StringBuffer path(xPath.get());
  5098. const char* value = values.item(i);
  5099. if (!isEmptyString(value))
  5100. {
  5101. appendFilterToQueryString(path, flags, fieldName, value);
  5102. IPropertyTreeIterator *itr = conn->getElements(path.str());
  5103. if (itr)
  5104. {
  5105. multi->addSource(*itr);
  5106. added = true;
  5107. }
  5108. }
  5109. }
  5110. if (added)
  5111. iter.setown(multi.getClear());
  5112. }
  5113. if (!iter)
  5114. return NULL;
  5115. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  5116. return conn.getClear();
  5117. }
  5118. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  5119. };
  5120. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  5121. {
  5122. UniqueScopes done;
  5123. ISecManager *secmgr;
  5124. ISecUser *secuser;
  5125. CriticalSection crit;
  5126. public:
  5127. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  5128. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  5129. {
  5130. secmgr = _secmgr;
  5131. secuser = _secuser;
  5132. }
  5133. bool isOK(IPropertyTree &tree)
  5134. {
  5135. const char *scopename = tree.queryProp("@scope");
  5136. if (!scopename||!*scopename)
  5137. return true;
  5138. {
  5139. CriticalBlock block(crit);
  5140. const bool *b = done.getValue(scopename);
  5141. if (b)
  5142. return *b;
  5143. }
  5144. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  5145. {
  5146. // conceivably could have already been checked and added, but ok.
  5147. CriticalBlock block(crit);
  5148. done.setValue(scopename,ret);
  5149. }
  5150. return ret;
  5151. }
  5152. };
  5153. Owned<CQueryOrFilter> orFilter;
  5154. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  5155. StringBuffer query;
  5156. StringBuffer so;
  5157. StringAttr namefilter("*");
  5158. StringAttr namefilterlo;
  5159. StringAttr namefilterhi;
  5160. StringArray unknownAttributes;
  5161. if (filters)
  5162. {
  5163. const char *fv = (const char *) filterbuf;
  5164. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  5165. {
  5166. assertex(fv);
  5167. int fmt = filters[i];
  5168. int subfmt = (fmt&0xff);
  5169. if (subfmt==WUSFwuid)
  5170. namefilterlo.set(fv);
  5171. else if (subfmt==WUSFwuidhigh)
  5172. namefilterhi.set(fv);
  5173. else if (subfmt==WUSFwildwuid)
  5174. namefilter.set(fv);
  5175. else if (subfmt==WUSFappvalue)
  5176. {
  5177. const char *app = fv;
  5178. fv = fv + strlen(fv)+1;
  5179. query.append("[Application/").append(app);
  5180. if (*fv)
  5181. query.append("=?~\"").append(fv).append('\"');
  5182. query.append("]");
  5183. }
  5184. else if (subfmt==WUSFtotalthortime)
  5185. {
  5186. query.append("[@totalThorTime>=\"");
  5187. formatTimeCollatable(query, milliToNano(atoi(fv)), false);
  5188. query.append("\"]");
  5189. }
  5190. else if (!*fv)
  5191. {
  5192. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  5193. if (subfmt==WUSFtotalthortime)
  5194. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5195. }
  5196. else
  5197. {
  5198. const char* fieldName = getEnumText(subfmt,workunitSortFields);
  5199. if (!strchr(fv, '|'))
  5200. appendFilterToQueryString(query, fmt, fieldName, fv);
  5201. else if (orFilter)
  5202. throw MakeStringException(WUERR_InvalidUserInput, "Multiple OR filters not allowed");
  5203. else
  5204. {
  5205. if (!strieq(fieldName, getEnumText(WUSFstate,workunitSortFields)) &&
  5206. !strieq(fieldName, getEnumText(WUSFuser,workunitSortFields)) &&
  5207. !strieq(fieldName, getEnumText(WUSFcluster,workunitSortFields)))
  5208. throw MakeStringException(WUERR_InvalidUserInput, "OR filters not allowed for %s", fieldName);
  5209. orFilter.setown(new CQueryOrFilter(fmt, fieldName, fv));
  5210. }
  5211. }
  5212. fv = fv + strlen(fv)+1;
  5213. }
  5214. }
  5215. if ((sortorder&0xff)==WUSFtotalthortime)
  5216. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  5217. query.insert(0, namefilter.get());
  5218. if (sortorder)
  5219. {
  5220. if (so.length())
  5221. so.append(',');
  5222. if (sortorder & WUSFreverse)
  5223. so.append('-');
  5224. if (sortorder & WUSFnocase)
  5225. so.append('?');
  5226. if (sortorder & WUSFnumeric)
  5227. so.append('#');
  5228. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  5229. }
  5230. IArrayOf<IPropertyTree> results;
  5231. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), orFilter.getClear(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  5232. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  5233. return new CConstWUArrayIterator(results);
  5234. }
  5235. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5236. {
  5237. WUState ret = WUStateUnknown;
  5238. StringBuffer wuRoot;
  5239. getXPath(wuRoot, wuid);
  5240. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5241. if (timeout == 0) //no need to subscribe
  5242. {
  5243. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5244. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5245. if (it != expectedStates.end())
  5246. return ret;
  5247. switch (ret)
  5248. {
  5249. case WUStateCompiled:
  5250. case WUStateUploadingFiles:
  5251. if (!compiled)
  5252. break;
  5253. //fall through
  5254. case WUStateCompleted:
  5255. case WUStateFailed:
  5256. case WUStateAborted:
  5257. return ret;
  5258. default:
  5259. break;
  5260. }
  5261. return WUStateUnknown;
  5262. }
  5263. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  5264. LocalIAbortHandler abortHandler(*waiter);
  5265. if (conn)
  5266. {
  5267. SessionId agent = -1;
  5268. bool agentSessionStopped = false;
  5269. unsigned start = msTick();
  5270. for (;;)
  5271. {
  5272. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  5273. auto it = std::find(expectedStates.begin(), expectedStates.end(), ret);
  5274. if (it != expectedStates.end())
  5275. return ret;
  5276. switch (ret)
  5277. {
  5278. case WUStateCompiled:
  5279. case WUStateUploadingFiles:
  5280. if (!compiled)
  5281. break;
  5282. // fall into
  5283. case WUStateCompleted:
  5284. case WUStateFailed:
  5285. case WUStateAborted:
  5286. return ret;
  5287. case WUStateWait:
  5288. break;
  5289. case WUStateCompiling:
  5290. case WUStateRunning:
  5291. case WUStateDebugPaused:
  5292. case WUStateDebugRunning:
  5293. case WUStateBlocked:
  5294. case WUStateAborting:
  5295. if (agentSessionStopped)
  5296. {
  5297. reportAbnormalTermination(wuid, ret, agent);
  5298. return ret;
  5299. }
  5300. if (queryDaliServerVersion().compare("2.1")>=0)
  5301. {
  5302. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  5303. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  5304. {
  5305. agentSessionStopped = true;
  5306. conn->reload();
  5307. continue;
  5308. }
  5309. }
  5310. break;
  5311. }
  5312. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  5313. unsigned waited = msTick() - start;
  5314. if (timeout==-1 || waited + 20000 < timeout)
  5315. {
  5316. waiter->wait(20000); // recheck state every 20 seconds, in case eclagent has crashed.
  5317. if (waiter->isAborted())
  5318. {
  5319. ret = WUStateUnknown; // MORE - throw an exception?
  5320. break;
  5321. }
  5322. }
  5323. else if (waited > timeout || !waiter->wait(timeout-waited))
  5324. {
  5325. ret = WUStateUnknown; // MORE - throw an exception?
  5326. break;
  5327. }
  5328. conn->reload();
  5329. }
  5330. }
  5331. return ret;
  5332. }
  5333. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5334. {
  5335. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  5336. LocalIAbortHandler abortHandler(*waiter);
  5337. WUAction ret = WUActionUnknown;
  5338. StringBuffer wuRoot;
  5339. getXPath(wuRoot, wuid);
  5340. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  5341. if (conn)
  5342. {
  5343. unsigned start = msTick();
  5344. for (;;)
  5345. {
  5346. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  5347. if (ret != original)
  5348. break;
  5349. unsigned waited = msTick() - start;
  5350. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  5351. if (waiter->isAborted())
  5352. {
  5353. ret = WUActionUnknown; // MORE - throw an exception?
  5354. break;
  5355. }
  5356. conn->reload();
  5357. }
  5358. }
  5359. waiter->unsubscribe();
  5360. return ret;
  5361. }
  5362. protected:
  5363. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  5364. {
  5365. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  5366. if (conn)
  5367. {
  5368. CDaliVersion serverVersionNeeded("3.2");
  5369. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  5370. conn->queryRoot()->getElements(xpath) :
  5371. conn->getElements(xpath));
  5372. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  5373. }
  5374. else
  5375. return NULL;
  5376. }
  5377. ISDSManager *sdsManager;
  5378. SessionId session;
  5379. };
  5380. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5381. {
  5382. if (secmgr)
  5383. return new CSecureConstWUIterator(iter, secmgr, secuser);
  5384. else
  5385. return iter;
  5386. }
  5387. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  5388. {
  5389. if (secmgr)
  5390. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  5391. else
  5392. return new CConstWUIterator(iter);
  5393. }
  5394. static CriticalSection factoryCrit;
  5395. static Owned<IWorkUnitFactory> factory;
  5396. void CDaliWorkUnitFactory::clientShutdown()
  5397. {
  5398. CriticalBlock b(factoryCrit);
  5399. factory.clear();
  5400. }
  5401. void clientShutdownWorkUnit()
  5402. {
  5403. CriticalBlock b(factoryCrit);
  5404. factory.clear();
  5405. }
  5406. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  5407. {
  5408. CriticalBlock b(factoryCrit);
  5409. factory.setown(_factory);
  5410. }
  5411. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  5412. {
  5413. if (!factory)
  5414. {
  5415. CriticalBlock b(factoryCrit);
  5416. 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.
  5417. {
  5418. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  5419. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  5420. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  5421. IPropertyTree *pluginInfo = NULL;
  5422. if (env)
  5423. {
  5424. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  5425. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  5426. if (daliInfo)
  5427. {
  5428. const char *daliName = daliInfo->queryProp("@name");
  5429. if (daliName)
  5430. {
  5431. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  5432. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  5433. }
  5434. if (!pluginInfo)
  5435. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  5436. }
  5437. }
  5438. if (pluginInfo && !forceDali)
  5439. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  5440. else
  5441. factory.setown(new CDaliWorkUnitFactory());
  5442. }
  5443. }
  5444. return factory.getLink();
  5445. }
  5446. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  5447. {
  5448. if (!factory)
  5449. {
  5450. CriticalBlock b(factoryCrit);
  5451. 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.
  5452. factory.setown(new CDaliWorkUnitFactory());
  5453. }
  5454. return factory.getLink();
  5455. }
  5456. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  5457. // They can still be supplied if you want...
  5458. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  5459. {
  5460. public:
  5461. IMPLEMENT_IINTERFACE;
  5462. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  5463. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  5464. {
  5465. }
  5466. virtual bool initializeStore()
  5467. {
  5468. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  5469. }
  5470. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  5471. {
  5472. return baseFactory->getWatcher(subscriber, options, wuid);
  5473. }
  5474. virtual unsigned validateRepository(bool fix)
  5475. {
  5476. return baseFactory->validateRepository(fix);
  5477. }
  5478. virtual void deleteRepository(bool recreate)
  5479. {
  5480. return baseFactory->deleteRepository(recreate);
  5481. }
  5482. virtual void createRepository()
  5483. {
  5484. return baseFactory->createRepository();
  5485. }
  5486. virtual const char *queryStoreType() const
  5487. {
  5488. return baseFactory->queryStoreType();
  5489. }
  5490. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  5491. {
  5492. return baseFactory->getUniqueValues(field, prefix, result);
  5493. }
  5494. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5495. {
  5496. if (!secMgr) secMgr = defaultSecMgr.get();
  5497. if (!secUser) secUser = defaultSecUser.get();
  5498. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  5499. }
  5500. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  5501. {
  5502. if (!secMgr) secMgr = defaultSecMgr.get();
  5503. if (!secUser) secUser = defaultSecUser.get();
  5504. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  5505. }
  5506. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  5507. {
  5508. if (!secMgr) secMgr = defaultSecMgr.get();
  5509. if (!secUser) secUser = defaultSecUser.get();
  5510. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  5511. }
  5512. virtual bool deleteWorkUnitEx(const char * wuid, bool throwException, ISecManager *secMgr, ISecUser *secUser)
  5513. {
  5514. if (!secMgr) secMgr = defaultSecMgr.get();
  5515. if (!secUser) secUser = defaultSecUser.get();
  5516. return baseFactory->deleteWorkUnitEx(wuid, throwException, secMgr, secUser);
  5517. }
  5518. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5519. {
  5520. if (!secMgr) secMgr = defaultSecMgr.get();
  5521. if (!secUser) secUser = defaultSecUser.get();
  5522. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  5523. }
  5524. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  5525. {
  5526. if (!secMgr) secMgr = defaultSecMgr.get();
  5527. if (!secUser) secUser = defaultSecUser.get();
  5528. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  5529. }
  5530. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  5531. {
  5532. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  5533. }
  5534. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  5535. {
  5536. if (!secMgr) secMgr = defaultSecMgr.get();
  5537. if (!secUser) secUser = defaultSecUser.get();
  5538. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  5539. }
  5540. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  5541. {
  5542. if (!secMgr) secMgr = defaultSecMgr.get();
  5543. if (!secUser) secUser = defaultSecUser.get();
  5544. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  5545. }
  5546. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5547. {
  5548. if (!secMgr) secMgr = defaultSecMgr.get();
  5549. if (!secUser) secUser = defaultSecUser.get();
  5550. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  5551. }
  5552. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  5553. {
  5554. if (!secMgr) secMgr = defaultSecMgr.get();
  5555. if (!secUser) secUser = defaultSecUser.get();
  5556. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  5557. }
  5558. virtual int setTracingLevel(int newLevel)
  5559. {
  5560. return baseFactory->setTracingLevel(newLevel);
  5561. }
  5562. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  5563. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  5564. const void *filterbuf, // (appended) string values for filters
  5565. unsigned startoffset,
  5566. unsigned maxnum,
  5567. __int64 *cachehint,
  5568. unsigned *total,
  5569. ISecManager *secMgr, ISecUser *secUser)
  5570. {
  5571. if (!secMgr) secMgr = defaultSecMgr.get();
  5572. if (!secUser) secUser = defaultSecUser.get();
  5573. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  5574. }
  5575. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  5576. WUQuerySortField *filters,
  5577. const void *filterbuf,
  5578. unsigned startoffset,
  5579. unsigned maxnum,
  5580. __int64 *cachehint,
  5581. unsigned *total,
  5582. const MapStringTo<bool> *subset)
  5583. {
  5584. // MORE - why no security?
  5585. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  5586. }
  5587. virtual unsigned numWorkUnits()
  5588. {
  5589. return baseFactory->numWorkUnits();
  5590. }
  5591. virtual bool isAborting(const char *wuid) const
  5592. {
  5593. return baseFactory->isAborting(wuid);
  5594. }
  5595. virtual void clearAborting(const char *wuid)
  5596. {
  5597. baseFactory->clearAborting(wuid);
  5598. }
  5599. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates)
  5600. {
  5601. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, expectedStates);
  5602. }
  5603. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  5604. {
  5605. return baseFactory->waitForWorkUnitAction(wuid, original);
  5606. }
  5607. private:
  5608. Owned<IWorkUnitFactory> baseFactory;
  5609. Linked<ISecManager> defaultSecMgr;
  5610. Linked<ISecUser> defaultSecUser;
  5611. };
  5612. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  5613. {
  5614. if (secmgr && secuser)
  5615. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  5616. else
  5617. return getWorkUnitFactory();
  5618. }
  5619. //==========================================================================================
  5620. class CStringPTreeIterator : implements IStringIterator, public CInterface
  5621. {
  5622. Owned<IPropertyTreeIterator> it;
  5623. public:
  5624. IMPLEMENT_IINTERFACE;
  5625. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  5626. virtual bool first() { return it->first(); }
  5627. virtual bool next() { return it->next(); }
  5628. virtual bool isValid() { return it->isValid(); }
  5629. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  5630. };
  5631. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  5632. {
  5633. Owned<IPropertyTreeIterator> it;
  5634. public:
  5635. IMPLEMENT_IINTERFACE;
  5636. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  5637. virtual bool first() { return it->first(); }
  5638. virtual bool next() { return it->next(); }
  5639. virtual bool isValid() { return it->isValid(); }
  5640. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  5641. };
  5642. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  5643. {
  5644. Owned<IPropertyTreeIterator> it;
  5645. StringAttr name;
  5646. public:
  5647. IMPLEMENT_IINTERFACE;
  5648. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  5649. virtual bool first() { return it->first(); }
  5650. virtual bool next() { return it->next(); }
  5651. virtual bool isValid() { return it->isValid(); }
  5652. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  5653. };
  5654. //==========================================================================================
  5655. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  5656. {
  5657. clearCached(false);
  5658. secMgr.set(secmgr);
  5659. secUser.set(secuser);
  5660. workflowIteratorCached = false;
  5661. resultsCached = false;
  5662. graphsCached = false;
  5663. temporariesCached = false;
  5664. variablesCached = false;
  5665. exceptionsCached = false;
  5666. pluginsCached = false;
  5667. librariesCached = false;
  5668. activitiesCached = false;
  5669. webServicesInfoCached = false;
  5670. roxieQueryInfoCached = false;
  5671. }
  5672. void CLocalWorkUnit::clearCached(bool clearTree)
  5673. {
  5674. query.clear();
  5675. webServicesInfo.clear();
  5676. workflowIterator.clear();
  5677. graphs.kill();
  5678. results.kill();
  5679. variables.kill();
  5680. plugins.kill();
  5681. libraries.kill();
  5682. exceptions.kill();
  5683. temporaries.kill();
  5684. statistics.kill();
  5685. appvalues.kill();
  5686. if (clearTree)
  5687. p.clear();
  5688. workflowIteratorCached = false;
  5689. resultsCached = false;
  5690. graphsCached = false;
  5691. temporariesCached = false;
  5692. variablesCached = false;
  5693. exceptionsCached = false;
  5694. pluginsCached = false;
  5695. librariesCached = false;
  5696. activitiesCached = false;
  5697. webServicesInfoCached = false;
  5698. roxieQueryInfoCached = false;
  5699. }
  5700. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  5701. {
  5702. clearCached(false);
  5703. p.setown(ptree);
  5704. }
  5705. void CLocalWorkUnit::beforeDispose()
  5706. {
  5707. try
  5708. {
  5709. unsubscribe();
  5710. clearCached(true);
  5711. userDesc.clear();
  5712. secMgr.clear();
  5713. secUser.clear();
  5714. }
  5715. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  5716. }
  5717. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  5718. {
  5719. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  5720. // Delete any related things in SDS etc that might otherwise be forgotten
  5721. if (p->getPropBool("@protected", false))
  5722. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  5723. switch (getState())
  5724. {
  5725. case WUStateAborted:
  5726. case WUStateCompleted:
  5727. case WUStateFailed:
  5728. case WUStateArchived:
  5729. break;
  5730. case WUStateCompiled:
  5731. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  5732. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5733. break;
  5734. case WUStateWait:
  5735. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  5736. default:
  5737. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  5738. break;
  5739. }
  5740. if (getIsQueryService())
  5741. {
  5742. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  5743. if (registry)
  5744. {
  5745. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  5746. if (registry->hasProp(xpath.str()))
  5747. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  5748. }
  5749. }
  5750. try
  5751. {
  5752. if (deldll && !p->getPropBool("@isClone", false))
  5753. {
  5754. Owned<IConstWUQuery> q = getQuery();
  5755. if (q)
  5756. {
  5757. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5758. SCMStringBuffer name;
  5759. ForEach(*iter)
  5760. {
  5761. IConstWUAssociatedFile & cur = iter->query();
  5762. cur.getNameTail(name);
  5763. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  5764. {
  5765. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5766. if (entry.get())
  5767. asyncRemoveDll(name.str());
  5768. else
  5769. {
  5770. SCMStringBuffer ip, localPath;
  5771. cur.getName(localPath);
  5772. cur.getIp(ip);
  5773. asyncRemoveFile(ip.str(), localPath.str());
  5774. }
  5775. }
  5776. }
  5777. }
  5778. }
  5779. factory->clearAborting(queryWuid());
  5780. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  5781. }
  5782. catch(IException *E)
  5783. {
  5784. StringBuffer s;
  5785. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  5786. E->Release();
  5787. }
  5788. catch (...)
  5789. {
  5790. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  5791. }
  5792. }
  5793. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  5794. {
  5795. SCMStringBuffer strval;
  5796. val.getGmtString(strval);
  5797. p->setProp("@timescheduled",strval.str());
  5798. }
  5799. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  5800. {
  5801. StringBuffer str;
  5802. p->getProp("@timescheduled",str);
  5803. if(str.length())
  5804. val.setGmtString(str.str());
  5805. return val;
  5806. }
  5807. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  5808. {
  5809. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  5810. if (extra.length())
  5811. {
  5812. const char *bufStart = buf.str();
  5813. const char *bufPtr = bufStart+buf.length();
  5814. while (bufStart != bufPtr)
  5815. {
  5816. --bufPtr;
  5817. if (!isspace(*bufPtr))
  5818. break;
  5819. }
  5820. assertex('>' == *bufPtr);
  5821. size_t l = strlen(wuid);
  5822. assertex((size_t)(bufPtr-bufStart) > l+2); // e.g. at least </W20171111-111111>
  5823. bufPtr -= l+2; // skip back over </wuid
  5824. assertex(0 == memcmp(bufPtr, "</", 2) );
  5825. assertex(0 == memcmp(bufPtr+2, wuid, l));
  5826. buf.insert(bufPtr-bufStart, extra);
  5827. }
  5828. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  5829. }
  5830. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  5831. {
  5832. CriticalBlock block(crit);
  5833. StringBuffer path(base);
  5834. if (!p)
  5835. return false;
  5836. const char *wuid = p->queryName();
  5837. if (!wuid||!*wuid)
  5838. return false;
  5839. addPathSepChar(path).append(wuid).append(".xml");
  5840. Owned<IFile> file = createIFile(path.str());
  5841. if (!file)
  5842. return false;
  5843. Owned<IFileIO> fileio = file->open(IFOcreate);
  5844. if (!fileio)
  5845. return false;
  5846. StringBuffer buf;
  5847. exportWorkUnitToXML(this, buf, false, false, true);
  5848. StringBuffer extraWorkUnitXML;
  5849. Owned<IPTree> graphProgress = getGraphProgressTree();
  5850. if (graphProgress)
  5851. {
  5852. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  5853. graphProgress.clear();
  5854. }
  5855. Owned<IConstWUQuery> q = getQuery();
  5856. if (!q)
  5857. {
  5858. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5859. return false;
  5860. if (del)
  5861. {
  5862. if (getState()==WUStateUnknown)
  5863. setState(WUStateArchived); // to allow delete
  5864. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  5865. }
  5866. return false;
  5867. }
  5868. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  5869. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  5870. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  5871. ForEach(*iter)
  5872. {
  5873. IConstWUAssociatedFile & cur = iter->query();
  5874. SCMStringBuffer name;
  5875. cur.getNameTail(name);
  5876. if (name.length())
  5877. {
  5878. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  5879. SCMStringBuffer curPath, curIp;
  5880. cur.getName(curPath);
  5881. cur.getIp(curIp);
  5882. SocketEndpoint curEp(curIp.str());
  5883. RemoteFilename curRfn;
  5884. curRfn.setPath(curEp, curPath.str());
  5885. StringBuffer dst(base);
  5886. addPathSepChar(dst);
  5887. curRfn.getTail(dst);
  5888. Owned<IFile> dstFile = createIFile(dst.str());
  5889. if (entry.get())
  5890. {
  5891. Owned<IException> exception;
  5892. Owned<IDllLocation> loc;
  5893. Owned<IPropertyTree> generatedDllBranch = createPTree();
  5894. generatedDllBranch->setProp("@name", entry->queryName());
  5895. generatedDllBranch->setProp("@kind", entry->queryKind());
  5896. if (exportAssociatedFiles)
  5897. {
  5898. try
  5899. {
  5900. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  5901. }
  5902. catch(IException * e)
  5903. {
  5904. exception.setown(e);
  5905. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  5906. }
  5907. RemoteFilename filename;
  5908. loc->getDllFilename(filename);
  5909. if (!exception)
  5910. {
  5911. Owned<IFile> srcfile = createIFile(filename);
  5912. try
  5913. {
  5914. if (dstFile->exists())
  5915. {
  5916. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  5917. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  5918. // still want to delete if already archived but there are source file copies
  5919. }
  5920. else
  5921. copyFile(dstFile, srcfile);
  5922. }
  5923. catch(IException * e)
  5924. {
  5925. exception.setown(e);
  5926. }
  5927. }
  5928. if (exception)
  5929. {
  5930. if (ignoredllerrors)
  5931. {
  5932. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  5933. //copy failed, so don't delete the registered dll files
  5934. deleteExclusions.append(name.str());
  5935. }
  5936. else
  5937. throw exception.getClear();
  5938. }
  5939. }
  5940. // Record Associated path to restore back to
  5941. StringBuffer restorePath;
  5942. curRfn.getRemotePath(restorePath);
  5943. generatedDllBranch->setProp("@location", restorePath.str());
  5944. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  5945. }
  5946. else if (exportAssociatedFiles) // no generated dll entry
  5947. {
  5948. Owned<IFile> srcFile = createIFile(curRfn);
  5949. try
  5950. {
  5951. copyFile(dstFile, srcFile);
  5952. }
  5953. catch (IException *e)
  5954. {
  5955. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  5956. EXCLOG(e, msg.str());
  5957. e->Release();
  5958. deleteExclusions.append(name.str());
  5959. }
  5960. }
  5961. }
  5962. }
  5963. iter.clear();
  5964. if (generatedDlls->numChildren())
  5965. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  5966. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  5967. return false;
  5968. if (del)
  5969. {
  5970. //setState(WUStateArchived); // this isn't useful as about to delete it!
  5971. q.clear();
  5972. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  5973. }
  5974. return true;
  5975. }
  5976. void CLocalWorkUnit::loadXML(const char *xml)
  5977. {
  5978. CriticalBlock block(crit);
  5979. clearCached(true);
  5980. assertex(xml);
  5981. p.setown(createPTreeFromXMLString(xml,ipt_lowmem));
  5982. }
  5983. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  5984. {
  5985. CriticalBlock block(crit);
  5986. StringBuffer x;
  5987. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  5988. }
  5989. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  5990. {
  5991. CriticalBlock block(crit);
  5992. StringAttr value;
  5993. src.read(value);
  5994. loadXML(value);
  5995. }
  5996. void CLocalWorkUnit::requestAbort()
  5997. {
  5998. CriticalBlock block(crit);
  5999. abortWorkUnit(p->queryName());
  6000. }
  6001. void CLocalWorkUnit::unlockRemote()
  6002. {
  6003. CriticalBlock block(crit);
  6004. locked.unlock();
  6005. _unlockRemote();
  6006. }
  6007. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  6008. {
  6009. if (secMgr)
  6010. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  6011. locked.lock();
  6012. CriticalBlock block(crit);
  6013. if (commit)
  6014. {
  6015. try
  6016. {
  6017. _lockRemote();
  6018. }
  6019. catch (IException *E)
  6020. {
  6021. StringBuffer s;
  6022. IERRLOG("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  6023. locked.unlock();
  6024. throw;
  6025. }
  6026. }
  6027. return *new CLockedWorkUnit(LINK(this));
  6028. }
  6029. void CLocalWorkUnit::commit()
  6030. {
  6031. // Nothing to do if not backed by a persistent store
  6032. }
  6033. IWorkUnit& CLocalWorkUnit::lock()
  6034. {
  6035. return lockRemote(true);
  6036. }
  6037. const char *CLocalWorkUnit::queryWuid() const
  6038. {
  6039. CriticalBlock block(crit);
  6040. return p->queryName();
  6041. }
  6042. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  6043. {
  6044. CriticalBlock block(crit);
  6045. return p->getPropInt("@DebugListenerPort", 0);
  6046. }
  6047. unsigned CLocalWorkUnit::getTotalThorTime() const
  6048. {
  6049. CriticalBlock block(crit);
  6050. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  6051. }
  6052. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  6053. {
  6054. CriticalBlock block(crit);
  6055. p->setPropInt("@DebugListenerPort", port);
  6056. }
  6057. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  6058. {
  6059. CriticalBlock block(crit);
  6060. ip.set(p->queryProp("@DebugListenerIP"));
  6061. return ip;
  6062. }
  6063. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  6064. {
  6065. CriticalBlock block(crit);
  6066. p->setProp("@DebugListenerIP", ip);
  6067. }
  6068. IStringVal & CLocalWorkUnit::getWorkunitDistributedAccessToken(IStringVal & datoken) const
  6069. {
  6070. CriticalBlock block(crit);
  6071. datoken.set(p->queryProp("@distributedAccessToken"));
  6072. return datoken;
  6073. }
  6074. bool CLocalWorkUnit::setDistributedAccessToken(const char * user)
  6075. {
  6076. CriticalBlock block(crit);
  6077. //If this format changes, you must update the isWorkunitDAToken() and extractFromWorkunitDAToken() methods
  6078. VStringBuffer datoken("HPCC[u=%s,w=%s]", user, queryWuid());
  6079. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6080. if (pDSM && pDSM->isDigiSignerConfigured())
  6081. {
  6082. datoken.append(pDSM->queryKeyName()).append(';');
  6083. StringBuffer b64Signature;
  6084. if (pDSM->digiSign(b64Signature, datoken))
  6085. {
  6086. datoken.append(b64Signature.str());
  6087. }
  6088. else
  6089. {
  6090. ERRLOG("Cannot create workunit Distributed Access Token, digisign failed");
  6091. return false;
  6092. }
  6093. }
  6094. else
  6095. {
  6096. WARNLOG("Cannot sign Distributed Access Token, digisign signing not configured");
  6097. datoken.append(";");
  6098. }
  6099. p->setProp("@distributedAccessToken", datoken);
  6100. return true;
  6101. }
  6102. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  6103. {
  6104. // Only implemented in derived classes
  6105. return false;
  6106. }
  6107. void CLocalWorkUnit::setJobName(const char *value)
  6108. {
  6109. CriticalBlock block(crit);
  6110. p->setProp("@jobName", value);
  6111. }
  6112. const char *CLocalWorkUnit::queryJobName() const
  6113. {
  6114. CriticalBlock block(crit);
  6115. const char *ret = p->queryProp("@jobName");
  6116. if (!ret)
  6117. ret = "";
  6118. return ret;
  6119. }
  6120. void CLocalWorkUnit::setClusterName(const char *value)
  6121. {
  6122. CriticalBlock block(crit);
  6123. p->setProp("@clusterName", value);
  6124. }
  6125. const char *CLocalWorkUnit::queryClusterName() const
  6126. {
  6127. CriticalBlock block(crit);
  6128. const char *ret = p->queryProp("@clusterName");
  6129. if (!ret)
  6130. ret = "";
  6131. return ret;
  6132. }
  6133. void CLocalWorkUnit::setAllowedClusters(const char *value)
  6134. {
  6135. setDebugValue("allowedclusters",value, true);
  6136. }
  6137. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  6138. {
  6139. CriticalBlock block(crit);
  6140. getDebugValue("allowedclusters",str);
  6141. if (str.length()!=0)
  6142. return str;
  6143. str.set(p->queryProp("@clusterName"));
  6144. return str;
  6145. }
  6146. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  6147. {
  6148. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  6149. }
  6150. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  6151. {
  6152. CriticalBlock block(crit);
  6153. return getDebugValueBool("allowautoqueueswitch",false);
  6154. }
  6155. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  6156. {
  6157. StringBuffer suffix;
  6158. if (name && *name)
  6159. setApplicationValue("LibraryModule", "name", name, true);
  6160. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  6161. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  6162. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  6163. }
  6164. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  6165. {
  6166. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  6167. if (writeaccess)
  6168. auditflags |= DALI_LDAP_WRITE_WANTED;
  6169. SecAccessFlags perm = SecAccess_Full;
  6170. const char *scopename = p->queryProp("@scope");
  6171. if (scopename&&*scopename) {
  6172. if (!user)
  6173. user = queryUserDescriptor();
  6174. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  6175. if (perm<0) {
  6176. if (perm == SecAccess_Unavailable)
  6177. perm = SecAccess_Full;
  6178. else
  6179. perm = SecAccess_None;
  6180. }
  6181. }
  6182. if (!HASREADPERMISSION(perm))
  6183. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  6184. if (writeaccess && !HASWRITEPERMISSION(perm))
  6185. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  6186. }
  6187. void CLocalWorkUnit::setUser(const char * value)
  6188. {
  6189. CriticalBlock block(crit);
  6190. p->setProp("@submitID", value);
  6191. }
  6192. const char *CLocalWorkUnit::queryUser() const
  6193. {
  6194. CriticalBlock block(crit);
  6195. const char *ret = p->queryProp("@submitID");
  6196. if (!ret)
  6197. ret = "";
  6198. return ret;
  6199. }
  6200. void CLocalWorkUnit::setWuScope(const char * value)
  6201. {
  6202. if (value && *value)
  6203. {
  6204. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  6205. {
  6206. CriticalBlock block(crit);
  6207. p->setProp("@scope", value);
  6208. }
  6209. }
  6210. }
  6211. const char *CLocalWorkUnit::queryWuScope() const
  6212. {
  6213. CriticalBlock block(crit);
  6214. const char *ret = p->queryProp("@scope");
  6215. if (!ret)
  6216. ret = "";
  6217. return ret;
  6218. }
  6219. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  6220. {
  6221. CriticalBlock block(crit);
  6222. setEnum(p, "@priorityClass", cls, priorityClasses);
  6223. }
  6224. WUPriorityClass CLocalWorkUnit::getPriority() const
  6225. {
  6226. CriticalBlock block(crit);
  6227. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  6228. }
  6229. const char *CLocalWorkUnit::queryPriorityDesc() const
  6230. {
  6231. return getEnumText(getPriority(), priorityClasses);
  6232. }
  6233. void CLocalWorkUnit::setState(WUState value)
  6234. {
  6235. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  6236. {
  6237. if (factory)
  6238. factory->clearAborting(queryWuid());
  6239. }
  6240. CriticalBlock block(crit);
  6241. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  6242. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  6243. if (getDebugValueBool("monitorWorkunit", false))
  6244. {
  6245. switch(value)
  6246. {
  6247. case WUStateAborted:
  6248. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  6249. break;
  6250. case WUStateCompleted:
  6251. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  6252. break;
  6253. case WUStateFailed:
  6254. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  6255. break;
  6256. }
  6257. }
  6258. p->removeProp("@stateEx");
  6259. }
  6260. void CLocalWorkUnit::setStateEx(const char * text)
  6261. {
  6262. CriticalBlock block(crit);
  6263. p->setProp("@stateEx", text);
  6264. }
  6265. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  6266. {
  6267. CriticalBlock block(crit);
  6268. p->setPropInt64("@agentSession", sessionId);
  6269. }
  6270. bool CLocalWorkUnit::getIsQueryService() const
  6271. {
  6272. CriticalBlock block(crit);
  6273. return p->getPropBool("@isQueryService", false);
  6274. }
  6275. void CLocalWorkUnit::setIsQueryService(bool value)
  6276. {
  6277. CriticalBlock block(crit);
  6278. p->setPropBool("@isQueryService", value);
  6279. }
  6280. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  6281. {
  6282. if (queryDaliServerVersion().compare("2.1")<0)
  6283. return;
  6284. switch(state)
  6285. {
  6286. case WUStateRunning:
  6287. case WUStateDebugPaused:
  6288. case WUStateDebugRunning:
  6289. case WUStateBlocked:
  6290. case WUStateAborting:
  6291. case WUStateCompiling:
  6292. case WUStatePaused:
  6293. {
  6294. SessionId agent = getAgentSession();
  6295. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  6296. {
  6297. forceReload();
  6298. state = (WUState) getEnum(p, "@state", states);
  6299. bool isecl=state==WUStateCompiling;
  6300. if (aborting())
  6301. state = WUStateAborted;
  6302. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  6303. state = WUStateFailed;
  6304. else
  6305. return;
  6306. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  6307. Owned<IWorkUnit> w = &lock();
  6308. w->setState(state);
  6309. Owned<IWUException> e = w->createException();
  6310. WUAction action = w->getAction();
  6311. switch (action)
  6312. {
  6313. case WUActionPause:
  6314. case WUActionPauseNow:
  6315. case WUActionResume:
  6316. w->setAction(WUActionUnknown);
  6317. }
  6318. if(isecl)
  6319. {
  6320. e->setExceptionCode(1001);
  6321. e->setExceptionMessage("EclServer terminated unexpectedly");
  6322. }
  6323. else
  6324. {
  6325. e->setExceptionCode(1000);
  6326. e->setExceptionMessage("Workunit terminated unexpectedly");
  6327. }
  6328. }
  6329. }
  6330. }
  6331. }
  6332. WUState CLocalWorkUnit::getState() const
  6333. {
  6334. CriticalBlock block(crit);
  6335. WUState state = (WUState) getEnum(p, "@state", states);
  6336. switch (state)
  6337. {
  6338. case WUStateRunning:
  6339. case WUStateDebugPaused:
  6340. case WUStateDebugRunning:
  6341. case WUStateBlocked:
  6342. case WUStateCompiling:
  6343. if (aborting())
  6344. state = WUStateAborting;
  6345. break;
  6346. case WUStateSubmitted:
  6347. if (aborting())
  6348. state = WUStateAborted;
  6349. break;
  6350. }
  6351. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  6352. return state;
  6353. }
  6354. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  6355. {
  6356. CriticalBlock block(crit);
  6357. str.set(p->queryProp("@stateEx"));
  6358. return str;
  6359. }
  6360. __int64 CLocalWorkUnit::getAgentSession() const
  6361. {
  6362. CriticalBlock block(crit);
  6363. return p->getPropInt64("@agentSession", -1);
  6364. }
  6365. unsigned CLocalWorkUnit::getAgentPID() const
  6366. {
  6367. CriticalBlock block(crit);
  6368. return p->getPropInt("@agentPID", -1);
  6369. }
  6370. const char * CLocalWorkUnit::queryStateDesc() const
  6371. {
  6372. // MORE - not sure about this - may prefer a separate interface
  6373. CriticalBlock block(crit);
  6374. try
  6375. {
  6376. return getEnumText(getState(), states);
  6377. }
  6378. catch (...)
  6379. {
  6380. return "???";
  6381. }
  6382. }
  6383. void CLocalWorkUnit::setAction(WUAction value)
  6384. {
  6385. CriticalBlock block(crit);
  6386. setEnum(p, "Action", value, actions);
  6387. }
  6388. WUAction CLocalWorkUnit::getAction() const
  6389. {
  6390. CriticalBlock block(crit);
  6391. return (WUAction) getEnum(p, "Action", actions);
  6392. }
  6393. const char *CLocalWorkUnit::queryActionDesc() const
  6394. {
  6395. CriticalBlock block(crit);
  6396. return p->queryProp("Action");
  6397. }
  6398. bool CLocalWorkUnit::hasApplicationValue(const char *app, const char *propname) const
  6399. {
  6400. StringBuffer prop("Application/");
  6401. prop.append(app).append('/').append(propname);
  6402. CriticalBlock block(crit);
  6403. return p->hasProp(prop);
  6404. }
  6405. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  6406. {
  6407. StringBuffer prop("Application/");
  6408. prop.append(app).append('/').append(propname);
  6409. CriticalBlock block(crit);
  6410. str.set(p->queryProp(prop.str()));
  6411. return str;
  6412. }
  6413. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  6414. {
  6415. StringBuffer prop("Application/");
  6416. prop.append(app).append('/').append(propname);
  6417. CriticalBlock block(crit);
  6418. return p->getPropInt(prop.str(), defVal);
  6419. }
  6420. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  6421. {
  6422. CriticalBlock block(crit);
  6423. appvalues.load(p,"Application/*");
  6424. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  6425. }
  6426. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  6427. {
  6428. CriticalBlock block(crit);
  6429. StringBuffer prop("Application/");
  6430. prop.append(app).append('/').append(propname);
  6431. if (overwrite || !p->hasProp(prop.str()))
  6432. {
  6433. StringBuffer sp;
  6434. p->setProp(sp.append("Application").str(), "");
  6435. p->setProp(sp.append('/').append(app).str(), "");
  6436. p->setProp(prop.str(), value);
  6437. }
  6438. }
  6439. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  6440. {
  6441. VStringBuffer s("%d", value);
  6442. setApplicationValue(app, propname, s, overwrite);
  6443. }
  6444. void CLocalWorkUnit::setPriorityLevel(int level)
  6445. {
  6446. CriticalBlock block(crit);
  6447. p->setPropInt("PriorityFlag", level);
  6448. }
  6449. int CLocalWorkUnit::getPriorityLevel() const
  6450. {
  6451. CriticalBlock block(crit);
  6452. return p->getPropInt("PriorityFlag");
  6453. }
  6454. int calcPriorityValue(const IPropertyTree * p)
  6455. {
  6456. int priority = p->getPropInt("PriorityFlag");
  6457. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  6458. {
  6459. case PriorityClassLow:
  6460. priority -= 100;
  6461. break;
  6462. case PriorityClassHigh:
  6463. priority += 100;
  6464. break;
  6465. }
  6466. return priority;
  6467. }
  6468. int CLocalWorkUnit::getPriorityValue() const
  6469. {
  6470. CriticalBlock block(crit);
  6471. return calcPriorityValue(p);
  6472. }
  6473. void CLocalWorkUnit::setRescheduleFlag(bool value)
  6474. {
  6475. CriticalBlock block(crit);
  6476. p->setPropInt("RescheduleFlag", (int) value);
  6477. }
  6478. bool CLocalWorkUnit::getRescheduleFlag() const
  6479. {
  6480. CriticalBlock block(crit);
  6481. return p->getPropInt("RescheduleFlag") != 0;
  6482. }
  6483. class NullIStringIterator : implements IStringIterator, public CInterface
  6484. {
  6485. public:
  6486. IMPLEMENT_IINTERFACE;
  6487. bool first() { return false; }
  6488. bool next() { return false; }
  6489. bool isValid() { return false; }
  6490. IStringVal & str(IStringVal & str) { return str; }
  6491. };
  6492. ClusterType getClusterType(const char * platform, ClusterType dft)
  6493. {
  6494. if (stricmp(platform, "thor") == 0)
  6495. return ThorLCRCluster;
  6496. if (stricmp(platform, "thorlcr") == 0)
  6497. return ThorLCRCluster;
  6498. if (stricmp(platform, "hthor") == 0)
  6499. return HThorCluster;
  6500. if (stricmp(platform, "roxie") == 0)
  6501. return RoxieCluster;
  6502. return dft;
  6503. }
  6504. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  6505. {
  6506. switch (clusterType)
  6507. {
  6508. case ThorLCRCluster:
  6509. if (lcrSensitive)
  6510. return "thorlcr";
  6511. return "thor";
  6512. case RoxieCluster:
  6513. return "roxie";
  6514. case HThorCluster:
  6515. return "hthor";
  6516. }
  6517. throwUnexpected();
  6518. }
  6519. bool extractFromWorkunitDAToken(const char * distributedAccessToken, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey)
  6520. {
  6521. if (!isWorkunitDAToken(distributedAccessToken))
  6522. {
  6523. DBGLOG("Not a valid workunit distributed access token");
  6524. return false;
  6525. }
  6526. //Extract the string between [ and ]
  6527. const char * pEndBracket = strchr(distributedAccessToken + 5, ']');
  6528. StringBuffer tokenValues;
  6529. tokenValues.append(pEndBracket - distributedAccessToken - 5, distributedAccessToken + 5);
  6530. StringArray nameValues;
  6531. nameValues.appendList(tokenValues.str(), ",",true);
  6532. if (user || wuid)
  6533. {
  6534. for (int x = 0; x < nameValues.ordinality(); x++)
  6535. {
  6536. if (user && 0==strncmp(nameValues[x],"u=",2))//Extract user
  6537. user->append(nameValues[x] + 2);
  6538. if (wuid && 0==strncmp(nameValues[x],"w=",2))//Extract wuid
  6539. wuid->append(nameValues[x] + 2);
  6540. }
  6541. }
  6542. if (privKey)
  6543. {
  6544. const char * finger = pEndBracket;
  6545. ++finger;
  6546. while (*finger && *finger != ';')
  6547. privKey->append(1, finger++);
  6548. }
  6549. return true;
  6550. }
  6551. //Verifies the given signed workunit distributed access token was created
  6552. //and signed by the given wuid and user, and that the workunit is still active
  6553. //Returns:
  6554. // 0 : Success, token is valid and workunit is active
  6555. // 1 : Signature does not verify (wuid/username don't match, or signature does not verify)
  6556. // 2 : Workunit not active
  6557. // Throws if unable to open workunit
  6558. wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken)
  6559. {
  6560. if (isEmptyString(daToken))
  6561. {
  6562. ERRLOG("verifyWorkunitDAToken : Token must be provided");
  6563. return wuTokenInvalid;
  6564. }
  6565. StringBuffer tokWuid;
  6566. StringBuffer tokUser;
  6567. if (!extractFromWorkunitDAToken(daToken, &tokWuid, &tokUser, nullptr))//get the wuid and user
  6568. {
  6569. //Not a valid workunit distributed access token
  6570. return wuTokenInvalid;
  6571. }
  6572. //Validate signature
  6573. IDigitalSignatureManager * pDSM = queryDigitalSignatureManagerInstanceFromEnv();
  6574. if (pDSM && pDSM->isDigiVerifierConfigured())
  6575. {
  6576. const char * finger;
  6577. StringBuffer token;//receives copy of everything up until signature
  6578. for (finger = daToken; *finger && *finger != ';'; finger++)
  6579. token.append(1, finger);
  6580. token.append(1, finger);//append ;
  6581. StringBuffer sig(++finger);
  6582. if (!pDSM->digiVerify(sig, token))
  6583. {
  6584. ERRLOG("verifyWorkunitDAToken : workunit distributed access token does not verify");
  6585. return wuTokenInvalid;
  6586. }
  6587. }
  6588. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6589. Owned<IConstWorkUnit> cw = factory->openWorkUnit(tokWuid.str());
  6590. if(!cw)
  6591. {
  6592. throw MakeStringException(WUERR_WorkunitAccessDenied,"verifyWorkunitDAToken : Cannot open workunit %s",tokWuid.str());
  6593. }
  6594. //Verify user matches
  6595. bool wuUserExist = !isEmptyString(cw->queryUser());
  6596. bool tokUserExist = !isEmptyString(tokUser.str());
  6597. bool ctxUserExist = !isEmptyString(ctxUser);
  6598. if (wuUserExist && tokUserExist)
  6599. {
  6600. //if both users are found, they must match
  6601. if (!streq(tokUser.str(), cw->queryUser()))
  6602. {
  6603. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match WU user (%s)", tokUser.str(), cw->queryUser());
  6604. return wuTokenInvalid;//Possible Internal error
  6605. }
  6606. else if (ctxUserExist && !streq(tokUser.str(), ctxUser))//ctxUser will be empty if security not enabled
  6607. {
  6608. ERRLOG("verifyWorkunitDAToken : Token user (%s) does not match Context user (%s)", cw->queryUser(), ctxUser);
  6609. return wuTokenInvalid;
  6610. }
  6611. }
  6612. else if (!wuUserExist && !tokUserExist)//both users will be empty if no security enabled
  6613. {
  6614. if (ctxUserExist)
  6615. {
  6616. ERRLOG("verifyWorkunitDAToken : Security enabled but WU user and Token user not specified");
  6617. return wuTokenInvalid;
  6618. }
  6619. //both users empty and no context user means if no security enabled
  6620. }
  6621. else
  6622. {
  6623. //one user found, but not the other, treat as an error
  6624. ERRLOG("verifyWorkunitDAToken : WU user %s and Token user %s must be provided", wuUserExist ? cw->queryUser() : "(NULL)", tokUserExist ? tokUser.str() : "(NULL)");
  6625. return wuTokenInvalid;
  6626. }
  6627. // no need to compare tokWuid with workunit wuid, because it will always match
  6628. bool wuActive;
  6629. switch (cw->getState())
  6630. {
  6631. case WUStateRunning:
  6632. case WUStateDebugRunning:
  6633. case WUStateBlocked:
  6634. case WUStateAborting:
  6635. case WUStateUploadingFiles:
  6636. #ifdef _DEBUG
  6637. DBGLOG("verifyWorkunitDAToken : Workunit token validated for %s %s, state is '%s'", cw->queryWuid(), cw->queryUser(), getWorkunitStateStr(cw->getState()));
  6638. #endif
  6639. wuActive = true;
  6640. break;
  6641. default:
  6642. ERRLOG("verifyWorkunitDAToken : Workunit %s not active, state is '%s'", cw->queryWuid(), getWorkunitStateStr(cw->getState()));
  6643. wuActive = false;
  6644. break;
  6645. }
  6646. return wuActive ? wuTokenValid : wuTokenWorkunitInactive;
  6647. }
  6648. bool CLocalWorkUnit::resolveFilePrefix(StringBuffer & prefix, const char * queue) const
  6649. {
  6650. if (hasApplicationValue("prefix", queue))
  6651. {
  6652. getApplicationValue("prefix", queue, StringBufferAdaptor(prefix));
  6653. return true;
  6654. }
  6655. #ifndef _CONTAINERIZED
  6656. Owned<IConstWUClusterInfo> ci = getTargetClusterInfo(queue);
  6657. if (ci)
  6658. {
  6659. ci->getScope(StringBufferAdaptor(prefix));
  6660. return true;
  6661. }
  6662. #endif
  6663. return false;
  6664. }
  6665. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  6666. {
  6667. StringBuffer prefix;
  6668. CriticalBlock block(crit);
  6669. if (p->hasProp("Debug/ForceScope"))
  6670. {
  6671. prefix.append(p->queryProp("Debug/ForceScope")).toLowerCase();
  6672. }
  6673. else
  6674. {
  6675. resolveFilePrefix(prefix, p->queryProp("@clusterName"));
  6676. }
  6677. str.set(prefix.str());
  6678. return str;
  6679. }
  6680. //Queries
  6681. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  6682. {
  6683. CriticalBlock block(crit);
  6684. p->setPropInt("@codeVersion", codeVersion);
  6685. p->setProp("@buildVersion", buildVersion);
  6686. p->setProp("@eclVersion", eclVersion);
  6687. }
  6688. unsigned CLocalWorkUnit::getCodeVersion() const
  6689. {
  6690. CriticalBlock block(crit);
  6691. return p->getPropInt("@codeVersion");
  6692. }
  6693. unsigned CLocalWorkUnit::getWuidVersion() const
  6694. {
  6695. CriticalBlock block(crit);
  6696. return p->getPropInt("@wuidVersion");
  6697. }
  6698. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  6699. {
  6700. CriticalBlock block(crit);
  6701. buildVersion.set(p->queryProp("@buildVersion"));
  6702. eclVersion.set(p->queryProp("@eclVersion"));
  6703. }
  6704. void CLocalWorkUnit::setCloneable(bool value)
  6705. {
  6706. CriticalBlock block(crit);
  6707. p->setPropInt("@cloneable", value);
  6708. }
  6709. void CLocalWorkUnit::setIsClone(bool value)
  6710. {
  6711. CriticalBlock block(crit);
  6712. p->setPropInt("@isClone", value);
  6713. }
  6714. bool CLocalWorkUnit::getCloneable() const
  6715. {
  6716. CriticalBlock block(crit);
  6717. return p->getPropBool("@cloneable", false);
  6718. }
  6719. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  6720. {
  6721. CriticalBlock block(crit);
  6722. if (!userDesc)
  6723. {
  6724. userDesc.setown(createUserDescriptor());
  6725. SCMStringBuffer token;
  6726. getWorkunitDistributedAccessToken(token);
  6727. userDesc->set(queryUser(), token.str());//use token as password
  6728. }
  6729. return userDesc;
  6730. }
  6731. bool CLocalWorkUnit::isProtected() const
  6732. {
  6733. CriticalBlock block(crit);
  6734. return p->getPropBool("@protected", false);
  6735. }
  6736. bool CLocalWorkUnit::isPausing() const
  6737. {
  6738. CriticalBlock block(crit);
  6739. if (WUActionPause == getAction())
  6740. {
  6741. switch (getState())
  6742. {
  6743. case WUStateRunning:
  6744. case WUStateAborting:
  6745. return true;
  6746. }
  6747. }
  6748. return false;
  6749. }
  6750. void CLocalWorkUnit::protect(bool protectMode)
  6751. {
  6752. CriticalBlock block(crit);
  6753. p->setPropBool("@protected", protectMode);
  6754. }
  6755. void CLocalWorkUnit::setResultLimit(unsigned value)
  6756. {
  6757. CriticalBlock block(crit);
  6758. p->setPropInt("resultLimit", value);
  6759. }
  6760. unsigned CLocalWorkUnit::getResultLimit() const
  6761. {
  6762. CriticalBlock block(crit);
  6763. return p->getPropInt("resultLimit");
  6764. }
  6765. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  6766. {
  6767. CriticalBlock block(crit);
  6768. str.set(p->queryProp("SNAPSHOT"));
  6769. return str;
  6770. }
  6771. void CLocalWorkUnit::setSnapshot(const char * val)
  6772. {
  6773. CriticalBlock block(crit);
  6774. p->setProp("SNAPSHOT", val);
  6775. }
  6776. const static EnumMapping warningSeverityMap[] =
  6777. {
  6778. { SeverityInformation, "info" },
  6779. { SeverityWarning, "warning" },
  6780. { SeverityError, "error" },
  6781. { SeverityAlert, "alert" },
  6782. { SeverityIgnore, "ignore" },
  6783. { SeverityFatal, "fatal" },
  6784. { SeverityUnknown, NULL }
  6785. };
  6786. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  6787. {
  6788. StringBuffer xpath;
  6789. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6790. CriticalBlock block(crit);
  6791. IPropertyTree * mapping = p->queryPropTree(xpath);
  6792. if (mapping)
  6793. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  6794. return defaultSeverity;
  6795. }
  6796. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  6797. {
  6798. StringBuffer xpath;
  6799. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  6800. CriticalBlock block(crit);
  6801. IPropertyTree * mapping = p->queryPropTree(xpath);
  6802. if (!mapping)
  6803. {
  6804. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  6805. mapping = onWarnings->addPropTree("OnWarning");
  6806. mapping->setPropInt("@code", code);
  6807. }
  6808. setEnum(mapping, "@severity", severity, warningSeverityMap);
  6809. }
  6810. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  6811. {
  6812. IPropertyTree *l = (IPropertyTree *) *ll;
  6813. IPropertyTree *r = (IPropertyTree *) *rr;
  6814. return stricmp(l->queryName(), r->queryName());
  6815. };
  6816. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  6817. {
  6818. // Any other values in the WU that could affect generated code should be crc'ed here
  6819. IPropertyTree *tree = p->queryBranch("Debug");
  6820. if (tree)
  6821. {
  6822. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  6823. ICopyArrayOf<IPropertyTree> subs;
  6824. for(sub->first(); sub->isValid(); sub->next())
  6825. subs.append(sub->query());
  6826. subs.sort(comparePropTrees);
  6827. ForEachItemIn(idx, subs)
  6828. {
  6829. const char *name = subs.item(idx).queryName();
  6830. const char *val = subs.item(idx).queryProp(NULL);
  6831. crc = crc32(name, (size32_t)strlen(name), crc);
  6832. if (val)
  6833. crc = crc32(val, (size32_t)strlen(val), crc);
  6834. }
  6835. }
  6836. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  6837. for (plugins->first();plugins->isValid();plugins->next())
  6838. {
  6839. IConstWUPlugin &thisplugin = plugins->query();
  6840. SCMStringBuffer version;
  6841. thisplugin.getPluginVersion(version);
  6842. crc = crc32(version.str(), version.length(), crc);
  6843. }
  6844. return crc;
  6845. }
  6846. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6847. {
  6848. if (!to->hasProp(xpath) && from->hasProp(xpath))
  6849. to->setProp(xpath, from->queryProp(xpath));
  6850. }
  6851. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6852. {
  6853. if (from->hasProp(xpath))
  6854. to->setProp(xpath, from->queryProp(xpath));
  6855. }
  6856. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  6857. {
  6858. IPropertyTree * match = from->getBranch(xpath);
  6859. if (match)
  6860. to->setPropTree(xpath, match);
  6861. }
  6862. IPropertyTree *CLocalWorkUnit::queryPTree() const
  6863. {
  6864. return p;
  6865. }
  6866. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all)
  6867. {
  6868. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  6869. if (!from)
  6870. {
  6871. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  6872. if (!fl)
  6873. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  6874. from = fl->c;
  6875. }
  6876. // Need to copy the query, the results, and the graphs from the cached query.
  6877. // The cache is made before the query is executed so there is no need to clear them.
  6878. if (!cached->getCloneable())
  6879. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  6880. const IPropertyTree * fromP = from->p;
  6881. IPropertyTree *pt;
  6882. CriticalBlock block(crit);
  6883. clearCached(false);
  6884. query.clear();
  6885. updateProp(p, fromP, "@jobName");
  6886. copyTree(p, fromP, "Query");
  6887. pt = fromP->getBranch("Application/LibraryModule");
  6888. if (pt)
  6889. {
  6890. ensurePTree(p, "Application");
  6891. p->setPropTree("Application/LibraryModule", pt);
  6892. }
  6893. pt = fromP->getBranch("Application/prefix");
  6894. if (pt)
  6895. {
  6896. ensurePTree(p, "Application");
  6897. p->setPropTree("Application/prefix", pt);
  6898. }
  6899. pt = fromP->queryBranch("Debug");
  6900. if (pt)
  6901. {
  6902. IPropertyTree *curDebug = p->queryPropTree("Debug");
  6903. if (curDebug)
  6904. {
  6905. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  6906. ForEach(*elems)
  6907. {
  6908. IPropertyTree *elem = &elems->query();
  6909. if (!curDebug->hasProp(elem->queryName()))
  6910. curDebug->setPropTree(elem->queryName(),LINK(elem));
  6911. }
  6912. }
  6913. else
  6914. p->setPropTree("Debug", LINK(pt));
  6915. }
  6916. copyTree(p, fromP, "OnWarnings");
  6917. copyTree(p, fromP, "Plugins");
  6918. copyTree(p, fromP, "Libraries");
  6919. copyTree(p, fromP, "Results");
  6920. copyTree(p, fromP, "Graphs");
  6921. copyTree(p, fromP, "Workflow");
  6922. copyTree(p, fromP, "WebServicesInfo");
  6923. if (copyStats)
  6924. {
  6925. // Merge timing info from both branches
  6926. pt = fromP->getBranch("Statistics");
  6927. if (pt)
  6928. {
  6929. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  6930. mergePTree(tgtStatistics, pt);
  6931. pt->Release();
  6932. }
  6933. }
  6934. updateProp(p, fromP, "@clusterName");
  6935. updateProp(p, fromP, "allowedclusters");
  6936. updateProp(p, fromP, "@submitID");
  6937. updateProp(p, fromP, "SNAPSHOT");
  6938. setProp(p, fromP, "@eventScheduledCount");
  6939. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  6940. if (all)
  6941. {
  6942. setProp(p, fromP, "PriorityFlag");
  6943. setProp(p, fromP, "@priorityClass");
  6944. setProp(p, fromP, "@protected");
  6945. setProp(p, fromP, "@clusterName");
  6946. updateProp(p, fromP, "@scope");
  6947. }
  6948. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  6949. pt = fromP->getBranch("Variables");
  6950. if (pt)
  6951. {
  6952. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  6953. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  6954. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  6955. {
  6956. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  6957. const char *name = ptSrcVariable->queryProp("@name");
  6958. assertex(name);
  6959. StringBuffer xpath;
  6960. xpath.append("Variable[@name='").append(name).append("']");
  6961. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  6962. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  6963. merged->removeProp("Value"); // except value and status
  6964. merged->setProp("@status", "undefined");
  6965. if (!merged->getPropBool("@isScalar"))
  6966. merged->removeProp("totalRowCount");
  6967. merged->removeProp("rowCount");
  6968. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  6969. if (ptTgtVariable)
  6970. {
  6971. // copy status and Value from what is already set in target
  6972. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  6973. MemoryBuffer value;
  6974. if (ptTgtVariable->getPropBin("Value", value))
  6975. merged->setPropBin("Value", value.length(), value.toByteArray());
  6976. ptTgtVariable->removeProp(xpath.str());
  6977. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  6978. }
  6979. ptTgtVariables->addPropTree("Variable", merged);
  6980. }
  6981. pt->Release();
  6982. }
  6983. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  6984. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  6985. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  6986. p->setProp("@totalThorTime", fromP->queryProp("@totalThorTime"));
  6987. p->setProp("@hash", fromP->queryProp("@hash"));
  6988. p->setPropBool("@cloneable", true);
  6989. p->setPropBool("@isClone", true);
  6990. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  6991. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  6992. ForEach(*results)
  6993. {
  6994. CLocalWUResult result(LINK(&results->query()));
  6995. result.setResultStatus(ResultStatusUndefined);
  6996. }
  6997. copyTree(p, fromP, "usedsources"); // field usage
  6998. }
  6999. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  7000. {
  7001. StringBuffer lower;
  7002. lower.append(propname).toLowerCase();
  7003. CriticalBlock block(crit);
  7004. StringBuffer prop("Debug/");
  7005. return p->hasProp(prop.append(lower));
  7006. }
  7007. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  7008. {
  7009. StringBuffer lower;
  7010. lower.append(propname).toLowerCase();
  7011. CriticalBlock block(crit);
  7012. StringBuffer prop("Debug/");
  7013. str.set(p->queryProp(prop.append(lower).str()));
  7014. return str;
  7015. }
  7016. IStringIterator& CLocalWorkUnit::getDebugValues() const
  7017. {
  7018. return getDebugValues(NULL);
  7019. }
  7020. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  7021. {
  7022. CriticalBlock block(crit);
  7023. StringBuffer path("Debug/");
  7024. if (prop)
  7025. {
  7026. StringBuffer lower;
  7027. lower.append(prop).toLowerCase();
  7028. path.append(lower);
  7029. }
  7030. else
  7031. path.append("*");
  7032. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  7033. }
  7034. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  7035. {
  7036. StringBuffer lower;
  7037. lower.append(propname).toLowerCase();
  7038. CriticalBlock block(crit);
  7039. StringBuffer prop("Debug/");
  7040. prop.append(lower);
  7041. return p->getPropInt(prop.str(), defVal);
  7042. }
  7043. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  7044. {
  7045. StringBuffer lower;
  7046. lower.append(propname).toLowerCase();
  7047. CriticalBlock block(crit);
  7048. StringBuffer prop("Debug/");
  7049. prop.append(lower);
  7050. return p->getPropInt64(prop.str(), defVal);
  7051. }
  7052. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  7053. {
  7054. StringBuffer lower;
  7055. lower.append(propname).toLowerCase();
  7056. CriticalBlock block(crit);
  7057. StringBuffer prop("Debug/");
  7058. prop.append(lower);
  7059. return p->getPropBool(prop.str(), defVal);
  7060. }
  7061. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  7062. {
  7063. VStringBuffer xpath("Process/%s/", type);
  7064. if (instance)
  7065. xpath.append(instance);
  7066. else
  7067. xpath.append("*");
  7068. CriticalBlock block(crit);
  7069. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  7070. {
  7071. // NB: instance unused
  7072. if (streq("EclAgent", type))
  7073. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  7074. else if (streq("Thor", type))
  7075. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  7076. VStringBuffer xpath("Debug/%s", type);
  7077. return new CStringPTreeIterator(p->getElements(xpath.str()));
  7078. }
  7079. else
  7080. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  7081. }
  7082. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  7083. {
  7084. VStringBuffer xpath("Process/%s/", type);
  7085. if (instance)
  7086. xpath.append(instance);
  7087. else
  7088. xpath.append("*");
  7089. CriticalBlock block(crit);
  7090. return p->getElements(xpath.str());
  7091. }
  7092. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  7093. {
  7094. VStringBuffer xpath("Process/%s/*", type);
  7095. CriticalBlock block(crit);
  7096. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  7097. }
  7098. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  7099. {
  7100. VStringBuffer processType("Process/%s", type);
  7101. VStringBuffer xpath("%s/%s", processType.str(), instance);
  7102. if (log)
  7103. xpath.appendf("[@log=\"%s\"]", log);
  7104. CriticalBlock block(crit);
  7105. if (!p->hasProp(xpath))
  7106. {
  7107. IPropertyTree *node = ensurePTree(p, processType.str());
  7108. node = node->addPropTree(instance);
  7109. node->setProp("@log", log);
  7110. node->setPropInt("@pid", pid);
  7111. }
  7112. }
  7113. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  7114. {
  7115. StringBuffer lower;
  7116. lower.append(propname).toLowerCase();
  7117. CriticalBlock block(crit);
  7118. StringBuffer prop("Debug/");
  7119. prop.append(lower);
  7120. if (overwrite || !p->hasProp(prop.str()))
  7121. {
  7122. // MORE - not sure this line should be needed....
  7123. p->setProp("Debug", "");
  7124. p->setProp(prop.str(), value);
  7125. }
  7126. }
  7127. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  7128. {
  7129. StringBuffer lower;
  7130. lower.append(propname).toLowerCase();
  7131. CriticalBlock block(crit);
  7132. StringBuffer prop("Debug/");
  7133. prop.append(lower);
  7134. if (overwrite || !p->hasProp(prop.str()))
  7135. {
  7136. // MORE - not sure this line should be needed....
  7137. p->setProp("Debug", "");
  7138. p->setPropInt(prop.str(), value);
  7139. }
  7140. }
  7141. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  7142. {
  7143. CriticalBlock block(crit);
  7144. // MORE - not sure this line should be needed....
  7145. p->setProp("Tracing", "");
  7146. StringBuffer prop("Tracing/");
  7147. p->setProp(prop.append(propname).str(), value);
  7148. }
  7149. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  7150. {
  7151. CriticalBlock block(crit);
  7152. StringBuffer prop("Tracing/");
  7153. p->setPropInt(prop.append(propname).str(), value);
  7154. }
  7155. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  7156. {
  7157. CriticalBlock block(crit);
  7158. VStringBuffer prop("Tracing/%s", propname);
  7159. p->setPropInt64(prop.str(), value);
  7160. }
  7161. IConstWUQuery* CLocalWorkUnit::getQuery() const
  7162. {
  7163. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7164. CriticalBlock block(crit);
  7165. if (!query)
  7166. {
  7167. IPropertyTree *s = p->getPropTree("Query");
  7168. if (s)
  7169. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  7170. }
  7171. return query.getLink();
  7172. }
  7173. IWUQuery* CLocalWorkUnit::updateQuery()
  7174. {
  7175. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7176. CriticalBlock block(crit);
  7177. if (!query)
  7178. {
  7179. IPropertyTree *s = p->queryPropTree("Query");
  7180. if (!s)
  7181. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  7182. s->Link();
  7183. query.setown(new CLocalWUQuery(s));
  7184. }
  7185. return query.getLink();
  7186. }
  7187. void CLocalWorkUnit::loadPlugins() const
  7188. {
  7189. CriticalBlock block(crit);
  7190. if (!pluginsCached)
  7191. {
  7192. assertex(plugins.length() == 0);
  7193. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  7194. for (r->first(); r->isValid(); r->next())
  7195. {
  7196. IPropertyTree *rp = &r->query();
  7197. rp->Link();
  7198. plugins.append(*new CLocalWUPlugin(rp));
  7199. }
  7200. pluginsCached = true;
  7201. }
  7202. }
  7203. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  7204. {
  7205. CriticalBlock block(crit);
  7206. loadPlugins();
  7207. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  7208. }
  7209. void CLocalWorkUnit::loadLibraries() const
  7210. {
  7211. CriticalBlock block(crit);
  7212. if (!librariesCached)
  7213. {
  7214. assertex(libraries.length() == 0);
  7215. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  7216. ForEach(*r)
  7217. {
  7218. IPropertyTree *rp = &r->query();
  7219. rp->Link();
  7220. libraries.append(*new CLocalWULibrary(rp));
  7221. }
  7222. librariesCached = true;
  7223. }
  7224. }
  7225. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  7226. {
  7227. CriticalBlock block(crit);
  7228. loadLibraries();
  7229. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  7230. }
  7231. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  7232. {
  7233. CriticalBlock block(crit);
  7234. loadLibraries();
  7235. ForEachItemIn(idx, libraries)
  7236. {
  7237. SCMStringBuffer name;
  7238. IConstWULibrary &cur = libraries.item(idx);
  7239. cur.getName(name);
  7240. if (stricmp(name.str(), search)==0)
  7241. return &OLINK(cur);
  7242. }
  7243. return NULL;
  7244. }
  7245. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7246. {
  7247. str.append("Graph ").append(graphName);
  7248. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  7249. else if (subId) str.append(" - id(").append(subId).append(")");
  7250. return str;
  7251. }
  7252. StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  7253. {
  7254. if (wfid)
  7255. str.append(WorkflowScopePrefix).append(wfid).append(":");
  7256. str.append(graphName);
  7257. if (subId) str.append(":sg").append(subId);
  7258. return str;
  7259. }
  7260. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  7261. {
  7262. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  7263. unsigned len = (size32_t)strlen(label);
  7264. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  7265. return false;
  7266. graphNum = 0;
  7267. subGraphNum = 0;
  7268. subId = 0;
  7269. const char *finger = label+6;
  7270. const char *finger2 = strchr(finger, '-');
  7271. if (NULL == finger2) // just graphName
  7272. graphName.set(finger);
  7273. else
  7274. {
  7275. graphName.set(finger, (size32_t)((finger2-1)-finger));
  7276. finger = finger2+2; // skip '-' and space
  7277. finger2 = strchr(finger, ' ');
  7278. if (finger2)
  7279. {
  7280. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  7281. finger = finger2+2; // skip space and '('
  7282. finger2 = strchr(finger, ')');
  7283. if (finger2)
  7284. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7285. }
  7286. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  7287. {
  7288. finger += 3;
  7289. finger2 = strchr(finger, ')');
  7290. if (finger2)
  7291. subId = atoi_l(finger, (size32_t)(finger2-finger));
  7292. }
  7293. }
  7294. if (graphName && !memicmp(graphName, "graph", 5))
  7295. graphNum = atoi(graphName + 5);
  7296. return true;
  7297. }
  7298. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  7299. {
  7300. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  7301. return false;
  7302. graphNum = atoi(scope + strlen(GraphScopePrefix));
  7303. subGraphId = 0;
  7304. const char * colon = strchr(scope, ':');
  7305. if (!colon)
  7306. {
  7307. graphName.set(scope);
  7308. return true;
  7309. }
  7310. const char * subgraph = colon+1;
  7311. graphName.set(scope, (size32_t)(colon - scope));
  7312. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  7313. subGraphId = atoi(subgraph+strlen(SubGraphScopePrefix));
  7314. return true;
  7315. }
  7316. 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)
  7317. {
  7318. if (!scope) scope = GLOBAL_SCOPE;
  7319. const char * kindName = queryStatisticName(kind);
  7320. StatisticMeasure measure = queryMeasure(kind);
  7321. //creator. scope and name must all be present, and must not contain semi colons.
  7322. assertex(creator && scope);
  7323. CriticalBlock block(crit);
  7324. IPropertyTree * stats = p->queryPropTree("Statistics");
  7325. if (!stats)
  7326. stats = p->addPropTree("Statistics");
  7327. IPropertyTree * statTree = NULL;
  7328. if (mergeAction != StatsMergeAppend)
  7329. {
  7330. StringBuffer xpath;
  7331. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  7332. statTree = stats->queryPropTree(xpath.str());
  7333. }
  7334. if (!statTree)
  7335. {
  7336. statTree = stats->addPropTree("Statistic");
  7337. statTree->setProp("@creator", creator);
  7338. statTree->setProp("@scope", scope);
  7339. statTree->setProp("@kind", kindName);
  7340. //These items are primarily here to facilitate filtering.
  7341. statTree->setProp("@unit", queryMeasureName(measure));
  7342. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  7343. statTree->setProp("@s", queryScopeTypeName(scopeType));
  7344. statTree->setPropInt64("@ts", getTimeStampNowValue());
  7345. if (optDescription)
  7346. statTree->setProp("@desc", optDescription);
  7347. if (statistics.cached)
  7348. statistics.append(LINK(statTree));
  7349. mergeAction = StatsMergeAppend;
  7350. }
  7351. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  7352. {
  7353. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  7354. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  7355. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  7356. if (oldMax < oldValue)
  7357. oldMax = oldValue;
  7358. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  7359. statTree->setPropInt64("@count", count + oldCount);
  7360. if (maxValue > oldMax)
  7361. statTree->setPropInt64("@max", maxValue);
  7362. }
  7363. else
  7364. {
  7365. statTree->setPropInt64("@value", value);
  7366. statTree->setPropInt64("@count", count);
  7367. if (maxValue)
  7368. statTree->setPropInt64("@max", maxValue);
  7369. else
  7370. statTree->removeProp("@max");
  7371. }
  7372. //Whenever a graph time is updated recalculate the total time spent in thor, and save it
  7373. if ((scopeType == SSTgraph) && (kind == StTimeElapsed))
  7374. {
  7375. _loadStatistics();
  7376. stat_type totalTime = 0;
  7377. ForEachItemIn(i, statistics)
  7378. {
  7379. IConstWUStatistic & cur = statistics.item(i);
  7380. if ((cur.getScopeType() == SSTgraph) && (cur.getKind() == StTimeElapsed))
  7381. totalTime += cur.getValue();
  7382. }
  7383. StringBuffer t;
  7384. formatTimeCollatable(t, totalTime, false);
  7385. p->setProp("@totalThorTime", t);
  7386. }
  7387. }
  7388. void CLocalWorkUnit::_loadStatistics() const
  7389. {
  7390. statistics.load(p,"Statistics/*");
  7391. }
  7392. bool CLocalWorkUnit::getStatistic(stat_type & value, const char * scope, StatisticKind kind) const
  7393. {
  7394. //MORE: Optimize this....
  7395. WuScopeFilter filter;
  7396. filter.addScope(scope).setIncludeNesting(0).addRequiredStat(kind).addOutputStatistic(kind).finishedFilter();
  7397. Owned<IConstWUScopeIterator> stats = &getScopeIterator(filter);
  7398. if (stats->first())
  7399. return stats->getStat(kind, value);
  7400. return false;
  7401. }
  7402. IConstWUScopeIterator & CLocalWorkUnit::getScopeIterator(const WuScopeFilter & filter) const
  7403. {
  7404. assertex(filter.isOptimized());
  7405. WuScopeSourceFlags sources = filter.sourceFlags;
  7406. Owned<CompoundStatisticsScopeIterator> compoundIter = new CompoundStatisticsScopeIterator(filter);
  7407. if (sources & SSFsearchGlobalStats)
  7408. {
  7409. {
  7410. CriticalBlock block(crit);
  7411. statistics.loadBranch(p,"Statistics");
  7412. }
  7413. Owned<IConstWUScopeIterator> localStats(new WorkUnitStatisticsScopeIterator(statistics, filter.queryIterFilter()));
  7414. compoundIter->addIter(localStats);
  7415. }
  7416. if (sources & SSFsearchGraphStats)
  7417. {
  7418. const char * wuid = p->queryName();
  7419. Owned<IConstWUScopeIterator> scopeIter(new CConstGraphProgressScopeIterator(wuid, filter.queryIterFilter(), filter.minVersion));
  7420. compoundIter->addIter(scopeIter);
  7421. }
  7422. if (sources & SSFsearchGraph)
  7423. {
  7424. Owned<IConstWUScopeIterator> graphIter(new GraphScopeIterator(this, filter.queryIterFilter()));
  7425. compoundIter->addIter(graphIter);
  7426. }
  7427. if (sources & SSFsearchWorkflow)
  7428. {
  7429. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  7430. if (iter)
  7431. {
  7432. Owned<IConstWUScopeIterator> workflowIter(new WorkflowStatisticsScopeIterator(iter));
  7433. compoundIter->addIter(workflowIter);
  7434. }
  7435. }
  7436. if (sources & SSFsearchExceptions)
  7437. {
  7438. Owned<IConstWUScopeIterator> notesIter(new NotesIterator(this,filter.queryIterFilter()));
  7439. compoundIter->addIter(notesIter);
  7440. }
  7441. return *compoundIter.getClear();
  7442. }
  7443. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  7444. {
  7445. CriticalBlock block(crit);
  7446. IConstWUPlugin *existing = getPluginByName(qname);
  7447. if (existing)
  7448. return (IWUPlugin *) existing;
  7449. if (!plugins.length())
  7450. p->addPropTree("Plugins");
  7451. IPropertyTree *pl = p->queryPropTree("Plugins");
  7452. IPropertyTree *s = pl->addPropTree("Plugin");
  7453. s->Link();
  7454. IWUPlugin* q = new CLocalWUPlugin(s);
  7455. q->Link();
  7456. plugins.append(*q);
  7457. q->setPluginName(qname);
  7458. return q;
  7459. }
  7460. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  7461. {
  7462. CriticalBlock block(crit);
  7463. loadPlugins();
  7464. ForEachItemIn(idx, plugins)
  7465. {
  7466. SCMStringBuffer name;
  7467. IConstWUPlugin &cur = plugins.item(idx);
  7468. cur.getPluginName(name);
  7469. if (stricmp(name.str(), qname)==0)
  7470. {
  7471. cur.Link();
  7472. return &cur;
  7473. }
  7474. }
  7475. return NULL;
  7476. }
  7477. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  7478. {
  7479. CriticalBlock block(crit);
  7480. IConstWULibrary *existing = getLibraryByName(qname);
  7481. if (existing)
  7482. return (IWULibrary *) existing;
  7483. if (!libraries.length())
  7484. p->addPropTree("Libraries");
  7485. IPropertyTree *pl = p->queryPropTree("Libraries");
  7486. IPropertyTree *s = pl->addPropTree("Library");
  7487. s->Link();
  7488. IWULibrary* q = new CLocalWULibrary(s);
  7489. q->Link();
  7490. libraries.append(*q);
  7491. q->setName(qname);
  7492. return q;
  7493. }
  7494. void CLocalWorkUnit::_loadExceptions() const
  7495. {
  7496. assertex(exceptions.length() == 0);
  7497. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  7498. for (r->first(); r->isValid(); r->next())
  7499. {
  7500. IPropertyTree *rp = &r->query();
  7501. rp->Link();
  7502. exceptions.append(*new CLocalWUException(rp));
  7503. }
  7504. }
  7505. void CLocalWorkUnit::loadExceptions() const
  7506. {
  7507. CriticalBlock block(crit);
  7508. if (!exceptionsCached)
  7509. {
  7510. _loadExceptions();
  7511. exceptionsCached = true;
  7512. }
  7513. }
  7514. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  7515. {
  7516. CriticalBlock block(crit);
  7517. loadExceptions();
  7518. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  7519. }
  7520. unsigned CLocalWorkUnit::getExceptionCount() const
  7521. {
  7522. CriticalBlock block(crit);
  7523. loadExceptions();
  7524. return exceptions.length();
  7525. }
  7526. void CLocalWorkUnit::clearExceptions(const char *source)
  7527. {
  7528. CriticalBlock block(crit);
  7529. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7530. loadExceptions();
  7531. ForEachItemInRev(idx, exceptions)
  7532. {
  7533. IWUException &e = exceptions.item(idx);
  7534. SCMStringBuffer s;
  7535. e.getExceptionSource(s);
  7536. if (source)
  7537. {
  7538. if (!strieq(s.s, source))
  7539. continue;
  7540. }
  7541. else
  7542. {
  7543. if (strieq(s.s, "eclcc") || strieq(s.s, "eclccserver") || strieq(s.s, "eclserver") )
  7544. break;
  7545. }
  7546. VStringBuffer xpath("Exceptions/Exception[@sequence='%d']", e.getSequence());
  7547. p->removeProp(xpath);
  7548. exceptions.remove(idx);
  7549. }
  7550. if (exceptions.length() == 0)
  7551. p->removeProp("Exceptions");
  7552. }
  7553. IWUException* CLocalWorkUnit::createException()
  7554. {
  7555. CriticalBlock block(crit);
  7556. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7557. loadExceptions();
  7558. if (!exceptions.length())
  7559. p->addPropTree("Exceptions");
  7560. IPropertyTree *r = p->queryPropTree("Exceptions");
  7561. IPropertyTree *s = r->addPropTree("Exception");
  7562. s->setPropInt("@sequence", exceptions.ordinality());
  7563. IWUException* q = new CLocalWUException(LINK(s));
  7564. exceptions.append(*LINK(q));
  7565. Owned<IJlibDateTime> now = createDateTimeNow();
  7566. SCMStringBuffer temp;
  7567. now->getString(temp);
  7568. q->setTimeStamp(temp.str());
  7569. return q;
  7570. }
  7571. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  7572. {
  7573. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7574. CriticalBlock block(crit);
  7575. if (!webServicesInfoCached)
  7576. {
  7577. assertex(!webServicesInfo);
  7578. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  7579. if (s)
  7580. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  7581. webServicesInfoCached = true;
  7582. }
  7583. return webServicesInfo.getLink();
  7584. }
  7585. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  7586. {
  7587. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7588. CriticalBlock block(crit);
  7589. if (!webServicesInfoCached)
  7590. {
  7591. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  7592. if (!s)
  7593. {
  7594. if (create)
  7595. s = p->addPropTree("WebServicesInfo");
  7596. else
  7597. return NULL;
  7598. }
  7599. s->Link();
  7600. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  7601. webServicesInfoCached = true;
  7602. }
  7603. return webServicesInfo.getLink();
  7604. }
  7605. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  7606. {
  7607. CLocalWUResult *l = (CLocalWUResult *) *ll;
  7608. CLocalWUResult *r = (CLocalWUResult *) *rr;
  7609. return l->getResultSequence() - r->getResultSequence();
  7610. }
  7611. void CLocalWorkUnit::_loadResults() const
  7612. {
  7613. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  7614. for (r->first(); r->isValid(); r->next())
  7615. {
  7616. IPropertyTree *rp = &r->query();
  7617. rp->Link();
  7618. results.append(*new CLocalWUResult(rp));
  7619. }
  7620. }
  7621. void CLocalWorkUnit::loadResults() const
  7622. {
  7623. if (!resultsCached)
  7624. {
  7625. assertex(results.length() == 0);
  7626. _loadResults();
  7627. results.sort(compareResults);
  7628. resultsCached = true;
  7629. }
  7630. }
  7631. void CLocalWorkUnit::_loadVariables() const
  7632. {
  7633. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  7634. for (r->first(); r->isValid(); r->next())
  7635. {
  7636. IPropertyTree *rp = &r->query();
  7637. rp->Link();
  7638. variables.append(*new CLocalWUResult(rp));
  7639. }
  7640. }
  7641. void CLocalWorkUnit::loadVariables() const
  7642. {
  7643. if (!variablesCached)
  7644. {
  7645. assertex(variables.length() == 0);
  7646. _loadVariables();
  7647. variablesCached = true;
  7648. }
  7649. }
  7650. void CLocalWorkUnit::_loadTemporaries() const
  7651. {
  7652. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  7653. for (r->first(); r->isValid(); r->next())
  7654. {
  7655. IPropertyTree *rp = &r->query();
  7656. rp->Link();
  7657. temporaries.append(*new CLocalWUResult(rp));
  7658. }
  7659. }
  7660. void CLocalWorkUnit::loadTemporaries() const
  7661. {
  7662. if (!temporariesCached)
  7663. {
  7664. assertex(temporaries.length() == 0);
  7665. _loadTemporaries();
  7666. temporariesCached = true;
  7667. }
  7668. }
  7669. void CLocalWorkUnit::deleteTemporaries()
  7670. {
  7671. CriticalBlock block(crit);
  7672. if (temporariesCached)
  7673. {
  7674. temporaries.kill();
  7675. temporariesCached = false;
  7676. }
  7677. p->removeProp("Temporaries");
  7678. }
  7679. IWUResult* CLocalWorkUnit::createResult()
  7680. {
  7681. CriticalBlock block(crit);
  7682. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7683. loadResults();
  7684. if (!results.length())
  7685. p->addPropTree("Results");
  7686. IPropertyTree *r = p->queryPropTree("Results");
  7687. IPropertyTree *s = r->addPropTree("Result");
  7688. s->Link();
  7689. IWUResult* q = new CLocalWUResult(s);
  7690. q->Link();
  7691. results.append(*q);
  7692. return q;
  7693. }
  7694. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  7695. {
  7696. CriticalBlock block(crit);
  7697. IConstWUResult *existing = getResultByName(qname);
  7698. if (existing)
  7699. return (IWUResult *) existing;
  7700. IWUResult* q = createResult();
  7701. q->setResultName(qname);
  7702. return q;
  7703. }
  7704. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  7705. {
  7706. CriticalBlock block(crit);
  7707. IConstWUResult *existing = getResultBySequence(seq);
  7708. if (existing)
  7709. return (IWUResult *) existing;
  7710. IWUResult* q = createResult();
  7711. q->setResultSequence(seq);
  7712. return q;
  7713. }
  7714. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  7715. {
  7716. CriticalBlock block(crit);
  7717. loadResults();
  7718. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  7719. }
  7720. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  7721. {
  7722. CriticalBlock block(crit);
  7723. loadResults();
  7724. ForEachItemIn(idx, results)
  7725. {
  7726. SCMStringBuffer name;
  7727. IConstWUResult &cur = results.item(idx);
  7728. cur.getResultName(name);
  7729. if (stricmp(name.str(), qname)==0)
  7730. {
  7731. cur.Link();
  7732. return &cur;
  7733. }
  7734. }
  7735. return NULL;
  7736. }
  7737. IConstWUResult* CLocalWorkUnit::getQueryResultByName(const char *qname) const
  7738. {
  7739. CriticalBlock block(crit);
  7740. loadResults();
  7741. ForEachItemIn(idx, results)
  7742. {
  7743. IConstWUResult &cur = results.item(idx);
  7744. if (!isSpecialResultSequence(cur.getResultSequence()))
  7745. {
  7746. SCMStringBuffer name;
  7747. cur.getResultName(name);
  7748. if (stricmp(name.str(), qname)==0)
  7749. {
  7750. cur.Link();
  7751. return &cur;
  7752. }
  7753. }
  7754. }
  7755. return NULL;
  7756. }
  7757. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  7758. {
  7759. CriticalBlock block(crit);
  7760. loadResults();
  7761. ForEachItemIn(idx, results)
  7762. {
  7763. IConstWUResult &cur = results.item(idx);
  7764. if (cur.getResultSequence() == seq)
  7765. {
  7766. cur.Link();
  7767. return &cur;
  7768. }
  7769. }
  7770. return NULL;
  7771. }
  7772. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  7773. {
  7774. CriticalBlock block(crit);
  7775. loadVariables();
  7776. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  7777. }
  7778. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  7779. {
  7780. CriticalBlock block(crit);
  7781. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7782. return getVariableByName(qname);
  7783. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7784. return global->getVariableByName(qname);
  7785. }
  7786. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  7787. {
  7788. CriticalBlock block(crit);
  7789. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  7790. return updateVariableByName(qname);
  7791. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  7792. return global->updateVariableByName(qname);
  7793. }
  7794. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  7795. {
  7796. CriticalBlock block(crit);
  7797. loadVariables();
  7798. ForEachItemIn(idx, variables)
  7799. {
  7800. SCMStringBuffer name;
  7801. IConstWUResult &cur = variables.item(idx);
  7802. cur.getResultName(name);
  7803. if (stricmp(name.str(), qname)==0)
  7804. {
  7805. cur.Link();
  7806. return &cur;
  7807. }
  7808. }
  7809. return NULL;
  7810. }
  7811. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  7812. {
  7813. CriticalBlock block(crit);
  7814. loadTemporaries();
  7815. ForEachItemIn(idx, temporaries)
  7816. {
  7817. SCMStringBuffer name;
  7818. IConstWUResult &cur = temporaries.item(idx);
  7819. cur.getResultName(name);
  7820. if (stricmp(name.str(), qname)==0)
  7821. {
  7822. cur.Link();
  7823. return &cur;
  7824. }
  7825. }
  7826. return NULL;
  7827. }
  7828. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  7829. {
  7830. CriticalBlock block(crit);
  7831. loadTemporaries();
  7832. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  7833. }
  7834. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  7835. {
  7836. CriticalBlock block(crit);
  7837. IConstWUResult *existing = getTemporaryByName(qname);
  7838. if (existing)
  7839. return (IWUResult *) existing;
  7840. IPropertyTree *vars = (temporaries.length()) ? p->queryPropTree("Temporaries") : p->addPropTree("Temporaries");
  7841. IPropertyTree *s = vars->addPropTree("Variable");
  7842. s->Link();
  7843. IWUResult* q = new CLocalWUResult(s);
  7844. q->Link();
  7845. temporaries.append(*q);
  7846. q->setResultName(qname);
  7847. q->setResultSequence(ResultSequenceInternal);
  7848. return q;
  7849. }
  7850. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  7851. {
  7852. CriticalBlock block(crit);
  7853. IConstWUResult *existing = getVariableByName(qname);
  7854. if (existing)
  7855. return (IWUResult *) existing;
  7856. if (!variables.length())
  7857. p->addPropTree("Variables");
  7858. IPropertyTree *vars = p->queryPropTree("Variables");
  7859. IPropertyTree *s = vars->addPropTree("Variable");
  7860. s->Link();
  7861. IWUResult* q = new CLocalWUResult(s);
  7862. q->Link();
  7863. variables.append(*q);
  7864. q->setResultName(qname);
  7865. q->setResultSequence(ResultSequenceStored);
  7866. return q;
  7867. }
  7868. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  7869. {
  7870. CriticalBlock block(crit);
  7871. IPropertyTree *files = p->queryPropTree("Files");
  7872. if (!files) return;
  7873. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  7874. ICopyArrayOf<IPropertyTree> toRemove;
  7875. ForEach (*iter)
  7876. {
  7877. IPropertyTree &file = iter->query();
  7878. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  7879. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  7880. bool needDelete;
  7881. switch(fileKind)
  7882. {
  7883. case WUFileTemporary:
  7884. if(graph==NULL)
  7885. needDelete = true;
  7886. else
  7887. {
  7888. const char *graphOwner = file.queryProp("@graph");
  7889. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  7890. }
  7891. break;
  7892. case WUFileJobOwned:
  7893. needDelete = ((graph==NULL) && deleteJobOwned);
  7894. break;
  7895. case WUFileOwned:
  7896. needDelete = ((graph==NULL) && deleteOwned);
  7897. break;
  7898. default:
  7899. needDelete = false;
  7900. }
  7901. if(needDelete)
  7902. {
  7903. const char *name = file.queryProp("@name");
  7904. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  7905. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  7906. toRemove.append(file);
  7907. }
  7908. }
  7909. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  7910. }
  7911. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  7912. {
  7913. IDistributedSuperFile *super = file->querySuperFile();
  7914. StringBuffer fname;
  7915. file->getLogicalName(fname);
  7916. if (fname.length())
  7917. {
  7918. StringBuffer path("File[@name=\"");
  7919. path.append(fname).append("\"]");
  7920. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  7921. if (fileTree)
  7922. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  7923. else
  7924. {
  7925. StringBuffer cluster;
  7926. file->getClusterName(0,cluster);
  7927. fileTree = createPTree();
  7928. fileTree->setProp("@name", fname.str());
  7929. fileTree->setProp("@cluster", cluster.str());
  7930. fileTree->setPropInt("@useCount", 1);
  7931. fileTree = filesRead->addPropTree("File", fileTree);
  7932. }
  7933. if (super)
  7934. {
  7935. fileTree->setPropBool("@super", true);
  7936. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  7937. ForEach (*iter)
  7938. {
  7939. IDistributedFile &file = iter->query();
  7940. StringBuffer fname;
  7941. file.getLogicalName(fname);
  7942. fileTree->addPropTree("Subfile")->setProp("@name", fname.str());
  7943. _noteFileRead(&file, filesRead);
  7944. }
  7945. }
  7946. }
  7947. }
  7948. void CLocalWorkUnit::_loadFilesRead() const
  7949. {
  7950. // Nothing to do
  7951. }
  7952. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  7953. {
  7954. if (file)
  7955. {
  7956. CriticalBlock block(crit);
  7957. IPropertyTree *files = p->queryPropTree("FilesRead");
  7958. if (!files)
  7959. files = p->addPropTree("FilesRead");
  7960. _noteFileRead(file, files);
  7961. }
  7962. }
  7963. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  7964. {
  7965. if (fieldUsage)
  7966. {
  7967. CriticalBlock block(crit);
  7968. p->addPropTree("usedsources", fieldUsage);
  7969. }
  7970. }
  7971. void CLocalWorkUnit::_loadFilesWritten() const
  7972. {
  7973. // Nothing to do
  7974. }
  7975. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  7976. {
  7977. StringBuffer path("File[@name=\"");
  7978. path.append(fileName).append("\"]");
  7979. if (cluster)
  7980. path.append("[@cluster=\"").append(cluster).append("\"]");
  7981. IPropertyTree *file = files->queryPropTree(path.str());
  7982. if (file) files->removeTree(file);
  7983. file = createPTree();
  7984. file->setProp("@name", fileName);
  7985. if (cluster)
  7986. file->setProp("@cluster", cluster);
  7987. if (graphOwner)
  7988. file->setProp("@graph", graphOwner);
  7989. file->setPropInt("@kind", (unsigned)fileKind);
  7990. if (WUFileTemporary == fileKind)
  7991. file->setPropInt("@usageCount", usageCount);
  7992. files->addPropTree("File", file);
  7993. }
  7994. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  7995. {
  7996. CriticalBlock block(crit);
  7997. IPropertyTree *files = p->queryPropTree("Files");
  7998. if (!files)
  7999. files = p->addPropTree("Files");
  8000. if (!clusters)
  8001. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  8002. else
  8003. {
  8004. ForEachItemIn(c, *clusters)
  8005. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  8006. }
  8007. }
  8008. void CLocalWorkUnit::releaseFile(const char *fileName)
  8009. {
  8010. StringBuffer path("File[@name=\"");
  8011. path.append(fileName).append("\"]");
  8012. CriticalBlock block(crit);
  8013. IPropertyTree *files = p->queryPropTree("Files");
  8014. if (!files) return;
  8015. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  8016. ForEach (*fiter)
  8017. {
  8018. IPropertyTree *file = &fiter->query();
  8019. unsigned usageCount = file->getPropInt("@usageCount");
  8020. if (usageCount > 1)
  8021. file->setPropInt("@usageCount", usageCount-1);
  8022. else
  8023. {
  8024. StringAttr name(file->queryProp("@name"));
  8025. files->removeTree(file);
  8026. if (!name.isEmpty()&&(1 == usageCount))
  8027. {
  8028. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  8029. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  8030. }
  8031. }
  8032. }
  8033. }
  8034. void CLocalWorkUnit::clearGraphProgress() const
  8035. {
  8036. }
  8037. void CLocalWorkUnit::resetBeforeGeneration()
  8038. {
  8039. CriticalBlock block(crit);
  8040. //Remove all associated files
  8041. Owned<IWUQuery> q = updateQuery();
  8042. q->removeAssociatedFiles();
  8043. //Remove any pre-existing workflow information
  8044. workflowIterator.clear();
  8045. p->removeProp("Workflow");
  8046. }
  8047. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  8048. {
  8049. StringBuffer path("Files/File[@name=\"");
  8050. path.append(fileName).append("\"]/@usageCount");
  8051. CriticalBlock block(crit);
  8052. return p->getPropInt(path.str());
  8053. }
  8054. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  8055. {
  8056. CriticalBlock block(crit);
  8057. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  8058. if (!fieldUsageTree)
  8059. return NULL;
  8060. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  8061. return new CConstWUFileUsageIterator(iter);
  8062. }
  8063. bool isFilenameResolved(StringBuffer& filename)
  8064. {
  8065. size32_t length = filename.length();
  8066. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  8067. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  8068. return true;
  8069. else
  8070. return false;
  8071. }
  8072. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  8073. {
  8074. bool scopeLoaded = false;
  8075. StringBuffer defaultScope;
  8076. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  8077. if (!files)
  8078. return false; // this query was not compiled with recordFieldUsage option.
  8079. ForEach(*files)
  8080. {
  8081. Owned<IConstWUFileUsage> file = files->get();
  8082. StringBuffer filename(file->queryName());
  8083. size32_t length = filename.length();
  8084. if (length == 0)
  8085. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8086. StringBuffer normalizedFilename;
  8087. // Two cases to handle:
  8088. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  8089. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  8090. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  8091. if (isFilenameResolved(filename))
  8092. {
  8093. // filename cannot be empty (i.e. empty single quotes '')
  8094. if (length == 2)
  8095. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  8096. // Remove surrounding single quotes
  8097. StringAttr cleanFilename(filename.str()+1, length-2);
  8098. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  8099. // We need to load a default scope from config and prefix the filename with it.
  8100. if (cleanFilename.str()[0] != '~')
  8101. {
  8102. // loading a default scope from config is expensive, and should be only done once and be reused later.
  8103. if (!scopeLoaded)
  8104. {
  8105. //MORE: This should actually depend on the cluster that was active when the file was read!
  8106. if (!resolveFilePrefix(defaultScope, clusterName))
  8107. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  8108. scopeLoaded = true;
  8109. }
  8110. normalizedFilename.append(defaultScope.str());
  8111. normalizedFilename.append(cleanFilename.str());
  8112. }
  8113. else
  8114. {
  8115. normalizedFilename.append(cleanFilename);
  8116. }
  8117. }
  8118. else
  8119. {
  8120. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  8121. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  8122. normalizedFilename.append(filename.str());
  8123. }
  8124. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  8125. ForEach(*fields)
  8126. {
  8127. Owned<IConstWUFieldUsage> field = fields->get();
  8128. filenames.append(normalizedFilename.str());
  8129. columnnames.append(field->queryName());
  8130. }
  8131. }
  8132. return true;
  8133. }
  8134. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  8135. {
  8136. return p->getPropTree("DiskUsageStats");
  8137. }
  8138. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  8139. {
  8140. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  8141. offset_t maxNodeUsage;
  8142. if (stats)
  8143. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  8144. else
  8145. {
  8146. stats = p->addPropTree("DiskUsageStats");
  8147. maxNodeUsage = 0;
  8148. }
  8149. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  8150. {
  8151. // record all details at time of max node usage.
  8152. stats->setPropInt("@minNode", _minNode);
  8153. stats->setPropInt("@maxNode", _maxNode);
  8154. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  8155. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  8156. stats->setPropInt64("@graphId", _graphId);
  8157. if (_avgNodeUsage)
  8158. {
  8159. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  8160. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  8161. stats->setPropInt("@skewHi", _skewHi);
  8162. stats->setPropInt("@skewLo", _skewLo);
  8163. }
  8164. }
  8165. }
  8166. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  8167. {
  8168. CriticalBlock block(crit);
  8169. _loadFilesWritten();
  8170. return * p->getElements("Files/File");
  8171. }
  8172. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  8173. {
  8174. CriticalBlock block(crit);
  8175. _loadFilesRead();
  8176. return * p->getElements("FilesRead/File");
  8177. }
  8178. //=================================================================================================
  8179. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  8180. {
  8181. CriticalBlock block(crit);
  8182. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  8183. return false;
  8184. const char * currentcluster = queryClusterName();
  8185. const char *wuid = p->queryName();
  8186. StringBuffer curqname;
  8187. getClusterThorQueueName(curqname, currentcluster);
  8188. void *qi = qs->getQ(curqname.str(),wuid);
  8189. if (!qi)
  8190. return false;
  8191. setClusterName(cluster);
  8192. StringBuffer newqname;
  8193. getClusterThorQueueName(newqname, cluster);
  8194. qs->putQ(newqname.str(),wuid,qi);
  8195. return true;
  8196. }
  8197. //=================================================================================================
  8198. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  8199. {
  8200. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  8201. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  8202. ForEach(*graphIter)
  8203. {
  8204. IConstWUGraph &graph = graphIter->query();
  8205. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  8206. SCMStringBuffer gName;
  8207. graph.getName(gName);
  8208. StringBuffer xpath("Graphs/Graph[@name=\"");
  8209. xpath.append(gName.s).append("\"]/xgmml");
  8210. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  8211. if (xgmml) // don't know of any reason it shouldn't exist
  8212. {
  8213. xgmml->removeProp("graphBin");
  8214. xgmml->setPropTree("graph", graphTree.getClear());
  8215. }
  8216. }
  8217. return ret.getClear();
  8218. }
  8219. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  8220. {
  8221. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  8222. ForEach(*iter)
  8223. {
  8224. IPropertyTree &graph = iter->query();
  8225. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  8226. }
  8227. }
  8228. void CLocalWorkUnit::loadGraphs(bool heavy) const
  8229. {
  8230. if (graphsCached < (heavy ? 2 : 1))
  8231. {
  8232. graphs.kill();
  8233. _loadGraphs(heavy);
  8234. graphsCached = (heavy ? 2 : 1);
  8235. }
  8236. }
  8237. EnumMapping graphTypes[] = {
  8238. { GraphTypeAny, "unknown" },
  8239. { GraphTypeProgress, "progress" },
  8240. { GraphTypeEcl, "ECL" },
  8241. { GraphTypeActivities, "activities" },
  8242. { GraphTypeSubProgress, "subgraph" },
  8243. { GraphTypeSize, NULL },
  8244. };
  8245. WUGraphType getGraphTypeFromString(const char* type)
  8246. {
  8247. return (WUGraphType) getEnum(type, graphTypes);
  8248. }
  8249. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  8250. {
  8251. wuidVersion = owner.getWuidVersion();
  8252. }
  8253. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  8254. {
  8255. str.set(p->queryProp("@name"));
  8256. return str;
  8257. }
  8258. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  8259. {
  8260. if (wuidVersion >= 2)
  8261. {
  8262. str.set(p->queryProp("@label"));
  8263. return str;
  8264. }
  8265. else
  8266. {
  8267. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  8268. str.set(xgmml->queryProp("@label"));
  8269. return str;
  8270. }
  8271. }
  8272. WUGraphState CLocalWUGraph::getState() const
  8273. {
  8274. return owner.queryGraphState(p->queryProp("@name"));
  8275. }
  8276. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  8277. {
  8278. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  8279. if (xgmml)
  8280. {
  8281. StringBuffer x;
  8282. toXML(xgmml, x);
  8283. str.set(x.str());
  8284. }
  8285. return str;
  8286. }
  8287. unsigned CLocalWorkUnit::getGraphCount() const
  8288. {
  8289. CriticalBlock block(crit);
  8290. if (p->hasProp("Graphs"))
  8291. {
  8292. return p->queryPropTree("Graphs")->numChildren();
  8293. }
  8294. return 0;
  8295. }
  8296. unsigned CLocalWorkUnit::getSourceFileCount() const
  8297. {
  8298. CriticalBlock block(crit);
  8299. _loadFilesRead();
  8300. if (p->hasProp("FilesRead"))
  8301. {
  8302. return p->queryPropTree("FilesRead")->numChildren();
  8303. }
  8304. return 0;
  8305. }
  8306. unsigned CLocalWorkUnit::getResultCount() const
  8307. {
  8308. CriticalBlock block(crit);
  8309. if (p->hasProp("Results"))
  8310. {
  8311. return p->queryPropTree("Results")->numChildren();
  8312. }
  8313. return 0;
  8314. }
  8315. unsigned CLocalWorkUnit::getVariableCount() const
  8316. {
  8317. CriticalBlock block(crit);
  8318. if (p->hasProp("Variables"))
  8319. {
  8320. return p->queryPropTree("Variables")->numChildren();
  8321. }
  8322. return 0;
  8323. }
  8324. unsigned CLocalWorkUnit::getApplicationValueCount() const
  8325. {
  8326. CriticalBlock block(crit);
  8327. if (p->hasProp("Application"))
  8328. {
  8329. return p->queryPropTree("Application")->numChildren();
  8330. }
  8331. return 0;
  8332. }
  8333. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent, bool hidePasswords)
  8334. {
  8335. appendXMLOpenTag(s, name, NULL, false);
  8336. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  8337. if (attrs->first())
  8338. {
  8339. unsigned attributeindent = indent + (size32_t) strlen(name);
  8340. unsigned count = attrs->count();
  8341. bool doindent = false;
  8342. ForEach(*attrs)
  8343. {
  8344. if (hidePasswords && streq(attrs->queryName(), "@token"))
  8345. continue;
  8346. #ifndef _DEBUG
  8347. if (hidePasswords && streq(attrs->queryName(), "@distributedAccessToken"))
  8348. continue;
  8349. #endif
  8350. if (doindent)
  8351. s.append('\n').appendN(attributeindent, ' ');
  8352. else if (count > 3)
  8353. doindent = true;
  8354. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  8355. }
  8356. }
  8357. s.append('>');
  8358. return s;
  8359. }
  8360. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  8361. {
  8362. CriticalBlock block(crit);
  8363. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  8364. if (!paramTree)
  8365. return str;
  8366. StringBuffer xml;
  8367. if (!hidePasswords)
  8368. toXML(paramTree, xml);
  8369. else
  8370. {
  8371. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0, false).append('\n');
  8372. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  8373. ForEach(*elems)
  8374. {
  8375. const char *paramname = elems->query().queryName();
  8376. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8377. if (p->getPropBool(xpath))
  8378. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  8379. else
  8380. toXML(&elems->query(), xml, 2);
  8381. }
  8382. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  8383. }
  8384. str.set(xml);
  8385. return str;
  8386. }
  8387. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  8388. {
  8389. CriticalBlock block(crit);
  8390. return p->getPropTree("Parameters");
  8391. }
  8392. void CLocalWorkUnit::setXmlParams(const char *params)
  8393. {
  8394. CriticalBlock block(crit);
  8395. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  8396. }
  8397. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  8398. {
  8399. CriticalBlock block(crit);
  8400. p->setPropTree("Parameters", tree);
  8401. }
  8402. unsigned __int64 CLocalWorkUnit::getHash() const
  8403. {
  8404. CriticalBlock block(crit);
  8405. return p->getPropInt64("@hash");
  8406. }
  8407. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  8408. {
  8409. CriticalBlock block(crit);
  8410. p->setPropInt64("@hash", hash);
  8411. }
  8412. // getGraphs / getGraphsMeta
  8413. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  8414. // If a type other than any is requested, a postfilter is needed.
  8415. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  8416. {
  8417. WUGraphType type;
  8418. Owned<T> base;
  8419. bool match()
  8420. {
  8421. return base->query().getType()==type;
  8422. }
  8423. public:
  8424. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  8425. : base(_base), type(_type)
  8426. {
  8427. }
  8428. bool first()
  8429. {
  8430. if (!base->first())
  8431. return false;
  8432. if (match())
  8433. return true;
  8434. return next();
  8435. }
  8436. bool next()
  8437. {
  8438. while (base->next())
  8439. if (match())
  8440. return true;
  8441. return false;
  8442. }
  8443. virtual bool isValid()
  8444. {
  8445. return base->isValid();
  8446. }
  8447. U & query()
  8448. {
  8449. return base->query();
  8450. }
  8451. };
  8452. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  8453. {
  8454. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  8455. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  8456. */
  8457. CriticalBlock block(crit);
  8458. loadGraphs(false);
  8459. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  8460. if (type!=GraphTypeAny)
  8461. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  8462. return *giter;
  8463. }
  8464. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  8465. {
  8466. CriticalBlock block(crit);
  8467. loadGraphs(true);
  8468. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  8469. if (type!=GraphTypeAny)
  8470. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  8471. return *giter;
  8472. }
  8473. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  8474. {
  8475. CriticalBlock block(crit);
  8476. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  8477. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  8478. IPTree *graph = p->queryPropTree(xpath);
  8479. if (graph)
  8480. return new CLocalWUGraph(*this, LINK(graph));
  8481. return NULL;
  8482. }
  8483. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid)
  8484. {
  8485. CriticalBlock block(crit);
  8486. if (!graphs.length())
  8487. p->addPropTree("Graphs");
  8488. IPropertyTree *r = p->queryPropTree("Graphs");
  8489. IPropertyTree *s = r->addPropTree("Graph");
  8490. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  8491. q->setName(name);
  8492. q->setLabel(label);
  8493. q->setType(type);
  8494. q->setWfid(wfid);
  8495. q->setXGMMLTree(xgmml);
  8496. graphs.append(*q);
  8497. }
  8498. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  8499. {
  8500. /* Owned<IRemoteConnection> conn = getProgressConnection();
  8501. if (conn)
  8502. {
  8503. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  8504. if (progress)
  8505. return new CConstGraphProgress(p->queryName(), graphName, progress);
  8506. }
  8507. */
  8508. return NULL;
  8509. }
  8510. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  8511. {
  8512. throwUnexpected(); // Should only be used for persisted workunits
  8513. }
  8514. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  8515. {
  8516. throwUnexpected(); // Should only be used for persisted workunits
  8517. }
  8518. void CLocalWorkUnit::setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const
  8519. {
  8520. throwUnexpected(); // Should only be used for persisted workunits
  8521. }
  8522. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  8523. {
  8524. throwUnexpected(); // Should only be used for persisted workunits
  8525. }
  8526. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const
  8527. {
  8528. return new CWuGraphStats(LINK(p), creatorType, creator, _wfid, graphName, subgraph);
  8529. }
  8530. void CLocalWUGraph::setName(const char *str)
  8531. {
  8532. p->setProp("@name", str);
  8533. }
  8534. void CLocalWUGraph::setLabel(const char *str)
  8535. {
  8536. p->setProp("@label", str);
  8537. }
  8538. void CLocalWUGraph::setWfid(unsigned wfid)
  8539. {
  8540. p->setPropInt("@wfid", wfid);
  8541. }
  8542. void CLocalWUGraph::setXGMML(const char *str)
  8543. {
  8544. setXGMMLTree(createPTreeFromXMLString(str,ipt_lowmem));
  8545. }
  8546. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  8547. {
  8548. assertex(strcmp(_graph->queryName(), "graph")==0);
  8549. IPropertyTree *xgmml = p->setPropTree("xgmml");
  8550. MemoryBuffer mb;
  8551. _graph->serialize(mb);
  8552. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  8553. // Cassandra workunit code actually lzw compresses the parent anyway
  8554. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  8555. graph.setown(_graph);
  8556. }
  8557. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  8558. {
  8559. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  8560. ForEach (*aIter)
  8561. {
  8562. const char *aName = aIter->queryName()+1;
  8563. if (0 != stricmp("id", aName)) // "id" reserved.
  8564. {
  8565. IPropertyTree *att = targetNode.addPropTree("att");
  8566. att->setProp("@name", aName);
  8567. att->setProp("@value", aIter->queryValue());
  8568. }
  8569. }
  8570. }
  8571. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  8572. {
  8573. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  8574. if (!graphNode) return;
  8575. unsigned nodeId = rootNode.getPropInt("@id");
  8576. StringBuffer progressNodePath("node[@id=\"");
  8577. progressNodePath.append(nodeId).append("\"]");
  8578. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  8579. if (progressNode)
  8580. {
  8581. expandAttributes(*graphNode, *progressNode);
  8582. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  8583. ForEach (*edges)
  8584. {
  8585. IPropertyTree &edge = edges->query();
  8586. StringBuffer edgePath("edge[@id=\"");
  8587. edgePath.append(edge.queryProp("@id")).append("\"]");
  8588. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  8589. if (graphEdge)
  8590. {
  8591. if (progressV < 1)
  8592. mergePTree(graphEdge, &edge);
  8593. else
  8594. { // must translate to XGMML format
  8595. expandAttributes(*graphEdge, edge);
  8596. // 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)
  8597. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  8598. ForEach (*iter)
  8599. {
  8600. IPropertyTree &t = iter->query();
  8601. IPropertyTree *att = graphEdge->addPropTree("att");
  8602. att->setProp("@name", t.queryName());
  8603. att->setProp("@value", t.queryProp(NULL));
  8604. }
  8605. }
  8606. }
  8607. }
  8608. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  8609. ForEach (*nodes)
  8610. {
  8611. IPropertyTree &node = nodes->query();
  8612. StringBuffer nodePath("node[@id=\"");
  8613. nodePath.append(node.queryProp("@id")).append("\"]");
  8614. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  8615. if (_node)
  8616. {
  8617. if (progressV < 1)
  8618. mergePTree(_node, &node);
  8619. else
  8620. { // must translate to XGMML format
  8621. expandAttributes(*_node, node);
  8622. }
  8623. }
  8624. }
  8625. }
  8626. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  8627. ForEach (*iter)
  8628. mergeProgress(iter->query(), progressTree, progressV);
  8629. }
  8630. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  8631. {
  8632. return p->getPropTree("xgmml");
  8633. }
  8634. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  8635. {
  8636. if (!graph)
  8637. {
  8638. // NB: although graphBin introduced in wuidVersion==2,
  8639. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  8640. MemoryBuffer mb;
  8641. if (p->getPropBin("xgmml/graphBin", mb))
  8642. graph.setown(createPTree(mb, ipt_lowmem));
  8643. else
  8644. graph.setown(p->getBranch("xgmml/graph"));
  8645. if (!graph)
  8646. return NULL;
  8647. }
  8648. if (!doMergeProgress)
  8649. return graph.getLink();
  8650. else
  8651. {
  8652. Owned<IPropertyTree> copy = createPTreeFromIPT(graph, ipt_lowmem);
  8653. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  8654. if (progress)
  8655. {
  8656. //MORE: Eventually this should directly access the new stats structure
  8657. unsigned progressV = progress->queryFormatVersion();
  8658. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  8659. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  8660. ForEach (*nodeIterator)
  8661. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  8662. }
  8663. return copy.getClear();
  8664. }
  8665. }
  8666. WUGraphType CLocalWUGraph::getType() const
  8667. {
  8668. return (WUGraphType) getEnum(p, "@type", graphTypes);
  8669. }
  8670. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  8671. {
  8672. str.set(p->queryProp("@type"));
  8673. if (!str.length())
  8674. str.set("unknown");
  8675. return str;
  8676. }
  8677. unsigned CLocalWUGraph::getWfid() const
  8678. {
  8679. return p->getPropInt("@wfid", 0);
  8680. }
  8681. void CLocalWUGraph::setType(WUGraphType _type)
  8682. {
  8683. setEnum(p, "@type", _type, graphTypes);
  8684. }
  8685. //=================================================================================================
  8686. EnumMapping queryFileTypes[] = {
  8687. { FileTypeCpp, "cpp" },
  8688. { FileTypeDll, "dll" },
  8689. { FileTypeResText, "res" },
  8690. { FileTypeHintXml, "hint" },
  8691. { FileTypeXml, "xml" },
  8692. { FileTypeLog, "log" },
  8693. { FileTypeSize, NULL },
  8694. };
  8695. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  8696. {
  8697. }
  8698. WUFileType CLocalWUAssociated::getType() const
  8699. {
  8700. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  8701. }
  8702. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  8703. {
  8704. str.set(p->queryProp("@desc"));
  8705. return str;
  8706. }
  8707. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  8708. {
  8709. str.set(p->queryProp("@ip"));
  8710. return str;
  8711. }
  8712. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  8713. {
  8714. str.set(p->queryProp("@filename"));
  8715. return str;
  8716. }
  8717. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  8718. {
  8719. str.set(pathTail(p->queryProp("@filename")));
  8720. return str;
  8721. }
  8722. unsigned CLocalWUAssociated::getCrc() const
  8723. {
  8724. return p->getPropInt("@crc", 0);
  8725. }
  8726. unsigned CLocalWUAssociated::getMinActivityId() const
  8727. {
  8728. return p->getPropInt("@minActivity", 0);
  8729. }
  8730. unsigned CLocalWUAssociated::getMaxActivityId() const
  8731. {
  8732. return p->getPropInt("@maxActivity", 0);
  8733. }
  8734. //=================================================================================================
  8735. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  8736. {
  8737. associatedCached = false;
  8738. }
  8739. EnumMapping queryTypes[] = {
  8740. { QueryTypeUnknown, "unknown" },
  8741. { QueryTypeEcl, "ECL" },
  8742. { QueryTypeSql, "SQL" },
  8743. { QueryTypeXml, "XML" },
  8744. { QueryTypeAttribute, "Attribute" },
  8745. { QueryTypeSize, NULL },
  8746. };
  8747. WUQueryType CLocalWUQuery::getQueryType() const
  8748. {
  8749. return (WUQueryType) getEnum(p, "@type", queryTypes);
  8750. }
  8751. void CLocalWUQuery::setQueryType(WUQueryType qt)
  8752. {
  8753. setEnum(p, "@type", qt, queryTypes);
  8754. }
  8755. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  8756. {
  8757. const char *text = p->queryProp("Text");
  8758. if (!text)
  8759. text = p->queryProp("ShortText");
  8760. str.set(text);
  8761. return str;
  8762. }
  8763. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  8764. {
  8765. const char * text = p->queryProp("ShortText");
  8766. if (text)
  8767. str.set(text);
  8768. else
  8769. {
  8770. text = p->queryProp("Text");
  8771. if (isArchiveQuery(text))
  8772. {
  8773. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8774. const char * path = xml->queryProp("Query/@attributePath");
  8775. if (path)
  8776. {
  8777. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8778. if (resolved)
  8779. str.set(resolved->queryProp(NULL));
  8780. }
  8781. else
  8782. str.set(xml->queryProp("Query"));
  8783. }
  8784. else
  8785. str.set(text);
  8786. }
  8787. return str;
  8788. }
  8789. bool CLocalWUQuery::isArchive() const
  8790. {
  8791. if (p->hasProp("@isArchive"))
  8792. return p->getPropBool("@isArchive");
  8793. const char *text = p->queryProp("Text");
  8794. return isArchiveQuery(text);
  8795. }
  8796. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  8797. {
  8798. str.set(p->queryProp("@name"));
  8799. return str;
  8800. }
  8801. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  8802. {
  8803. str.set(p->queryProp("@main"));
  8804. return str;
  8805. }
  8806. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  8807. {
  8808. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8809. if (entry)
  8810. entry->getNameTail(str);
  8811. return str;
  8812. }
  8813. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  8814. {
  8815. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  8816. if (entry)
  8817. entry->getName(str);
  8818. return str;
  8819. }
  8820. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  8821. {
  8822. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  8823. if (entry)
  8824. entry->getName(str);
  8825. return str;
  8826. }
  8827. unsigned CLocalWUQuery::getQueryDllCrc() const
  8828. {
  8829. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  8830. if (entry)
  8831. return entry->getCrc();
  8832. return 0;
  8833. }
  8834. void CLocalWUQuery::setQueryText(const char *text)
  8835. {
  8836. bool isArchive = isArchiveQuery(text);
  8837. if (isArchive)
  8838. {
  8839. p->setProp("Text", text);
  8840. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive|ipt_lowmem);
  8841. const char * path = xml->queryProp("Query/@attributePath");
  8842. if (path)
  8843. {
  8844. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  8845. if (resolved)
  8846. p->setProp("ShortText", resolved->queryProp(NULL));
  8847. }
  8848. else
  8849. p->setProp("ShortText", xml->queryProp("Query"));
  8850. }
  8851. else
  8852. {
  8853. p->setProp("Text", text); // At some point in the future we may be able to remove this,
  8854. // but as long as there may be new workunits compiled by old systems, we can't
  8855. p->setProp("ShortText", text);
  8856. }
  8857. p->setPropBool("@isArchive", isArchive);
  8858. if (isArchive)
  8859. p->setPropBool("@hasArchive", true); //preserved if setQueryText is called multiple times. Should setting this be more explicit?
  8860. }
  8861. void CLocalWUQuery::setQueryName(const char *qname)
  8862. {
  8863. p->setProp("@name", qname);
  8864. }
  8865. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  8866. {
  8867. p->setProp("@main", str);
  8868. }
  8869. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  8870. {
  8871. CriticalBlock block(crit);
  8872. loadAssociated();
  8873. StringBuffer xpath;
  8874. xpath.append("Associated/File[@filename=\"").append(name).append("\"]");
  8875. if (p->hasProp(xpath))
  8876. return;
  8877. if (!associated.length())
  8878. p->addPropTree("Associated");
  8879. IPropertyTree *pl = p->queryPropTree("Associated");
  8880. IPropertyTree *s = pl->addPropTree("File");
  8881. setEnum(s, "@type", type, queryFileTypes);
  8882. s->setProp("@filename", name);
  8883. s->setProp("@ip", ip);
  8884. s->setProp("@desc", desc);
  8885. if (crc)
  8886. s->setPropInt("@crc", crc);
  8887. if (minActivity)
  8888. s->setPropInt("@minActivity", minActivity);
  8889. if (maxActivity)
  8890. s->setPropInt("@maxActivity", maxActivity);
  8891. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  8892. associated.append(*q);
  8893. }
  8894. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  8895. {
  8896. CriticalBlock block(crit);
  8897. associatedCached = false;
  8898. associated.kill();
  8899. StringBuffer xpath;
  8900. xpath.append("Associated/File");
  8901. if (type)
  8902. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  8903. if (name)
  8904. xpath.append("[@filename=\"").append(name).append("\"]");
  8905. if (desc)
  8906. xpath.append("[@desc=\"").append(desc).append("\"]");
  8907. p->removeProp(xpath.str());
  8908. }
  8909. void CLocalWUQuery::removeAssociatedFiles()
  8910. {
  8911. associatedCached = false;
  8912. associated.kill();
  8913. p->removeProp("Associated");
  8914. }
  8915. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  8916. {
  8917. CriticalBlock block(crit);
  8918. loadAssociated();
  8919. ForEachItemIn(idx, associated)
  8920. {
  8921. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  8922. if (cur.getType() == type)
  8923. {
  8924. if (index-- == 0)
  8925. return &OLINK(cur);
  8926. }
  8927. }
  8928. return NULL;
  8929. }
  8930. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  8931. {
  8932. const char * name = p->queryProp(propname);
  8933. if (name)
  8934. {
  8935. IPropertyTree *s = createPTree("File");
  8936. setEnum(s, "@type", type, queryFileTypes);
  8937. s->setProp("@filename", name);
  8938. if (crc)
  8939. s->setPropInt("@crc", crc);
  8940. associated.append(*new CLocalWUAssociated(s));
  8941. }
  8942. }
  8943. void CLocalWUQuery::loadAssociated() const
  8944. {
  8945. CriticalBlock block(crit);
  8946. if (!associatedCached)
  8947. {
  8948. assertex(associated.length() == 0);
  8949. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  8950. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  8951. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  8952. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  8953. for (r->first(); r->isValid(); r->next())
  8954. {
  8955. IPropertyTree *rp = &r->query();
  8956. rp->Link();
  8957. associated.append(*new CLocalWUAssociated(rp));
  8958. }
  8959. associatedCached = true;
  8960. }
  8961. }
  8962. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  8963. {
  8964. CriticalBlock block(crit);
  8965. loadAssociated();
  8966. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  8967. }
  8968. //========================================================================================
  8969. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  8970. {
  8971. }
  8972. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  8973. {
  8974. str.set(p->queryProp("@module"));
  8975. return str;
  8976. }
  8977. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  8978. {
  8979. str.set(p->queryProp("@attribute"));
  8980. return str;
  8981. }
  8982. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  8983. {
  8984. str.set(p->queryProp("@defaultName"));
  8985. return str;
  8986. }
  8987. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  8988. {
  8989. return (unsigned) p->getPropInt("@crc");
  8990. }
  8991. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  8992. {
  8993. if (!name)
  8994. {
  8995. StringBuffer ws_info;
  8996. ws_info.appendf("<%s ", p->queryName());
  8997. Owned<IAttributeIterator> attrs = p->getAttributes();
  8998. for(attrs->first(); attrs->isValid(); attrs->next())
  8999. {
  9000. const char *name = attrs->queryName()+1;
  9001. const char *value = attrs->queryValue();
  9002. ws_info.appendf("%s='%s' ", name, value);
  9003. }
  9004. ws_info.append("> \n");
  9005. Owned<IPropertyTreeIterator> info = p->getElements("*");
  9006. ForEach(*info)
  9007. {
  9008. IPropertyTree &item = info->query();
  9009. const char *name = item.queryName();
  9010. if (name)
  9011. {
  9012. MemoryBuffer mb;
  9013. bool isbin = p->isBinary(name);
  9014. if (isbin)
  9015. {
  9016. p->getPropBin(name,mb);
  9017. if (mb.length())
  9018. {
  9019. unsigned len = 0;
  9020. mb.read(len);
  9021. StringBuffer encodedString;
  9022. StringBuffer val(len, (const char *) mb.readDirect(len));
  9023. encodeXML(val, encodedString);
  9024. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  9025. }
  9026. }
  9027. else
  9028. {
  9029. StringBuffer tmp;
  9030. toXML(&item, tmp);
  9031. ws_info.append(tmp.str());
  9032. }
  9033. }
  9034. }
  9035. ws_info.appendf("</%s>", p->queryName());
  9036. str.setLen(ws_info.str(), ws_info.length());
  9037. }
  9038. else
  9039. {
  9040. MemoryBuffer mb;
  9041. p->getPropBin(name,mb);
  9042. if (mb.length())
  9043. {
  9044. unsigned len;
  9045. mb.read(len);
  9046. str.setLen((const char *) mb.readDirect(len), len);
  9047. }
  9048. }
  9049. return str;
  9050. }
  9051. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  9052. {
  9053. str.set(p->queryProp(name));
  9054. return str;
  9055. }
  9056. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  9057. {
  9058. p->setProp("@module", mname);
  9059. }
  9060. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  9061. {
  9062. p->setProp("@attribute", aname);
  9063. }
  9064. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  9065. {
  9066. p->setProp("@defaultName", dname);
  9067. }
  9068. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  9069. {
  9070. p->setPropInt("@crc", crc);
  9071. }
  9072. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  9073. {
  9074. MemoryBuffer m;
  9075. unsigned len = (size32_t)strlen(info);
  9076. serializeLPString(len, info, m);
  9077. p->setPropBin(name, m.length(), m.toByteArray());
  9078. }
  9079. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  9080. {
  9081. p->setProp(name, info);
  9082. }
  9083. //========================================================================================
  9084. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  9085. {
  9086. }
  9087. EnumMapping resultStatuses[] = {
  9088. { ResultStatusUndefined, "undefined" },
  9089. { ResultStatusCalculated, "calculated" },
  9090. { ResultStatusSupplied, "supplied" },
  9091. { ResultStatusFailed, "failed" },
  9092. { ResultStatusPartial, "partial" },
  9093. { ResultStatusSize, NULL }
  9094. };
  9095. WUResultStatus CLocalWUResult::getResultStatus() const
  9096. {
  9097. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  9098. }
  9099. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  9100. {
  9101. str.set(p->queryProp("@name"));
  9102. return str;
  9103. }
  9104. int CLocalWUResult::getResultSequence() const
  9105. {
  9106. return p->getPropInt("@sequence", -1);
  9107. }
  9108. bool CLocalWUResult::isResultScalar() const
  9109. {
  9110. return p->getPropInt("@isScalar", 1) != 0;
  9111. }
  9112. bool findSize(int size, IntArray &sizes)
  9113. {
  9114. ForEachItemIn(idx, sizes)
  9115. {
  9116. if (sizes.item(idx)==size)
  9117. return true;
  9118. }
  9119. return false;
  9120. }
  9121. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  9122. {
  9123. MemoryBuffer schema;
  9124. p->getPropBin("SchemaRaw", schema);
  9125. if (schema.length())
  9126. {
  9127. for (;;)
  9128. {
  9129. StringAttr name;
  9130. schema.read(name);
  9131. if (*schema.readDirect(0)==type_void)
  9132. break;
  9133. names.append(*new StringAttrItem(name));
  9134. types.append(*deserializeType(schema)); // MORE - nested records!
  9135. }
  9136. schema.skip(1);
  9137. if (schema.length() != schema.getPos())
  9138. {
  9139. unsigned eclLen;
  9140. schema.read(eclLen);
  9141. const char * schemaData = (const char *)schema.readDirect(eclLen);
  9142. if (eclText)
  9143. {
  9144. eclText->setLen(schemaData, eclLen);
  9145. if ((eclLen == 0) && names.ordinality())
  9146. {
  9147. const char * firstName = names.item(0).text;
  9148. StringBuffer temp;
  9149. temp.append("RECORD ");
  9150. types.item(0).getECLType(temp);
  9151. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  9152. eclText->set(temp.str());
  9153. }
  9154. }
  9155. }
  9156. }
  9157. }
  9158. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  9159. {
  9160. ForEachItemIn(idx, types)
  9161. {
  9162. StringAttrItem &name = names.item(idx);
  9163. ITypeInfo &type = types.item(idx);
  9164. unsigned size = type.getSize();
  9165. switch(type.getTypeCode())
  9166. {
  9167. case type_data:
  9168. if (size==UNKNOWN_LENGTH)
  9169. {
  9170. if (in.remaining() < sizeof(int))
  9171. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9172. in.read(size);
  9173. }
  9174. outputXmlData(size, in.readDirect(size), name.text, out);
  9175. break;
  9176. case type_string:
  9177. if (size==UNKNOWN_LENGTH)
  9178. {
  9179. if (in.remaining() < sizeof(int))
  9180. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  9181. in.read(size);
  9182. }
  9183. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  9184. break;
  9185. case type_varstring:
  9186. {
  9187. if (size == UNKNOWN_LENGTH)
  9188. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  9189. const char * text = (const char *) in.readDirect(size);
  9190. outputXmlString((size32_t)strlen(text), text, name.text, out);
  9191. break;
  9192. }
  9193. case type_unicode:
  9194. {
  9195. unsigned len = type.getStringLen();
  9196. if (size==UNKNOWN_LENGTH)
  9197. in.read(len);
  9198. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  9199. }
  9200. break;
  9201. case type_utf8:
  9202. {
  9203. unsigned len = type.getStringLen();
  9204. if (size==UNKNOWN_LENGTH)
  9205. {
  9206. in.read(len);
  9207. size = rtlUtf8Size(len, in.readDirect(0));
  9208. }
  9209. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  9210. }
  9211. break;
  9212. case type_qstring:
  9213. {
  9214. unsigned len = type.getStringLen();
  9215. if (size==UNKNOWN_LENGTH)
  9216. in.read(len);
  9217. unsigned outlen;
  9218. char *outstr;
  9219. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  9220. outputXmlString(outlen, outstr, name.text, out);
  9221. free(outstr);
  9222. break;
  9223. }
  9224. case type_int:
  9225. case type_swapint:
  9226. if (type.isSigned())
  9227. {
  9228. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9229. unsigned __int64 cval8 = 0;
  9230. //MORE: I think this is wrong - swapped doesn't mean little/big/
  9231. if (type.isSwappedEndian())
  9232. {
  9233. unsigned idx = 0;
  9234. if (raw[idx] & 0x80)
  9235. cval8 = (__int64)-1;
  9236. while (size--)
  9237. cval8 = (cval8 << 8) | raw[idx++];
  9238. }
  9239. else
  9240. {
  9241. if (raw[size-1] & 0x80)
  9242. cval8 = (__int64)-1;
  9243. while (size--)
  9244. cval8 = (cval8 << 8) | raw[size];
  9245. }
  9246. outputXmlInt((__int64) cval8, name.text, out);
  9247. }
  9248. else
  9249. {
  9250. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  9251. unsigned __int64 cval8 = 0;
  9252. if (type.isSwappedEndian())
  9253. {
  9254. unsigned idx = 0;
  9255. while (size--)
  9256. cval8 = (cval8 << 8) | raw[idx++];
  9257. }
  9258. else
  9259. {
  9260. while (size--)
  9261. cval8 = (cval8 << 8) | raw[size];
  9262. }
  9263. outputXmlUInt(cval8, name.text, out);
  9264. }
  9265. break;
  9266. case type_boolean:
  9267. bool cvalb;
  9268. in.read(cvalb);
  9269. outputXmlBool(cvalb, name.text, out);
  9270. break;
  9271. case type_decimal:
  9272. if (type.isSigned())
  9273. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9274. else
  9275. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  9276. break;
  9277. case type_real:
  9278. double cvald;
  9279. switch(size)
  9280. {
  9281. case 4:
  9282. float cvalf;
  9283. in.read(cvalf);
  9284. cvald = cvalf;
  9285. break;
  9286. case 8:
  9287. in.read(cvald);
  9288. break;
  9289. default:
  9290. throwUnexpected();
  9291. }
  9292. outputXmlReal(cvald, name.text, out);
  9293. break;
  9294. default:
  9295. assertex(!"unexpected type in raw record");
  9296. break;
  9297. }
  9298. }
  9299. }
  9300. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  9301. {
  9302. TypeInfoArray types;
  9303. StringAttrArray names;
  9304. getSchema(types, names);
  9305. StringBuffer xml;
  9306. const char * name = p->queryProp("@name");
  9307. if (name)
  9308. xml.appendf("<Dataset name=\'%s\'>\n", name);
  9309. else
  9310. xml.append("<Dataset>\n");
  9311. if (hidePassword && p->getPropBool("Format/@password"))
  9312. {
  9313. xml.append(" <Row>");
  9314. appendXMLTag(xml, name, "****");
  9315. xml.append("</Row>\n");
  9316. }
  9317. else if (p->hasProp("Value"))
  9318. {
  9319. MemoryBuffer raw;
  9320. p->getPropBin("Value", raw);
  9321. unsigned __int64 numrows = getResultRowCount();
  9322. while (numrows--)
  9323. {
  9324. xml.append(" <Row>");
  9325. readRow(xml, raw, types, names);
  9326. xml.append("</Row>\n");
  9327. }
  9328. }
  9329. else if (p->hasProp("xmlValue"))
  9330. {
  9331. xml.append(" <Row>");
  9332. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  9333. xml.append("</Row>\n");
  9334. }
  9335. xml.append("</Dataset>\n");
  9336. str.set(xml.str());
  9337. return str;
  9338. }
  9339. IProperties *CLocalWUResult::queryResultXmlns()
  9340. {
  9341. CriticalBlock block(crit);
  9342. if (xmlns)
  9343. return xmlns;
  9344. xmlns.setown(createProperties());
  9345. Owned<IAttributeIterator> it = p->getAttributes();
  9346. unsigned prefixLen = strlen("@xmlns");
  9347. ForEach(*it)
  9348. {
  9349. const char *name = it->queryName();
  9350. if (!strncmp("@xmlns", name, prefixLen))
  9351. {
  9352. if (name[prefixLen]==':') //normal case
  9353. xmlns->setProp(name+prefixLen+1, it->queryValue());
  9354. else if (!name[prefixLen]) //special case, unprefixed namespace
  9355. xmlns->setProp("xmlns", it->queryValue());
  9356. }
  9357. }
  9358. return xmlns;
  9359. }
  9360. unsigned CLocalWUResult::getResultFetchSize() const
  9361. {
  9362. return p->getPropInt("fetchSize", 100);
  9363. }
  9364. __int64 CLocalWUResult::getResultTotalRowCount() const
  9365. {
  9366. return p->getPropInt64("totalRowCount", -1);
  9367. }
  9368. __int64 CLocalWUResult::getResultRowCount() const
  9369. {
  9370. return p->getPropInt64("rowCount", 0);
  9371. }
  9372. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  9373. {
  9374. ecl.set(p->queryProp("datasetEcl"));
  9375. defs.set(p->queryProp("datasetEclDefs"));
  9376. }
  9377. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  9378. {
  9379. val.set(p->queryProp("logicalName"));
  9380. return val;
  9381. }
  9382. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  9383. {
  9384. ecl.set(p->queryProp("keyField"));
  9385. return ecl;
  9386. }
  9387. unsigned CLocalWUResult::getResultRequestedRows() const
  9388. {
  9389. return p->getPropInt("requestedRows", 1);
  9390. }
  9391. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  9392. {
  9393. TypeInfoArray types;
  9394. StringAttrArray names;
  9395. getSchema(types, names, &str);
  9396. return str;
  9397. }
  9398. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  9399. {
  9400. str.set(p->queryProp("@recordSizeEntry"));
  9401. return str;
  9402. }
  9403. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  9404. {
  9405. str.set(p->queryProp("@transformerEntry"));
  9406. return str;
  9407. }
  9408. __int64 CLocalWUResult::getResultRowLimit() const
  9409. {
  9410. return p->getPropInt64("@rowLimit");
  9411. }
  9412. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  9413. {
  9414. str.set(p->queryProp("@tempFilename"));
  9415. return str;
  9416. }
  9417. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  9418. {
  9419. str.clear();
  9420. if (!name || !*name)
  9421. return str;
  9422. IPropertyTree *format = p->queryPropTree("Format");
  9423. if (!format)
  9424. return str;
  9425. VStringBuffer xpath("@%s", name);
  9426. str.set(format->queryProp(xpath));
  9427. return str;
  9428. }
  9429. void CLocalWUResult::getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const
  9430. {
  9431. _graph.set(p->queryProp("@graph"));
  9432. _activityId = p->getPropInt("@activity", 0);
  9433. }
  9434. void CLocalWUResult::setResultStatus(WUResultStatus status)
  9435. {
  9436. setEnum(p, "@status", status, resultStatuses);
  9437. if (status==ResultStatusUndefined)
  9438. {
  9439. p->removeProp("Value");
  9440. p->removeProp("totalRowCount");
  9441. p->removeProp("rowCount");
  9442. p->removeProp("@format");
  9443. p->removeProp("@tempFileNmae");
  9444. p->removeProp("logicalName");
  9445. }
  9446. }
  9447. void CLocalWUResult::setResultName(const char *s)
  9448. {
  9449. p->setProp("@name", s);
  9450. }
  9451. void CLocalWUResult::setResultSequence(unsigned seq)
  9452. {
  9453. p->setPropInt("@sequence", seq);
  9454. }
  9455. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  9456. {
  9457. p->setPropBin("SchemaRaw", size, schema);
  9458. }
  9459. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  9460. {
  9461. StringBuffer xpath("@xmlns");
  9462. if (prefix && *prefix)
  9463. xpath.append(':').append(prefix);
  9464. p->setProp(xpath, uri);
  9465. }
  9466. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  9467. {
  9468. if (!name || !*name)
  9469. return;
  9470. IPropertyTree *format = ensurePTree(p, "Format");
  9471. VStringBuffer xpath("@%s", name);
  9472. format->setProp(xpath, value);
  9473. }
  9474. void CLocalWUResult::setResultWriteLocation(const char * _graph, unsigned _activityId)
  9475. {
  9476. p->setProp("@graph", _graph);
  9477. p->setPropInt("@activity", _activityId);
  9478. }
  9479. void CLocalWUResult::setResultScalar(bool isScalar)
  9480. {
  9481. p->setPropInt("@isScalar", (int) isScalar);
  9482. if (isScalar)
  9483. setResultTotalRowCount(1);
  9484. }
  9485. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  9486. {
  9487. p->setPropBin("Value", len, data);
  9488. setResultStatus(ResultStatusSupplied);
  9489. setResultFormat(format);
  9490. }
  9491. void CLocalWUResult::setResultFormat(WUResultFormat format)
  9492. {
  9493. switch (format)
  9494. {
  9495. case ResultFormatXml:
  9496. p->setProp("@format","xml");
  9497. break;
  9498. case ResultFormatXmlSet:
  9499. p->setProp("@format","xmlSet");
  9500. break;
  9501. case ResultFormatCsv:
  9502. p->setProp("@format","csv");
  9503. break;
  9504. default:
  9505. p->removeProp("@format");
  9506. break;
  9507. }
  9508. }
  9509. void CLocalWUResult::setResultXML(const char *val)
  9510. {
  9511. p->setProp("xmlValue", val);
  9512. }
  9513. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  9514. {
  9515. p->appendPropBin("Value", len, data);
  9516. setResultStatus(ResultStatusPartial);
  9517. const char *existingFormat = p->queryProp("@format");
  9518. const char *formatStr = NULL;
  9519. switch (format)
  9520. {
  9521. case ResultFormatXml:
  9522. formatStr = "xml";
  9523. break;
  9524. case ResultFormatXmlSet:
  9525. formatStr = "xmlSet";
  9526. break;
  9527. case ResultFormatCsv:
  9528. formatStr = "csv";
  9529. break;
  9530. default:
  9531. existingFormat = nullptr;
  9532. p->removeProp("@format");
  9533. break;
  9534. }
  9535. if (format)
  9536. {
  9537. if (existingFormat)
  9538. {
  9539. if (0 != stricmp(formatStr, existingFormat))
  9540. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  9541. }
  9542. else
  9543. p->setProp("@format", formatStr);
  9544. }
  9545. }
  9546. void CLocalWUResult::setResultFetchSize(unsigned rows)
  9547. {
  9548. p->setPropInt("fetchSize", rows);
  9549. }
  9550. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  9551. {
  9552. p->setPropInt64("totalRowCount", rows);
  9553. }
  9554. void CLocalWUResult::setResultRowCount(__int64 rows)
  9555. {
  9556. p->setPropInt64("rowCount", rows);
  9557. }
  9558. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  9559. {
  9560. p->setProp("datasetEcl", ecl);
  9561. p->setProp("datasetEclDefs", defs);
  9562. }
  9563. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  9564. {
  9565. p->setProp("logicalName", logicalName);
  9566. }
  9567. void CLocalWUResult::setResultKeyField(const char *ecl)
  9568. {
  9569. p->setProp("keyField", ecl);
  9570. }
  9571. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  9572. {
  9573. p->setPropInt("requestedRows", rows);
  9574. }
  9575. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  9576. {
  9577. p->setProp("@recordSizeEntry", entry);
  9578. }
  9579. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  9580. {
  9581. p->setProp("@transformerEntry", entry);
  9582. }
  9583. void CLocalWUResult::setResultRowLimit(__int64 value)
  9584. {
  9585. p->setPropInt64("@rowLimit", value);
  9586. }
  9587. void CLocalWUResult::setResultFilename(const char * name)
  9588. {
  9589. p->setProp("@tempFilename", name);
  9590. }
  9591. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  9592. __int64 CLocalWUResult::getResultInt() const
  9593. {
  9594. __int64 result = 0;
  9595. MemoryBuffer s;
  9596. p->getPropBin("Value", s);
  9597. if (s.length())
  9598. s.read(result);
  9599. else
  9600. result = p->getPropInt64("xmlValue");
  9601. return result;
  9602. }
  9603. bool CLocalWUResult::getResultBool() const
  9604. {
  9605. bool result = false;
  9606. MemoryBuffer s;
  9607. p->getPropBin("Value", s);
  9608. if (s.length())
  9609. s.read(result);
  9610. else
  9611. result = p->getPropBool("xmlValue");
  9612. return result;
  9613. }
  9614. double CLocalWUResult::getResultReal() const
  9615. {
  9616. double result = 0;
  9617. MemoryBuffer s;
  9618. p->getPropBin("Value", s);
  9619. if (s.length())
  9620. s.read(result);
  9621. else
  9622. {
  9623. const char *xmlVal = p->queryProp("xmlValue");
  9624. if (xmlVal)
  9625. result = atof(xmlVal);
  9626. }
  9627. return result;
  9628. }
  9629. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  9630. {
  9631. MemoryBuffer s;
  9632. p->getPropBin("Value", s);
  9633. if (s.length())
  9634. {
  9635. assertex(s.length() == len);
  9636. s.read(len, val);
  9637. }
  9638. else
  9639. {
  9640. const char *xmlVal = p->queryProp("xmlValue");
  9641. if (xmlVal)
  9642. {
  9643. Decimal d;
  9644. d.setString(strlen(xmlVal), xmlVal);
  9645. if (isSigned)
  9646. d.getDecimal(len, precision, val);
  9647. else
  9648. d.getUDecimal(len, precision, val);
  9649. }
  9650. else
  9651. memset(val, 0, len);
  9652. }
  9653. }
  9654. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  9655. {
  9656. if (hidePassword && p->getPropBool("@password"))
  9657. {
  9658. str.set("****");
  9659. return str;
  9660. }
  9661. MemoryBuffer s;
  9662. p->getPropBin("Value", s);
  9663. if (s.length())
  9664. {
  9665. unsigned len;
  9666. s.read(len);
  9667. str.setLen((const char *) s.readDirect(len), len);
  9668. }
  9669. else
  9670. {
  9671. p->getPropBin("xmlValue", s);
  9672. if (p->isBinary("xmlValue"))
  9673. str.setLen(s.toByteArray(), s.length());
  9674. else
  9675. {
  9676. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  9677. str.set(ascii);
  9678. rtlFree(ascii);
  9679. }
  9680. }
  9681. return str;
  9682. }
  9683. WUResultFormat CLocalWUResult::getResultFormat() const
  9684. {
  9685. const char * format = p->queryProp("@format");
  9686. if (!format)
  9687. return ResultFormatRaw;
  9688. else if (strcmp(format, "xml") == 0)
  9689. return ResultFormatXml;
  9690. else if (strcmp(format, "xmlSet") == 0)
  9691. return ResultFormatXmlSet;
  9692. else if (strcmp(format, "csv") == 0)
  9693. return ResultFormatCsv;
  9694. else
  9695. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  9696. }
  9697. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9698. {
  9699. MemoryBuffer s;
  9700. p->getPropBin("Value", s);
  9701. unsigned len = s.length();
  9702. if (len)
  9703. {
  9704. WUResultFormat format = getResultFormat();
  9705. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  9706. {
  9707. if (!xmlTransformer)
  9708. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  9709. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  9710. }
  9711. else if (format == ResultFormatCsv)
  9712. {
  9713. if (!csvTransformer)
  9714. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  9715. csvTransformer->transform(data, len, s.readDirect(len), true);
  9716. }
  9717. else
  9718. data.setLen(s.readDirect(len), len);
  9719. }
  9720. else
  9721. data.clear();
  9722. return data;
  9723. }
  9724. unsigned CLocalWUResult::getResultHash() const
  9725. {
  9726. MemoryBuffer s;
  9727. p->getPropBin("Value", s);
  9728. unsigned len = s.length();
  9729. const byte * data = (const byte *)s.toByteArray();
  9730. return ~hashc(data, len, ~0);
  9731. }
  9732. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  9733. {
  9734. MemoryBuffer s;
  9735. p->getPropBin("Value", s);
  9736. if (s.length())
  9737. {
  9738. unsigned len;
  9739. s.read(len);
  9740. data.setLen(s.readDirect(len*2), len*2);
  9741. }
  9742. else
  9743. {
  9744. StringBuffer utf8;
  9745. if (p->getProp("xmlValue", utf8))
  9746. {
  9747. unsigned outlen;
  9748. UChar *out;
  9749. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  9750. data.setLen(out, outlen*2);
  9751. rtlFree(out);
  9752. }
  9753. else
  9754. data.clear();
  9755. }
  9756. return data;
  9757. }
  9758. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9759. {
  9760. WUResultFormat format = getResultFormat();
  9761. if (format == ResultFormatRaw)
  9762. {
  9763. //MORE: This should not load the whole property...
  9764. MemoryBuffer s;
  9765. p->getPropBin("Value", s);
  9766. return s.length();
  9767. }
  9768. else
  9769. {
  9770. MemoryBuffer temp;
  9771. MemoryBuffer2IDataVal adaptor(temp);
  9772. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9773. return temp.length();
  9774. }
  9775. }
  9776. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  9777. {
  9778. WUResultFormat format = getResultFormat();
  9779. if (format != ResultFormatRaw)
  9780. {
  9781. MemoryBuffer temp;
  9782. MemoryBuffer2IDataVal adaptor(temp);
  9783. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  9784. unsigned len = temp.length();
  9785. if (from > len) from = len;
  9786. if (from + length > len) length = len - from;
  9787. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  9788. return data;
  9789. }
  9790. else
  9791. {
  9792. //MORE: This should not load the whole property, and should be different from the code above...
  9793. MemoryBuffer s;
  9794. p->getPropBin("Value", s);
  9795. unsigned len = s.length();
  9796. if (from > len) from = len;
  9797. if (from + length > len) length = len - from;
  9798. data.setLen(s.readDirect(len) + from, (size32_t)length);
  9799. return data;
  9800. }
  9801. }
  9802. bool CLocalWUResult::getResultIsAll() const
  9803. {
  9804. return p->getPropBool("@isAll", false);
  9805. }
  9806. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  9807. void CLocalWUResult::setResultInt(__int64 val)
  9808. {
  9809. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  9810. MemoryBuffer m;
  9811. serializeInt8(val, m);
  9812. p->setPropBin("Value", m.length(), m.toByteArray());
  9813. setResultRowCount(1);
  9814. setResultTotalRowCount(1);
  9815. }
  9816. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  9817. {
  9818. setResultInt((__int64) val);
  9819. }
  9820. void CLocalWUResult::setResultReal(double val)
  9821. {
  9822. // Note: we always serialize scalar real results as real8, and schema must reflect this
  9823. MemoryBuffer m;
  9824. serializeReal8(val, m);
  9825. p->setPropBin("Value", m.length(), m.toByteArray());
  9826. setResultRowCount(1);
  9827. setResultTotalRowCount(1);
  9828. }
  9829. void CLocalWUResult::setResultBool(bool val)
  9830. {
  9831. MemoryBuffer m;
  9832. serializeBool(val, m);
  9833. p->setPropBin("Value", m.length(), m.toByteArray());
  9834. setResultRowCount(1);
  9835. setResultTotalRowCount(1);
  9836. }
  9837. void CLocalWUResult::setResultString(const char *val, unsigned len)
  9838. {
  9839. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9840. MemoryBuffer m;
  9841. serializeLPString(len, val, m);
  9842. p->setPropBin("Value", m.length(), m.toByteArray());
  9843. setResultRowCount(1);
  9844. setResultTotalRowCount(1);
  9845. }
  9846. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  9847. {
  9848. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  9849. MemoryBuffer m;
  9850. m.append(len).append(len*2, val);
  9851. p->setPropBin("Value", m.length(), m.toByteArray());
  9852. setResultRowCount(1);
  9853. setResultTotalRowCount(1);
  9854. }
  9855. void CLocalWUResult::setResultData(const void *val, unsigned len)
  9856. {
  9857. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  9858. MemoryBuffer m;
  9859. serializeLPString(len, (const char *)val, m);
  9860. p->setPropBin("Value", m.length(), m.toByteArray());
  9861. setResultRowCount(1);
  9862. setResultTotalRowCount(1);
  9863. }
  9864. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  9865. {
  9866. // Note: serialized as data but with length known from schema
  9867. MemoryBuffer m;
  9868. serializeFixedData(len, val, m);
  9869. p->setPropBin("Value", m.length(), m.toByteArray());
  9870. setResultRowCount(1);
  9871. setResultTotalRowCount(1);
  9872. }
  9873. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  9874. {
  9875. p->setPropBin("Value", len, data);
  9876. setResultRowCount(1);
  9877. setResultTotalRowCount(1);
  9878. setResultFormat(ResultFormatRaw);
  9879. }
  9880. void CLocalWUResult::setResultIsAll(bool value)
  9881. {
  9882. p->setPropBool("@isAll", value);
  9883. }
  9884. //==========================================================================================
  9885. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  9886. {
  9887. }
  9888. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  9889. {
  9890. str.set(p->queryProp("@dllname"));
  9891. return str;
  9892. }
  9893. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  9894. {
  9895. str.set(p->queryProp("@version"));
  9896. return str;
  9897. }
  9898. void CLocalWUPlugin::setPluginName(const char *str)
  9899. {
  9900. p->setProp("@dllname", str);
  9901. }
  9902. void CLocalWUPlugin::setPluginVersion(const char *str)
  9903. {
  9904. p->setProp("@version", str);
  9905. }
  9906. //==========================================================================================
  9907. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  9908. {
  9909. }
  9910. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  9911. {
  9912. str.set(p->queryProp("@name"));
  9913. return str;
  9914. }
  9915. void CLocalWULibrary::setName(const char *str)
  9916. {
  9917. p->setProp("@name", str);
  9918. }
  9919. //==========================================================================================
  9920. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  9921. {
  9922. }
  9923. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  9924. {
  9925. str.set(p->queryProp("@source"));
  9926. return str;
  9927. }
  9928. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  9929. {
  9930. str.set(p->queryProp(NULL));
  9931. return str;
  9932. }
  9933. unsigned CLocalWUException::getExceptionCode() const
  9934. {
  9935. return p->getPropInt("@code", 0);
  9936. }
  9937. ErrorSeverity CLocalWUException::getSeverity() const
  9938. {
  9939. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  9940. }
  9941. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  9942. {
  9943. dt.set(p->queryProp("@time"));
  9944. return dt;
  9945. }
  9946. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  9947. {
  9948. str.set(p->queryProp("@filename"));
  9949. return str;
  9950. }
  9951. unsigned CLocalWUException::getExceptionLineNo() const
  9952. {
  9953. return p->getPropInt("@row", 0);
  9954. }
  9955. unsigned CLocalWUException::getExceptionColumn() const
  9956. {
  9957. return p->getPropInt("@col", 0);
  9958. }
  9959. unsigned CLocalWUException::getActivityId() const
  9960. {
  9961. const char * scope = queryScope();
  9962. if (scope)
  9963. {
  9964. const char * colon = strrchr(scope, ':');
  9965. if (colon && hasPrefix(colon+1, ActivityScopePrefix, true))
  9966. return atoi(colon+1+strlen(ActivityScopePrefix));
  9967. }
  9968. return p->getPropInt("@activity", 0);
  9969. }
  9970. unsigned CLocalWUException::getSequence() const
  9971. {
  9972. return p->getPropInt("@sequence", 0);
  9973. }
  9974. const char * CLocalWUException::queryScope() const
  9975. {
  9976. return p->queryProp("@scope");
  9977. }
  9978. unsigned CLocalWUException::getPriority() const
  9979. {
  9980. return p->getPropInt("@prio", 0);
  9981. }
  9982. void CLocalWUException::setExceptionSource(const char *str)
  9983. {
  9984. p->setProp("@source", str);
  9985. }
  9986. void CLocalWUException::setExceptionMessage(const char *str)
  9987. {
  9988. p->setProp(NULL, str);
  9989. }
  9990. void CLocalWUException::setExceptionCode(unsigned code)
  9991. {
  9992. p->setPropInt("@code", code);
  9993. }
  9994. void CLocalWUException::setSeverity(ErrorSeverity level)
  9995. {
  9996. p->setPropInt("@severity", level);
  9997. }
  9998. void CLocalWUException::setTimeStamp(const char *str)
  9999. {
  10000. p->setProp("@time", str);
  10001. }
  10002. void CLocalWUException::setExceptionFileName(const char *str)
  10003. {
  10004. p->setProp("@filename", str);
  10005. }
  10006. void CLocalWUException::setExceptionLineNo(unsigned r)
  10007. {
  10008. p->setPropInt("@row", r);
  10009. }
  10010. void CLocalWUException::setExceptionColumn(unsigned c)
  10011. {
  10012. p->setPropInt("@col", c);
  10013. }
  10014. void CLocalWUException::setActivityId(unsigned _id)
  10015. {
  10016. p->setPropInt("@activity", _id);
  10017. }
  10018. void CLocalWUException::setScope(const char * _scope)
  10019. {
  10020. p->setProp("@scope", _scope);
  10021. }
  10022. void CLocalWUException::setPriority(unsigned _priority)
  10023. {
  10024. p->setPropInt("@prio", _priority);
  10025. }
  10026. //==========================================================================================
  10027. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  10028. {
  10029. StringAttrBuilder propPath(prop);
  10030. propPath.append("*[").append(child).append("]");
  10031. }
  10032. const char * CLocalWUAppValue::queryApplication() const
  10033. {
  10034. return p->queryName();
  10035. }
  10036. const char * CLocalWUAppValue::queryName() const
  10037. {
  10038. IPropertyTree* val=p->queryPropTree(prop.str());
  10039. if(val)
  10040. return val->queryName();
  10041. return ""; // Should not happen in normal usage
  10042. }
  10043. const char * CLocalWUAppValue::queryValue() const
  10044. {
  10045. return p->queryProp(prop.str());
  10046. }
  10047. //==========================================================================================
  10048. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  10049. {
  10050. }
  10051. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  10052. {
  10053. const char * creator = p->queryProp("@creator");
  10054. str.set(creator);
  10055. return str;
  10056. }
  10057. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  10058. {
  10059. const char * desc = p->queryProp("@desc");
  10060. if (desc)
  10061. {
  10062. str.set(desc); // legacy and in case it is overridden
  10063. }
  10064. else if (createDefault)
  10065. {
  10066. StatisticKind kind = getKind();
  10067. assertex(kind != StKindNone);
  10068. const char * scope = p->queryProp("@scope");
  10069. assertex(scope);
  10070. //Clean up the format of the scope when converting it to a description
  10071. StringBuffer descriptionText;
  10072. if (isGlobalScope(scope))
  10073. {
  10074. const char * creator = p->queryProp("@creator");
  10075. descriptionText.append(creator).append(":");
  10076. queryLongStatisticName(descriptionText, kind);
  10077. }
  10078. else
  10079. {
  10080. for (;;)
  10081. {
  10082. char c = *scope++;
  10083. if (!c)
  10084. break;
  10085. if (c == ':')
  10086. descriptionText.append(": ");
  10087. else
  10088. descriptionText.append(c);
  10089. }
  10090. if (kind != StTimeElapsed)
  10091. queryLongStatisticName(descriptionText.append(": "), kind);
  10092. }
  10093. str.set(descriptionText);
  10094. }
  10095. else
  10096. str.clear();
  10097. return str;
  10098. }
  10099. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  10100. {
  10101. StringBuffer formatted;
  10102. formatStatistic(formatted, getValue(), getMeasure());
  10103. str.set(formatted);
  10104. return str;
  10105. }
  10106. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  10107. {
  10108. return queryCreatorType(p->queryProp("@c"), SCTnone);
  10109. }
  10110. StatisticScopeType CLocalWUStatistic::getScopeType() const
  10111. {
  10112. return queryScopeType(p->queryProp("@s"), SSTnone);
  10113. }
  10114. StatisticKind CLocalWUStatistic::getKind() const
  10115. {
  10116. return queryStatisticKind(p->queryProp("@kind"), StKindNone);
  10117. }
  10118. const char * CLocalWUStatistic::queryScope() const
  10119. {
  10120. const char * scope = p->queryProp("@scope");
  10121. if (scope && streq(scope, LEGACY_GLOBAL_SCOPE))
  10122. scope = GLOBAL_SCOPE;
  10123. return scope;
  10124. }
  10125. StatisticMeasure CLocalWUStatistic::getMeasure() const
  10126. {
  10127. return queryMeasure(p->queryProp("@unit"), SMeasureNone);
  10128. }
  10129. unsigned __int64 CLocalWUStatistic::getValue() const
  10130. {
  10131. return p->getPropInt64("@value", 0);
  10132. }
  10133. unsigned __int64 CLocalWUStatistic::getCount() const
  10134. {
  10135. return p->getPropInt64("@count", 0);
  10136. }
  10137. unsigned __int64 CLocalWUStatistic::getMax() const
  10138. {
  10139. return p->getPropInt64("@max", 0);
  10140. }
  10141. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  10142. {
  10143. return p->getPropInt64("@ts", 0);
  10144. }
  10145. //==========================================================================================
  10146. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  10147. {
  10148. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  10149. if (xml)
  10150. cw->loadPTree(createPTreeFromXMLString(xml, ipt_lowmem));
  10151. else
  10152. {
  10153. Owned<IPropertyTree> p = createPTree("W_LOCAL", ipt_lowmem);
  10154. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  10155. cw->loadPTree(p.getClear());
  10156. }
  10157. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  10158. return ret;
  10159. }
  10160. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  10161. {
  10162. const char *name = p->queryName();
  10163. if (!name)
  10164. name = "__unnamed__";
  10165. StringBuffer temp;
  10166. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1, true));
  10167. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  10168. ForEach(*elems)
  10169. {
  10170. IPropertyTree &elem = elems->query();
  10171. if (streq(elem.queryName(), "Parameters"))
  10172. {
  10173. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2, false).append('\n'));
  10174. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  10175. ForEach(*params)
  10176. {
  10177. IPropertyTree &param = params->query();
  10178. const char *paramname = param.queryName();
  10179. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  10180. if (p->getPropBool(xpath))
  10181. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  10182. else
  10183. {
  10184. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10185. }
  10186. }
  10187. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  10188. }
  10189. else if (streq(elem.queryName(), "Variables"))
  10190. {
  10191. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2, false).append('\n'));
  10192. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  10193. ForEach(*vars)
  10194. {
  10195. Owned<IPropertyTree> var = LINK(&vars->query());
  10196. if (var->getPropBool("Format/@password"))
  10197. {
  10198. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  10199. var->removeProp("Value");
  10200. var->removeProp("xmlValue");
  10201. }
  10202. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  10203. }
  10204. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  10205. }
  10206. else
  10207. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  10208. }
  10209. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  10210. }
  10211. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  10212. {
  10213. class CAdapter : public CInterface, implements IIOStream
  10214. {
  10215. StringBuffer &out;
  10216. public:
  10217. IMPLEMENT_IINTERFACE;
  10218. CAdapter(StringBuffer &_out) : out(_out) { }
  10219. virtual void flush() { }
  10220. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  10221. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  10222. } adapter(str);
  10223. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  10224. return str;
  10225. }
  10226. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  10227. {
  10228. OwnedIFile ifile = createIFile(filename);
  10229. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  10230. Owned<IIOStream> stream = createIOStream(ifileio);
  10231. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  10232. }
  10233. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  10234. {
  10235. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  10236. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10237. if (ewu)
  10238. {
  10239. Linked<IPropertyTree> p;
  10240. if (unpack||includeProgress)
  10241. p.setown(ewu->getUnpackedTree(includeProgress));
  10242. else
  10243. p.set(ewu->queryPTree());
  10244. if (hidePasswords)
  10245. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  10246. else
  10247. return toXML(p, str, 0, XML_Format|XML_SortTags);
  10248. }
  10249. else
  10250. return str.append("Unrecognized workunit format");
  10251. }
  10252. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool regressionTest)
  10253. {
  10254. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  10255. if (ewu)
  10256. {
  10257. Linked<IPropertyTree> p;
  10258. if (unpack||includeProgress)
  10259. p.setown(ewu->getUnpackedTree(includeProgress));
  10260. else if (regressionTest)
  10261. p.setown(createPTreeFromIPT(ewu->queryPTree()));
  10262. else
  10263. p.set(ewu->queryPTree());
  10264. if (hidePasswords)
  10265. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  10266. if (regressionTest)
  10267. {
  10268. //This removes any items from the xml that will vary from run to run, so they can be binary compared from run to run
  10269. //The following attributes change with the build. Simpler to remove rather than needing to updated each build
  10270. p->removeProp("@buildVersion");
  10271. p->removeProp("@eclVersion");
  10272. p->removeProp("@hash");
  10273. //Remove statistics, and extract them to a separate file
  10274. IPropertyTree * stats = p->queryPropTree("Statistics");
  10275. if (stats)
  10276. {
  10277. StringBuffer statsFilename;
  10278. statsFilename.append(filename).append(".stats");
  10279. saveXML(statsFilename, stats, 0, (XML_Format|XML_SortTags|extraXmlFlags) & ~XML_LineBreakAttributes);
  10280. p->removeProp("Statistics");
  10281. }
  10282. //Now remove timestamps from exceptions
  10283. Owned<IPropertyTreeIterator> elems = p->getElements("Exceptions/Exception", iptiter_sort);
  10284. ForEach(*elems)
  10285. {
  10286. IPropertyTree &elem = elems->query();
  10287. elem.removeProp("@time");
  10288. }
  10289. }
  10290. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  10291. }
  10292. else
  10293. throw makeStringException(0, "Unrecognized workunit format");
  10294. }
  10295. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  10296. {
  10297. MemoryBuffer buffer;
  10298. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  10299. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  10300. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  10301. assertex(workunit);
  10302. StringAttr clusterName(workunit->queryClusterName());
  10303. if (!clusterName.length())
  10304. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  10305. workunit->commit();
  10306. workunit.clear();
  10307. StringBuffer serverQueue;
  10308. getClusterEclCCServerQueueName(serverQueue, clusterName);
  10309. assertex(serverQueue.length());
  10310. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  10311. if (!queue.get())
  10312. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  10313. IJobQueueItem *item = createJobQueueItem(wuid);
  10314. queue->enqueue(item);
  10315. }
  10316. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  10317. {
  10318. StringBuffer xpath("/WorkUnitAborts/");
  10319. xpath.append(wuid);
  10320. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  10321. acon->queryRoot()->setPropInt(NULL, 1);
  10322. }
  10323. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10324. {
  10325. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10326. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  10327. }
  10328. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  10329. {
  10330. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  10331. return;
  10332. abortWorkUnit(wuid);
  10333. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  10334. if(!cw)
  10335. return;
  10336. WorkunitUpdate wu(&cw->lock());
  10337. const char *abortBy = secuser.getName();
  10338. if (abortBy && *abortBy)
  10339. wu->setTracingValue("AbortBy", abortBy);
  10340. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  10341. }
  10342. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10343. {
  10344. if (secmgr && secuser)
  10345. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  10346. if (secuser)
  10347. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  10348. submitWorkUnit(wuid, "", "");
  10349. }
  10350. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  10351. {
  10352. if (secmgr && secuser)
  10353. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  10354. abortWorkUnit(wuid);
  10355. }
  10356. bool CLocalWorkUnit::hasWorkflow() const
  10357. {
  10358. return p->hasProp("Workflow");
  10359. }
  10360. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  10361. {
  10362. CriticalBlock block(crit);
  10363. if (p->hasProp("@eventScheduledCount"))
  10364. return p->getPropInt("@eventScheduledCount", 0);
  10365. else
  10366. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  10367. }
  10368. void CLocalWorkUnit::incEventScheduledCount()
  10369. {
  10370. CriticalBlock block(crit);
  10371. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  10372. }
  10373. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  10374. {
  10375. CriticalBlock block(crit);
  10376. return p->queryPropTree("Workflow");
  10377. }
  10378. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  10379. {
  10380. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10381. CriticalBlock block(crit);
  10382. if(!workflowIteratorCached)
  10383. {
  10384. assertex(!workflowIterator);
  10385. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  10386. if(s)
  10387. workflowIterator.setown(createWorkflowItemIterator(s));
  10388. workflowIteratorCached = true;
  10389. }
  10390. return workflowIterator.getLink();
  10391. }
  10392. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  10393. {
  10394. unsigned count = 0;
  10395. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10396. for(iter->first(); iter->isValid(); iter->next())
  10397. count++;
  10398. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  10399. for(iter->first(); iter->isValid(); iter->next())
  10400. array->addClone(iter->query());
  10401. return array.getLink();
  10402. }
  10403. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  10404. {
  10405. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10406. CriticalBlock block(crit);
  10407. workflowIterator.clear();
  10408. workflowIteratorCached = false;
  10409. IPropertyTree * s = p->queryPropTree("Workflow");
  10410. if(!s)
  10411. s = p->addPropTree("Workflow");
  10412. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  10413. }
  10414. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  10415. {
  10416. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10417. CriticalBlock block(crit);
  10418. if(!workflowIterator)
  10419. {
  10420. IPropertyTree * s = p->queryPropTree("Workflow");
  10421. if(!s)
  10422. s = p->addPropTree("Workflow");
  10423. workflowIterator.setown(createWorkflowItemIterator(s));
  10424. workflowIteratorCached = true;
  10425. }
  10426. return workflowIterator.getLink();
  10427. }
  10428. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  10429. {
  10430. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10431. Owned<IWorkflowItem> item;
  10432. for(iter->first(); iter->isValid(); iter->next())
  10433. {
  10434. item.setown(iter->get());
  10435. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  10436. }
  10437. workflowIterator.clear();
  10438. workflowIteratorCached = false;
  10439. }
  10440. void CLocalWorkUnit::resetWorkflow()
  10441. {
  10442. if (hasWorkflow())
  10443. {
  10444. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  10445. Owned<IWorkflowItem> wf;
  10446. for(iter->first(); iter->isValid(); iter->next())
  10447. {
  10448. wf.setown(iter->get());
  10449. wf->reset();
  10450. }
  10451. workflowIterator.clear();
  10452. workflowIteratorCached = false;
  10453. }
  10454. }
  10455. void CLocalWorkUnit::schedule()
  10456. {
  10457. CriticalBlock block(crit);
  10458. if(queryEventScheduledCount() == 0) return;
  10459. switch(getState())
  10460. {
  10461. case WUStateCompleted:
  10462. setState(WUStateWait);
  10463. break;
  10464. case WUStateFailed:
  10465. case WUStateArchived:
  10466. case WUStateAborting:
  10467. case WUStateAborted:
  10468. case WUStateScheduled:
  10469. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  10470. }
  10471. StringBuffer rootPath;
  10472. rootPath.append("/Schedule/").append(queryClusterName());
  10473. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10474. Owned<IPropertyTree> root = conn->getRoot();
  10475. if(!root->hasChildren())
  10476. {
  10477. StringBuffer addPath;
  10478. addPath.append("/Schedulers/").append(queryClusterName());
  10479. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  10480. }
  10481. char const * wuid = p->queryName();
  10482. StringBuffer xpath("*/*/");
  10483. ncnameEscape(wuid, xpath);
  10484. bool more;
  10485. do more = root->removeProp(xpath.str()); while(more);
  10486. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  10487. Owned<IWorkflowEvent> event;
  10488. Owned<IPropertyTree> branch1, branch2;
  10489. for(iter->first(); iter->isValid(); iter->next())
  10490. {
  10491. event.setown(iter->query()->getScheduleEvent());
  10492. if(!event) continue;
  10493. ncnameEscape(event->queryName(), xpath.clear());
  10494. ensurePTree(root, xpath.str());
  10495. branch1.setown(root->getPropTree(xpath.str()));
  10496. ncnameEscape(event->queryText(), xpath.clear());
  10497. ensurePTree(branch1, xpath.str());
  10498. branch2.setown(branch1->getPropTree(xpath.str()));
  10499. ncnameEscape(wuid, xpath.clear());
  10500. ensurePTree(branch2, xpath.str());
  10501. }
  10502. }
  10503. void CLocalWorkUnit::deschedule()
  10504. {
  10505. if(queryEventScheduledCount() == 0) return;
  10506. if(getState() == WUStateWait)
  10507. setState(WUStateCompleted);
  10508. doDescheduleWorkkunit(p->queryName());
  10509. }
  10510. EnumMapping localFileUploadTypes[] = {
  10511. { UploadTypeFileSpray, "FileSpray" },
  10512. { UploadTypeWUResult, "WUResult" },
  10513. { UploadTypeWUResultCsv, "WUResultCsv" },
  10514. { UploadTypeWUResultXml, "WUResultXml" },
  10515. { UploadTypeSize, NULL }
  10516. };
  10517. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  10518. {
  10519. public:
  10520. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  10521. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10522. {
  10523. tree.setown(createPTree());
  10524. tree->setPropInt("@id", id);
  10525. setEnum(tree, "@type", type, localFileUploadTypes);
  10526. tree->setProp("@source", source);
  10527. tree->setProp("@destination", destination);
  10528. if (eventTag)
  10529. tree->setProp("@eventTag", eventTag);
  10530. }
  10531. IMPLEMENT_IINTERFACE;
  10532. IPropertyTree * getTree() { return tree.getLink(); }
  10533. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  10534. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  10535. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  10536. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  10537. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  10538. private:
  10539. Owned<IPropertyTree> tree;
  10540. };
  10541. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  10542. {
  10543. public:
  10544. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  10545. IMPLEMENT_IINTERFACE;
  10546. bool first() { return iter->first(); }
  10547. bool isValid() { return iter->isValid(); }
  10548. bool next() { return iter->next(); }
  10549. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  10550. private:
  10551. Owned<IPropertyTree> tree;
  10552. Owned<IPropertyTreeIterator> iter;
  10553. };
  10554. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  10555. {
  10556. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  10557. CriticalBlock block(crit);
  10558. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  10559. if(s)
  10560. return new CLocalFileUploadIterator(s.getClear());
  10561. else
  10562. return NULL;
  10563. }
  10564. bool CLocalWorkUnit::requiresLocalFileUpload() const
  10565. {
  10566. SCMStringBuffer dest;
  10567. Owned<IConstWUResult> result;
  10568. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  10569. if(!iter)
  10570. return false;
  10571. for(iter->first(); iter->isValid(); iter->next())
  10572. {
  10573. Owned<IConstLocalFileUpload> upload(iter->get());
  10574. switch(upload->queryType())
  10575. {
  10576. case UploadTypeWUResult:
  10577. case UploadTypeWUResultCsv:
  10578. case UploadTypeWUResultXml:
  10579. upload->getDestination(dest);
  10580. result.setown(getResultByName(dest.str()));
  10581. if(!result)
  10582. return true;
  10583. break;
  10584. default:
  10585. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  10586. }
  10587. }
  10588. return false;
  10589. }
  10590. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  10591. {
  10592. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  10593. CriticalBlock block(crit);
  10594. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  10595. if(!s)
  10596. s = p->addPropTree("LocalFileUploads");
  10597. unsigned id = s->numChildren();
  10598. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  10599. s->addPropTree("LocalFileUpload", upload->getTree());
  10600. return id;
  10601. }
  10602. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  10603. {
  10604. CriticalBlock block(crit);
  10605. str.set(p->queryProp("Tracing/AbortBy"));
  10606. return str;
  10607. }
  10608. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  10609. {
  10610. CriticalBlock block(crit);
  10611. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  10612. }
  10613. #if 0
  10614. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  10615. {
  10616. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  10617. unsigned deps = 0;
  10618. Owned<IWorkflowDependencyIterator> diter;
  10619. switch(cwf->queryWfid())
  10620. {
  10621. case 1:
  10622. assertex(!cwf->isScheduled());
  10623. assertex(cwf->queryType() == WFTypeNormal);
  10624. assertex(cwf->queryState() == WFStateNull);
  10625. diter.setown(cwf->getDependencies());
  10626. for(diter->first(); diter->isValid(); diter->next())
  10627. deps++;
  10628. assertex(deps==0);
  10629. okay[0] = true;
  10630. break;
  10631. case 2:
  10632. assertex(!cwf->isScheduled());
  10633. assertex(cwf->queryType() == WFTypeRecovery);
  10634. assertex(cwf->queryState() == WFStateSkip);
  10635. okay[1] = true;
  10636. break;
  10637. case 3:
  10638. assertex(cwf->queryContingencyFor() == 4);
  10639. okay[2] = true;
  10640. break;
  10641. case 4:
  10642. assertex(cwf->isScheduled());
  10643. assertex(cwf->queryType() == WFTypeNormal);
  10644. assertex(cwf->queryState() == WFStateReqd);
  10645. assertex(cwf->querySuccess() == 0);
  10646. assertex(cwf->queryFailure() == 3);
  10647. assertex(cwf->queryRecovery() == 2);
  10648. assertex(cwf->queryRetriesAllowed() == 10);
  10649. assertex(cwf->queryRetriesRemaining() == 10);
  10650. diter.setown(cwf->getDependencies());
  10651. for(diter->first(); diter->isValid(); diter->next())
  10652. {
  10653. dep[diter->query()-1] = true;
  10654. deps++;
  10655. }
  10656. assertex(deps==2);
  10657. assertex(dep[0]);
  10658. assertex(dep[1]);
  10659. okay[3] = true;
  10660. break;
  10661. case 5:
  10662. assertex(cwf->isScheduled());
  10663. assertex(!cwf->isScheduledNow());
  10664. assertex(cwf->querySchedulePriority() == 75);
  10665. assertex(cwf->queryScheduleCount() == 5);
  10666. assertex(cwf->queryScheduleCountRemaining() == 5);
  10667. okay[4] = true;
  10668. break;
  10669. case 6:
  10670. assertex(cwf->isScheduled());
  10671. assertex(!cwf->isScheduledNow());
  10672. assertex(cwf->querySchedulePriority() == 25);
  10673. assertex(!cwf->hasScheduleCount());
  10674. okay[5] = true;
  10675. break;
  10676. default:
  10677. assertex(!"unknown wfid in test");
  10678. }
  10679. }
  10680. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  10681. {
  10682. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  10683. switch(rwf->queryWfid())
  10684. {
  10685. case 1:
  10686. case 2:
  10687. case 3:
  10688. okay[rwf->queryWfid()-1] = true;
  10689. break;
  10690. case 4:
  10691. {
  10692. unsigned tries = 0;
  10693. while(rwf->testAndDecRetries())
  10694. tries++;
  10695. assertex(tries == 10);
  10696. assertex(rwf->queryRetriesRemaining() == 0);
  10697. rwf->setState(WFStateFail);
  10698. assertex(rwf->queryState() == WFStateFail);
  10699. rwf->reset();
  10700. assertex(rwf->queryRetriesRemaining() == 10);
  10701. assertex(rwf->queryState() == WFStateReqd);
  10702. }
  10703. okay[3] = true;
  10704. break;
  10705. case 5:
  10706. {
  10707. assertex(rwf->queryScheduleCountRemaining() == 5);
  10708. unsigned count = 0;
  10709. do count++; while(rwf->decAndTestScheduleCountRemaining());
  10710. assertex(count == 5);
  10711. assertex(rwf->queryScheduleCountRemaining() == 0);
  10712. rwf->reset();
  10713. assertex(rwf->queryScheduleCountRemaining() == 5);
  10714. }
  10715. okay[4] = true;
  10716. break;
  10717. case 6:
  10718. {
  10719. assertex(!rwf->hasScheduleCount());
  10720. unsigned count;
  10721. for(count=0; count<20; count++)
  10722. assertex(rwf->decAndTestScheduleCountRemaining());
  10723. }
  10724. okay[5] = true;
  10725. break;
  10726. default:
  10727. assertex(!"unknown wfid in test");
  10728. }
  10729. }
  10730. void testWorkflow()
  10731. {
  10732. DBGLOG("workunit.cpp : testWorkflow");
  10733. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  10734. Owned<IWorkflowItem> wf;
  10735. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  10736. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  10737. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  10738. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  10739. wf->setScheduledNow();
  10740. wf->addDependency(1);
  10741. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  10742. wf->setScheduledOn("test", "foo*");
  10743. wf->setSchedulePriority(75);
  10744. wf->setScheduleCount(5);
  10745. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  10746. wf->setScheduledOn("test", "bar*");
  10747. wf->setSchedulePriority(25);
  10748. unsigned const n = 6;
  10749. bool okay[n];
  10750. bool dep[n];
  10751. unsigned i;
  10752. for(i=0; i<n; i++)
  10753. okay[i] = dep[i] = 0;
  10754. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  10755. for(citer->first(); citer->isValid(); citer->next())
  10756. testConstWorkflow(citer->query(), okay, dep);
  10757. for(i=0; i<n; i++)
  10758. {
  10759. assertex(okay[i]);
  10760. okay[i] = false;
  10761. }
  10762. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  10763. for(miter->first(); miter->isValid(); miter->next())
  10764. {
  10765. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  10766. testRuntimeWorkflow(rwf, okay);
  10767. }
  10768. for(i=0; i<n; i++)
  10769. {
  10770. assertex(okay[i]);
  10771. okay[i] = dep[i] = false;
  10772. }
  10773. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  10774. unsigned wfid;
  10775. for(wfid = 1; array->isValid(wfid); wfid++)
  10776. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  10777. for(i=0; i<n; i++)
  10778. {
  10779. assertex(okay[i]);
  10780. okay[i] = false;
  10781. }
  10782. for(wfid = 1; array->isValid(wfid); wfid++)
  10783. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  10784. for(i=0; i<n; i++)
  10785. {
  10786. assertex(okay[i]);
  10787. okay[i] = false;
  10788. }
  10789. }
  10790. #endif
  10791. //------------------------------------------------------------------------------------------
  10792. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, std::list<WUState> expectedStates)
  10793. {
  10794. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, expectedStates);
  10795. }
  10796. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, std::list<WUState> expectedStates)
  10797. {
  10798. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  10799. return waitForWorkUnitToComplete(wuid, timeout, expectedStates);
  10800. return WUStateUnknown;
  10801. }
  10802. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  10803. {
  10804. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, { WUStateWait }))
  10805. {
  10806. case WUStateCompiled:
  10807. case WUStateCompleted:
  10808. case WUStateWait:
  10809. case WUStateUploadingFiles:
  10810. return true;
  10811. default:
  10812. return false;
  10813. }
  10814. }
  10815. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  10816. {
  10817. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  10818. return waitForWorkUnitToCompile(wuid, timeout);
  10819. return false;
  10820. }
  10821. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  10822. {
  10823. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  10824. {
  10825. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  10826. SCMStringBuffer ip;
  10827. unsigned port;
  10828. try
  10829. {
  10830. port = wu->getDebugAgentListenerPort();
  10831. wu->getDebugAgentListenerIP(ip);
  10832. SocketEndpoint debugEP(ip.str(), port);
  10833. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  10834. unsigned len = (size32_t)strlen(command);
  10835. unsigned revlen = len;
  10836. _WINREV(revlen);
  10837. socket->write(&revlen, sizeof(revlen));
  10838. socket->write(command, len);
  10839. for (;;)
  10840. {
  10841. socket->read(&len, sizeof(len));
  10842. _WINREV(len);
  10843. if (len == 0)
  10844. break;
  10845. if (len & 0x80000000)
  10846. {
  10847. throwUnexpected();
  10848. }
  10849. char * mem = (char*) response.reserve(len);
  10850. socket->read(mem, len);
  10851. }
  10852. return true;
  10853. }
  10854. catch (IException *E)
  10855. {
  10856. VStringBuffer msg("In secDebugWorkunit wuid %s port %d ip %s command %s", wuid, port, ip.str(), command);
  10857. EXCLOG(E, msg.str());
  10858. throw;
  10859. }
  10860. }
  10861. return false;
  10862. }
  10863. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  10864. {
  10865. TypeInfoArray types;
  10866. StringAttrArray names;
  10867. r->getSchema(types, names, NULL);
  10868. if (types.ordinality()==1)
  10869. type.set(&types.item(0));
  10870. }
  10871. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  10872. {
  10873. if (!r->isResultScalar())
  10874. return false;
  10875. if (!curVal.hasChildren())
  10876. return true;
  10877. getSimpleResultType(r, type);
  10878. return type && type->isScalar();
  10879. }
  10880. void updateSuppliedXmlParams(IWorkUnit * w)
  10881. {
  10882. Owned<const IPropertyTree> params = w->getXmlParams();
  10883. if (!params)
  10884. return;
  10885. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  10886. ForEach(*elems)
  10887. {
  10888. IPropertyTree & curVal = elems->query();
  10889. const char *name = curVal.queryName();
  10890. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  10891. if (r)
  10892. {
  10893. Owned<ITypeInfo> type;
  10894. StringBuffer s;
  10895. if (isSuppliedParamScalar(r, curVal, type))
  10896. {
  10897. curVal.getProp(".", s);
  10898. r->setResultXML(s);
  10899. r->setResultStatus(ResultStatusSupplied);
  10900. }
  10901. else
  10902. {
  10903. toXML(&curVal, s);
  10904. if (!type)
  10905. getSimpleResultType(r, type);
  10906. bool isSet = (type && type->getTypeCode()==type_set);
  10907. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  10908. }
  10909. }
  10910. else
  10911. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  10912. }
  10913. }
  10914. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  10915. {
  10916. switch ((int)sequence)
  10917. {
  10918. case ResultSequenceStored:
  10919. return w->updateVariableByName(name);
  10920. case ResultSequencePersist:
  10921. return w->updateGlobalByName(name);
  10922. case ResultSequenceInternal:
  10923. case ResultSequenceOnce:
  10924. return w->updateTemporaryByName(name);
  10925. default:
  10926. return w->updateResultBySequence(sequence);
  10927. }
  10928. }
  10929. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  10930. {
  10931. switch ((int)sequence)
  10932. {
  10933. case ResultSequenceStored:
  10934. return w->getVariableByName(name);
  10935. case ResultSequencePersist:
  10936. return w->getGlobalByName(name);
  10937. case ResultSequenceInternal:
  10938. case ResultSequenceOnce:
  10939. return w->getTemporaryByName(name);
  10940. default:
  10941. if (name && name[0])
  10942. return w->getResultByName(name);//name takes precedence over sequence
  10943. else
  10944. return w->getResultBySequence(sequence);
  10945. }
  10946. }
  10947. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  10948. {
  10949. if (wuid) {
  10950. char prefchar;
  10951. unsigned year,month,day,hour,min,sec;
  10952. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  10953. time.set(year, month, day, hour, min, sec, 0, true);
  10954. // time.setDate(year, month, day);
  10955. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  10956. return true;
  10957. }
  10958. }
  10959. return false;
  10960. }
  10961. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  10962. {
  10963. return (WUState) getEnum(state, states);
  10964. }
  10965. constexpr LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  10966. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  10967. {
  10968. public:
  10969. CWorkflowScheduleConnection(char const * wuid)
  10970. {
  10971. basexpath.append("/WorkflowSchedule/").append(wuid);
  10972. flagxpath.append(basexpath.str()).append("/Active");
  10973. }
  10974. IMPLEMENT_IINTERFACE;
  10975. virtual void lock()
  10976. {
  10977. LOG(MCschedconn, "Locking base schedule connection");
  10978. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  10979. if(!baseconn)
  10980. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  10981. }
  10982. virtual void unlock()
  10983. {
  10984. LOG(MCschedconn, "Unlocking base schedule connection");
  10985. baseconn.clear();
  10986. }
  10987. virtual void setActive()
  10988. {
  10989. LOG(MCschedconn, "Setting active flag in schedule connection");
  10990. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  10991. if(!flagconn)
  10992. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  10993. }
  10994. virtual void resetActive()
  10995. {
  10996. LOG(MCschedconn, "Resetting active flag in schedule connection");
  10997. flagconn.clear();
  10998. }
  10999. virtual bool queryActive()
  11000. {
  11001. return baseconn->queryRoot()->hasProp("Active");
  11002. }
  11003. virtual bool pull(IWorkflowItemArray * workflow)
  11004. {
  11005. assertex(baseconn);
  11006. Owned<IPropertyTree> root = baseconn->getRoot();
  11007. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  11008. if(!eventQueue) return false;
  11009. if(!eventQueue->hasProp("Item")) return false;
  11010. {
  11011. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  11012. Owned<IPropertyTree> eventItem;
  11013. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  11014. Owned<IRuntimeWorkflowItem> wfItem;
  11015. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  11016. {
  11017. eventItem.setown(&eventItems->get());
  11018. const char * eventName = eventItem->queryProp("@name");
  11019. const char * eventText = eventItem->queryProp("@text");
  11020. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  11021. {
  11022. wfItem.setown(wfItems->get());
  11023. if(wfItem->queryState() != WFStateWait)
  11024. continue;
  11025. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  11026. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  11027. continue;
  11028. wfItem->setEvent(eventName, eventText);
  11029. wfItem->setState(WFStateReqd);
  11030. resetDependentsState(workflow, *wfItem);
  11031. }
  11032. }
  11033. }
  11034. bool more;
  11035. do
  11036. more = eventQueue->removeProp("Item");
  11037. while(more);
  11038. return true;
  11039. }
  11040. virtual void push(char const * name, char const * text)
  11041. {
  11042. assertex(baseconn);
  11043. Owned<IPropertyTree> root = baseconn->getRoot();
  11044. IPropertyTree *eventQueue = ensurePTree(root, "EventQueue");
  11045. IPropertyTree *eventItem = eventQueue->addPropTree("Item");
  11046. eventItem->setProp("@name", name);
  11047. eventItem->setProp("@text", text);
  11048. }
  11049. virtual void remove()
  11050. {
  11051. if (baseconn)
  11052. {
  11053. baseconn->close(true);
  11054. baseconn.clear();
  11055. }
  11056. }
  11057. private:
  11058. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  11059. {
  11060. if (wfid)
  11061. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  11062. }
  11063. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11064. {
  11065. switch(item.queryState())
  11066. {
  11067. case WFStateDone:
  11068. case WFStateFail:
  11069. {
  11070. item.setState(WFStateNull);
  11071. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  11072. resetDependentsState(workflow, item);
  11073. break;
  11074. }
  11075. }
  11076. }
  11077. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  11078. {
  11079. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  11080. for(iter->first(); iter->isValid(); iter->next())
  11081. {
  11082. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  11083. resetItemStateAndDependents(workflow, dep);
  11084. }
  11085. }
  11086. private:
  11087. StringBuffer basexpath;
  11088. StringBuffer flagxpath;
  11089. Owned<IRemoteConnection> baseconn;
  11090. Owned<IRemoteConnection> flagconn;
  11091. };
  11092. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  11093. {
  11094. return new CWorkflowScheduleConnection(wuid);
  11095. }
  11096. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  11097. {
  11098. return QUERYINTERFACE(wu, IExtendedWUInterface);
  11099. }
  11100. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  11101. {
  11102. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  11103. }
  11104. 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)
  11105. {
  11106. Owned<IWUException> we = wu->createException();
  11107. we->setSeverity(severity);
  11108. we->setExceptionMessage(text);
  11109. if (source)
  11110. we->setExceptionSource(source);
  11111. if (code)
  11112. we->setExceptionCode(code);
  11113. if (filename)
  11114. we->setExceptionFileName(filename);
  11115. if (lineno)
  11116. {
  11117. we->setExceptionLineNo(lineno);
  11118. if (column)
  11119. we->setExceptionColumn(lineno);
  11120. }
  11121. if (activity)
  11122. we->setActivityId(activity);
  11123. }
  11124. const char * skipLeadingXml(const char * text)
  11125. {
  11126. if (!text)
  11127. return NULL;
  11128. //skip utf8 BOM, probably excessive
  11129. if (memcmp(text, UTF8_BOM, 3) == 0)
  11130. text += 3;
  11131. for (;;)
  11132. {
  11133. if (isspace(*text))
  11134. text++;
  11135. else if (text[0] == '<' && text[1] == '?')
  11136. {
  11137. text += 2;
  11138. for (;;)
  11139. {
  11140. if (!*text) break;
  11141. if (text[0] == '?' && text[1] == '>')
  11142. {
  11143. text += 2;
  11144. break;
  11145. }
  11146. text++;
  11147. }
  11148. }
  11149. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  11150. {
  11151. text += 4;
  11152. for (;;)
  11153. {
  11154. if (!*text) break;
  11155. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  11156. {
  11157. text += 3;
  11158. break;
  11159. }
  11160. text++;
  11161. }
  11162. }
  11163. else
  11164. break;
  11165. }
  11166. return text;
  11167. }
  11168. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  11169. {
  11170. text = skipLeadingXml(text);
  11171. if (!text)
  11172. return false;
  11173. const char * archivePrefix = "<Archive";
  11174. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  11175. }
  11176. extern WORKUNIT_API bool isQueryManifest(const char * text)
  11177. {
  11178. text = skipLeadingXml(text);
  11179. if (!text)
  11180. return false;
  11181. const char * manifestPrefix = "<Manifest";
  11182. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  11183. }
  11184. //------------------------------------------------------------------------------
  11185. // Named Alias helper function
  11186. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  11187. {
  11188. StringBuffer xpath;
  11189. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  11190. return queryRegistry->getPropTree(xpath);
  11191. }
  11192. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  11193. {
  11194. StringBuffer xpath;
  11195. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  11196. return queryRegistry->getPropTree(xpath);
  11197. }
  11198. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  11199. {
  11200. StringBuffer lcId(id);
  11201. lcId.toLowerCase();
  11202. StringBuffer xpath;
  11203. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  11204. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11205. ForEach(*iter)
  11206. {
  11207. queryRegistry->removeProp(xpath.str());
  11208. }
  11209. }
  11210. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  11211. {
  11212. StringBuffer lcName(name);
  11213. lcName.toLowerCase();
  11214. StringBuffer xpath;
  11215. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  11216. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  11217. unsigned seq = 1;
  11218. ForEach(*iter)
  11219. {
  11220. IPropertyTree &item = iter->query();
  11221. const char *thisWuid = item.queryProp("@wuid");
  11222. if (strieq(wuid, thisWuid))
  11223. return &item;
  11224. unsigned thisSeq = item.getPropInt("@seq");
  11225. if (thisSeq >= seq)
  11226. seq = thisSeq + 1;
  11227. }
  11228. StringBuffer id;
  11229. id.append(lcName).append(".").append(seq);
  11230. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive|ipt_lowmem);
  11231. newEntry->setProp("@name", lcName);
  11232. newEntry->setProp("@wuid", wuid);
  11233. newEntry->setProp("@dll", dll);
  11234. newEntry->setProp("@id", id);
  11235. newEntry->setPropInt("@seq", seq);
  11236. if (library)
  11237. newEntry->setPropBool("@isLibrary", true);
  11238. if (userid && *userid)
  11239. newEntry->setProp("@publishedBy", userid);
  11240. if (snapshot && *snapshot)
  11241. newEntry->setProp("@snapshot", snapshot);
  11242. return queryRegistry->addPropTree("Query", newEntry);
  11243. }
  11244. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11245. {
  11246. StringBuffer lcId(id);
  11247. lcId.toLowerCase();
  11248. clearAliases(queryRegistry, lcId);
  11249. StringBuffer xpath;
  11250. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11251. queryRegistry->removeProp(xpath);
  11252. }
  11253. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  11254. {
  11255. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  11256. if (!match)
  11257. return;
  11258. clearAliases(queryRegistry, match->queryProp("@id"));
  11259. queryRegistry->removeTree(match);
  11260. }
  11261. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  11262. {
  11263. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  11264. if (!match)
  11265. return;
  11266. clearAliases(queryRegistry, match->queryProp("@id"));
  11267. queryRegistry->removeTree(match);
  11268. }
  11269. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  11270. {
  11271. clearAliases(queryRegistry, id);
  11272. }
  11273. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  11274. {
  11275. StringBuffer lcName(name);
  11276. lcName.toLowerCase();
  11277. StringBuffer xpath;
  11278. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  11279. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  11280. if (!match)
  11281. {
  11282. match = queryRegistry->addPropTree("Alias");
  11283. match->setProp("@name", lcName);
  11284. }
  11285. match->setProp("@id", value);
  11286. }
  11287. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  11288. {
  11289. if (!queryRegistry || !queryid)
  11290. return NULL;
  11291. StringBuffer xpath;
  11292. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  11293. return queryRegistry->getPropTree(xpath);
  11294. }
  11295. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  11296. {
  11297. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11298. return getQueryById(queryRegistry, queryid);
  11299. }
  11300. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  11301. {
  11302. if (!queryRegistry || !alias)
  11303. return NULL;
  11304. StringBuffer xpath;
  11305. unsigned cnt = 0;
  11306. StringBuffer lc(alias);
  11307. const char * search = lc.toLowerCase().str();
  11308. for (;;)
  11309. {
  11310. xpath.set("Alias[@name='").append(search).append("']/@id");
  11311. const char * queryId = queryRegistry->queryProp(xpath);
  11312. if (!queryId)
  11313. break;
  11314. //Check for too many alias indirections.
  11315. if (cnt++ > 10)
  11316. return NULL;
  11317. search = lc.set(queryId).toLowerCase().str();
  11318. }
  11319. return getQueryById(queryRegistry, search);
  11320. }
  11321. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  11322. {
  11323. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  11324. return resolveQueryAlias(queryRegistry, alias);
  11325. }
  11326. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  11327. {
  11328. StringBuffer lcId(id);
  11329. lcId.toLowerCase();
  11330. StringBuffer xpath;
  11331. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11332. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11333. if (tree)
  11334. {
  11335. if (tree->getPropBool("@suspended", false) == suspend)
  11336. return;
  11337. if (suspend)
  11338. {
  11339. tree->addPropBool("@suspended", true);
  11340. if (userid && *userid)
  11341. tree->addProp("@suspendedBy", userid);
  11342. }
  11343. else
  11344. {
  11345. tree->removeProp("@suspended");
  11346. tree->removeProp("@suspendedBy");
  11347. }
  11348. }
  11349. else
  11350. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  11351. }
  11352. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  11353. {
  11354. if (queryComment)
  11355. {
  11356. StringBuffer lcId(id);
  11357. lcId.toLowerCase();
  11358. StringBuffer xpath;
  11359. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  11360. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  11361. if (tree)
  11362. tree->setProp("@queryComment", queryComment);
  11363. else
  11364. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  11365. }
  11366. }
  11367. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  11368. {
  11369. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  11370. if (conn)
  11371. return conn->getRoot();
  11372. else
  11373. return NULL;
  11374. }
  11375. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  11376. {
  11377. if (!queryTree || !libraries)
  11378. return;
  11379. if (queryTree->hasProp("@libCount")) //already added
  11380. return;
  11381. unsigned libCount=0;
  11382. ForEach(*libraries)
  11383. {
  11384. IConstWULibrary &library = libraries->query();
  11385. SCMStringBuffer libname;
  11386. if (!library.getName(libname).length())
  11387. continue;
  11388. queryTree->addProp("Library", libname.str());
  11389. libCount++;
  11390. }
  11391. queryTree->setPropInt("@libCount", libCount);
  11392. }
  11393. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  11394. {
  11395. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  11396. checkAddLibrariesToQueryEntry(queryTree, libraries);
  11397. }
  11398. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  11399. {
  11400. //Only lock the branch for the target we're interested in.
  11401. StringBuffer xpath;
  11402. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  11403. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11404. if (conn)
  11405. return conn->getRoot();
  11406. if (readonly)
  11407. return NULL;
  11408. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  11409. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11410. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  11411. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11412. if (conn)
  11413. return conn->getRoot();
  11414. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11415. if (!conn)
  11416. throwUnexpected();
  11417. IPropertyTree * root = conn->queryRoot();
  11418. root->setProp("@id",wsEclId);
  11419. conn->commit();
  11420. return LINK(root);
  11421. }
  11422. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  11423. {
  11424. StringBuffer xpath;
  11425. StringBuffer lcName(name);
  11426. lcName.toLowerCase();
  11427. // see if "name" already exists
  11428. xpath.append("Package[@id='").append(name).append("']");
  11429. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  11430. if (pkgTree)
  11431. {
  11432. if (overWrite)
  11433. packageRegistry->removeTree(pkgTree);
  11434. else
  11435. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  11436. }
  11437. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  11438. tree->setProp("@id", lcName);
  11439. return tree;
  11440. }
  11441. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  11442. {
  11443. StringBuffer lcId(id);
  11444. lcId.toLowerCase();
  11445. StringBuffer xpath;
  11446. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  11447. packageRegistry->removeProp(xpath);
  11448. }
  11449. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  11450. {
  11451. //Only lock the branch for the target we're interested in.
  11452. StringBuffer xpath;
  11453. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  11454. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11455. if (conn)
  11456. return conn->getRoot();
  11457. if (readonly)
  11458. return NULL;
  11459. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  11460. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  11461. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  11462. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  11463. if (conn)
  11464. return conn->getRoot();
  11465. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  11466. if (!conn)
  11467. throwUnexpected();
  11468. IPropertyTree* root = conn->queryRoot();
  11469. root->setProp("@id",wsEclId);
  11470. conn->commit();
  11471. return LINK(root);
  11472. }
  11473. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11474. {
  11475. StringBuffer cleanQueryName;
  11476. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11477. SCMStringBuffer dllName;
  11478. Owned<IConstWUQuery> q = workunit->getQuery();
  11479. q->getQueryDllName(dllName);
  11480. if (!dllName.length())
  11481. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  11482. StringBuffer currentTargetClusterType;
  11483. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  11484. SCMStringBuffer targetClusterType;
  11485. workunit->getDebugValue("targetclustertype", targetClusterType);
  11486. SCMStringBuffer snapshot;
  11487. workunit->getSnapshot(snapshot);
  11488. if (currentTargetClusterType.length() < 1)
  11489. {
  11490. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  11491. }
  11492. else
  11493. {
  11494. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  11495. {
  11496. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  11497. }
  11498. }
  11499. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  11500. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  11501. checkAddLibrariesToQueryEntry(newEntry, libraries);
  11502. newQueryId.append(newEntry->queryProp("@id"));
  11503. workunit->setIsQueryService(true); //will check querysets before delete
  11504. workunit->commit();
  11505. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  11506. }
  11507. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  11508. {
  11509. StringBuffer cleanQueryName;
  11510. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  11511. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  11512. {
  11513. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  11514. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11515. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  11516. {
  11517. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  11518. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  11519. else
  11520. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  11521. }
  11522. }
  11523. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  11524. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  11525. }
  11526. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  11527. {
  11528. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11529. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  11530. }
  11531. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  11532. {
  11533. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11534. StringBuffer xpath;
  11535. xpath.appendf("Alias[@name='%s']", alias);
  11536. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  11537. return queryRegistry->removeTree(t);
  11538. }
  11539. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  11540. {
  11541. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  11542. setQueryAlias(queryRegistry, alias, id);
  11543. }
  11544. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  11545. {
  11546. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11547. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  11548. }
  11549. void deleteQuerySetQuery(const char *querySetName, const char *id)
  11550. {
  11551. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11552. removeNamedQuery(queryRegistry, id);
  11553. }
  11554. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  11555. {
  11556. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11557. clearAliases(queryRegistry, id);
  11558. }
  11559. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  11560. {
  11561. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11562. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  11563. }
  11564. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  11565. {
  11566. if (!queryRegistry)
  11567. return NULL;
  11568. StringBuffer xpath;
  11569. xpath.appendf("Query[@wuid='%s']", wuid);
  11570. if (queryName && *queryName)
  11571. xpath.appendf("[@name='%s']", queryName);
  11572. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  11573. if (q)
  11574. {
  11575. id.set(q->queryProp("@id"));
  11576. }
  11577. return id.str();
  11578. }
  11579. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  11580. {
  11581. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  11582. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  11583. }
  11584. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  11585. {
  11586. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  11587. ForEach(*wulibraries)
  11588. {
  11589. SCMStringBuffer libname;
  11590. IConstWULibrary &wulibrary = wulibraries->query();
  11591. wulibrary.getName(libname);
  11592. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  11593. continue;
  11594. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  11595. if (query && query->getPropBool("@isLibrary"))
  11596. {
  11597. const char *wuid = query->queryProp("@wuid");
  11598. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  11599. if (libcw)
  11600. {
  11601. names.appendUniq(libname.str());
  11602. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  11603. continue;
  11604. }
  11605. }
  11606. unresolved.appendUniq(libname.str());
  11607. }
  11608. }
  11609. bool looksLikeAWuid(const char * wuid, const char firstChar)
  11610. {
  11611. if (!wuid)
  11612. return false;
  11613. if (wuid[0] != firstChar)
  11614. return false;
  11615. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  11616. return false;
  11617. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  11618. return false;
  11619. return (wuid[9]=='-');
  11620. }
  11621. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  11622. {
  11623. IPropertyTree * module = archive;
  11624. const char * dot = strrchr(path, '.');
  11625. StringBuffer xpath;
  11626. if (dot)
  11627. {
  11628. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  11629. module = archive->queryPropTree(xpath);
  11630. path = dot+1;
  11631. }
  11632. else
  11633. module = archive->queryPropTree("Module[@key='']");
  11634. if (!module)
  11635. return NULL;
  11636. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  11637. return module->queryPropTree(xpath);
  11638. }
  11639. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  11640. {
  11641. StringBuffer fullPathName;
  11642. makeAbsolutePath(name, fullPathName);
  11643. if (isContainerized())
  11644. {
  11645. const char *dllserver_root = getenv("HPCC_DLLSERVER_PATH");
  11646. assertex(dllserver_root != nullptr);
  11647. StringBuffer destPathName(dllserver_root);
  11648. addNonEmptyPathSepChar(destPathName);
  11649. splitFilename(fullPathName.str(), nullptr, nullptr, &destPathName, &destPathName);
  11650. OwnedIFile source = createIFile(fullPathName);
  11651. OwnedIFile target = createIFile(destPathName);
  11652. if (!target->exists())
  11653. {
  11654. source->copyTo(target, 0, NULL, true);
  11655. }
  11656. query->addAssociatedFile(type, destPathName, "localhost", description, crc, minActivity, maxActivity);
  11657. // Should we delete the local files? May not matter...
  11658. }
  11659. else
  11660. {
  11661. StringBuffer hostname;
  11662. queryHostIP().getIpText(hostname);
  11663. query->addAssociatedFile(type, fullPathName, hostname, description, crc, minActivity, maxActivity);
  11664. }
  11665. }
  11666. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  11667. {
  11668. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  11669. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  11670. if(workunit)
  11671. workunit->deschedule();
  11672. else
  11673. doDescheduleWorkkunit(wuid);
  11674. }
  11675. extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid)
  11676. {
  11677. StringBuffer scopestr;
  11678. if (wfid && scope && *scope)
  11679. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11680. else
  11681. scopestr.set(scope);
  11682. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, description, value, 1, 0, StatsMergeReplace);
  11683. }
  11684. class WuTimingUpdater : implements ITimeReportInfo
  11685. {
  11686. public:
  11687. WuTimingUpdater(IWorkUnit * _wu, StatisticScopeType _scopeType, StatisticKind _kind)
  11688. : wu(_wu), scopeType(_scopeType), kind(_kind)
  11689. { }
  11690. virtual void report(const char * scope, const __int64 totaltime, const __int64 maxtime, const unsigned count)
  11691. {
  11692. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, nullptr, totaltime, count, maxtime, StatsMergeReplace);
  11693. }
  11694. protected:
  11695. IWorkUnit * wu;
  11696. StatisticScopeType scopeType;
  11697. StatisticKind kind;
  11698. };
  11699. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  11700. {
  11701. WuTimingUpdater target(wu, SSTsection, StTimeTotalExecute);
  11702. timer->report(target);
  11703. }
  11704. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer)
  11705. {
  11706. WuTimingUpdater target(wu, scopeType, kind);
  11707. timer->report(target);
  11708. }
  11709. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid)
  11710. {
  11711. StringBuffer scopestr;
  11712. if (wfid && scope && *scope)
  11713. scopestr.append(WorkflowScopePrefix).append(wfid).append(":").append(scope);
  11714. else
  11715. scopestr.set(scope);
  11716. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scopestr, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  11717. }
  11718. extern WORKUNIT_API double calculateThorCost(__int64 timeNs, unsigned clusterWidth)
  11719. {
  11720. IPropertyTree *costs = queryCostsConfiguration();
  11721. if (costs)
  11722. {
  11723. double thor_master_rate = costs->getPropReal("thor/@master", 0.0);
  11724. double thor_slave_rate = costs->getPropReal("thor/@slave", 0.0);
  11725. double time_seconds = ((double)timeNs/1000000000);
  11726. return (time_seconds * thor_master_rate + time_seconds * thor_slave_rate * clusterWidth)*1E6;
  11727. }
  11728. return 0;
  11729. }
  11730. void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search)
  11731. {
  11732. SimpleReferenceAggregator aggregator(search, result);
  11733. Owned<IConstWUScopeIterator> it = &wu->getScopeIterator(filter);
  11734. ForEach(*it)
  11735. it->playProperties(aggregator);
  11736. }
  11737. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  11738. {
  11739. public:
  11740. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  11741. virtual void beginScope(const StatsScopeId & id)
  11742. {
  11743. prevLenStack.append(scope.length());
  11744. if (scope.length())
  11745. scope.append(":");
  11746. id.getScopeText(scope);
  11747. scopeTypeStack.append(id.queryScopeType());
  11748. }
  11749. virtual void beginSubGraphScope(unsigned id)
  11750. {
  11751. StatsScopeId scopeId(SSTsubgraph, id);
  11752. beginScope(scopeId);
  11753. }
  11754. virtual void beginActivityScope(unsigned id)
  11755. {
  11756. StatsScopeId scopeId(SSTactivity, id);
  11757. beginScope(scopeId);
  11758. }
  11759. virtual void beginEdgeScope(unsigned id, unsigned oid)
  11760. {
  11761. StatsScopeId scopeId(SSTedge, id, oid);
  11762. beginScope(scopeId);
  11763. }
  11764. virtual void beginChildGraphScope(unsigned id)
  11765. {
  11766. StatsScopeId scopeId(SSTchildgraph, id);
  11767. beginScope(scopeId);
  11768. }
  11769. virtual void endScope()
  11770. {
  11771. scope.setLength(prevLenStack.popGet());
  11772. scopeTypeStack.pop();
  11773. }
  11774. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  11775. {
  11776. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11777. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  11778. }
  11779. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  11780. {
  11781. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  11782. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  11783. }
  11784. virtual IStatisticCollection * getResult()
  11785. {
  11786. return NULL;
  11787. }
  11788. protected:
  11789. Linked<IWorkUnit> wu;
  11790. StringBuffer scope;
  11791. UnsignedArray prevLenStack;
  11792. UnsignedArray scopeTypeStack;
  11793. };
  11794. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  11795. {
  11796. return new GlobalStatisticGatherer(wu);
  11797. }
  11798. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  11799. {
  11800. if (!wuid || !*wuid)
  11801. return NULL;
  11802. VStringBuffer path("/GraphProgress/%s", wuid);
  11803. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  11804. if (conn)
  11805. return conn->getRoot();
  11806. else
  11807. return NULL;
  11808. }
  11809. void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp)
  11810. {
  11811. ErrorSeverity wuSeverity = SeverityInformation;
  11812. ErrorSeverity severity = error->getSeverity();
  11813. switch (severity)
  11814. {
  11815. case SeverityIgnore:
  11816. return;
  11817. case SeverityInformation:
  11818. break;
  11819. case SeverityWarning:
  11820. wuSeverity = SeverityWarning;
  11821. break;
  11822. case SeverityError:
  11823. case SeverityFatal:
  11824. wuSeverity = SeverityError;
  11825. break;
  11826. }
  11827. Owned<IWUException> exception = wu->createException();
  11828. exception->setSeverity(wuSeverity);
  11829. StringBuffer msg;
  11830. exception->setExceptionCode(error->errorCode());
  11831. exception->setExceptionMessage(error->errorMessage(msg).str());
  11832. const char * source = queryCreatorTypeName(queryStatisticsComponentType());
  11833. exception->setExceptionSource(source);
  11834. exception->setExceptionFileName(error->getFilename());
  11835. exception->setExceptionLineNo(error->getLine());
  11836. exception->setExceptionColumn(error->getColumn());
  11837. if (removeTimeStamp)
  11838. exception->setTimeStamp(nullptr);
  11839. if (error->getActivity())
  11840. exception->setActivityId(error->getActivity());
  11841. if (error->queryScope())
  11842. exception->setScope(error->queryScope());
  11843. }
  11844. IError * WorkUnitErrorReceiver::mapError(IError * error)
  11845. {
  11846. return LINK(error);
  11847. }
  11848. void WorkUnitErrorReceiver::report(IError* eclError)
  11849. {
  11850. addWorkunitException(wu, eclError, removeTimeStamp);
  11851. }
  11852. size32_t WorkUnitErrorReceiver::errCount()
  11853. {
  11854. unsigned count = 0;
  11855. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11856. ForEach(*exceptions)
  11857. if (exceptions->query().getSeverity() == SeverityError)
  11858. count++;
  11859. return count;
  11860. }
  11861. size32_t WorkUnitErrorReceiver::warnCount()
  11862. {
  11863. unsigned count = 0;
  11864. Owned<IConstWUExceptionIterator> exceptions = &wu->getExceptions();
  11865. ForEach(*exceptions)
  11866. if (exceptions->query().getSeverity() == SeverityWarning)
  11867. count++;
  11868. return count;
  11869. }
  11870. bool isValidPriorityValue(const char *priority)
  11871. {
  11872. if (isEmptyString(priority))
  11873. return false;
  11874. if (strieq("SLA", priority) || strieq("LOW", priority) || strieq("HIGH", priority) || strieq("NONE", priority))
  11875. return true;
  11876. return false;
  11877. }
  11878. bool isValidMemoryValue(const char *memoryUnit)
  11879. {
  11880. if (isEmptyString(memoryUnit) || !isdigit(*memoryUnit))
  11881. return false;
  11882. while (isdigit(*++memoryUnit));
  11883. if (!*memoryUnit)
  11884. return true;
  11885. switch (toupper(*memoryUnit++))
  11886. {
  11887. case 'E':
  11888. case 'P':
  11889. case 'T':
  11890. case 'G':
  11891. case 'M':
  11892. case 'K':
  11893. if (!*memoryUnit || strieq("B", memoryUnit))
  11894. return true;
  11895. break;
  11896. case 'B':
  11897. if (!*memoryUnit)
  11898. return true;
  11899. break;
  11900. }
  11901. return false;
  11902. }
  11903. #ifdef _CONTAINERIZED
  11904. static void setResources(StringBuffer &jobYaml, const IConstWorkUnit *workunit, const char *process)
  11905. {
  11906. StringBuffer s;
  11907. unsigned memRequest = workunit->getDebugValueInt(s.clear().appendf("%s-memRequest", process), 0);
  11908. unsigned memLimit = workunit->getDebugValueInt(s.clear().appendf("%s-memLimit", process), 0);
  11909. if (memLimit && memLimit < memRequest)
  11910. memLimit = memRequest;
  11911. if (memRequest)
  11912. jobYaml.replaceString("#request-memory", s.clear().appendf("memory: \"%uMi\"", memRequest));
  11913. if (memLimit)
  11914. jobYaml.replaceString("#limit-memory", s.clear().appendf("memory: \"%uMi\"", memLimit));
  11915. unsigned cpuRequest = workunit->getDebugValueInt(s.clear().appendf("%s-cpuRequest", process), 0);
  11916. unsigned cpuLimit = workunit->getDebugValueInt(s.clear().appendf("%s-cpuLimit", process), 0);
  11917. if (cpuLimit && cpuLimit < cpuRequest)
  11918. cpuLimit = cpuRequest;
  11919. if (cpuRequest)
  11920. jobYaml.replaceString("#request-cpu", s.clear().appendf("cpu: \"%um\"", cpuRequest));
  11921. if (cpuLimit)
  11922. jobYaml.replaceString("#limit-cpu", s.clear().appendf("cpu: \"%um\"", cpuLimit));
  11923. }
  11924. void deleteK8sJob(const char *componentName, const char *job)
  11925. {
  11926. VStringBuffer jobname("%s-%s", componentName, job);
  11927. jobname.toLowerCase();
  11928. VStringBuffer deleteJob("kubectl delete job/%s", jobname.str());
  11929. StringBuffer output, error;
  11930. bool ret = runExternalCommand(output, error, deleteJob.str(), nullptr);
  11931. DBGLOG("kubectl delete output: %s", output.str());
  11932. if (error.length())
  11933. DBGLOG("kubectl delete error: %s", error.str());
  11934. if (ret)
  11935. throw makeStringException(0, "Failed to run kubectl delete");
  11936. }
  11937. void waitK8sJob(const char *componentName, const char *job, const char *condition)
  11938. {
  11939. VStringBuffer jobname("%s-%s", componentName, job);
  11940. jobname.toLowerCase();
  11941. if (isEmptyString(condition))
  11942. condition = "condition=complete";
  11943. // MORE - blocks indefinitely here if you request too many resources
  11944. VStringBuffer waitJob("kubectl wait --for=%s --timeout=10h job/%s", condition, jobname.str()); // MORE - make timeout configurable
  11945. StringBuffer output, error;
  11946. bool ret = runExternalCommand(output, error, waitJob.str(), nullptr);
  11947. DBGLOG("kubectl wait output: %s", output.str());
  11948. if (error.length())
  11949. DBGLOG("kubectl wait error: %s", error.str());
  11950. if (ret)
  11951. throw makeStringException(0, "Failed to run kubectl wait");
  11952. }
  11953. void launchK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams)
  11954. {
  11955. VStringBuffer jobname("%s-%s", componentName, job);
  11956. jobname.toLowerCase();
  11957. VStringBuffer args("\"--workunit=%s\"", wuid);
  11958. for (const auto &p: extraParams)
  11959. args.append(',').newline().append("\"--").append(p.first.c_str()).append('=').append(p.second.c_str()).append("\"");
  11960. VStringBuffer jobSpecFilename("/etc/config/%s-jobspec.yaml", componentName);
  11961. StringBuffer jobYaml;
  11962. jobYaml.loadFile(jobSpecFilename, false);
  11963. jobYaml.replaceString("%jobname", jobname.str());
  11964. jobYaml.replaceString("%args", args.str());
  11965. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  11966. if (factory)
  11967. {
  11968. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(wuid);
  11969. if (workunit)
  11970. setResources(jobYaml, workunit, componentName);
  11971. }
  11972. StringBuffer output, error;
  11973. unsigned ret = runExternalCommand(output, error, "kubectl apply -f -", jobYaml.str());
  11974. DBGLOG("kubectl output: %s", output.str());
  11975. if (error.length())
  11976. DBGLOG("kubectl error: %s", error.str());
  11977. if (ret)
  11978. {
  11979. DBGLOG("Using job yaml %s", jobYaml.str());
  11980. throw makeStringException(0, "Failed to start kubectl job");
  11981. }
  11982. }
  11983. void runK8sJob(const char *componentName, const char *wuid, const char *job, bool del, const std::list<std::pair<std::string, std::string>> &extraParams)
  11984. {
  11985. launchK8sJob(componentName, wuid, job, extraParams);
  11986. waitK8sJob(componentName, job);
  11987. if (del)
  11988. deleteK8sJob(componentName, job);
  11989. }
  11990. #endif