workunit.cpp 348 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "jlib.hpp"
  14. #include "workunit.hpp"
  15. #include "jprop.hpp"
  16. #include "jmisc.hpp"
  17. #include "jexcept.hpp"
  18. #include "jiter.ipp"
  19. #include "jptree.hpp"
  20. #include "jtime.ipp"
  21. #include "jencrypt.hpp"
  22. #include "junicode.hpp"
  23. #include "jlzw.hpp"
  24. #include "jregexp.hpp"
  25. #include "eclrtl.hpp"
  26. #include "deftype.hpp"
  27. #include <time.h>
  28. #include "mpbase.hpp"
  29. #include "daclient.hpp"
  30. #include "dadfs.hpp"
  31. #include "dafdesc.hpp"
  32. #include "dasds.hpp"
  33. #include "danqs.hpp"
  34. #include "dautils.hpp"
  35. #include "dllserver.hpp"
  36. #include "thorplugin.hpp"
  37. #include "thorhelper.hpp"
  38. #include "workflow.hpp"
  39. #include "nbcd.hpp"
  40. #include "seclib.hpp"
  41. #include "wuerror.hpp"
  42. #include "wujobq.hpp"
  43. #include "environment.hpp"
  44. #include "workunit.ipp"
  45. static int workUnitTraceLevel = 1;
  46. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  47. {
  48. // MORE - can fold in the date
  49. return wuRoot.append("/WorkUnits/").append(wuid);
  50. }
  51. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  52. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  53. {
  54. #ifdef _WIN32
  55. suffix.append("W");
  56. #else
  57. suffix.append("L");
  58. #endif
  59. #ifdef __64BIT__
  60. suffix.append("64");
  61. #else
  62. suffix.append("32");
  63. #endif
  64. return suffix;
  65. }
  66. typedef MapStringTo<bool> UniqueScopes;
  67. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  68. {
  69. StringBuffer err;
  70. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  71. if (wuid)
  72. err.append(" workunit:").append(wuid);
  73. if (wuscope)
  74. err.append(" scope:").append(wuscope);
  75. //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
  76. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  77. if (log)
  78. LOG(MCuserError, "%s", err.str());
  79. if (excpt)
  80. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  81. }
  82. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  83. {
  84. if (!secmgr || !secuser)
  85. return true;
  86. bool ret = secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required;
  87. if (!ret && (log || excpt))
  88. wuAccessError(secuser->getName(), action, wuscope, NULL, excpt, log);
  89. return ret;
  90. }
  91. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  92. {
  93. if (!scopes)
  94. return true;
  95. bool ret=true;
  96. if (wuscope)
  97. {
  98. Owned<ISecResource> res=scopes->getResource(wuscope);
  99. if (!res || res->getAccessFlags()<required)
  100. ret=false;
  101. }
  102. else
  103. {
  104. for (int seq=0; ret && seq<scopes->count(); seq++)
  105. {
  106. ISecResource *res=scopes->queryResource(seq);
  107. if (res && res->getAccessFlags()<required)
  108. return false;
  109. }
  110. }
  111. if (!ret && (log || excpt))
  112. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  113. return ret;
  114. }
  115. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  116. {
  117. if (!secmgr || !secuser)
  118. return true;
  119. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.queryWuScope())>=required;
  120. if (!ret && (log || excpt))
  121. {
  122. wuAccessError(secuser->getName(), action, cw.queryWuScope(), cw.queryWuid(), excpt, log);
  123. }
  124. return ret;
  125. }
  126. static bool checkWuSecAccess(const char *wuid, ISecManager *secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  127. {
  128. if (!secmgr || !secuser)
  129. return true;
  130. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  131. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  132. bool ret=secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw->queryWuScope())>=required;
  133. if (!ret && (log || excpt))
  134. {
  135. wuAccessError(secuser->getName(), action, cw->queryWuScope(), cw->queryWuid(), excpt, log);
  136. }
  137. return ret;
  138. }
  139. void doDescheduleWorkkunit(char const * wuid)
  140. {
  141. StringBuffer xpath;
  142. xpath.append("*/*/*/");
  143. ncnameEscape(wuid, xpath);
  144. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  145. if(!conn) return;
  146. Owned<IPropertyTree> root = conn->getRoot();
  147. bool more;
  148. do more = root->removeProp(xpath.str()); while(more);
  149. }
  150. //======================================================
  151. /*
  152. * Graph progress support
  153. */
  154. CWuGraphStats::CWuGraphStats(IPropertyTree *_progress, StatisticCreatorType _creatorType, const char * _creator, const char * _rootScope, unsigned _id)
  155. : progress(_progress), creatorType(_creatorType), creator(_creator), id(_id)
  156. {
  157. StatisticScopeType scopeType = SSTgraph;
  158. StatsScopeId rootScopeId;
  159. verifyex(rootScopeId.setScopeText(_rootScope));
  160. collector.setown(createStatisticsGatherer(_creatorType, _creator, rootScopeId));
  161. }
  162. void CWuGraphStats::beforeDispose()
  163. {
  164. Owned<IStatisticCollection> stats = collector->getResult();
  165. MemoryBuffer compressed;
  166. {
  167. MemoryBuffer serialized;
  168. serializeStatisticCollection(serialized, stats);
  169. compressToBuffer(compressed, serialized.length(), serialized.toByteArray());
  170. }
  171. unsigned minActivity = 0;
  172. unsigned maxActivity = 0;
  173. stats->getMinMaxActivity(minActivity, maxActivity);
  174. StringBuffer tag;
  175. tag.append("sg").append(id);
  176. IPropertyTree * subgraph = createPTree(tag);
  177. subgraph->setProp("@c", queryCreatorTypeName(creatorType));
  178. subgraph->setProp("@creator", creator);
  179. subgraph->setPropInt("@minActivity", minActivity);
  180. subgraph->setPropInt("@maxActivity", maxActivity);
  181. //Replace the particular subgraph statistics added by this creator
  182. StringBuffer qualified(tag);
  183. qualified.append("[@creator='").append(creator).append("']");
  184. progress->removeProp(qualified);
  185. subgraph = progress->addPropTree(tag, subgraph);
  186. subgraph->setPropBin("Stats", compressed.length(), compressed.toByteArray());
  187. if (!progress->getPropBool("@stats", false))
  188. progress->setPropBool("@stats", true);
  189. }
  190. IStatisticGatherer & CWuGraphStats::queryStatsBuilder()
  191. {
  192. return *collector;
  193. }
  194. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  195. {
  196. public:
  197. IMPLEMENT_IINTERFACE;
  198. CConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress) : wuid(_wuid), graphName(_graphName), progress(_progress)
  199. {
  200. if (!progress)
  201. progress.setown(createPTree());
  202. formatVersion = progress->getPropInt("@format", PROGRESS_FORMAT_V);
  203. }
  204. virtual IPropertyTree * getProgressTree()
  205. {
  206. if (progress->getPropBool("@stats"))
  207. return createProcessTreeFromStats(); // Should we cache that?
  208. return LINK(progress);
  209. }
  210. virtual unsigned queryFormatVersion()
  211. {
  212. return formatVersion;
  213. }
  214. protected:
  215. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  216. {
  217. formatVersion = PROGRESS_FORMAT_V;
  218. }
  219. static void expandStats(IPropertyTree * target, IStatisticCollection & collection)
  220. {
  221. StringBuffer formattedValue;
  222. unsigned numStats = collection.getNumStatistics();
  223. for (unsigned i=0; i < numStats; i++)
  224. {
  225. StatisticKind kind;
  226. unsigned __int64 value;
  227. collection.getStatistic(kind, value, i);
  228. formatStatistic(formattedValue.clear(), value, kind);
  229. target->setProp(queryTreeTag(kind), formattedValue);
  230. }
  231. }
  232. void expandProcessTreeFromStats(IPropertyTree * rootTarget, IPropertyTree * target, IStatisticCollection * collection)
  233. {
  234. expandStats(target, *collection);
  235. StringBuffer scopeName;
  236. Owned<IStatisticCollectionIterator> activityIter = &collection->getScopes(NULL);
  237. ForEach(*activityIter)
  238. {
  239. IStatisticCollection & cur = activityIter->query();
  240. cur.getScope(scopeName.clear());
  241. const char * id = scopeName.str();
  242. const char * tag;
  243. IPropertyTree * curTarget = target;
  244. switch (cur.queryScopeType())
  245. {
  246. case SSTedge:
  247. tag = "edge";
  248. id += strlen(EdgeScopePrefix);
  249. break;
  250. case SSTactivity:
  251. tag = "node";
  252. id += strlen(ActivityScopePrefix);
  253. break;
  254. case SSTsubgraph:
  255. //All subgraphs are added a root elements in the progress tree
  256. curTarget = rootTarget;
  257. tag = "node";
  258. id += strlen(SubGraphScopePrefix);
  259. break;
  260. case SSTfunction:
  261. //MORE:Should function scopes be included in the graph scope somehow, and if so how?
  262. continue;
  263. default:
  264. throwUnexpected();
  265. }
  266. IPropertyTree * next = curTarget->addPropTree(tag, createPTree());
  267. next->setProp("@id", id);
  268. expandProcessTreeFromStats(rootTarget, next, &cur);
  269. }
  270. }
  271. IPropertyTree * createProcessTreeFromStats()
  272. {
  273. MemoryBuffer compressed;
  274. MemoryBuffer serialized;
  275. Owned<IPropertyTree> progressTree = createPTree();
  276. Owned<IPropertyTreeIterator> iter = progress->getElements("sg*");
  277. ForEach(*iter)
  278. {
  279. IPropertyTree & curSubGraph = iter->query();
  280. curSubGraph.getPropBin("Stats", compressed.clear());
  281. //Protect against updates that delete the stats while we are iterating
  282. if (compressed.length())
  283. {
  284. decompressToBuffer(serialized.clear(), compressed);
  285. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  286. expandProcessTreeFromStats(progressTree, progressTree, collection);
  287. }
  288. }
  289. return progressTree.getClear();
  290. }
  291. protected:
  292. Linked<IPropertyTree> progress;
  293. StringAttr wuid, graphName;
  294. unsigned formatVersion;
  295. };
  296. extern WORKUNIT_API IConstWUGraphProgress *createConstGraphProgress(const char *_wuid, const char *_graphName, IPropertyTree *_progress)
  297. {
  298. return new CConstGraphProgress(_wuid, _graphName, _progress);
  299. }
  300. //--------------------------------------------------------------------------------------------------------------------
  301. class ExtractedStatistic : public CInterfaceOf<IConstWUStatistic>
  302. {
  303. public:
  304. virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const
  305. {
  306. if (!description && createDefault)
  307. {
  308. switch (kind)
  309. {
  310. case StTimeElapsed:
  311. {
  312. if (scopeType != SSTsubgraph)
  313. break;
  314. //Create a default description for a root subgraph
  315. const char * colon = strchr(scope, ':');
  316. if (!colon)
  317. break;
  318. const char * subgraph = colon+1;
  319. //Check for nested subgraph
  320. if (strchr(subgraph, ':'))
  321. break;
  322. assertex(strncmp(subgraph, SubGraphScopePrefix, strlen(SubGraphScopePrefix)) == 0);
  323. StringAttr graphname;
  324. graphname.set(scope, colon - scope);
  325. unsigned subId = atoi(subgraph + strlen(SubGraphScopePrefix));
  326. StringBuffer desc;
  327. formatGraphTimerLabel(desc, graphname, 0, subId);
  328. str.set(desc);
  329. return str;
  330. }
  331. }
  332. }
  333. str.set(description);
  334. return str;
  335. }
  336. virtual IStringVal & getCreator(IStringVal & str) const
  337. {
  338. str.set(creator);
  339. return str;
  340. }
  341. virtual IStringVal & getScope(IStringVal & str) const
  342. {
  343. str.set(scope);
  344. return str;
  345. }
  346. virtual IStringVal & getFormattedValue(IStringVal & str) const
  347. {
  348. StringBuffer formatted;
  349. formatStatistic(formatted, value, measure);
  350. str.set(formatted);
  351. return str;
  352. }
  353. virtual StatisticMeasure getMeasure() const
  354. {
  355. return measure;
  356. }
  357. virtual StatisticKind getKind() const
  358. {
  359. return kind;
  360. }
  361. virtual StatisticCreatorType getCreatorType() const
  362. {
  363. return creatorType;
  364. }
  365. virtual StatisticScopeType getScopeType() const
  366. {
  367. return scopeType;
  368. }
  369. virtual unsigned __int64 getValue() const
  370. {
  371. return value;
  372. }
  373. virtual unsigned __int64 getCount() const
  374. {
  375. return count;
  376. }
  377. virtual unsigned __int64 getMax() const
  378. {
  379. return max;
  380. }
  381. virtual unsigned __int64 getTimestamp() const
  382. {
  383. return timeStamp;
  384. }
  385. virtual bool matches(const IStatisticsFilter * filter) const
  386. {
  387. return filter->matches(creatorType, creator, scopeType, scope, measure, kind);
  388. }
  389. public:
  390. StringAttr creator;
  391. StringAttr description;
  392. StringBuffer scope;
  393. StatisticMeasure measure;
  394. StatisticKind kind;
  395. StatisticCreatorType creatorType;
  396. StatisticScopeType scopeType;
  397. unsigned __int64 value;
  398. unsigned __int64 count;
  399. unsigned __int64 max;
  400. unsigned __int64 timeStamp;
  401. };
  402. class CConstGraphProgressStatisticsIterator : public CInterfaceOf<IConstWUStatisticIterator>
  403. {
  404. public:
  405. CConstGraphProgressStatisticsIterator(const char * wuid, const IStatisticsFilter * _filter) : filter(_filter)
  406. {
  407. if (filter)
  408. scopes.appendList(filter->queryScope(), ":");
  409. const char * searchGraph = "*";
  410. if (scopes.ordinality())
  411. searchGraph = scopes.item(0);
  412. rootPath.append("/GraphProgress/").append(wuid).append('/');
  413. bool singleGraph = false;
  414. if (!containsWildcard(searchGraph))
  415. {
  416. rootPath.append(searchGraph).append("/");
  417. singleGraph = true;
  418. }
  419. //Don't lock the statistics while we iterate - any partial updates must not cause problems
  420. if (daliClientActive())
  421. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_NONE, SDS_LOCK_TIMEOUT));
  422. if (conn && !singleGraph)
  423. graphIter.setown(conn->queryRoot()->getElements("*"));
  424. curStat.setown(new ExtractedStatistic);
  425. //These are currently constant for all graph statistics instances
  426. curStat->count = 1;
  427. curStat->max = 0;
  428. valid = false;
  429. }
  430. virtual IConstWUStatistic & query()
  431. {
  432. return *curStat;
  433. }
  434. virtual bool first()
  435. {
  436. valid = false;
  437. if (!conn)
  438. return false;
  439. if (graphIter && !graphIter->first())
  440. return false;
  441. ensureUniqueStatistic();
  442. if (!firstSubGraph())
  443. {
  444. if (!nextGraph())
  445. return false;
  446. }
  447. valid = true;
  448. return true;
  449. }
  450. virtual bool next()
  451. {
  452. ensureUniqueStatistic();
  453. if (!nextStatistic())
  454. {
  455. if (!nextSubGraph())
  456. {
  457. if (!nextGraph())
  458. {
  459. valid = false;
  460. return false;
  461. }
  462. }
  463. }
  464. return true;
  465. }
  466. virtual bool isValid()
  467. {
  468. return valid;
  469. }
  470. protected:
  471. bool firstSubGraph()
  472. {
  473. IPropertyTree & graphNode = graphIter ? graphIter->query() : *conn->queryRoot();
  474. const char * xpath = "sg*";
  475. StringBuffer childXpath;
  476. if (scopes.isItem(1))
  477. {
  478. const char * scope1 = scopes.item(1);
  479. if (strnicmp(scope1, "sg", 2) == 0)
  480. {
  481. childXpath.append(scope1);
  482. xpath = childXpath.str();
  483. }
  484. }
  485. subgraphIter.setown(graphNode.getElements(xpath));
  486. if (!subgraphIter)
  487. subgraphIter.setown(graphNode.getElements("sg0"));
  488. if (!subgraphIter->first())
  489. return false;
  490. if (firstStat())
  491. return true;
  492. return nextSubGraph();
  493. }
  494. bool nextSubGraph()
  495. {
  496. loop
  497. {
  498. if (!subgraphIter->next())
  499. return false;
  500. if (firstStat())
  501. return true;
  502. }
  503. }
  504. bool nextGraph()
  505. {
  506. if (!graphIter)
  507. return false;
  508. loop
  509. {
  510. if (!graphIter->next())
  511. return false;
  512. if (firstSubGraph())
  513. return true;
  514. }
  515. }
  516. bool firstStat()
  517. {
  518. IPropertyTree & curSubGraph = subgraphIter->query();
  519. if (!checkSubGraph())
  520. return false;
  521. curSubGraph.getPropBin("Stats", compressed.clear());
  522. //Don't crash on old format progress...
  523. if (compressed.length() == 0)
  524. return false;
  525. decompressToBuffer(serialized.clear(), compressed);
  526. Owned<IStatisticCollection> collection = createStatisticCollection(serialized);
  527. curStat->timeStamp = collection->queryWhenCreated();
  528. return beginCollection(*collection);
  529. }
  530. bool beginCollection(IStatisticCollection & collection)
  531. {
  532. collections.append(OLINK(collection));
  533. numStats = collection.getNumStatistics();
  534. curStatIndex = 0;
  535. if (checkScope())
  536. {
  537. if (curStatIndex < numStats)
  538. {
  539. if (checkStatistic())
  540. return true;
  541. return nextStatistic();
  542. }
  543. }
  544. return nextChildScope();
  545. }
  546. bool nextStatistic()
  547. {
  548. //Finish iterating the statistics at this level.
  549. while (++curStatIndex < numStats)
  550. {
  551. if (checkStatistic())
  552. return true;
  553. }
  554. return nextChildScope();
  555. }
  556. bool nextChildScope()
  557. {
  558. loop
  559. {
  560. if (collections.ordinality() == 0)
  561. return false;
  562. IStatisticCollection * curCollection = &collections.tos();
  563. if (childIterators.ordinality() < collections.ordinality())
  564. {
  565. if (!filter || filter->recurseChildScopes(curStat->scopeType, curStat->scope))
  566. {
  567. //Start iterating the children for the current collection
  568. childIterators.append(curCollection->getScopes(NULL));
  569. if (!childIterators.tos().first())
  570. {
  571. finishCollection();
  572. continue;
  573. }
  574. }
  575. else
  576. {
  577. //Don't walk the child scopes
  578. collections.pop();
  579. continue;
  580. }
  581. }
  582. else if (!childIterators.tos().next())
  583. {
  584. finishCollection();
  585. continue;
  586. }
  587. if (beginCollection(childIterators.tos().query()))
  588. return true;
  589. }
  590. }
  591. void finishCollection()
  592. {
  593. collections.pop();
  594. childIterators.pop();
  595. }
  596. bool checkSubGraph()
  597. {
  598. if (!filter)
  599. return true;
  600. IPropertyTree & curSubGraph = subgraphIter->query();
  601. curStat->creatorType = queryCreatorType(curSubGraph.queryProp("@c"));
  602. curStat->creator.set(curSubGraph.queryProp("@creator"));
  603. return filter->matches(curStat->creatorType, curStat->creator, SSTall, NULL, SMeasureAll, StKindAll);
  604. }
  605. bool checkScope()
  606. {
  607. if (!filter)
  608. return true;
  609. IStatisticCollection * collection = &collections.tos();
  610. curStat->scopeType = collection->queryScopeType();
  611. collection->getFullScope(curStat->scope.clear());
  612. return filter->matches(SCTall, NULL, curStat->scopeType, curStat->scope, SMeasureAll, StKindAll);
  613. }
  614. bool checkStatistic()
  615. {
  616. IStatisticCollection & collection = collections.tos();
  617. collection.getStatistic(curStat->kind, curStat->value, curStatIndex);
  618. curStat->measure = queryMeasure(curStat->kind);
  619. if (!filter)
  620. return true;
  621. if (!filter->matches(SCTall, NULL, SSTall, NULL, curStat->measure, curStat->kind))
  622. return false;
  623. return true;
  624. }
  625. void ensureUniqueStatistic()
  626. {
  627. //If something else has linked this statistic, clone a unique one.
  628. if (curStat->IsShared())
  629. curStat.setown(new ExtractedStatistic(*curStat));
  630. }
  631. private:
  632. Owned<IRemoteConnection> conn;
  633. Owned<ExtractedStatistic> curStat;
  634. const IStatisticsFilter * filter;
  635. StringArray scopes;
  636. StringBuffer rootPath;
  637. Owned<IPropertyTreeIterator> graphIter;
  638. Owned<IPropertyTreeIterator> subgraphIter;
  639. IArrayOf<IStatisticCollection> collections;
  640. IArrayOf<IStatisticCollectionIterator> childIterators;
  641. MemoryBuffer compressed;
  642. MemoryBuffer serialized;
  643. unsigned numStats;
  644. unsigned curStatIndex;
  645. bool valid;
  646. };
  647. //--------------------------------------------------------------------------------------------------------------------
  648. mapEnums states[] = {
  649. { WUStateUnknown, "unknown" },
  650. { WUStateCompiled, "compiled" },
  651. { WUStateRunning, "running" },
  652. { WUStateCompleted, "completed" },
  653. { WUStateFailed, "failed" },
  654. { WUStateArchived, "archived" },
  655. { WUStateAborting, "aborting" },
  656. { WUStateAborted, "aborted" },
  657. { WUStateBlocked, "blocked" },
  658. { WUStateSubmitted, "submitted" },
  659. { WUStateScheduled, "scheduled" },
  660. { WUStateCompiling, "compiling" },
  661. { WUStateWait, "wait" },
  662. { WUStateUploadingFiles, "uploading_files" },
  663. { WUStateDebugPaused, "debugging" },
  664. { WUStateDebugRunning, "debug_running" },
  665. { WUStatePaused, "paused" },
  666. { WUStateSize, NULL }
  667. };
  668. mapEnums actions[] = {
  669. { WUActionUnknown, "unknown" },
  670. { WUActionCompile, "compile" },
  671. { WUActionCheck, "check" },
  672. { WUActionRun, "run" },
  673. { WUActionExecuteExisting, "execute" },
  674. { WUActionPause, "pause" },
  675. { WUActionPauseNow, "pausenow" },
  676. { WUActionResume, "resume" },
  677. { WUActionSize, NULL },
  678. };
  679. mapEnums priorityClasses[] = {
  680. { PriorityClassUnknown, "unknown" },
  681. { PriorityClassLow, "low" },
  682. { PriorityClassNormal, "normal" },
  683. { PriorityClassHigh, "high" },
  684. { PriorityClassSize, NULL },
  685. };
  686. const char * getWorkunitStateStr(WUState state)
  687. {
  688. dbgassertex(state < WUStateSize);
  689. return states[state].str; // MORE - should be using getEnumText, or need to take steps to ensure values remain contiguous and in order.
  690. }
  691. void setEnum(IPropertyTree *p, const char *propname, int value, const mapEnums *map)
  692. {
  693. const char *defval = map->str;
  694. while (map->str)
  695. {
  696. if (value==map->val)
  697. {
  698. p->setProp(propname, map->str);
  699. return;
  700. }
  701. map++;
  702. }
  703. assertex(!"Unexpected value in setEnum");
  704. p->setProp(propname, defval);
  705. }
  706. static int getEnum(const char *v, const mapEnums *map)
  707. {
  708. if (v)
  709. {
  710. while (map->str)
  711. {
  712. if (stricmp(v, map->str)==0)
  713. return map->val;
  714. map++;
  715. }
  716. assertex(!"Unexpected value in getEnum");
  717. }
  718. return 0;
  719. }
  720. static int getEnum(const IPropertyTree *p, const char *propname, const mapEnums *map)
  721. {
  722. return getEnum(p->queryProp(propname),map);
  723. }
  724. const char * getWorkunitActionStr(WUAction action)
  725. {
  726. return getEnumText(action, actions);
  727. }
  728. WUAction getWorkunitAction(const char *actionStr)
  729. {
  730. return (WUAction) getEnum(actionStr, actions);
  731. }
  732. //==========================================================================================
  733. class CLightweightWorkunitInfo : public CInterfaceOf<IConstWorkUnitInfo>
  734. {
  735. public:
  736. CLightweightWorkunitInfo(IPropertyTree &p)
  737. {
  738. wuid.set(p.queryName());
  739. user.set(p.queryProp("@submitID"));
  740. jobName.set(p.queryProp("@jobName"));
  741. clusterName.set(p.queryProp("@clusterName"));
  742. timeScheduled.set(p.queryProp("@timeScheduled"));
  743. state = (WUState) getEnum(&p, "@state", states);
  744. action = (WUAction) getEnum(&p, "Action", actions);
  745. priority = (WUPriorityClass) getEnum(&p, "@priorityClass", priorityClasses);
  746. priorityLevel = calcPriorityValue(&p);
  747. wuscope.set(p.queryProp("@scope"));
  748. appvalues.load(&p,"Application/*");
  749. totalThorTime = (unsigned)nanoToMilli(extractTimeCollatable(p.queryProp("@totalThorTime"), false));
  750. _isProtected = p.getPropBool("@protected", false);
  751. }
  752. virtual const char *queryWuid() const { return wuid.str(); }
  753. virtual const char *queryUser() const { return user.str(); }
  754. virtual const char *queryJobName() const { return jobName.str(); }
  755. virtual const char *queryClusterName() const { return clusterName.str(); }
  756. virtual const char *queryWuScope() const { return wuscope.str(); }
  757. virtual WUState getState() const { return state; }
  758. virtual const char *queryStateDesc() const { return getEnumText(state, states); }
  759. virtual WUAction getAction() const { return action; }
  760. virtual const char *queryActionDesc() const { return getEnumText(action, actions); }
  761. virtual WUPriorityClass getPriority() const { return priority; }
  762. virtual const char *queryPriorityDesc() const { return getEnumText(priority, priorityClasses); }
  763. virtual int getPriorityLevel() const { return priorityLevel; }
  764. virtual bool isProtected() const { return _isProtected; }
  765. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const
  766. {
  767. if (timeScheduled.length())
  768. val.setGmtString(timeScheduled.str());
  769. return val;
  770. }
  771. virtual unsigned getTotalThorTime() const { return totalThorTime; };
  772. virtual IConstWUAppValueIterator & getApplicationValues() const { return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnitInfo *) this); };
  773. protected:
  774. StringAttr wuid, user, jobName, clusterName, timeScheduled, wuscope;
  775. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  776. unsigned totalThorTime;
  777. WUState state;
  778. WUAction action;
  779. WUPriorityClass priority;
  780. int priorityLevel;
  781. bool _isProtected;
  782. };
  783. extern IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p)
  784. {
  785. return new CLightweightWorkunitInfo(p);
  786. }
  787. class CDaliWuGraphStats : public CWuGraphStats
  788. {
  789. public:
  790. CDaliWuGraphStats(IRemoteConnection *_conn, StatisticCreatorType _creatorType, const char * _creator, const char * _rootScope, unsigned _id)
  791. : CWuGraphStats(LINK(_conn->queryRoot()), _creatorType, _creator, _rootScope, _id), conn(_conn)
  792. {
  793. }
  794. protected:
  795. Owned<IRemoteConnection> conn;
  796. };
  797. CWorkUnitWatcher::CWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid) : subscriber(_subscriber)
  798. {
  799. abortId = 0;
  800. stateId = 0;
  801. actionId = 0;
  802. assertex((flags & ~SubscribeOptionAbort) == 0);
  803. if (flags & SubscribeOptionAbort)
  804. {
  805. VStringBuffer xpath("/WorkUnitAborts/%s", wuid);
  806. abortId = querySDS().subscribe(xpath.str(), *this);
  807. }
  808. }
  809. CWorkUnitWatcher::~CWorkUnitWatcher()
  810. {
  811. assertex(abortId==0 && stateId==0 && actionId==0);
  812. }
  813. void CWorkUnitWatcher::unsubscribe()
  814. {
  815. CriticalBlock b(crit);
  816. if (abortId)
  817. querySDS().unsubscribe(abortId);
  818. if (stateId)
  819. querySDS().unsubscribe(stateId);
  820. if (actionId)
  821. querySDS().unsubscribe(actionId);
  822. abortId = 0;
  823. stateId = 0;
  824. actionId = 0;
  825. }
  826. void CWorkUnitWatcher::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  827. {
  828. CriticalBlock b(crit);
  829. if (id==stateId)
  830. subscriber->notify(SubscribeOptionState);
  831. else if (id==actionId)
  832. subscriber->notify(SubscribeOptionAction);
  833. else if (id==abortId)
  834. subscriber->notify(SubscribeOptionAbort);
  835. }
  836. class CDaliWorkUnitWatcher : public CWorkUnitWatcher
  837. {
  838. public:
  839. CDaliWorkUnitWatcher(IWorkUnitSubscriber *_subscriber, WUSubscribeOptions flags, const char *wuid)
  840. : CWorkUnitWatcher(_subscriber, (WUSubscribeOptions) (flags & SubscribeOptionAbort), wuid)
  841. {
  842. if (flags & SubscribeOptionState)
  843. {
  844. VStringBuffer xpath("/WorkUnits/%s/State", wuid);
  845. stateId = querySDS().subscribe(xpath.str(), *this);
  846. }
  847. if (flags & SubscribeOptionAction)
  848. {
  849. VStringBuffer xpath("/WorkUnits/%s/Action", wuid);
  850. actionId = querySDS().subscribe(xpath.str(), *this);
  851. }
  852. }
  853. };
  854. void CPersistedWorkUnit::subscribe(WUSubscribeOptions options)
  855. {
  856. CriticalBlock block(crit);
  857. assertex(options==SubscribeOptionAbort);
  858. if (!abortWatcher)
  859. {
  860. abortWatcher.setown(new CWorkUnitWatcher(this, SubscribeOptionAbort, p->queryName()));
  861. abortDirty = true;
  862. }
  863. }
  864. void CPersistedWorkUnit::unsubscribe()
  865. {
  866. CriticalBlock block(crit);
  867. if (abortWatcher)
  868. {
  869. abortWatcher->unsubscribe();
  870. abortWatcher.clear();
  871. }
  872. }
  873. bool CPersistedWorkUnit::aborting() const
  874. {
  875. CriticalBlock block(crit);
  876. if (abortDirty)
  877. {
  878. StringBuffer apath;
  879. apath.append("/WorkUnitAborts/").append(p->queryName());
  880. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  881. if (acon)
  882. abortState = acon->queryRoot()->getPropInt(NULL) != 0;
  883. else
  884. abortState = false;
  885. abortDirty = false;
  886. }
  887. return abortState;
  888. }
  889. class CDaliWorkUnit : public CPersistedWorkUnit
  890. {
  891. public:
  892. CDaliWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser)
  893. : connection(_conn), CPersistedWorkUnit(secmgr, secuser)
  894. {
  895. loadPTree(connection->getRoot());
  896. }
  897. ~CDaliWorkUnit()
  898. {
  899. // NOTE - order is important - we need to construct connection before p and (especially) destroy after p
  900. // We use the beforeDispose() in base class to help ensure this
  901. p.clear();
  902. }
  903. IConstWUGraphProgress *getGraphProgress(const char *graphName) const
  904. {
  905. Owned<IRemoteConnection> conn = getProgressConnection();
  906. if (conn)
  907. {
  908. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  909. if (progress)
  910. return new CConstGraphProgress(p->queryName(), graphName, progress);
  911. }
  912. return NULL;
  913. }
  914. virtual WUGraphState queryGraphState(const char *graphName) const
  915. {
  916. Owned<IRemoteConnection> conn = getProgressConnection();
  917. if (conn)
  918. {
  919. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  920. if (progress)
  921. return (WUGraphState) progress->getPropInt("@_state", (unsigned) WUGraphUnknown);
  922. }
  923. return WUGraphUnknown;
  924. }
  925. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  926. {
  927. Owned<IRemoteConnection> conn = getProgressConnection();
  928. if (conn)
  929. {
  930. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  931. if (progress)
  932. {
  933. StringBuffer path;
  934. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  935. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  936. return (WUGraphState) progress->getPropInt(path, (unsigned) WUGraphUnknown);
  937. }
  938. }
  939. return WUGraphUnknown;
  940. }
  941. virtual void clearGraphProgress() const
  942. {
  943. CriticalBlock block(crit);
  944. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  945. StringBuffer path("/GraphProgress/");
  946. path.append(p->queryName());
  947. Owned<IRemoteConnection> delconn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  948. if (delconn)
  949. delconn->close(true);
  950. }
  951. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  952. {
  953. Owned<IRemoteConnection> conn = getProgressConnection();
  954. if (!conn)
  955. return false;
  956. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  957. if (name)
  958. {
  959. graphName.set(name);
  960. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  961. return true;
  962. }
  963. else
  964. return false;
  965. }
  966. virtual void forceReload()
  967. {
  968. synchronized sync(locked); // protect locked workunits (uncommitted writes) from reload
  969. CriticalBlock block(crit);
  970. clearCached(true);
  971. connection->reload();
  972. progressConnection.clear();
  973. abortDirty = true;
  974. p.setown(connection->getRoot());
  975. }
  976. virtual void cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  977. {
  978. CPersistedWorkUnit::cleanupAndDelete(deldll, deleteOwned, deleteExclusions);
  979. clearGraphProgress();
  980. connection->close(true);
  981. connection.clear();
  982. }
  983. virtual void commit()
  984. {
  985. CPersistedWorkUnit::commit();
  986. if (connection)
  987. connection->commit();
  988. }
  989. virtual void _lockRemote()
  990. {
  991. StringBuffer wuRoot;
  992. getXPath(wuRoot, p->queryName());
  993. if (connection)
  994. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  995. else
  996. connection.setown(querySDS().connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  997. if (!connection)
  998. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  999. clearCached(true);
  1000. p.setown(connection->getRoot());
  1001. }
  1002. virtual void _unlockRemote()
  1003. {
  1004. if (connection)
  1005. {
  1006. try
  1007. {
  1008. try
  1009. {
  1010. connection->commit();
  1011. }
  1012. catch (IException *e)
  1013. {
  1014. EXCLOG(e, "Error during workunit commit");
  1015. connection->rollback();
  1016. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  1017. throw;
  1018. }
  1019. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  1020. }
  1021. catch (IException *E)
  1022. {
  1023. StringBuffer s;
  1024. PrintLog("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  1025. throw;
  1026. }
  1027. }
  1028. }
  1029. virtual void setGraphState(const char *graphName, WUGraphState state) const
  1030. {
  1031. Owned<IRemoteConnection> conn = getWritableProgressConnection(graphName);
  1032. conn->queryRoot()->setPropInt("@_state", state);
  1033. }
  1034. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  1035. {
  1036. CriticalBlock block(crit);
  1037. progressConnection.clear(); // Make sure nothing is locking for read or we won't be able to lock for write
  1038. VStringBuffer path("/GraphProgress/%s", queryWuid());
  1039. Owned<IRemoteConnection> conn = querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  1040. IPTree *progress = ensurePTree(conn->queryRoot(), graphName);
  1041. // NOTE - the node state info still uses the old graph layout, even when the stats are using the new...
  1042. path.clear().append("node[@id=\"").append(nodeId).append("\"]");
  1043. IPropertyTree *node = progress->queryPropTree(path.str());
  1044. if (!node)
  1045. {
  1046. node = progress->addPropTree("node", createPTree());
  1047. node->setPropInt64("@id", nodeId);
  1048. }
  1049. node->setPropInt("@_state", (unsigned)state);
  1050. switch (state)
  1051. {
  1052. case WUGraphRunning:
  1053. {
  1054. IPropertyTree *running = conn->queryRoot()->setPropTree("Running", createPTree());
  1055. running->setProp("@graph", graphName);
  1056. running->setPropInt64("@subId", nodeId);
  1057. break;
  1058. }
  1059. case WUGraphComplete:
  1060. {
  1061. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  1062. break;
  1063. }
  1064. }
  1065. }
  1066. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  1067. {
  1068. return new CDaliWuGraphStats(getWritableProgressConnection(graphName), creatorType, creator, graphName, subgraph);
  1069. }
  1070. protected:
  1071. IRemoteConnection *getProgressConnection() const
  1072. {
  1073. CriticalBlock block(crit);
  1074. if (!progressConnection)
  1075. {
  1076. VStringBuffer path("/GraphProgress/%s", queryWuid());
  1077. progressConnection.setown(querySDS().connect(path, myProcessSession(), 0, SDS_LOCK_TIMEOUT)); // Note - we don't lock. The writes are atomic.
  1078. }
  1079. return progressConnection.getLink();
  1080. }
  1081. IRemoteConnection *getWritableProgressConnection(const char *graphName) const
  1082. {
  1083. CriticalBlock block(crit);
  1084. progressConnection.clear(); // Make sure subsequent reads from this workunit get the changes I am making
  1085. VStringBuffer path("/GraphProgress/%s/%s", queryWuid(), graphName);
  1086. return querySDS().connect(path, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  1087. }
  1088. IPropertyTree *getGraphProgressTree() const
  1089. {
  1090. Owned<IRemoteConnection> conn = getProgressConnection();
  1091. if (conn)
  1092. {
  1093. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  1094. mergePTree(tmp,conn->queryRoot());
  1095. return tmp.getClear();
  1096. }
  1097. return NULL;
  1098. }
  1099. Owned<IRemoteConnection> connection;
  1100. mutable Owned<IRemoteConnection> progressConnection;
  1101. };
  1102. class CLockedWorkUnit : implements ILocalWorkUnit, implements IExtendedWUInterface, public CInterface
  1103. {
  1104. public:
  1105. Owned<CLocalWorkUnit> c;
  1106. IMPLEMENT_IINTERFACE;
  1107. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  1108. ~CLockedWorkUnit()
  1109. {
  1110. if (workUnitTraceLevel > 1)
  1111. PrintLog("Releasing locked workunit %s", queryWuid());
  1112. if (c)
  1113. c->unlockRemote();
  1114. }
  1115. virtual IConstWorkUnit * unlock()
  1116. {
  1117. c->unlockRemote();
  1118. return c.getClear();
  1119. }
  1120. virtual bool aborting() const
  1121. { return c->aborting(); }
  1122. virtual void forceReload()
  1123. { UNIMPLEMENTED; }
  1124. virtual WUAction getAction() const
  1125. { return c->getAction(); }
  1126. virtual const char *queryActionDesc() const
  1127. { return c->queryActionDesc(); }
  1128. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  1129. { return c->getApplicationValue(application, propname, str); }
  1130. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  1131. { return c->getApplicationValueInt(application, propname, defVal); }
  1132. virtual IConstWUAppValueIterator & getApplicationValues() const
  1133. { return c->getApplicationValues(); }
  1134. virtual bool hasWorkflow() const
  1135. { return c->hasWorkflow(); }
  1136. virtual unsigned queryEventScheduledCount() const
  1137. { return c->queryEventScheduledCount(); }
  1138. virtual IPropertyTree * queryWorkflowTree() const
  1139. { return c->queryWorkflowTree(); }
  1140. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  1141. { return c->getWorkflowItems(); }
  1142. virtual IWorkflowItemArray * getWorkflowClone() const
  1143. { return c->getWorkflowClone(); }
  1144. virtual bool requiresLocalFileUpload() const
  1145. { return c->requiresLocalFileUpload(); }
  1146. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  1147. { return c->getLocalFileUploads(); }
  1148. virtual bool getIsQueryService() const
  1149. { return c->getIsQueryService(); }
  1150. virtual bool getCloneable() const
  1151. { return c->getCloneable(); }
  1152. virtual IUserDescriptor * queryUserDescriptor() const
  1153. { return c->queryUserDescriptor(); }
  1154. virtual const char *queryClusterName() const
  1155. { return c->queryClusterName(); }
  1156. virtual unsigned getCodeVersion() const
  1157. { return c->getCodeVersion(); }
  1158. virtual unsigned getWuidVersion() const
  1159. { return c->getWuidVersion(); }
  1160. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  1161. { c->getBuildVersion(buildVersion, eclVersion); }
  1162. virtual bool hasDebugValue(const char * propname) const
  1163. { return c->hasDebugValue(propname); }
  1164. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  1165. { return c->getDebugValue(propname, str); }
  1166. virtual int getDebugValueInt(const char * propname, int defVal) const
  1167. { return c->getDebugValueInt(propname, defVal); }
  1168. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  1169. { return c->getDebugValueInt64(propname, defVal); }
  1170. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  1171. { return c->getDebugValueBool(propname, defVal); }
  1172. virtual IStringIterator & getDebugValues() const
  1173. { return c->getDebugValues(NULL); }
  1174. virtual IStringIterator & getDebugValues(const char *prop) const
  1175. { return c->getDebugValues(prop); }
  1176. virtual unsigned getExceptionCount() const
  1177. { return c->getExceptionCount(); }
  1178. virtual IConstWUExceptionIterator & getExceptions() const
  1179. { return c->getExceptions(); }
  1180. virtual unsigned getGraphCount() const
  1181. { return c->getGraphCount(); }
  1182. virtual unsigned getSourceFileCount() const
  1183. { return c->getSourceFileCount(); }
  1184. virtual unsigned getResultCount() const
  1185. { return c->getResultCount(); }
  1186. virtual unsigned getVariableCount() const
  1187. { return c->getVariableCount(); }
  1188. virtual unsigned getApplicationValueCount() const
  1189. { return c->getApplicationValueCount(); }
  1190. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  1191. { return c->getGraphs(type); }
  1192. virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const
  1193. { return c->getGraphsMeta(type); }
  1194. virtual IConstWUGraph * getGraph(const char *name) const
  1195. { return c->getGraph(name); }
  1196. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  1197. { return c->getGraphProgress(name); }
  1198. virtual const char *queryJobName() const
  1199. { return c->queryJobName(); }
  1200. virtual IConstWUPlugin * getPluginByName(const char * name) const
  1201. { return c->getPluginByName(name); }
  1202. virtual IConstWUPluginIterator & getPlugins() const
  1203. { return c->getPlugins(); }
  1204. virtual IConstWULibrary* getLibraryByName(const char *name) const
  1205. { return c->getLibraryByName(name); }
  1206. virtual IConstWULibraryIterator & getLibraries() const
  1207. { return c->getLibraries(); }
  1208. virtual WUPriorityClass getPriority() const
  1209. { return c->getPriority(); }
  1210. virtual const char *queryPriorityDesc() const
  1211. { return c->queryPriorityDesc(); }
  1212. virtual int getPriorityLevel() const
  1213. { return c->getPriorityLevel(); }
  1214. virtual int getPriorityValue() const
  1215. { return c->getPriorityValue(); }
  1216. virtual IConstWUQuery * getQuery() const
  1217. { return c->getQuery(); }
  1218. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  1219. { return c->getWebServicesInfo(); }
  1220. virtual bool getRescheduleFlag() const
  1221. { return c->getRescheduleFlag(); }
  1222. virtual IConstWUResult * getResultByName(const char * name) const
  1223. { return c->getResultByName(name); }
  1224. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  1225. { return c->getResultBySequence(seq); }
  1226. virtual unsigned getResultLimit() const
  1227. { return c->getResultLimit(); }
  1228. virtual IConstWUResultIterator & getResults() const
  1229. { return c->getResults(); }
  1230. virtual IStringVal & getScope(IStringVal & str) const
  1231. { return c->getScope(str); }
  1232. virtual IStringVal & getSecurityToken(IStringVal & str) const
  1233. { return c->getSecurityToken(str); }
  1234. virtual WUState getState() const
  1235. { return c->getState(); }
  1236. virtual IStringVal & getStateEx(IStringVal & str) const
  1237. { return c->getStateEx(str); }
  1238. virtual __int64 getAgentSession() const
  1239. { return c->getAgentSession(); }
  1240. virtual unsigned getAgentPID() const
  1241. { return c->getAgentPID(); }
  1242. virtual const char *queryStateDesc() const
  1243. { return c->queryStateDesc(); }
  1244. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  1245. { return c->getRunningGraph(graphName, subId); }
  1246. virtual IConstWUStatisticIterator & getStatistics(const IStatisticsFilter * filter) const
  1247. { return c->getStatistics(filter); }
  1248. virtual IConstWUStatistic * getStatistic(const char * creator, const char * scope, StatisticKind kind) const
  1249. { return c->getStatistic(creator, scope, kind); }
  1250. virtual IStringVal & getSnapshot(IStringVal & str) const
  1251. { return c->getSnapshot(str); }
  1252. virtual const char *queryUser() const
  1253. { return c->queryUser(); }
  1254. virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  1255. { return c->getWarningSeverity(code, defaultSeverity); }
  1256. virtual const char *queryWuScope() const
  1257. { return c->queryWuScope(); }
  1258. virtual const char *queryWuid() const
  1259. { return c->queryWuid(); }
  1260. virtual IConstWUResult * getGlobalByName(const char * name) const
  1261. { return c->getGlobalByName(name); }
  1262. virtual IConstWUResult * getTemporaryByName(const char * name) const
  1263. { return c->getTemporaryByName(name); }
  1264. virtual IConstWUResultIterator & getTemporaries() const
  1265. { return c->getTemporaries(); }
  1266. virtual IConstWUResult * getVariableByName(const char * name) const
  1267. { return c->getVariableByName(name); }
  1268. virtual IConstWUResultIterator & getVariables() const
  1269. { return c->getVariables(); }
  1270. virtual bool isProtected() const
  1271. { return c->isProtected(); }
  1272. virtual bool isPausing() const
  1273. { return c->isPausing(); }
  1274. virtual IWorkUnit & lock()
  1275. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  1276. virtual bool reload()
  1277. { UNIMPLEMENTED; }
  1278. virtual void subscribe(WUSubscribeOptions options)
  1279. { c->subscribe(options); }
  1280. virtual void requestAbort()
  1281. { c->requestAbort(); }
  1282. virtual unsigned calculateHash(unsigned prevHash)
  1283. { return queryExtendedWU(c)->calculateHash(prevHash); }
  1284. virtual void copyWorkUnit(IConstWorkUnit *cached, bool all)
  1285. { queryExtendedWU(c)->copyWorkUnit(cached, all); }
  1286. virtual IPropertyTree *queryPTree() const
  1287. { return queryExtendedWU(c)->queryPTree(); }
  1288. virtual IPropertyTree *getUnpackedTree(bool includeProgress) const
  1289. { return queryExtendedWU(c)->getUnpackedTree(includeProgress); }
  1290. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned,bool exportAssociatedFiles)
  1291. { return queryExtendedWU(c)->archiveWorkUnit(base,del,deldll,deleteOwned,exportAssociatedFiles); }
  1292. virtual unsigned queryFileUsage(const char *filename) const
  1293. { return c->queryFileUsage(filename); }
  1294. virtual IConstWUFileUsageIterator * getFieldUsage() const
  1295. { return c->getFieldUsage(); }
  1296. virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  1297. { return c->getFieldUsageArray(filenames, columnnames, clusterName); }
  1298. virtual IJlibDateTime & getTimeScheduled(IJlibDateTime &val) const
  1299. { return c->getTimeScheduled(val); }
  1300. virtual unsigned getDebugAgentListenerPort() const
  1301. { return c->getDebugAgentListenerPort(); }
  1302. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  1303. { return c->getDebugAgentListenerIP(ip); }
  1304. virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const
  1305. { return c->getXmlParams(params, hidePasswords); }
  1306. virtual const IPropertyTree *getXmlParams() const
  1307. { return c->getXmlParams(); }
  1308. virtual unsigned __int64 getHash() const
  1309. { return c->getHash(); }
  1310. virtual IStringIterator *getLogs(const char *type, const char *instance) const
  1311. { return c->getLogs(type, instance); }
  1312. virtual IStringIterator *getProcesses(const char *type) const
  1313. { return c->getProcesses(type); }
  1314. virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const
  1315. { return c->getProcesses(type, instance); }
  1316. virtual unsigned getTotalThorTime() const
  1317. { return c->getTotalThorTime(); }
  1318. virtual WUGraphState queryGraphState(const char *graphName) const
  1319. { return c->queryGraphState(graphName); }
  1320. virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  1321. { return c->queryNodeState(graphName, nodeId); }
  1322. virtual void setGraphState(const char *graphName, WUGraphState state) const
  1323. { c->setGraphState(graphName, state); }
  1324. virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  1325. { c->setNodeState(graphName, nodeId, state); }
  1326. virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  1327. { return c->updateStats(graphName, creatorType, creator, subgraph); }
  1328. virtual void clearGraphProgress() const
  1329. { c->clearGraphProgress(); }
  1330. virtual IStringVal & getAbortBy(IStringVal & str) const
  1331. { return c->getAbortBy(str); }
  1332. virtual unsigned __int64 getAbortTimeStamp() const
  1333. { return c->getAbortTimeStamp(); }
  1334. virtual void clearExceptions()
  1335. { c->clearExceptions(); }
  1336. virtual void commit()
  1337. { c->commit(); }
  1338. virtual IWUException * createException()
  1339. { return c->createException(); }
  1340. virtual void addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  1341. { c->addProcess(type, instance, pid, log); }
  1342. virtual void protect(bool protectMode)
  1343. { c->protect(protectMode); }
  1344. virtual void setAction(WUAction action)
  1345. { c->setAction(action); }
  1346. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  1347. { c->setApplicationValue(application, propname, value, overwrite); }
  1348. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  1349. { c->setApplicationValueInt(application, propname, value, overwrite); }
  1350. virtual void incEventScheduledCount()
  1351. { c->incEventScheduledCount(); }
  1352. virtual void setIsQueryService(bool value)
  1353. { c->setIsQueryService(value); }
  1354. virtual void setCloneable(bool value)
  1355. { c->setCloneable(value); }
  1356. virtual void setIsClone(bool value)
  1357. { c->setIsClone(value); }
  1358. virtual void setClusterName(const char * value)
  1359. { c->setClusterName(value); }
  1360. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  1361. { c->setCodeVersion(version, buildVersion, eclVersion); }
  1362. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  1363. { c->setDebugValue(propname, value, overwrite); }
  1364. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  1365. { c->setDebugValueInt(propname, value, overwrite); }
  1366. virtual void setJobName(const char * value)
  1367. { c->setJobName(value); }
  1368. virtual void setPriority(WUPriorityClass cls)
  1369. { c->setPriority(cls); }
  1370. virtual void setPriorityLevel(int level)
  1371. { c->setPriorityLevel(level); }
  1372. virtual void setRescheduleFlag(bool value)
  1373. { c->setRescheduleFlag(value); }
  1374. virtual void setResultLimit(unsigned value)
  1375. { c->setResultLimit(value); }
  1376. virtual void setSecurityToken(const char *value)
  1377. { c->setSecurityToken(value); }
  1378. virtual void setState(WUState state)
  1379. { c->setState(state); }
  1380. virtual void setStateEx(const char * text)
  1381. { c->setStateEx(text); }
  1382. virtual void setAgentSession(__int64 sessionId)
  1383. { c->setAgentSession(sessionId); }
  1384. 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)
  1385. { c->setStatistic(creatorType, creator, scopeType, scope, kind, optDescription, value, count, maxValue, mergeAction); }
  1386. virtual void setTracingValue(const char * propname, const char * value)
  1387. { c->setTracingValue(propname, value); }
  1388. virtual void setTracingValueInt(const char * propname, int value)
  1389. { c->setTracingValueInt(propname, value); }
  1390. virtual void setTracingValueInt64(const char * propname, __int64 value)
  1391. { c->setTracingValueInt64(propname, value); }
  1392. virtual void setUser(const char * value)
  1393. { c->setUser(value); }
  1394. virtual void setWuScope(const char * value)
  1395. { c->setWuScope(value); }
  1396. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  1397. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  1398. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  1399. { c->syncRuntimeWorkflow(array); }
  1400. virtual IWorkflowItemIterator * updateWorkflowItems()
  1401. { return c->updateWorkflowItems(); }
  1402. virtual void resetWorkflow()
  1403. { c->resetWorkflow(); }
  1404. virtual void schedule()
  1405. { c->schedule(); }
  1406. virtual void deschedule()
  1407. { c->deschedule(); }
  1408. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  1409. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  1410. virtual IWUResult * updateGlobalByName(const char * name)
  1411. { return c->updateGlobalByName(name); }
  1412. virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml)
  1413. { c->createGraph(name, label, type, xgmml); }
  1414. virtual IWUQuery * updateQuery()
  1415. { return c->updateQuery(); }
  1416. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  1417. { return c->updateWebServicesInfo(create); }
  1418. virtual IWUPlugin * updatePluginByName(const char * name)
  1419. { return c->updatePluginByName(name); }
  1420. virtual IWULibrary * updateLibraryByName(const char * name)
  1421. { return c->updateLibraryByName(name); }
  1422. virtual IWUResult * updateResultByName(const char * name)
  1423. { return c->updateResultByName(name); }
  1424. virtual IWUResult * updateResultBySequence(unsigned seq)
  1425. { return c->updateResultBySequence(seq); }
  1426. virtual IWUResult * updateTemporaryByName(const char * name)
  1427. { return c->updateTemporaryByName(name); }
  1428. virtual IWUResult * updateVariableByName(const char * name)
  1429. { return c->updateVariableByName(name); }
  1430. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  1431. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  1432. virtual void noteFileRead(IDistributedFile *file)
  1433. { c->noteFileRead(file); }
  1434. virtual void noteFieldUsage(IPropertyTree * usage)
  1435. { c->noteFieldUsage(usage); }
  1436. virtual void releaseFile(const char *fileName)
  1437. { c->releaseFile(fileName); }
  1438. virtual void resetBeforeGeneration()
  1439. { c->resetBeforeGeneration(); }
  1440. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  1441. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  1442. virtual void deleteTemporaries()
  1443. { c->deleteTemporaries(); }
  1444. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  1445. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  1446. virtual IPropertyTree * getDiskUsageStats()
  1447. { return c->getDiskUsageStats(); }
  1448. virtual IPropertyTreeIterator & getFileIterator() const
  1449. { return c->getFileIterator(); }
  1450. virtual IPropertyTreeIterator & getFilesReadIterator() const
  1451. { return c->getFilesReadIterator(); }
  1452. virtual void setSnapshot(const char * value)
  1453. { c->setSnapshot(value); }
  1454. virtual void setWarningSeverity(unsigned code, ErrorSeverity severity)
  1455. { c->setWarningSeverity(code, severity); }
  1456. virtual void setTimeScheduled(const IJlibDateTime &val)
  1457. { c->setTimeScheduled(val); }
  1458. virtual void setDebugAgentListenerPort(unsigned port)
  1459. { c->setDebugAgentListenerPort(port); }
  1460. virtual void setDebugAgentListenerIP(const char * ip)
  1461. { c->setDebugAgentListenerIP(ip); }
  1462. virtual void setXmlParams(const char *params)
  1463. { c->setXmlParams(params); }
  1464. virtual void setXmlParams(IPropertyTree *tree)
  1465. { c->setXmlParams(tree); }
  1466. virtual void setHash(unsigned __int64 hash)
  1467. { c->setHash(hash); }
  1468. // ILocalWorkUnit - used for debugging etc
  1469. virtual void serialize(MemoryBuffer &tgt)
  1470. { c->serialize(tgt); }
  1471. virtual void deserialize(MemoryBuffer &src)
  1472. { c->deserialize(src); }
  1473. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  1474. { return c->switchThorQueue(cluster,qs); }
  1475. virtual void setAllowedClusters(const char *value)
  1476. { c->setAllowedClusters(value); }
  1477. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  1478. { return c->getAllowedClusters(str); }
  1479. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  1480. { c->remoteCheckAccess(user,writeaccess); }
  1481. virtual void setAllowAutoQueueSwitch(bool val)
  1482. { c->setAllowAutoQueueSwitch(val); }
  1483. virtual bool getAllowAutoQueueSwitch() const
  1484. { return c->getAllowAutoQueueSwitch(); }
  1485. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  1486. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  1487. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  1488. { c->setResultInt(name, sequence, val); }
  1489. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  1490. { c->setResultUInt(name, sequence, val); }
  1491. virtual void setResultReal(const char *name, unsigned sequence, double val)
  1492. { c->setResultReal(name, sequence, val); }
  1493. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  1494. { c->setResultVarString(stepname, sequence, val); }
  1495. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  1496. { c->setResultVarUnicode(stepname, sequence, val); }
  1497. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  1498. { c->setResultString(stepname, sequence, len, val); }
  1499. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  1500. { c->setResultData(stepname, sequence, len, val); }
  1501. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  1502. { c->setResultRaw(name, sequence, len, val); }
  1503. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *xform)
  1504. { c->setResultSet(name, sequence, isAll, len, val, xform); }
  1505. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  1506. { c->setResultUnicode(name, sequence, len, val); }
  1507. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  1508. { c->setResultBool(name, sequence, val); }
  1509. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  1510. { c->setResultDecimal(name, sequence, len, precision, isSigned, val); }
  1511. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  1512. { c->setResultDataset(name, sequence, len, val, numRows, extend); }
  1513. };
  1514. class CLocalWUAssociated : implements IConstWUAssociatedFile, public CInterface
  1515. {
  1516. Owned<IPropertyTree> p;
  1517. public:
  1518. IMPLEMENT_IINTERFACE;
  1519. CLocalWUAssociated(IPropertyTree *p);
  1520. virtual WUFileType getType() const;
  1521. virtual IStringVal & getDescription(IStringVal & ret) const;
  1522. virtual IStringVal & getIp(IStringVal & ret) const;
  1523. virtual IStringVal & getName(IStringVal & ret) const;
  1524. virtual IStringVal & getNameTail(IStringVal & ret) const;
  1525. virtual unsigned getCrc() const;
  1526. virtual unsigned getMinActivityId() const;
  1527. virtual unsigned getMaxActivityId() const;
  1528. };
  1529. class CLocalWUQuery : implements IWUQuery, public CInterface
  1530. {
  1531. Owned<IPropertyTree> p;
  1532. mutable IArrayOf<IConstWUAssociatedFile> associated;
  1533. mutable CriticalSection crit;
  1534. mutable bool associatedCached;
  1535. private:
  1536. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  1537. void loadAssociated() const;
  1538. public:
  1539. IMPLEMENT_IINTERFACE;
  1540. CLocalWUQuery(IPropertyTree *p);
  1541. virtual WUQueryType getQueryType() const;
  1542. virtual IStringVal& getQueryText(IStringVal &str) const;
  1543. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  1544. virtual IStringVal& getQueryName(IStringVal &str) const;
  1545. virtual IStringVal & getQueryMainDefinition(IStringVal & str) const;
  1546. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  1547. virtual unsigned getQueryDllCrc() const;
  1548. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  1549. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  1550. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  1551. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  1552. virtual bool isArchive() const;
  1553. virtual void setQueryType(WUQueryType qt);
  1554. virtual void setQueryText(const char *pstr);
  1555. virtual void setQueryName(const char *);
  1556. virtual void setQueryMainDefinition(const char * str);
  1557. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity);
  1558. virtual void removeAssociatedFiles();
  1559. virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc);
  1560. };
  1561. class CLocalWUWebServicesInfo : implements IWUWebServicesInfo, public CInterface
  1562. {
  1563. Owned<IPropertyTree> p;
  1564. mutable CriticalSection crit;
  1565. private:
  1566. public:
  1567. IMPLEMENT_IINTERFACE;
  1568. CLocalWUWebServicesInfo(IPropertyTree *p);
  1569. virtual IStringVal& getModuleName(IStringVal &str) const;
  1570. virtual IStringVal& getAttributeName(IStringVal &str) const;
  1571. virtual IStringVal& getDefaultName(IStringVal &str) const;
  1572. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  1573. virtual IStringVal& getText(const char *name, IStringVal &str) const;
  1574. virtual unsigned getWebServicesCRC() const;
  1575. virtual void setModuleName(const char *);
  1576. virtual void setAttributeName(const char *);
  1577. virtual void setDefaultName(const char *);
  1578. virtual void setInfo(const char *name, const char *info);
  1579. virtual void setText(const char *name, const char *info);
  1580. virtual void setWebServicesCRC(unsigned);
  1581. };
  1582. class CLocalWUResult : implements IWUResult, public CInterface
  1583. {
  1584. friend class CLocalWorkUnit;
  1585. mutable CriticalSection crit;
  1586. Owned<IPropertyTree> p;
  1587. Owned<IProperties> xmlns;
  1588. public:
  1589. IMPLEMENT_IINTERFACE;
  1590. CLocalWUResult(IPropertyTree *props);
  1591. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  1592. virtual WUResultStatus getResultStatus() const;
  1593. virtual IStringVal& getResultName(IStringVal &str) const;
  1594. virtual int getResultSequence() const;
  1595. virtual bool isResultScalar() const;
  1596. virtual IStringVal& getResultXml(IStringVal &str, bool hidePasswords) const;
  1597. virtual unsigned getResultFetchSize() const;
  1598. virtual __int64 getResultTotalRowCount() const;
  1599. virtual __int64 getResultRowCount() const;
  1600. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  1601. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  1602. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  1603. virtual unsigned getResultRequestedRows() const;
  1604. virtual __int64 getResultInt() const;
  1605. virtual bool getResultBool() const;
  1606. virtual double getResultReal() const;
  1607. virtual IStringVal& getResultString(IStringVal & str, bool hidePassword) const;
  1608. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1609. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  1610. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  1611. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  1612. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1613. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1614. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  1615. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  1616. virtual __int64 getResultRowLimit() const;
  1617. virtual IStringVal& getResultFilename(IStringVal & str) const;
  1618. virtual WUResultFormat getResultFormat() const;
  1619. virtual unsigned getResultHash() const;
  1620. virtual bool getResultIsAll() const;
  1621. virtual IProperties *queryResultXmlns();
  1622. virtual IStringVal& getResultFieldOpt(const char *name, IStringVal &str) const;
  1623. virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  1624. // interface IWUResult
  1625. virtual void setResultStatus(WUResultStatus status);
  1626. virtual void setResultName(const char *name);
  1627. virtual void setResultSequence(unsigned seq);
  1628. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  1629. virtual void setResultScalar(bool isScalar);
  1630. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  1631. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  1632. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  1633. virtual void setResultRowCount(__int64 rows);
  1634. virtual void setResultDataset(const char *ecl, const char *defs);
  1635. virtual void setResultLogicalName(const char *logicalName);
  1636. virtual void setResultKeyField(const char * name);
  1637. virtual void setResultRequestedRows(unsigned req);
  1638. virtual void setResultRecordSizeEntry(const char * val);
  1639. virtual void setResultTransformerEntry(const char * val);
  1640. virtual void setResultInt(__int64 val);
  1641. virtual void setResultReal(double val);
  1642. virtual void setResultBool(bool val);
  1643. virtual void setResultString(const char * val, unsigned length);
  1644. virtual void setResultUnicode(const void * val, unsigned length);
  1645. virtual void setResultData(const void * val, unsigned length);
  1646. virtual void setResultDecimal(const void * val, unsigned length);
  1647. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  1648. virtual void setResultRowLimit(__int64 value);
  1649. virtual void setResultFilename(const char * name);
  1650. virtual void setResultUInt(unsigned __int64 val);
  1651. virtual void setResultIsAll(bool value);
  1652. virtual void setResultFormat(WUResultFormat format);
  1653. virtual void setResultXML(const char *val);
  1654. virtual void setResultRow(unsigned len, const void * data);
  1655. virtual void setResultXmlns(const char *prefix, const char *uri);
  1656. virtual void setResultFieldOpt(const char *name, const char *value);
  1657. virtual IPropertyTree *queryPTree() { return p; }
  1658. };
  1659. class CLocalWUPlugin : implements IWUPlugin, public CInterface
  1660. {
  1661. Owned<IPropertyTree> p;
  1662. public:
  1663. IMPLEMENT_IINTERFACE;
  1664. CLocalWUPlugin(IPropertyTree *p);
  1665. virtual IStringVal& getPluginName(IStringVal &str) const;
  1666. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  1667. virtual void setPluginName(const char *str);
  1668. virtual void setPluginVersion(const char *str);
  1669. };
  1670. class CLocalWULibrary : implements IWULibrary, public CInterface
  1671. {
  1672. Owned<IPropertyTree> p;
  1673. public:
  1674. IMPLEMENT_IINTERFACE;
  1675. CLocalWULibrary(IPropertyTree *p);
  1676. virtual IStringVal & getName(IStringVal & str) const;
  1677. virtual void setName(const char * str);
  1678. };
  1679. class CLocalWUException : implements IWUException, public CInterface
  1680. {
  1681. Owned<IPropertyTree> p;
  1682. public:
  1683. IMPLEMENT_IINTERFACE;
  1684. CLocalWUException(IPropertyTree *p);
  1685. virtual IStringVal& getExceptionSource(IStringVal &str) const;
  1686. virtual IStringVal& getExceptionMessage(IStringVal &str) const;
  1687. virtual unsigned getExceptionCode() const;
  1688. virtual ErrorSeverity getSeverity() const;
  1689. virtual IStringVal & getTimeStamp(IStringVal & dt) const;
  1690. virtual IStringVal & getExceptionFileName(IStringVal & str) const;
  1691. virtual unsigned getExceptionLineNo() const;
  1692. virtual unsigned getExceptionColumn() const;
  1693. virtual unsigned getSequence() const;
  1694. virtual void setExceptionSource(const char *str);
  1695. virtual void setExceptionMessage(const char *str);
  1696. virtual void setExceptionCode(unsigned code);
  1697. virtual void setSeverity(ErrorSeverity level);
  1698. virtual void setTimeStamp(const char * dt);
  1699. virtual void setExceptionFileName(const char *str);
  1700. virtual void setExceptionLineNo(unsigned r);
  1701. virtual void setExceptionColumn(unsigned c);
  1702. };
  1703. //==========================================================================================
  1704. extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence)
  1705. {
  1706. switch ((int) sequence)
  1707. {
  1708. case ResultSequenceInternal:
  1709. case ResultSequenceOnce:
  1710. case ResultSequencePersist:
  1711. case ResultSequenceStored:
  1712. return true;
  1713. default:
  1714. assertex(sequence <= INT_MAX);
  1715. return false;
  1716. }
  1717. }
  1718. class CConstWUArrayIterator : implements IConstWorkUnitIterator, public CInterface
  1719. {
  1720. unsigned curTreeNum;
  1721. IArrayOf<IPropertyTree> trees;
  1722. Owned<IConstWorkUnitInfo> cur;
  1723. void setCurrent()
  1724. {
  1725. cur.setown(new CLightweightWorkunitInfo(trees.item(curTreeNum)));
  1726. }
  1727. public:
  1728. IMPLEMENT_IINTERFACE;
  1729. CConstWUArrayIterator(IArrayOf<IPropertyTree> &_trees)
  1730. {
  1731. ForEachItemIn(t, _trees)
  1732. trees.append(*LINK(&_trees.item(t)));
  1733. curTreeNum = 0;
  1734. }
  1735. bool first()
  1736. {
  1737. curTreeNum = 0;
  1738. return next();
  1739. }
  1740. bool isValid()
  1741. {
  1742. return (NULL != cur.get());
  1743. }
  1744. bool next()
  1745. {
  1746. if (curTreeNum >= trees.ordinality())
  1747. {
  1748. cur.clear();
  1749. return false;
  1750. }
  1751. setCurrent();
  1752. ++curTreeNum;
  1753. return true;
  1754. }
  1755. IConstWorkUnitInfo & query() { return *cur; }
  1756. };
  1757. class CLocalWUFieldUsage : public CInterface, implements IConstWUFieldUsage
  1758. {
  1759. Owned<IPropertyTree> p;
  1760. public:
  1761. IMPLEMENT_IINTERFACE;
  1762. CLocalWUFieldUsage(IPropertyTree& _p) { p.setown(&_p); }
  1763. virtual const char * queryName() const { return p->queryProp("@name"); }
  1764. };
  1765. class CConstWUFieldUsageIterator : public CInterface, implements IConstWUFieldUsageIterator
  1766. {
  1767. public:
  1768. IMPLEMENT_IINTERFACE;
  1769. CConstWUFieldUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  1770. bool first() override { return iter->first(); }
  1771. bool isValid() override { return iter->isValid(); }
  1772. bool next() override { return iter->next(); }
  1773. IConstWUFieldUsage * get() const override { return new CLocalWUFieldUsage(iter->get()); }
  1774. private:
  1775. Owned<IPropertyTreeIterator> iter;
  1776. };
  1777. class CLocalWUFileUsage : public CInterface, implements IConstWUFileUsage
  1778. {
  1779. Owned<IPropertyTree> p;
  1780. public:
  1781. IMPLEMENT_IINTERFACE;
  1782. CLocalWUFileUsage(IPropertyTree& _p) { p.setown(&_p); }
  1783. virtual const char * queryName() const { return p->queryProp("@name"); }
  1784. virtual const char * queryType() const { return p->queryProp("@type"); }
  1785. virtual unsigned getNumFields() const { return p->getPropInt("@numFields"); }
  1786. virtual unsigned getNumFieldsUsed() const { return p->getPropInt("@numFieldsUsed"); }
  1787. virtual IConstWUFieldUsageIterator * getFields() const { return new CConstWUFieldUsageIterator(p->getElements("fields/field")); }
  1788. };
  1789. class CConstWUFileUsageIterator : public CInterface, implements IConstWUFileUsageIterator
  1790. {
  1791. public:
  1792. IMPLEMENT_IINTERFACE;
  1793. CConstWUFileUsageIterator(IPropertyTreeIterator * tree) { iter.setown(tree); }
  1794. bool first() override { return iter->first(); }
  1795. bool isValid() override { return iter->isValid(); }
  1796. bool next() override { return iter->next(); }
  1797. IConstWUFileUsage * get() const override { return new CLocalWUFileUsage(iter->get()); }
  1798. private:
  1799. Owned<IPropertyTreeIterator> iter;
  1800. };
  1801. //==========================================================================================
  1802. class CStringArrayIterator : implements IStringIterator, public CInterface
  1803. {
  1804. unsigned idx;
  1805. StringArray strings;
  1806. public:
  1807. IMPLEMENT_IINTERFACE;
  1808. CStringArrayIterator() { idx = 0; };
  1809. void append(const char *str) { strings.append(str); }
  1810. virtual bool first() { idx = 0; return strings.isItem(idx); }
  1811. virtual bool next() { idx ++; return strings.isItem(idx); }
  1812. virtual bool isValid() { return strings.isItem(idx); }
  1813. virtual IStringVal & str(IStringVal &s) { s.set(strings.item(idx)); return s; }
  1814. };
  1815. class CCachedJobNameIterator : implements IStringIterator, public CInterface
  1816. {
  1817. Owned<IPropertyTreeIterator> it;
  1818. public:
  1819. IMPLEMENT_IINTERFACE;
  1820. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  1821. virtual bool first() { return it->first(); }
  1822. virtual bool next() { return it->next(); }
  1823. virtual bool isValid() { return it->isValid(); }
  1824. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  1825. };
  1826. class CEmptyStringIterator : implements IStringIterator, public CInterface
  1827. {
  1828. public:
  1829. IMPLEMENT_IINTERFACE;
  1830. virtual bool first() { return false; }
  1831. virtual bool next() { return false; }
  1832. virtual bool isValid() { return false; }
  1833. virtual IStringVal & str(IStringVal &s) { s.clear(); return s; }
  1834. };
  1835. mapEnums workunitSortFields[] =
  1836. {
  1837. { WUSFuser, "@submitID" },
  1838. { WUSFcluster, "@clusterName" },
  1839. { WUSFjob, "@jobName" },
  1840. { WUSFstate, "@state" },
  1841. { WUSFpriority, "@priorityClass" },
  1842. { WUSFprotected, "@protected" },
  1843. { WUSFwuid, "@" },
  1844. { WUSFecl, "Query/Text" },
  1845. { WUSFfileread, "FilesRead/File/@name" },
  1846. { WUSFtotalthortime, "@totalThorTime|"
  1847. "Statistics/Statistic[@c='summary'][@creator='thor'][@kind='TimeElapsed']/@value|"
  1848. "Statistics/Statistic[@c='summary'][@creator='hthor'][@kind='TimeElapsed']/@value|"
  1849. "Statistics/Statistic[@c='summary'][@creator='roxie'][@kind='TimeElapsed']/@value|"
  1850. "Statistics/Statistic[@desc='Total thor time']/@value|"
  1851. "Timings/Timing[@name='Total thor time']/@duration" //Use Statistics first. If not found, use Timings
  1852. },
  1853. { WUSFwuidhigh, "@" },
  1854. { WUSFwildwuid, "@" },
  1855. { WUSFappvalue, "Application" },
  1856. { WUSFfilewritten, "Files/File/@name" },
  1857. { WUSFterm, NULL }
  1858. };
  1859. extern const char *queryFilterXPath(WUSortField field)
  1860. {
  1861. return getEnumText(field, workunitSortFields);
  1862. }
  1863. mapEnums querySortFields[] =
  1864. {
  1865. { WUQSFId, "@id" },
  1866. { WUQSFwuid, "@wuid" },
  1867. { WUQSFname, "@name" },
  1868. { WUQSFdll, "@dll" },
  1869. { WUQSFmemoryLimit, "@memoryLimit" },
  1870. { WUQSFmemoryLimitHi, "@memoryLimit" },
  1871. { WUQSFtimeLimit, "@timeLimit" },
  1872. { WUQSFtimeLimitHi, "@timeLimit" },
  1873. { WUQSFwarnTimeLimit, "@warnTimeLimit" },
  1874. { WUQSFwarnTimeLimitHi, "@warnTimeLimit" },
  1875. { WUQSFpriority, "@priority" },
  1876. { WUQSFpriorityHi, "@priority" },
  1877. { WUQSFQuerySet, "@querySetId" },
  1878. { WUQSFActivited, "@activated" },
  1879. { WUQSFSuspendedByUser, "@suspended" },
  1880. { WUQSFLibrary, "Library"},
  1881. { WUQSFPublishedBy, "@publishedBy" },
  1882. { WUQSFterm, NULL }
  1883. };
  1884. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  1885. {
  1886. StringAttr name;
  1887. public:
  1888. IMPLEMENT_IINTERFACE;
  1889. asyncRemoveDllWorkItem(const char * _name) : name(_name)
  1890. {
  1891. }
  1892. void execute()
  1893. {
  1894. PROGLOG("WU removeDll %s", name.get());
  1895. queryDllServer().removeDll(name, true, true); // <name>, removeDlls=true, removeDirectory=true
  1896. }
  1897. };
  1898. class asyncRemoveRemoteFileWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveFile
  1899. {
  1900. RemoteFilename name;
  1901. public:
  1902. IMPLEMENT_IINTERFACE;
  1903. asyncRemoveRemoteFileWorkItem(const char * _ip, const char * _name)
  1904. {
  1905. SocketEndpoint ep(_ip);
  1906. name.setPath(ep, _name);
  1907. }
  1908. void execute()
  1909. {
  1910. Owned<IFile> file = createIFile(name);
  1911. PROGLOG("WU removeDll %s",file->queryFilename());
  1912. file->remove();
  1913. }
  1914. };
  1915. //==========================================================================================
  1916. class CConstQuerySetQueryIterator : implements IConstQuerySetQueryIterator, public CInterface
  1917. {
  1918. unsigned index;
  1919. IArrayOf<IPropertyTree> trees;
  1920. public:
  1921. IMPLEMENT_IINTERFACE;
  1922. CConstQuerySetQueryIterator(IArrayOf<IPropertyTree> &_trees)
  1923. {
  1924. ForEachItemIn(t, _trees)
  1925. trees.append(*LINK(&_trees.item(t)));
  1926. index = 0;
  1927. }
  1928. ~CConstQuerySetQueryIterator()
  1929. {
  1930. trees.kill();
  1931. }
  1932. bool first()
  1933. {
  1934. index = 0;
  1935. return (trees.ordinality()!=0);
  1936. }
  1937. bool next()
  1938. {
  1939. index++;
  1940. return (index<trees.ordinality());
  1941. }
  1942. bool isValid()
  1943. {
  1944. return (index<trees.ordinality());
  1945. }
  1946. IPropertyTree &query()
  1947. {
  1948. return trees.item(index);
  1949. }
  1950. };
  1951. class CSecurityCache
  1952. {
  1953. };
  1954. class CConstWUIterator : implements IConstWorkUnitIterator, public CInterface
  1955. {
  1956. public:
  1957. IMPLEMENT_IINTERFACE;
  1958. CConstWUIterator(IPropertyTreeIterator *_ptreeIter)
  1959. : ptreeIter(_ptreeIter)
  1960. {
  1961. }
  1962. bool first()
  1963. {
  1964. if (!ptreeIter->first())
  1965. {
  1966. cur.clear();
  1967. return false;
  1968. }
  1969. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  1970. return true;
  1971. }
  1972. bool isValid()
  1973. {
  1974. return (NULL != cur.get());
  1975. }
  1976. bool next()
  1977. {
  1978. if (!ptreeIter->next())
  1979. {
  1980. cur.clear();
  1981. return false;
  1982. }
  1983. cur.setown(new CLightweightWorkunitInfo(ptreeIter->query()));
  1984. return true;
  1985. }
  1986. IConstWorkUnitInfo & query() { return *cur; }
  1987. private:
  1988. Owned<IConstWorkUnitInfo> cur;
  1989. Owned<IPropertyTreeIterator> ptreeIter;
  1990. };
  1991. class CSecureConstWUIterator : public CInterfaceOf<IConstWorkUnitIterator>
  1992. {
  1993. public:
  1994. CSecureConstWUIterator(IConstWorkUnitIterator *_parent, ISecManager *_secmgr=NULL, ISecUser *_secuser=NULL)
  1995. : parent(_parent), secmgr(_secmgr), secuser(_secuser)
  1996. {
  1997. assertex(_secuser && _secmgr);
  1998. }
  1999. bool first()
  2000. {
  2001. if (!parent->first())
  2002. return false;
  2003. return getNext();
  2004. }
  2005. bool next()
  2006. {
  2007. if (!parent->next())
  2008. return false;
  2009. return getNext();
  2010. }
  2011. virtual bool isValid()
  2012. {
  2013. return parent->isValid();
  2014. }
  2015. virtual IConstWorkUnitInfo &query()
  2016. {
  2017. return parent->query();
  2018. }
  2019. private:
  2020. Owned<IConstWorkUnitIterator> parent;
  2021. MapStringTo<int> scopePermissions;
  2022. Linked<ISecManager> secmgr;
  2023. Linked<ISecUser> secuser;
  2024. bool getNext() // scan for a workunit with permissions
  2025. {
  2026. do
  2027. {
  2028. const char *scopeName = parent->query().queryWuScope();
  2029. if (!scopeName || !*scopeName || checkScope(scopeName))
  2030. return true;
  2031. } while (parent->next());
  2032. return false;
  2033. }
  2034. bool checkScope(const char *scopeName)
  2035. {
  2036. int *perms = scopePermissions.getValue(scopeName);
  2037. SecAccessFlags perm;
  2038. if (!perms)
  2039. {
  2040. perm = secuser.get() ? secmgr->authorizeWorkunitScope(*secuser, scopeName) : SecAccess_Unavailable;
  2041. scopePermissions.setValue(scopeName, perm);
  2042. }
  2043. else
  2044. perm = (SecAccessFlags)*perms;
  2045. return perm >= SecAccess_Read;
  2046. }
  2047. };
  2048. CWorkUnitFactory::CWorkUnitFactory()
  2049. {
  2050. }
  2051. CWorkUnitFactory::~CWorkUnitFactory()
  2052. {
  2053. }
  2054. IWorkUnit* CWorkUnitFactory::createNamedWorkUnit(const char *wuid, const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  2055. {
  2056. checkWuScopeSecAccess(scope, secmgr, secuser, SecAccess_Write, "Create", true, true);
  2057. Owned<CLocalWorkUnit> cw = _createWorkUnit(wuid, secmgr, secuser);
  2058. if (scope)
  2059. 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...
  2060. IWorkUnit* ret = &cw->lockRemote(false); // Note - this may throw exception if user does not have rights.
  2061. ret->setDebugValue("CREATED_BY", app, true);
  2062. ret->setDebugValue("CREATED_FOR", scope, true);
  2063. return ret;
  2064. }
  2065. IWorkUnit* CWorkUnitFactory::createWorkUnit(const char *app, const char *scope, ISecManager *secmgr, ISecUser *secuser)
  2066. {
  2067. StringBuffer wuid("W");
  2068. char result[32];
  2069. time_t ltime;
  2070. time( &ltime );
  2071. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  2072. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  2073. wuid.append(result);
  2074. if (workUnitTraceLevel > 1)
  2075. PrintLog("createWorkUnit created %s", wuid.str());
  2076. IWorkUnit* ret = createNamedWorkUnit(wuid.str(), app, scope, secmgr, secuser);
  2077. if (workUnitTraceLevel > 1)
  2078. PrintLog("createWorkUnit created %s", ret->queryWuid());
  2079. addTimeStamp(ret, SSTglobal, NULL, StWhenCreated);
  2080. return ret;
  2081. }
  2082. bool CWorkUnitFactory::deleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser)
  2083. {
  2084. if (workUnitTraceLevel > 1)
  2085. PrintLog("deleteWorkUnit %s", wuid);
  2086. StringBuffer wuRoot;
  2087. getXPath(wuRoot, wuid);
  2088. Owned<CLocalWorkUnit> cw = _updateWorkUnit(wuid, secmgr, secuser);
  2089. if (!checkWuSecAccess(*cw.get(), secmgr, secuser, SecAccess_Full, "delete", true, true))
  2090. return false;
  2091. try
  2092. {
  2093. cw->cleanupAndDelete(true, true);
  2094. }
  2095. catch (IException *E)
  2096. {
  2097. StringBuffer s;
  2098. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  2099. E->Release();
  2100. return false;
  2101. }
  2102. removeWorkUnitFromAllQueues(wuid); //known active workunits wouldn't make it this far
  2103. return true;
  2104. }
  2105. IConstWorkUnit* CWorkUnitFactory::openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2106. {
  2107. StringBuffer wuidStr(wuid);
  2108. wuidStr.trim();
  2109. if (wuidStr.length() && ('w' == wuidStr.charAt(0)))
  2110. wuidStr.setCharAt(0, 'W');
  2111. if (!wuidStr.length() || ('W' != wuidStr.charAt(0)))
  2112. {
  2113. if (workUnitTraceLevel > 1)
  2114. PrintLog("openWorkUnit %s invalid WUID", nullText(wuidStr.str()));
  2115. return NULL;
  2116. }
  2117. if (workUnitTraceLevel > 1)
  2118. PrintLog("openWorkUnit %s", wuidStr.str());
  2119. Owned<IConstWorkUnit> wu = _openWorkUnit(wuid, secmgr, secuser);
  2120. if (wu)
  2121. {
  2122. if (!checkWuSecAccess(*wu, secmgr, secuser, SecAccess_Read, "opening", true, true))
  2123. return NULL; // Actually throws exception on failure, so won't reach here
  2124. return wu.getClear();
  2125. }
  2126. else
  2127. {
  2128. if (workUnitTraceLevel > 0)
  2129. PrintLog("openWorkUnit %s not found", wuidStr.str());
  2130. return NULL;
  2131. }
  2132. }
  2133. IWorkUnit* CWorkUnitFactory::updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2134. {
  2135. if (workUnitTraceLevel > 1)
  2136. PrintLog("updateWorkUnit %s", wuid);
  2137. Owned<CLocalWorkUnit> wu = _updateWorkUnit(wuid, secmgr, secuser);
  2138. if (wu)
  2139. {
  2140. if (!checkWuSecAccess(*wu.get(), secmgr, secuser, SecAccess_Write, "updating", true, true))
  2141. return NULL;
  2142. return &wu->lockRemote(false);
  2143. }
  2144. else
  2145. {
  2146. if (workUnitTraceLevel > 0)
  2147. PrintLog("updateWorkUnit %s not found", wuid);
  2148. return NULL;
  2149. }
  2150. }
  2151. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  2152. {
  2153. Owned<IPropertyTree> ret;
  2154. IPropertyTree * branch = from->queryPropTree(xpath);
  2155. if(branch)
  2156. {
  2157. ret.setown(createPTreeFromIPT(branch));
  2158. from->removeTree(branch);
  2159. }
  2160. return ret.getClear();
  2161. }
  2162. bool CWorkUnitFactory::restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  2163. {
  2164. StringBuffer path(base);
  2165. addPathSepChar(path).append(wuid).append(".xml");
  2166. Owned<IPTree> pt = createPTreeFromXMLFile(path);
  2167. if (!pt)
  2168. return false;
  2169. CDateTime dt;
  2170. dt.setNow();
  2171. StringBuffer dts;
  2172. dt.getString(dts);
  2173. pt->setProp("@restoredDate", dts.str());
  2174. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  2175. Owned<IPropertyTree> associatedFiles;
  2176. IPropertyTree *srcAssociated = pt->queryPropTree("Query/Associated");
  2177. if (srcAssociated)
  2178. associatedFiles.setown(createPTreeFromIPT(srcAssociated));
  2179. // The updating of the repo is implementation specific...
  2180. if (!_restoreWorkUnit(pt.getClear(), wuid))
  2181. return false;
  2182. // now kludge back GeneratedDlls
  2183. if (generatedDlls)
  2184. {
  2185. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  2186. for(dlls->first(); dlls->isValid(); dlls->next())
  2187. {
  2188. IPropertyTree & dll = dlls->query();
  2189. char const * name = dll.queryProp("@name");
  2190. char const * kind = dll.queryProp("@kind");
  2191. char const * location = dll.queryProp("@location");
  2192. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  2193. if (!got)
  2194. {
  2195. RemoteFilename dstRfn;
  2196. dstRfn.setRemotePath(location);
  2197. StringBuffer srcPath(base);
  2198. addPathSepChar(srcPath);
  2199. dstRfn.getTail(srcPath);
  2200. OwnedIFile srcFile = createIFile(srcPath);
  2201. OwnedIFile dstFile = createIFile(dstRfn);
  2202. copyFile(dstFile, srcFile);
  2203. queryDllServer().registerDll(name, kind, location);
  2204. }
  2205. }
  2206. }
  2207. if (associatedFiles)
  2208. {
  2209. Owned<IPropertyTreeIterator> associated = associatedFiles->getElements("*");
  2210. ForEach(*associated)
  2211. {
  2212. IPropertyTree &file = associated->query();
  2213. const char *filename = file.queryProp("@filename");
  2214. SocketEndpoint ep(file.queryProp("@ip"));
  2215. RemoteFilename rfn;
  2216. rfn.setPath(ep, filename);
  2217. OwnedIFile dstFile = createIFile(rfn);
  2218. StringBuffer srcPath(base), name;
  2219. addPathSepChar(srcPath);
  2220. rfn.getTail(name);
  2221. srcPath.append(name);
  2222. if (generatedDlls)
  2223. {
  2224. VStringBuffer gDllPath("GeneratedDll[@name=\"%s\"]", name.str());
  2225. if (generatedDlls->hasProp(gDllPath))
  2226. continue; // generated dlls handled separately - see above
  2227. }
  2228. OwnedIFile srcFile = createIFile(srcPath);
  2229. if (srcFile->exists())
  2230. {
  2231. try
  2232. {
  2233. copyFile(dstFile, srcFile);
  2234. }
  2235. catch (IException *e)
  2236. {
  2237. VStringBuffer msg("Failed to restore associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  2238. EXCLOG(e, msg.str());
  2239. e->Release();
  2240. }
  2241. }
  2242. }
  2243. }
  2244. return true;
  2245. }
  2246. int CWorkUnitFactory::setTracingLevel(int newLevel)
  2247. {
  2248. if (newLevel)
  2249. PrintLog("Setting workunit trace level to %d", newLevel);
  2250. int level = workUnitTraceLevel;
  2251. workUnitTraceLevel = newLevel;
  2252. return level;
  2253. }
  2254. void CWorkUnitFactory::descheduleAllWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  2255. {
  2256. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2257. if(!conn) return;
  2258. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  2259. KeptAtomTable entries;
  2260. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  2261. StringBuffer wuid;
  2262. for(iter->first(); iter->isValid(); iter->next())
  2263. {
  2264. char const * entry = iter->query().queryName();
  2265. if(!entries.find(entry))
  2266. {
  2267. entries.addAtom(entry);
  2268. ncnameUnescape(entry, wuid.clear());
  2269. Owned<IWorkUnit> wu = updateWorkUnit(wuid, secmgr, secuser);
  2270. if(wu && (wu->getState() == WUStateWait))
  2271. wu->setState(WUStateCompleted);
  2272. }
  2273. }
  2274. bool more;
  2275. do more = root->removeProp("*"); while(more);
  2276. }
  2277. IConstQuerySetQueryIterator* CWorkUnitFactory::getQuerySetQueriesSorted( WUQuerySortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  2278. WUQuerySortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2279. const void *filterbuf, // (appended) string values for filters
  2280. unsigned startoffset,
  2281. unsigned maxnum,
  2282. __int64 *cachehint,
  2283. unsigned *total,
  2284. const MapStringTo<bool> *_subset)
  2285. {
  2286. struct PostFilters
  2287. {
  2288. WUQueryFilterBoolean activatedFilter;
  2289. WUQueryFilterBoolean suspendedByUserFilter;
  2290. PostFilters()
  2291. {
  2292. activatedFilter = WUQFSAll;
  2293. suspendedByUserFilter = WUQFSAll;
  2294. };
  2295. } postFilters;
  2296. class CQuerySetQueriesPager : public CSimpleInterface, implements IElementsPager
  2297. {
  2298. StringAttr querySet;
  2299. StringAttr xPath;
  2300. StringAttr sortOrder;
  2301. PostFilters postFilters;
  2302. StringArray unknownAttributes;
  2303. const MapStringTo<bool> *subset;
  2304. void populateQueryTree(const IPropertyTree* querySetTree, IPropertyTree* queryTree)
  2305. {
  2306. const char* querySetId = querySetTree->queryProp("@id");
  2307. VStringBuffer path("Query%s", xPath.get());
  2308. Owned<IPropertyTreeIterator> iter = querySetTree->getElements(path.str());
  2309. ForEach(*iter)
  2310. {
  2311. IPropertyTree &query = iter->query();
  2312. bool activated = false;
  2313. const char* queryId = query.queryProp("@id");
  2314. if (queryId && *queryId)
  2315. {
  2316. if (subset)
  2317. {
  2318. VStringBuffer match("%s/%s", querySetId, queryId);
  2319. if (!subset->getValue(match))
  2320. continue;
  2321. }
  2322. VStringBuffer aliasXPath("Alias[@id='%s']", queryId);
  2323. IPropertyTree *alias = querySetTree->queryPropTree(aliasXPath.str());
  2324. if (alias)
  2325. activated = true;
  2326. }
  2327. if (activated && (postFilters.activatedFilter == WUQFSNo))
  2328. continue;
  2329. if (!activated && (postFilters.activatedFilter == WUQFSYes))
  2330. continue;
  2331. if ((postFilters.suspendedByUserFilter == WUQFSNo) && query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  2332. continue;
  2333. if ((postFilters.suspendedByUserFilter == WUQFSYes) && !query.hasProp(getEnumText(WUQSFSuspendedByUser,querySortFields)))
  2334. continue;
  2335. IPropertyTree *queryWithSetId = queryTree->addPropTree("Query", createPTreeFromIPT(&query));
  2336. queryWithSetId->setProp("@querySetId", querySetId);
  2337. queryWithSetId->setPropBool("@activated", activated);
  2338. }
  2339. }
  2340. IRemoteConnection* populateQueryTree(IPropertyTree* queryTree)
  2341. {
  2342. StringBuffer querySetXPath("QuerySets");
  2343. if (!querySet.isEmpty())
  2344. querySetXPath.appendf("/QuerySet[@id=\"%s\"]", querySet.get());
  2345. Owned<IRemoteConnection> conn = querySDS().connect(querySetXPath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2346. if (!conn)
  2347. return NULL;
  2348. if (querySet.isEmpty())
  2349. {
  2350. Owned<IPropertyTreeIterator> querySetIter = conn->queryRoot()->getElements("*");
  2351. ForEach(*querySetIter)
  2352. populateQueryTree(&querySetIter->query(), queryTree);
  2353. }
  2354. else
  2355. populateQueryTree(conn->queryRoot(), queryTree);
  2356. return conn.getClear();
  2357. }
  2358. public:
  2359. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2360. CQuerySetQueriesPager(const char* _querySet, const char* _xPath, const char *_sortOrder, PostFilters& _postFilters, StringArray& _unknownAttributes, const MapStringTo<bool> *_subset)
  2361. : querySet(_querySet), xPath(_xPath), sortOrder(_sortOrder), subset(_subset)
  2362. {
  2363. postFilters.activatedFilter = _postFilters.activatedFilter;
  2364. postFilters.suspendedByUserFilter = _postFilters.suspendedByUserFilter;
  2365. ForEachItemIn(x, _unknownAttributes)
  2366. unknownAttributes.append(_unknownAttributes.item(x));
  2367. }
  2368. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  2369. {
  2370. Owned<IPropertyTree> elementTree = createPTree("Queries");
  2371. Owned<IRemoteConnection> conn = populateQueryTree(elementTree);
  2372. if (!conn)
  2373. return NULL;
  2374. Owned<IPropertyTreeIterator> iter = elementTree->getElements("*");
  2375. if (!iter)
  2376. return NULL;
  2377. sortElements(iter, sortOrder.get(), NULL, NULL, unknownAttributes, elements);
  2378. return conn.getClear();
  2379. }
  2380. virtual bool allMatchingElementsReceived() { return true; } //For now, dali always returns all of matched Queries.
  2381. };
  2382. StringAttr querySet;
  2383. StringBuffer xPath;
  2384. StringBuffer so;
  2385. StringArray unknownAttributes;
  2386. if (filters)
  2387. {
  2388. const char *fv = (const char *)filterbuf;
  2389. for (unsigned i=0;filters[i]!=WUQSFterm;i++) {
  2390. int fmt = filters[i];
  2391. int subfmt = (fmt&0xff);
  2392. if (subfmt==WUQSFQuerySet)
  2393. querySet.set(fv);
  2394. else if ((subfmt==WUQSFmemoryLimit) || (subfmt==WUQSFtimeLimit) || (subfmt==WUQSFwarnTimeLimit) || (subfmt==WUQSFpriority))
  2395. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append(">=").append(fv).append("]");
  2396. else if ((subfmt==WUQSFmemoryLimitHi) || (subfmt==WUQSFtimeLimitHi) || (subfmt==WUQSFwarnTimeLimitHi) || (subfmt==WUQSFpriorityHi))
  2397. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append("<=").append(fv).append("]");
  2398. else if (subfmt==WUQSFActivited)
  2399. postFilters.activatedFilter = (WUQueryFilterBoolean) atoi(fv);
  2400. else if (subfmt==WUQSFSuspendedByUser)
  2401. postFilters.suspendedByUserFilter = (WUQueryFilterBoolean) atoi(fv);
  2402. else if (!fv || !*fv)
  2403. unknownAttributes.append(getEnumText(subfmt,querySortFields));
  2404. else {
  2405. xPath.append('[').append(getEnumText(subfmt,querySortFields)).append('=');
  2406. if (fmt&WUQSFnocase)
  2407. xPath.append('?');
  2408. if (fmt&WUQSFnumeric)
  2409. xPath.append('#');
  2410. if (fmt&WUQSFwild)
  2411. xPath.append('~');
  2412. xPath.append('"').append(fv).append("\"]");
  2413. }
  2414. fv = fv + strlen(fv)+1;
  2415. }
  2416. }
  2417. if (sortorder) {
  2418. for (unsigned i=0;sortorder[i]!=WUQSFterm;i++) {
  2419. if (so.length())
  2420. so.append(',');
  2421. int fmt = sortorder[i];
  2422. if (fmt&WUQSFreverse)
  2423. so.append('-');
  2424. if (fmt&WUQSFnocase)
  2425. so.append('?');
  2426. if (fmt&WUQSFnumeric)
  2427. so.append('#');
  2428. so.append(getEnumText(fmt&0xff,querySortFields));
  2429. }
  2430. }
  2431. IArrayOf<IPropertyTree> results;
  2432. Owned<IElementsPager> elementsPager = new CQuerySetQueriesPager(querySet.get(), xPath.str(), so.length()?so.str():NULL, postFilters, unknownAttributes, _subset);
  2433. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,NULL,"",cachehint,results,total,NULL);
  2434. return new CConstQuerySetQueryIterator(results);
  2435. }
  2436. bool CWorkUnitFactory::isAborting(const char *wuid) const
  2437. {
  2438. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  2439. try
  2440. {
  2441. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2442. if (acon)
  2443. return acon->queryRoot()->getPropInt(NULL) != 0;
  2444. }
  2445. catch (IException *E)
  2446. {
  2447. EXCLOG(E);
  2448. E->Release();
  2449. }
  2450. return false;
  2451. }
  2452. void CWorkUnitFactory::clearAborting(const char *wuid)
  2453. {
  2454. VStringBuffer apath("/WorkUnitAborts/%s", wuid);
  2455. try
  2456. {
  2457. Owned<IRemoteConnection> acon = querySDS().connect(apath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  2458. if (acon)
  2459. acon->close(true);
  2460. }
  2461. catch (IException *E)
  2462. {
  2463. EXCLOG(E);
  2464. E->Release();
  2465. }
  2466. }
  2467. void CWorkUnitFactory::reportAbnormalTermination(const char *wuid, WUState &state, SessionId agent)
  2468. {
  2469. WARNLOG("reportAbnormalTermination: session stopped unexpectedly: %" I64F "d state: %d", (__int64) agent, (int) state);
  2470. bool isEcl = false;
  2471. switch (state)
  2472. {
  2473. case WUStateAborting:
  2474. state = WUStateAborted;
  2475. break;
  2476. case WUStateCompiling:
  2477. isEcl = true;
  2478. // drop into
  2479. default:
  2480. state = WUStateFailed;
  2481. }
  2482. Owned<IWorkUnit> wu = updateWorkUnit(wuid, NULL, NULL);
  2483. wu->setState(state);
  2484. Owned<IWUException> e = wu->createException();
  2485. e->setExceptionCode(isEcl ? 1001 : 1000);
  2486. e->setExceptionMessage(isEcl ? "EclServer terminated unexpectedly" : "Workunit terminated unexpectedly");
  2487. }
  2488. static CriticalSection deleteDllLock;
  2489. static Owned<IWorkQueueThread> deleteDllWorkQ;
  2490. static void asyncRemoveDll(const char * name)
  2491. {
  2492. CriticalBlock b(deleteDllLock);
  2493. if (!deleteDllWorkQ)
  2494. deleteDllWorkQ.setown(createWorkQueueThread());
  2495. deleteDllWorkQ->post(new asyncRemoveDllWorkItem(name));
  2496. }
  2497. static void asyncRemoveFile(const char * ip, const char * name)
  2498. {
  2499. CriticalBlock b(deleteDllLock);
  2500. if (!deleteDllWorkQ)
  2501. deleteDllWorkQ.setown(createWorkQueueThread());
  2502. deleteDllWorkQ->post(new asyncRemoveRemoteFileWorkItem(ip, name));
  2503. }
  2504. class CDaliWorkUnitFactory : public CWorkUnitFactory, implements IDaliClientShutdown
  2505. {
  2506. public:
  2507. IMPLEMENT_IINTERFACE_USING(CWorkUnitFactory);
  2508. CDaliWorkUnitFactory()
  2509. {
  2510. // Assumes dali client configuration has already been done
  2511. sdsManager = &querySDS();
  2512. session = myProcessSession();
  2513. addShutdownHook(*this);
  2514. }
  2515. ~CDaliWorkUnitFactory()
  2516. {
  2517. removeShutdownHook(*this);
  2518. }
  2519. virtual bool initializeStore()
  2520. {
  2521. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  2522. }
  2523. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  2524. {
  2525. return new CDaliWorkUnitWatcher(subscriber, options, wuid);
  2526. }
  2527. virtual unsigned validateRepository(bool fixErrors)
  2528. {
  2529. return 0;
  2530. }
  2531. virtual void deleteRepository(bool recreate)
  2532. {
  2533. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2534. if (conn)
  2535. conn->close(true);
  2536. conn.setown(sdsManager->connect("/GraphProgress", session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  2537. if (conn)
  2538. conn->close(true);
  2539. }
  2540. virtual void createRepository()
  2541. {
  2542. // Nothing to do
  2543. }
  2544. virtual const char *queryStoreType() const
  2545. {
  2546. return "Dali";
  2547. }
  2548. virtual CLocalWorkUnit *_createWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2549. {
  2550. StringBuffer wuRoot;
  2551. getXPath(wuRoot, wuid);
  2552. IRemoteConnection *conn;
  2553. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  2554. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  2555. conn->queryRoot()->setPropInt("@wuidVersion", WUID_VERSION);
  2556. return new CDaliWorkUnit(conn, secmgr, secuser);
  2557. }
  2558. virtual CLocalWorkUnit* _openWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2559. {
  2560. StringBuffer wuRoot;
  2561. getXPath(wuRoot, wuid);
  2562. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2563. if (conn)
  2564. return new CDaliWorkUnit(conn, secmgr, secuser);
  2565. else
  2566. return NULL;
  2567. }
  2568. virtual bool _restoreWorkUnit(IPTree *_pt, const char *wuid)
  2569. {
  2570. Owned<IPTree> pt(_pt);
  2571. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  2572. StringBuffer wuRoot;
  2573. getXPath(wuRoot, wuid);
  2574. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  2575. if (!conn)
  2576. {
  2577. ERRLOG("restoreWorkUnit could not create to %s", wuRoot.str());
  2578. return false;
  2579. }
  2580. IPropertyTree *root = conn->queryRoot();
  2581. if (root->hasChildren())
  2582. {
  2583. ERRLOG("restoreWorkUnit WUID %s already exists", wuid);
  2584. return false;
  2585. }
  2586. root->setPropTree(NULL, pt.getClear());
  2587. conn.clear();
  2588. // now kludge back GraphProgress
  2589. if (gprogress)
  2590. {
  2591. VStringBuffer xpath("/GraphProgress/%s", wuid);
  2592. conn.setown(querySDS().connect(xpath, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  2593. if (conn)
  2594. {
  2595. IPropertyTree *groot = conn->queryRoot();
  2596. if (groot->hasChildren())
  2597. WARNLOG("restoreWorkUnit WUID %s graphprogress already exists, replacing",wuid);
  2598. groot->setPropTree(NULL, gprogress.getClear());
  2599. }
  2600. }
  2601. return true;
  2602. }
  2603. virtual CLocalWorkUnit* _updateWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  2604. {
  2605. StringBuffer wuRoot;
  2606. getXPath(wuRoot, wuid);
  2607. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  2608. if (conn)
  2609. return new CDaliWorkUnit(conn, secmgr, secuser);
  2610. else
  2611. return NULL;
  2612. }
  2613. virtual IWorkUnit* getGlobalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  2614. {
  2615. // MORE - should it check security?
  2616. StringBuffer wuRoot;
  2617. getXPath(wuRoot, GLOBAL_WORKUNIT);
  2618. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  2619. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  2620. Owned<CLocalWorkUnit> cw = new CDaliWorkUnit(conn, (ISecManager *) NULL, NULL);
  2621. return &cw->lockRemote(false);
  2622. }
  2623. virtual IConstWorkUnitIterator* getWorkUnitsByOwner(const char * owner, ISecManager *secmgr, ISecUser *secuser)
  2624. {
  2625. StringBuffer path("*");
  2626. if (owner && *owner)
  2627. path.append("[@submitID=?~\"").append(owner).append("\"]");
  2628. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  2629. }
  2630. IConstWorkUnitIterator* getScheduledWorkUnits(ISecManager *secmgr, ISecUser *secuser)
  2631. {
  2632. StringBuffer path("*");
  2633. path.append("[@state=\"").append(getEnumText(WUStateScheduled, states)).append("\"]");
  2634. return _getWorkUnitsByXPath(path.str(), secmgr, secuser);
  2635. }
  2636. virtual void clientShutdown();
  2637. virtual unsigned numWorkUnits()
  2638. {
  2639. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  2640. if (!conn)
  2641. return 0;
  2642. IPropertyTree *root = conn->queryRoot();
  2643. return root->numChildren();
  2644. }
  2645. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by (and flags for desc sort etc)
  2646. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2647. const void *filterbuf, // (appended) string values for filters
  2648. unsigned startoffset,
  2649. unsigned maxnum,
  2650. __int64 *cachehint,
  2651. unsigned *total,
  2652. ISecManager *secmgr,
  2653. ISecUser *secuser)
  2654. {
  2655. class CWorkUnitsPager : public CSimpleInterface, implements IElementsPager
  2656. {
  2657. StringAttr xPath;
  2658. StringAttr sortOrder;
  2659. StringAttr nameFilterLo;
  2660. StringAttr nameFilterHi;
  2661. StringArray unknownAttributes;
  2662. public:
  2663. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2664. CWorkUnitsPager(const char* _xPath, const char *_sortOrder, const char* _nameFilterLo, const char* _nameFilterHi, StringArray& _unknownAttributes)
  2665. : xPath(_xPath), sortOrder(_sortOrder), nameFilterLo(_nameFilterLo), nameFilterHi(_nameFilterHi)
  2666. {
  2667. ForEachItemIn(x, _unknownAttributes)
  2668. unknownAttributes.append(_unknownAttributes.item(x));
  2669. }
  2670. virtual IRemoteConnection* getElements(IArrayOf<IPropertyTree> &elements)
  2671. {
  2672. Owned<IRemoteConnection> conn = querySDS().connect("WorkUnits", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2673. if (!conn)
  2674. return NULL;
  2675. Owned<IPropertyTreeIterator> iter = conn->getElements(xPath);
  2676. if (!iter)
  2677. return NULL;
  2678. sortElements(iter, sortOrder.get(), nameFilterLo.get(), nameFilterHi.get(), unknownAttributes, elements);
  2679. return conn.getClear();
  2680. }
  2681. virtual bool allMatchingElementsReceived() { return true; }//For now, dali always returns all of matched WUs.
  2682. };
  2683. class CScopeChecker : public CSimpleInterface, implements ISortedElementsTreeFilter
  2684. {
  2685. UniqueScopes done;
  2686. ISecManager *secmgr;
  2687. ISecUser *secuser;
  2688. CriticalSection crit;
  2689. public:
  2690. IMPLEMENT_IINTERFACE_USING(CSimpleInterface);
  2691. CScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  2692. {
  2693. secmgr = _secmgr;
  2694. secuser = _secuser;
  2695. }
  2696. bool isOK(IPropertyTree &tree)
  2697. {
  2698. const char *scopename = tree.queryProp("@scope");
  2699. if (!scopename||!*scopename)
  2700. return true;
  2701. {
  2702. CriticalBlock block(crit);
  2703. const bool *b = done.getValue(scopename);
  2704. if (b)
  2705. return *b;
  2706. }
  2707. bool ret = checkWuScopeSecAccess(scopename,secmgr,secuser,SecAccess_Read,"iterating",false,false);
  2708. {
  2709. // conceivably could have already been checked and added, but ok.
  2710. CriticalBlock block(crit);
  2711. done.setValue(scopename,ret);
  2712. }
  2713. return ret;
  2714. }
  2715. };
  2716. Owned<ISortedElementsTreeFilter> sc = new CScopeChecker(secmgr,secuser);
  2717. StringBuffer query;
  2718. StringBuffer so;
  2719. StringAttr namefilter("*");
  2720. StringAttr namefilterlo;
  2721. StringAttr namefilterhi;
  2722. StringArray unknownAttributes;
  2723. if (filters)
  2724. {
  2725. const char *fv = (const char *) filterbuf;
  2726. for (unsigned i=0;filters[i]!=WUSFterm;i++)
  2727. {
  2728. assertex(fv);
  2729. int fmt = filters[i];
  2730. int subfmt = (fmt&0xff);
  2731. if (subfmt==WUSFwuid)
  2732. namefilterlo.set(fv);
  2733. else if (subfmt==WUSFwuidhigh)
  2734. namefilterhi.set(fv);
  2735. else if (subfmt==WUSFwildwuid)
  2736. namefilter.set(fv);
  2737. else if (subfmt==WUSFappvalue)
  2738. {
  2739. const char *app = fv;
  2740. fv = fv + strlen(fv)+1;
  2741. query.append("[Application/").append(app);
  2742. if (*fv)
  2743. query.append("=?~\"").append(fv).append('\"');
  2744. query.append("]");
  2745. }
  2746. else if (!*fv)
  2747. {
  2748. unknownAttributes.append(getEnumText(subfmt,workunitSortFields));
  2749. if (subfmt==WUSFtotalthortime)
  2750. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  2751. }
  2752. else
  2753. {
  2754. query.append('[').append(getEnumText(subfmt,workunitSortFields)).append('=');
  2755. if (fmt&WUSFnocase)
  2756. query.append('?');
  2757. if (fmt&WUSFwild)
  2758. query.append('~');
  2759. query.append('"').append(fv).append("\"]");
  2760. }
  2761. fv = fv + strlen(fv)+1;
  2762. }
  2763. }
  2764. if ((sortorder&0xff)==WUSFtotalthortime)
  2765. sortorder = (WUSortField) (sortorder & ~WUSFnumeric);
  2766. query.insert(0, namefilter.get());
  2767. if (sortorder)
  2768. {
  2769. if (so.length())
  2770. so.append(',');
  2771. if (sortorder & WUSFreverse)
  2772. so.append('-');
  2773. if (sortorder & WUSFnocase)
  2774. so.append('?');
  2775. if (sortorder & WUSFnumeric)
  2776. so.append('#');
  2777. so.append(getEnumText(sortorder&0xff,workunitSortFields));
  2778. }
  2779. IArrayOf<IPropertyTree> results;
  2780. Owned<IElementsPager> elementsPager = new CWorkUnitsPager(query.str(), so.length()?so.str():NULL, namefilterlo.get(), namefilterhi.get(), unknownAttributes);
  2781. Owned<IRemoteConnection> conn=getElementsPaged(elementsPager,startoffset,maxnum,secmgr?sc:NULL,"",cachehint,results,total,NULL);
  2782. return new CConstWUArrayIterator(results);
  2783. }
  2784. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  2785. {
  2786. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionState);
  2787. LocalIAbortHandler abortHandler(*waiter);
  2788. WUState ret = WUStateUnknown;
  2789. StringBuffer wuRoot;
  2790. getXPath(wuRoot, wuid);
  2791. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2792. if (conn)
  2793. {
  2794. SessionId agent = -1;
  2795. bool agentSessionStopped = false;
  2796. unsigned start = msTick();
  2797. loop
  2798. {
  2799. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  2800. switch (ret)
  2801. {
  2802. case WUStateCompiled:
  2803. case WUStateUploadingFiles:
  2804. if (!compiled)
  2805. break;
  2806. // fall into
  2807. case WUStateCompleted:
  2808. case WUStateFailed:
  2809. case WUStateAborted:
  2810. return ret;
  2811. case WUStateWait:
  2812. if(returnOnWaitState)
  2813. {
  2814. return ret;
  2815. }
  2816. break;
  2817. case WUStateCompiling:
  2818. case WUStateRunning:
  2819. case WUStateDebugPaused:
  2820. case WUStateDebugRunning:
  2821. case WUStateBlocked:
  2822. case WUStateAborting:
  2823. if (agentSessionStopped)
  2824. {
  2825. reportAbnormalTermination(wuid, ret, agent);
  2826. return ret;
  2827. }
  2828. if (queryDaliServerVersion().compare("2.1")>=0)
  2829. {
  2830. agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  2831. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  2832. {
  2833. agentSessionStopped = true;
  2834. conn->reload();
  2835. continue;
  2836. }
  2837. }
  2838. break;
  2839. }
  2840. agentSessionStopped = false; // reset for state changes such as WUStateWait then WUStateRunning again
  2841. unsigned waited = msTick() - start;
  2842. if (timeout==-1)
  2843. {
  2844. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  2845. if (waiter->aborted)
  2846. {
  2847. ret = WUStateUnknown; // MORE - throw an exception?
  2848. break;
  2849. }
  2850. }
  2851. else if (waited > timeout || !waiter->wait(timeout-waited))
  2852. {
  2853. ret = WUStateUnknown; // MORE - throw an exception?
  2854. break;
  2855. }
  2856. conn->reload();
  2857. }
  2858. }
  2859. return ret;
  2860. }
  2861. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  2862. {
  2863. Owned<WorkUnitWaiter> waiter = new WorkUnitWaiter(wuid, SubscribeOptionAction);
  2864. LocalIAbortHandler abortHandler(*waiter);
  2865. WUAction ret = WUActionUnknown;
  2866. StringBuffer wuRoot;
  2867. getXPath(wuRoot, wuid);
  2868. Owned<IRemoteConnection> conn = sdsManager->connect(wuRoot.str(), session, 0, SDS_LOCK_TIMEOUT);
  2869. if (conn)
  2870. {
  2871. unsigned start = msTick();
  2872. loop
  2873. {
  2874. ret = (WUAction) getEnum(conn->queryRoot(), "Action", actions);
  2875. if (ret != original)
  2876. break;
  2877. unsigned waited = msTick() - start;
  2878. waiter->wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  2879. if (waiter->aborted)
  2880. {
  2881. ret = WUActionUnknown; // MORE - throw an exception?
  2882. break;
  2883. }
  2884. conn->reload();
  2885. }
  2886. }
  2887. waiter->unsubscribe();
  2888. return ret;
  2889. }
  2890. protected:
  2891. IConstWorkUnitIterator * _getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  2892. {
  2893. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  2894. if (conn)
  2895. {
  2896. CDaliVersion serverVersionNeeded("3.2");
  2897. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  2898. conn->queryRoot()->getElements(xpath) :
  2899. conn->getElements(xpath));
  2900. return createSecureConstWUIterator(iter.getClear(), secmgr, secuser);
  2901. }
  2902. else
  2903. return NULL;
  2904. }
  2905. ISDSManager *sdsManager;
  2906. SessionId session;
  2907. };
  2908. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  2909. {
  2910. if (secmgr)
  2911. return new CSecureConstWUIterator(iter, secmgr, secuser);
  2912. else
  2913. return iter;
  2914. }
  2915. extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser)
  2916. {
  2917. if (secmgr)
  2918. return new CSecureConstWUIterator(new CConstWUIterator(iter), secmgr, secuser);
  2919. else
  2920. return new CConstWUIterator(iter);
  2921. }
  2922. static CriticalSection factoryCrit;
  2923. static Owned<IWorkUnitFactory> factory;
  2924. void CDaliWorkUnitFactory::clientShutdown()
  2925. {
  2926. CriticalBlock b(factoryCrit);
  2927. factory.clear();
  2928. }
  2929. void clientShutdownWorkUnit()
  2930. {
  2931. CriticalBlock b(factoryCrit);
  2932. factory.clear();
  2933. }
  2934. extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory * _factory)
  2935. {
  2936. CriticalBlock b(factoryCrit);
  2937. factory.setown(_factory);
  2938. }
  2939. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  2940. {
  2941. if (!factory)
  2942. {
  2943. CriticalBlock b(factoryCrit);
  2944. 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.
  2945. {
  2946. const char *forceEnv = getenv("FORCE_DALI_WORKUNITS");
  2947. bool forceDali = forceEnv && !strieq(forceEnv, "off") && !strieq(forceEnv, "0");
  2948. Owned<IRemoteConnection> env = querySDS().connect("/Environment", myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  2949. IPropertyTree *pluginInfo = NULL;
  2950. if (env)
  2951. {
  2952. SocketEndpoint targetDali = queryCoven().queryGroup().queryNode(0).endpoint();
  2953. IPropertyTree *daliInfo = findDaliProcess(env->queryRoot(), targetDali);
  2954. if (daliInfo)
  2955. {
  2956. const char *daliName = daliInfo->queryProp("@name");
  2957. if (daliName)
  2958. {
  2959. VStringBuffer xpath("Software/DaliServerPlugin[@type='WorkunitServer'][@daliServers='%s']", daliName);
  2960. pluginInfo = env->queryRoot()->queryPropTree(xpath);
  2961. }
  2962. if (!pluginInfo)
  2963. pluginInfo = daliInfo->queryPropTree("Plugin[@type='WorkunitServer']"); // Compatibility with early betas of 6.0 ...
  2964. }
  2965. }
  2966. if (pluginInfo && !forceDali)
  2967. factory.setown( (IWorkUnitFactory *) loadPlugin(pluginInfo));
  2968. else
  2969. factory.setown(new CDaliWorkUnitFactory());
  2970. }
  2971. }
  2972. return factory.getLink();
  2973. }
  2974. extern WORKUNIT_API IWorkUnitFactory * getDaliWorkUnitFactory()
  2975. {
  2976. if (!factory)
  2977. {
  2978. CriticalBlock b(factoryCrit);
  2979. 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.
  2980. factory.setown(new CDaliWorkUnitFactory());
  2981. }
  2982. return factory.getLink();
  2983. }
  2984. // A SecureWorkUnitFactory allows the security params to be supplied once to the factory rather than being supplied to each call.
  2985. // They can still be supplied if you want...
  2986. class CSecureWorkUnitFactory : implements IWorkUnitFactory, public CInterface
  2987. {
  2988. public:
  2989. IMPLEMENT_IINTERFACE;
  2990. CSecureWorkUnitFactory(IWorkUnitFactory *_baseFactory, ISecManager *_secMgr, ISecUser *_secUser)
  2991. : baseFactory(_baseFactory), defaultSecMgr(_secMgr), defaultSecUser(_secUser)
  2992. {
  2993. }
  2994. virtual bool initializeStore()
  2995. {
  2996. throwUnexpected(); // Used when loading a plugin factory - not applicable here
  2997. }
  2998. virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const
  2999. {
  3000. return baseFactory->getWatcher(subscriber, options, wuid);
  3001. }
  3002. virtual unsigned validateRepository(bool fix)
  3003. {
  3004. return baseFactory->validateRepository(fix);
  3005. }
  3006. virtual void deleteRepository(bool recreate)
  3007. {
  3008. return baseFactory->deleteRepository(recreate);
  3009. }
  3010. virtual void createRepository()
  3011. {
  3012. return baseFactory->createRepository();
  3013. }
  3014. virtual const char *queryStoreType() const
  3015. {
  3016. return baseFactory->queryStoreType();
  3017. }
  3018. virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const
  3019. {
  3020. return baseFactory->getUniqueValues(field, prefix, result);
  3021. }
  3022. virtual IWorkUnit* createNamedWorkUnit(const char *wuid, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  3023. {
  3024. if (!secMgr) secMgr = defaultSecMgr.get();
  3025. if (!secUser) secUser = defaultSecUser.get();
  3026. return baseFactory->createNamedWorkUnit(wuid, app, user, secMgr, secUser);
  3027. }
  3028. virtual IWorkUnit* createWorkUnit(const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser)
  3029. {
  3030. if (!secMgr) secMgr = defaultSecMgr.get();
  3031. if (!secUser) secUser = defaultSecUser.get();
  3032. return baseFactory->createWorkUnit(app, user, secMgr, secUser);
  3033. }
  3034. virtual bool deleteWorkUnit(const char * wuid, ISecManager *secMgr, ISecUser *secUser)
  3035. {
  3036. if (!secMgr) secMgr = defaultSecMgr.get();
  3037. if (!secUser) secUser = defaultSecUser.get();
  3038. return baseFactory->deleteWorkUnit(wuid, secMgr, secUser);
  3039. }
  3040. virtual IConstWorkUnit* openWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  3041. {
  3042. if (!secMgr) secMgr = defaultSecMgr.get();
  3043. if (!secUser) secUser = defaultSecUser.get();
  3044. return baseFactory->openWorkUnit(wuid, secMgr, secUser);
  3045. }
  3046. virtual IWorkUnit* updateWorkUnit(const char *wuid, ISecManager *secMgr, ISecUser *secUser)
  3047. {
  3048. if (!secMgr) secMgr = defaultSecMgr.get();
  3049. if (!secUser) secUser = defaultSecUser.get();
  3050. return baseFactory->updateWorkUnit(wuid, secMgr, secUser);
  3051. }
  3052. virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociated)
  3053. {
  3054. return baseFactory->restoreWorkUnit(base, wuid, restoreAssociated);
  3055. }
  3056. virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secMgr, ISecUser *secUser)
  3057. {
  3058. if (!secMgr) secMgr = defaultSecMgr.get();
  3059. if (!secUser) secUser = defaultSecUser.get();
  3060. return baseFactory->getGlobalWorkUnit(secMgr, secUser);
  3061. }
  3062. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secMgr, ISecUser *secUser)
  3063. {
  3064. if (!secMgr) secMgr = defaultSecMgr.get();
  3065. if (!secUser) secUser = defaultSecUser.get();
  3066. return baseFactory->getWorkUnitsByOwner(owner, secMgr, secUser);
  3067. }
  3068. virtual IConstWorkUnitIterator * getScheduledWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  3069. {
  3070. if (!secMgr) secMgr = defaultSecMgr.get();
  3071. if (!secUser) secUser = defaultSecUser.get();
  3072. return baseFactory->getScheduledWorkUnits(secMgr, secUser);
  3073. }
  3074. virtual void descheduleAllWorkUnits(ISecManager *secMgr, ISecUser *secUser)
  3075. {
  3076. if (!secMgr) secMgr = defaultSecMgr.get();
  3077. if (!secUser) secUser = defaultSecUser.get();
  3078. baseFactory->descheduleAllWorkUnits(secMgr, secUser);
  3079. }
  3080. virtual int setTracingLevel(int newLevel)
  3081. {
  3082. return baseFactory->setTracingLevel(newLevel);
  3083. }
  3084. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField sortorder, // field to sort by
  3085. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  3086. const void *filterbuf, // (appended) string values for filters
  3087. unsigned startoffset,
  3088. unsigned maxnum,
  3089. __int64 *cachehint,
  3090. unsigned *total,
  3091. ISecManager *secMgr, ISecUser *secUser)
  3092. {
  3093. if (!secMgr) secMgr = defaultSecMgr.get();
  3094. if (!secUser) secUser = defaultSecUser.get();
  3095. return baseFactory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint, total, secMgr, secUser);
  3096. }
  3097. virtual IConstQuerySetQueryIterator* getQuerySetQueriesSorted( WUQuerySortField *sortorder,
  3098. WUQuerySortField *filters,
  3099. const void *filterbuf,
  3100. unsigned startoffset,
  3101. unsigned maxnum,
  3102. __int64 *cachehint,
  3103. unsigned *total,
  3104. const MapStringTo<bool> *subset)
  3105. {
  3106. // MORE - why no security?
  3107. return baseFactory->getQuerySetQueriesSorted(sortorder,filters,filterbuf,startoffset,maxnum,cachehint,total,subset);
  3108. }
  3109. virtual unsigned numWorkUnits()
  3110. {
  3111. return baseFactory->numWorkUnits();
  3112. }
  3113. virtual bool isAborting(const char *wuid) const
  3114. {
  3115. return baseFactory->isAborting(wuid);
  3116. }
  3117. virtual void clearAborting(const char *wuid)
  3118. {
  3119. baseFactory->clearAborting(wuid);
  3120. }
  3121. virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  3122. {
  3123. return baseFactory->waitForWorkUnit(wuid, timeout, compiled, returnOnWaitState);
  3124. }
  3125. virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original)
  3126. {
  3127. return baseFactory->waitForWorkUnitAction(wuid, original);
  3128. }
  3129. private:
  3130. Owned<IWorkUnitFactory> baseFactory;
  3131. Linked<ISecManager> defaultSecMgr;
  3132. Linked<ISecUser> defaultSecUser;
  3133. };
  3134. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser)
  3135. {
  3136. if (secmgr && secuser)
  3137. return new CSecureWorkUnitFactory(getWorkUnitFactory(), secmgr, secuser);
  3138. else
  3139. return getWorkUnitFactory();
  3140. }
  3141. //==========================================================================================
  3142. class CStringPTreeIterator : implements IStringIterator, public CInterface
  3143. {
  3144. Owned<IPropertyTreeIterator> it;
  3145. public:
  3146. IMPLEMENT_IINTERFACE;
  3147. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  3148. virtual bool first() { return it->first(); }
  3149. virtual bool next() { return it->next(); }
  3150. virtual bool isValid() { return it->isValid(); }
  3151. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  3152. };
  3153. class CStringPTreeTagIterator : implements IStringIterator, public CInterface
  3154. {
  3155. Owned<IPropertyTreeIterator> it;
  3156. public:
  3157. IMPLEMENT_IINTERFACE;
  3158. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  3159. virtual bool first() { return it->first(); }
  3160. virtual bool next() { return it->next(); }
  3161. virtual bool isValid() { return it->isValid(); }
  3162. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  3163. };
  3164. class CStringPTreeAttrIterator : implements IStringIterator, public CInterface
  3165. {
  3166. Owned<IPropertyTreeIterator> it;
  3167. StringAttr name;
  3168. public:
  3169. IMPLEMENT_IINTERFACE;
  3170. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  3171. virtual bool first() { return it->first(); }
  3172. virtual bool next() { return it->next(); }
  3173. virtual bool isValid() { return it->isValid(); }
  3174. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  3175. };
  3176. //==========================================================================================
  3177. CLocalWorkUnit::CLocalWorkUnit(ISecManager *secmgr, ISecUser *secuser)
  3178. {
  3179. clearCached(false);
  3180. secMgr.set(secmgr);
  3181. secUser.set(secuser);
  3182. workflowIteratorCached = false;
  3183. resultsCached = false;
  3184. graphsCached = false;
  3185. temporariesCached = false;
  3186. variablesCached = false;
  3187. exceptionsCached = false;
  3188. pluginsCached = false;
  3189. librariesCached = false;
  3190. activitiesCached = false;
  3191. webServicesInfoCached = false;
  3192. roxieQueryInfoCached = false;
  3193. }
  3194. void CLocalWorkUnit::clearCached(bool clearTree)
  3195. {
  3196. query.clear();
  3197. webServicesInfo.clear();
  3198. workflowIterator.clear();
  3199. graphs.kill();
  3200. results.kill();
  3201. variables.kill();
  3202. plugins.kill();
  3203. libraries.kill();
  3204. exceptions.kill();
  3205. temporaries.kill();
  3206. statistics.kill();
  3207. appvalues.kill();
  3208. if (clearTree)
  3209. p.clear();
  3210. workflowIteratorCached = false;
  3211. resultsCached = false;
  3212. graphsCached = false;
  3213. temporariesCached = false;
  3214. variablesCached = false;
  3215. exceptionsCached = false;
  3216. pluginsCached = false;
  3217. librariesCached = false;
  3218. activitiesCached = false;
  3219. webServicesInfoCached = false;
  3220. roxieQueryInfoCached = false;
  3221. }
  3222. void CLocalWorkUnit::loadPTree(IPropertyTree *ptree)
  3223. {
  3224. clearCached(false);
  3225. p.setown(ptree);
  3226. }
  3227. void CLocalWorkUnit::beforeDispose()
  3228. {
  3229. try
  3230. {
  3231. unsubscribe();
  3232. clearCached(true);
  3233. userDesc.clear();
  3234. secMgr.clear();
  3235. secUser.clear();
  3236. }
  3237. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  3238. }
  3239. void CLocalWorkUnit::cleanupAndDelete(bool deldll, bool deleteOwned, const StringArray *deleteExclusions)
  3240. {
  3241. MTIME_SECTION(queryActiveTimer(), "WUDELETE cleanupAndDelete total");
  3242. // Delete any related things in SDS etc that might otherwise be forgotten
  3243. if (p->getPropBool("@protected", false))
  3244. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  3245. switch (getState())
  3246. {
  3247. case WUStateAborted:
  3248. case WUStateCompleted:
  3249. case WUStateFailed:
  3250. case WUStateArchived:
  3251. break;
  3252. case WUStateCompiled:
  3253. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  3254. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  3255. break;
  3256. case WUStateWait:
  3257. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled",p->queryName());
  3258. default:
  3259. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active. Please abort before deleting this workunit.",p->queryName());
  3260. break;
  3261. }
  3262. if (getIsQueryService())
  3263. {
  3264. Owned<IPropertyTree> registry = getQueryRegistryRoot();
  3265. if (registry)
  3266. {
  3267. VStringBuffer xpath("QuerySet/Query[@wuid='%s']", p->queryName());
  3268. if (registry->hasProp(xpath.str()))
  3269. throw MakeStringException(WUERR_WorkunitPublished, "%s: Workunit is published",p->queryName());
  3270. }
  3271. }
  3272. try
  3273. {
  3274. if (deldll && !p->getPropBool("@isClone", false))
  3275. {
  3276. Owned<IConstWUQuery> q = getQuery();
  3277. if (q)
  3278. {
  3279. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  3280. SCMStringBuffer name;
  3281. ForEach(*iter)
  3282. {
  3283. IConstWUAssociatedFile & cur = iter->query();
  3284. cur.getNameTail(name);
  3285. if (!deleteExclusions || (NotFound == deleteExclusions->find(name.str())))
  3286. {
  3287. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  3288. if (entry.get())
  3289. asyncRemoveDll(name.str());
  3290. else
  3291. {
  3292. SCMStringBuffer ip, localPath;
  3293. cur.getName(localPath);
  3294. cur.getIp(ip);
  3295. asyncRemoveFile(ip.str(), localPath.str());
  3296. }
  3297. }
  3298. }
  3299. }
  3300. }
  3301. factory->clearAborting(queryWuid());
  3302. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  3303. }
  3304. catch(IException *E)
  3305. {
  3306. StringBuffer s;
  3307. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  3308. E->Release();
  3309. }
  3310. catch (...)
  3311. {
  3312. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  3313. }
  3314. }
  3315. void CLocalWorkUnit::setTimeScheduled(const IJlibDateTime &val)
  3316. {
  3317. SCMStringBuffer strval;
  3318. val.getGmtString(strval);
  3319. p->setProp("@timescheduled",strval.str());
  3320. }
  3321. IJlibDateTime & CLocalWorkUnit::getTimeScheduled(IJlibDateTime &val) const
  3322. {
  3323. StringBuffer str;
  3324. p->getProp("@timescheduled",str);
  3325. if(str.length())
  3326. val.setGmtString(str.str());
  3327. return val;
  3328. }
  3329. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  3330. {
  3331. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  3332. if(extra.length())
  3333. {
  3334. size32_t l = (size32_t)strlen(wuid);
  3335. size32_t p = buf.length()-l-4; // bit of a kludge
  3336. assertex(memcmp(buf.str()+p+2,wuid,l)==0);
  3337. StringAttr tail(buf.str()+p);
  3338. buf.setLength(p);
  3339. buf.append(extra);
  3340. buf.append(tail);
  3341. }
  3342. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  3343. }
  3344. bool CLocalWorkUnit::archiveWorkUnit(const char *base, bool del, bool ignoredllerrors, bool deleteOwned, bool exportAssociatedFiles)
  3345. {
  3346. CriticalBlock block(crit);
  3347. StringBuffer path(base);
  3348. if (!p)
  3349. return false;
  3350. const char *wuid = p->queryName();
  3351. if (!wuid||!*wuid)
  3352. return false;
  3353. addPathSepChar(path).append(wuid).append(".xml");
  3354. Owned<IFile> file = createIFile(path.str());
  3355. if (!file)
  3356. return false;
  3357. Owned<IFileIO> fileio = file->open(IFOcreate);
  3358. if (!fileio)
  3359. return false;
  3360. StringBuffer buf;
  3361. exportWorkUnitToXML(this, buf, false, false, true);
  3362. StringBuffer extraWorkUnitXML;
  3363. Owned<IPTree> graphProgress = getGraphProgressTree();
  3364. if (graphProgress)
  3365. {
  3366. toXML(graphProgress,extraWorkUnitXML,1,XML_Format);
  3367. graphProgress.clear();
  3368. }
  3369. Owned<IConstWUQuery> q = getQuery();
  3370. if (!q)
  3371. {
  3372. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  3373. return false;
  3374. if (del)
  3375. {
  3376. if (getState()==WUStateUnknown)
  3377. setState(WUStateArchived); // to allow delete
  3378. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  3379. }
  3380. return false;
  3381. }
  3382. StringArray deleteExclusions; // associated files not to delete, added if failure to copy
  3383. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  3384. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  3385. ForEach(*iter)
  3386. {
  3387. IConstWUAssociatedFile & cur = iter->query();
  3388. SCMStringBuffer name;
  3389. cur.getNameTail(name);
  3390. if (name.length())
  3391. {
  3392. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  3393. SCMStringBuffer curPath, curIp;
  3394. cur.getName(curPath);
  3395. cur.getIp(curIp);
  3396. SocketEndpoint curEp(curIp.str());
  3397. RemoteFilename curRfn;
  3398. curRfn.setPath(curEp, curPath.str());
  3399. StringBuffer dst(base);
  3400. addPathSepChar(dst);
  3401. curRfn.getTail(dst);
  3402. Owned<IFile> dstFile = createIFile(dst.str());
  3403. if (entry.get())
  3404. {
  3405. Owned<IException> exception;
  3406. Owned<IDllLocation> loc;
  3407. Owned<IPropertyTree> generatedDllBranch = createPTree();
  3408. generatedDllBranch->setProp("@name", entry->queryName());
  3409. generatedDllBranch->setProp("@kind", entry->queryKind());
  3410. if (exportAssociatedFiles)
  3411. {
  3412. try
  3413. {
  3414. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  3415. }
  3416. catch(IException * e)
  3417. {
  3418. exception.setown(e);
  3419. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  3420. }
  3421. RemoteFilename filename;
  3422. loc->getDllFilename(filename);
  3423. if (!exception)
  3424. {
  3425. Owned<IFile> srcfile = createIFile(filename);
  3426. try
  3427. {
  3428. if (dstFile->exists())
  3429. {
  3430. if (streq(srcfile->queryFilename(), dstFile->queryFilename()))
  3431. deleteExclusions.append(name.str()); // restored workunit, referencing archive location for query dll (no longer true post HPCC-11191 fix)
  3432. // still want to delete if already archived but there are source file copies
  3433. }
  3434. else
  3435. copyFile(dstFile, srcfile);
  3436. }
  3437. catch(IException * e)
  3438. {
  3439. exception.setown(e);
  3440. }
  3441. }
  3442. if (exception)
  3443. {
  3444. if (ignoredllerrors)
  3445. {
  3446. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  3447. //copy failed, so don't delete the registered dll files
  3448. deleteExclusions.append(name.str());
  3449. }
  3450. else
  3451. throw exception.getClear();
  3452. }
  3453. }
  3454. // Record Associated path to restore back to
  3455. StringBuffer restorePath;
  3456. curRfn.getRemotePath(restorePath);
  3457. generatedDllBranch->setProp("@location", restorePath.str());
  3458. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  3459. }
  3460. else if (exportAssociatedFiles) // no generated dll entry
  3461. {
  3462. Owned<IFile> srcFile = createIFile(curRfn);
  3463. try
  3464. {
  3465. copyFile(dstFile, srcFile);
  3466. }
  3467. catch (IException *e)
  3468. {
  3469. VStringBuffer msg("Failed to archive associated file '%s' to destination '%s'", srcFile->queryFilename(), dstFile->queryFilename());
  3470. EXCLOG(e, msg.str());
  3471. e->Release();
  3472. deleteExclusions.append(name.str());
  3473. }
  3474. }
  3475. }
  3476. }
  3477. iter.clear();
  3478. if (generatedDlls->numChildren())
  3479. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  3480. if (!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  3481. return false;
  3482. if (del)
  3483. {
  3484. //setState(WUStateArchived); // this isn't useful as about to delete it!
  3485. q.clear();
  3486. cleanupAndDelete(true, deleteOwned, &deleteExclusions);
  3487. }
  3488. return true;
  3489. }
  3490. void CLocalWorkUnit::loadXML(const char *xml)
  3491. {
  3492. CriticalBlock block(crit);
  3493. clearCached(true);
  3494. assertex(xml);
  3495. p.setown(createPTreeFromXMLString(xml));
  3496. }
  3497. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  3498. {
  3499. CriticalBlock block(crit);
  3500. StringBuffer x;
  3501. tgt.append(exportWorkUnitToXML(this, x, false, false, false).str());
  3502. }
  3503. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  3504. {
  3505. CriticalBlock block(crit);
  3506. StringAttr value;
  3507. src.read(value);
  3508. loadXML(value);
  3509. }
  3510. void CLocalWorkUnit::requestAbort()
  3511. {
  3512. CriticalBlock block(crit);
  3513. abortWorkUnit(p->queryName());
  3514. }
  3515. void CLocalWorkUnit::unlockRemote()
  3516. {
  3517. CriticalBlock block(crit);
  3518. locked.unlock();
  3519. _unlockRemote();
  3520. }
  3521. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  3522. {
  3523. if (secMgr)
  3524. checkWuSecAccess(*this, secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  3525. locked.lock();
  3526. CriticalBlock block(crit);
  3527. if (commit)
  3528. {
  3529. try
  3530. {
  3531. _lockRemote();
  3532. }
  3533. catch (IException *E)
  3534. {
  3535. StringBuffer s;
  3536. PrintLog("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  3537. locked.unlock();
  3538. throw;
  3539. }
  3540. }
  3541. return *new CLockedWorkUnit(LINK(this));
  3542. }
  3543. void CLocalWorkUnit::commit()
  3544. {
  3545. // Nothing to do if not backed by a persistent store
  3546. }
  3547. IWorkUnit& CLocalWorkUnit::lock()
  3548. {
  3549. return lockRemote(true);
  3550. }
  3551. const char *CLocalWorkUnit::queryWuid() const
  3552. {
  3553. CriticalBlock block(crit);
  3554. return p->queryName();
  3555. }
  3556. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  3557. {
  3558. CriticalBlock block(crit);
  3559. return p->getPropInt("@DebugListenerPort", 0);
  3560. }
  3561. unsigned CLocalWorkUnit::getTotalThorTime() const
  3562. {
  3563. CriticalBlock block(crit);
  3564. return (unsigned)nanoToMilli(extractTimeCollatable(p->queryProp("@totalThorTime"), false));
  3565. }
  3566. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  3567. {
  3568. CriticalBlock block(crit);
  3569. p->setPropInt("@DebugListenerPort", port);
  3570. }
  3571. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  3572. {
  3573. CriticalBlock block(crit);
  3574. ip.set(p->queryProp("@DebugListenerIP"));
  3575. return ip;
  3576. }
  3577. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  3578. {
  3579. CriticalBlock block(crit);
  3580. p->setProp("@DebugListenerIP", ip);
  3581. }
  3582. IStringVal& CLocalWorkUnit::getSecurityToken(IStringVal &str) const
  3583. {
  3584. CriticalBlock block(crit);
  3585. str.set(p->queryProp("@token"));
  3586. return str;
  3587. }
  3588. void CLocalWorkUnit::setSecurityToken(const char *value)
  3589. {
  3590. CriticalBlock block(crit);
  3591. p->setProp("@token", value);
  3592. }
  3593. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3594. {
  3595. // Only implemented in derived classes
  3596. return false;
  3597. }
  3598. void CLocalWorkUnit::setJobName(const char *value)
  3599. {
  3600. CriticalBlock block(crit);
  3601. p->setProp("@jobName", value);
  3602. }
  3603. const char *CLocalWorkUnit::queryJobName() const
  3604. {
  3605. CriticalBlock block(crit);
  3606. const char *ret = p->queryProp("@jobName");
  3607. if (!ret)
  3608. ret = "";
  3609. return ret;
  3610. }
  3611. void CLocalWorkUnit::setClusterName(const char *value)
  3612. {
  3613. CriticalBlock block(crit);
  3614. p->setProp("@clusterName", value);
  3615. }
  3616. const char *CLocalWorkUnit::queryClusterName() const
  3617. {
  3618. CriticalBlock block(crit);
  3619. const char *ret = p->queryProp("@clusterName");
  3620. if (!ret)
  3621. ret = "";
  3622. return ret;
  3623. }
  3624. void CLocalWorkUnit::setAllowedClusters(const char *value)
  3625. {
  3626. setDebugValue("allowedclusters",value, true);
  3627. }
  3628. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  3629. {
  3630. CriticalBlock block(crit);
  3631. getDebugValue("allowedclusters",str);
  3632. if (str.length()!=0)
  3633. return str;
  3634. str.set(p->queryProp("@clusterName"));
  3635. return str;
  3636. }
  3637. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  3638. {
  3639. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  3640. }
  3641. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  3642. {
  3643. CriticalBlock block(crit);
  3644. return getDebugValueBool("allowautoqueueswitch",false);
  3645. }
  3646. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3647. {
  3648. StringBuffer suffix;
  3649. if (name && *name)
  3650. setApplicationValue("LibraryModule", "name", name, true);
  3651. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  3652. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  3653. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  3654. }
  3655. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3656. {
  3657. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  3658. if (writeaccess)
  3659. auditflags |= DALI_LDAP_WRITE_WANTED;
  3660. SecAccessFlags perm = SecAccess_Full;
  3661. const char *scopename = p->queryProp("@scope");
  3662. if (scopename&&*scopename) {
  3663. if (!user)
  3664. user = queryUserDescriptor();
  3665. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  3666. if (perm<0) {
  3667. if (perm == SecAccess_Unavailable)
  3668. perm = SecAccess_Full;
  3669. else
  3670. perm = SecAccess_None;
  3671. }
  3672. }
  3673. if (!HASREADPERMISSION(perm))
  3674. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s", queryWuid());
  3675. if (writeaccess && !HASWRITEPERMISSION(perm))
  3676. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s", queryWuid());
  3677. }
  3678. void CLocalWorkUnit::setUser(const char * value)
  3679. {
  3680. CriticalBlock block(crit);
  3681. p->setProp("@submitID", value);
  3682. }
  3683. const char *CLocalWorkUnit::queryUser() const
  3684. {
  3685. CriticalBlock block(crit);
  3686. const char *ret = p->queryProp("@submitID");
  3687. if (!ret)
  3688. ret = "";
  3689. return ret;
  3690. }
  3691. void CLocalWorkUnit::setWuScope(const char * value)
  3692. {
  3693. if (value && *value)
  3694. {
  3695. if (checkWuScopeSecAccess(value, secMgr.get(), secUser.get(), SecAccess_Write, "Change Scope", true, true))
  3696. {
  3697. CriticalBlock block(crit);
  3698. p->setProp("@scope", value);
  3699. }
  3700. }
  3701. }
  3702. const char *CLocalWorkUnit::queryWuScope() const
  3703. {
  3704. CriticalBlock block(crit);
  3705. const char *ret = p->queryProp("@scope");
  3706. if (!ret)
  3707. ret = "";
  3708. return ret;
  3709. }
  3710. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  3711. {
  3712. CriticalBlock block(crit);
  3713. setEnum(p, "@priorityClass", cls, priorityClasses);
  3714. }
  3715. WUPriorityClass CLocalWorkUnit::getPriority() const
  3716. {
  3717. CriticalBlock block(crit);
  3718. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  3719. }
  3720. const char *CLocalWorkUnit::queryPriorityDesc() const
  3721. {
  3722. return getEnumText(getPriority(), priorityClasses);
  3723. }
  3724. void CLocalWorkUnit::setState(WUState value)
  3725. {
  3726. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  3727. {
  3728. if (factory)
  3729. factory->clearAborting(queryWuid());
  3730. }
  3731. CriticalBlock block(crit);
  3732. setEnum(p, "@state", value, states); // For historical reasons, we use state to store the state
  3733. setEnum(p, "State", value, states); // But we can only subscribe to elements, not attributes
  3734. if (getDebugValueBool("monitorWorkunit", false))
  3735. {
  3736. switch(value)
  3737. {
  3738. case WUStateAborted:
  3739. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  3740. break;
  3741. case WUStateCompleted:
  3742. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  3743. break;
  3744. case WUStateFailed:
  3745. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  3746. break;
  3747. }
  3748. }
  3749. p->removeProp("@stateEx");
  3750. }
  3751. void CLocalWorkUnit::setStateEx(const char * text)
  3752. {
  3753. CriticalBlock block(crit);
  3754. p->setProp("@stateEx", text);
  3755. }
  3756. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  3757. {
  3758. CriticalBlock block(crit);
  3759. p->setPropInt64("@agentSession", sessionId);
  3760. }
  3761. bool CLocalWorkUnit::getIsQueryService() const
  3762. {
  3763. CriticalBlock block(crit);
  3764. return p->getPropBool("@isQueryService", false);
  3765. }
  3766. void CLocalWorkUnit::setIsQueryService(bool value)
  3767. {
  3768. CriticalBlock block(crit);
  3769. p->setPropBool("@isQueryService", value);
  3770. }
  3771. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  3772. {
  3773. if (queryDaliServerVersion().compare("2.1")<0)
  3774. return;
  3775. switch(state)
  3776. {
  3777. case WUStateRunning:
  3778. case WUStateDebugPaused:
  3779. case WUStateDebugRunning:
  3780. case WUStateBlocked:
  3781. case WUStateAborting:
  3782. case WUStateCompiling:
  3783. case WUStatePaused:
  3784. {
  3785. SessionId agent = getAgentSession();
  3786. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  3787. {
  3788. forceReload();
  3789. state = (WUState) getEnum(p, "@state", states);
  3790. bool isecl=state==WUStateCompiling;
  3791. if (aborting())
  3792. state = WUStateAborted;
  3793. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  3794. state = WUStateFailed;
  3795. else
  3796. return;
  3797. WARNLOG("checkAgentRunning terminated: %" I64F "d state = %d",(__int64)agent,(int)state);
  3798. Owned<IWorkUnit> w = &lock();
  3799. w->setState(state);
  3800. Owned<IWUException> e = w->createException();
  3801. WUAction action = w->getAction();
  3802. switch (action)
  3803. {
  3804. case WUActionPause:
  3805. case WUActionPauseNow:
  3806. case WUActionResume:
  3807. w->setAction(WUActionUnknown);
  3808. }
  3809. if(isecl)
  3810. {
  3811. e->setExceptionCode(1001);
  3812. e->setExceptionMessage("EclServer terminated unexpectedly");
  3813. }
  3814. else
  3815. {
  3816. e->setExceptionCode(1000);
  3817. e->setExceptionMessage("Workunit terminated unexpectedly");
  3818. }
  3819. }
  3820. }
  3821. }
  3822. }
  3823. WUState CLocalWorkUnit::getState() const
  3824. {
  3825. CriticalBlock block(crit);
  3826. WUState state = (WUState) getEnum(p, "@state", states);
  3827. switch (state)
  3828. {
  3829. case WUStateRunning:
  3830. case WUStateDebugPaused:
  3831. case WUStateDebugRunning:
  3832. case WUStateBlocked:
  3833. case WUStateCompiling:
  3834. if (aborting())
  3835. state = WUStateAborting;
  3836. break;
  3837. case WUStateSubmitted:
  3838. if (aborting())
  3839. state = WUStateAborted;
  3840. break;
  3841. }
  3842. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  3843. return state;
  3844. }
  3845. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  3846. {
  3847. CriticalBlock block(crit);
  3848. str.set(p->queryProp("@stateEx"));
  3849. return str;
  3850. }
  3851. __int64 CLocalWorkUnit::getAgentSession() const
  3852. {
  3853. CriticalBlock block(crit);
  3854. return p->getPropInt64("@agentSession", -1);
  3855. }
  3856. unsigned CLocalWorkUnit::getAgentPID() const
  3857. {
  3858. CriticalBlock block(crit);
  3859. return p->getPropInt("@agentPID", -1);
  3860. }
  3861. const char * CLocalWorkUnit::queryStateDesc() const
  3862. {
  3863. // MORE - not sure about this - may prefer a separate interface
  3864. CriticalBlock block(crit);
  3865. try
  3866. {
  3867. return getEnumText(getState(), states);
  3868. }
  3869. catch (...)
  3870. {
  3871. return "???";
  3872. }
  3873. }
  3874. void CLocalWorkUnit::setAction(WUAction value)
  3875. {
  3876. CriticalBlock block(crit);
  3877. setEnum(p, "Action", value, actions);
  3878. }
  3879. WUAction CLocalWorkUnit::getAction() const
  3880. {
  3881. CriticalBlock block(crit);
  3882. return (WUAction) getEnum(p, "Action", actions);
  3883. }
  3884. const char *CLocalWorkUnit::queryActionDesc() const
  3885. {
  3886. CriticalBlock block(crit);
  3887. return p->queryProp("Action");
  3888. }
  3889. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  3890. {
  3891. CriticalBlock block(crit);
  3892. StringBuffer prop("Application/");
  3893. prop.append(app).append('/').append(propname);
  3894. str.set(p->queryProp(prop.str()));
  3895. return str;
  3896. }
  3897. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  3898. {
  3899. CriticalBlock block(crit);
  3900. StringBuffer prop("Application/");
  3901. prop.append(app).append('/').append(propname);
  3902. return p->getPropInt(prop.str(), defVal);
  3903. }
  3904. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  3905. {
  3906. CriticalBlock block(crit);
  3907. appvalues.load(p,"Application/*");
  3908. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  3909. }
  3910. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  3911. {
  3912. CriticalBlock block(crit);
  3913. StringBuffer prop("Application/");
  3914. prop.append(app).append('/').append(propname);
  3915. if (overwrite || !p->hasProp(prop.str()))
  3916. {
  3917. StringBuffer sp;
  3918. p->setProp(sp.append("Application").str(), "");
  3919. p->setProp(sp.append('/').append(app).str(), "");
  3920. p->setProp(prop.str(), value);
  3921. }
  3922. }
  3923. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  3924. {
  3925. VStringBuffer s("%d", value);
  3926. setApplicationValue(app, propname, s, overwrite);
  3927. }
  3928. void CLocalWorkUnit::setPriorityLevel(int level)
  3929. {
  3930. CriticalBlock block(crit);
  3931. p->setPropInt("PriorityFlag", level);
  3932. }
  3933. int CLocalWorkUnit::getPriorityLevel() const
  3934. {
  3935. CriticalBlock block(crit);
  3936. return p->getPropInt("PriorityFlag");
  3937. }
  3938. int calcPriorityValue(const IPropertyTree * p)
  3939. {
  3940. int priority = p->getPropInt("PriorityFlag");
  3941. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  3942. {
  3943. case PriorityClassLow:
  3944. priority -= 100;
  3945. break;
  3946. case PriorityClassHigh:
  3947. priority += 100;
  3948. break;
  3949. }
  3950. return priority;
  3951. }
  3952. int CLocalWorkUnit::getPriorityValue() const
  3953. {
  3954. CriticalBlock block(crit);
  3955. return calcPriorityValue(p);
  3956. }
  3957. void CLocalWorkUnit::setRescheduleFlag(bool value)
  3958. {
  3959. CriticalBlock block(crit);
  3960. p->setPropInt("RescheduleFlag", (int) value);
  3961. }
  3962. bool CLocalWorkUnit::getRescheduleFlag() const
  3963. {
  3964. CriticalBlock block(crit);
  3965. return p->getPropInt("RescheduleFlag") != 0;
  3966. }
  3967. class NullIStringIterator : implements IStringIterator, public CInterface
  3968. {
  3969. public:
  3970. IMPLEMENT_IINTERFACE;
  3971. bool first() { return false; }
  3972. bool next() { return false; }
  3973. bool isValid() { return false; }
  3974. IStringVal & str(IStringVal & str) { return str; }
  3975. };
  3976. ClusterType getClusterType(const char * platform, ClusterType dft)
  3977. {
  3978. if (stricmp(platform, "thor") == 0)
  3979. return ThorLCRCluster;
  3980. if (stricmp(platform, "thorlcr") == 0)
  3981. return ThorLCRCluster;
  3982. if (stricmp(platform, "hthor") == 0)
  3983. return HThorCluster;
  3984. if (stricmp(platform, "roxie") == 0)
  3985. return RoxieCluster;
  3986. return dft;
  3987. }
  3988. const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive)
  3989. {
  3990. switch (clusterType)
  3991. {
  3992. case ThorLCRCluster:
  3993. if (lcrSensitive)
  3994. return "thorlcr";
  3995. return "thor";
  3996. case RoxieCluster:
  3997. return "roxie";
  3998. case HThorCluster:
  3999. return "hthor";
  4000. }
  4001. throwUnexpected();
  4002. }
  4003. IPropertyTree *queryRoxieProcessTree(IPropertyTree *environment, const char *process)
  4004. {
  4005. if (!process || !*process)
  4006. return NULL;
  4007. VStringBuffer xpath("Software/RoxieCluster[@name=\"%s\"]", process);
  4008. return environment->queryPropTree(xpath.str());
  4009. }
  4010. void getRoxieProcessServers(IPropertyTree *roxie, SocketEndpointArray &endpoints)
  4011. {
  4012. if (!roxie)
  4013. return;
  4014. Owned<IPropertyTreeIterator> servers = roxie->getElements("RoxieServerProcess");
  4015. ForEach(*servers)
  4016. {
  4017. IPropertyTree &server = servers->query();
  4018. const char *netAddress = server.queryProp("@netAddress");
  4019. if (netAddress && *netAddress)
  4020. {
  4021. SocketEndpoint ep(netAddress, server.getPropInt("@port", 9876));
  4022. endpoints.append(ep);
  4023. }
  4024. }
  4025. }
  4026. void getRoxieProcessServers(const char *process, SocketEndpointArray &servers)
  4027. {
  4028. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4029. Owned<IConstEnvironment> env = factory->openEnvironment();
  4030. if (!env)
  4031. return;
  4032. Owned<IPropertyTree> root = &env->getPTree();
  4033. getRoxieProcessServers(queryRoxieProcessTree(root, process), servers);
  4034. }
  4035. class CEnvironmentClusterInfo: implements IConstWUClusterInfo, public CInterface
  4036. {
  4037. StringAttr name;
  4038. StringAttr alias;
  4039. StringAttr serverQueue;
  4040. StringAttr agentQueue;
  4041. StringAttr roxieProcess;
  4042. SocketEndpointArray roxieServers;
  4043. StringAttr thorQueue;
  4044. StringArray thorProcesses;
  4045. StringArray primaryThorProcesses;
  4046. StringAttr prefix;
  4047. StringAttr ldapUser;
  4048. StringBuffer ldapPassword;
  4049. ClusterType platform;
  4050. unsigned clusterWidth;
  4051. unsigned roxieRedundancy;
  4052. unsigned channelsPerNode;
  4053. int roxieReplicateOffset;
  4054. public:
  4055. IMPLEMENT_IINTERFACE;
  4056. CEnvironmentClusterInfo(const char *_name, const char *_prefix, const char *_alias, IPropertyTree *agent, IArrayOf<IPropertyTree> &thors, IPropertyTree *roxie)
  4057. : name(_name), prefix(_prefix), alias(_alias), roxieRedundancy(0), channelsPerNode(0), roxieReplicateOffset(1)
  4058. {
  4059. StringBuffer queue;
  4060. if (thors.ordinality())
  4061. {
  4062. thorQueue.set(getClusterThorQueueName(queue.clear(), name));
  4063. clusterWidth = 0;
  4064. bool isMultiThor = (thors.length() > 1);
  4065. ForEachItemIn(i,thors)
  4066. {
  4067. IPropertyTree &thor = thors.item(i);
  4068. const char* thorName = thor.queryProp("@name");
  4069. thorProcesses.append(thorName);
  4070. if (!isMultiThor)
  4071. primaryThorProcesses.append(thorName);
  4072. else
  4073. {
  4074. const char *nodeGroup = thor.queryProp("@nodeGroup");
  4075. if (!nodeGroup || strieq(nodeGroup, thorName))
  4076. primaryThorProcesses.append(thorName);
  4077. }
  4078. unsigned nodes = thor.getCount("ThorSlaveProcess");
  4079. if (!nodes)
  4080. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: Thor cluster can not have 0 slave processes");
  4081. unsigned slavesPerNode = thor.getPropInt("@slavesPerNode", 1);
  4082. unsigned channelsPerSlave = thor.getPropInt("@channelsPerSlave", 1);
  4083. unsigned ts = nodes * slavesPerNode * channelsPerSlave;
  4084. if (clusterWidth && (ts!=clusterWidth))
  4085. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: mismatched thor sizes in cluster");
  4086. clusterWidth = ts;
  4087. bool islcr = !thor.getPropBool("@Legacy");
  4088. if (!islcr)
  4089. throw MakeStringException(WUERR_MismatchThorType,"CEnvironmentClusterInfo: Legacy Thor no longer supported");
  4090. }
  4091. platform = ThorLCRCluster;
  4092. }
  4093. else if (roxie)
  4094. {
  4095. roxieProcess.set(roxie->queryProp("@name"));
  4096. platform = RoxieCluster;
  4097. getRoxieProcessServers(roxie, roxieServers);
  4098. clusterWidth = roxieServers.length();
  4099. ldapUser.set(roxie->queryProp("@ldapUser"));
  4100. StringBuffer encPassword = roxie->queryProp("@ldapPassword");
  4101. if (encPassword.length())
  4102. decrypt(ldapPassword, encPassword);
  4103. const char *redundancyMode = roxie->queryProp("@slaveConfig");
  4104. if (redundancyMode && *redundancyMode)
  4105. {
  4106. unsigned dataCopies = roxie->getPropInt("@numDataCopies", 1);
  4107. if (strieq(redundancyMode, "overloaded"))
  4108. channelsPerNode = roxie->getPropInt("@channelsPernode", 1);
  4109. else if (strieq(redundancyMode, "full redundancy"))
  4110. {
  4111. roxieRedundancy = dataCopies-1;
  4112. roxieReplicateOffset = 0;
  4113. }
  4114. else if (strieq(redundancyMode, "cyclic redundancy"))
  4115. {
  4116. roxieRedundancy = dataCopies-1;
  4117. channelsPerNode = dataCopies;
  4118. roxieReplicateOffset = roxie->getPropInt("@cyclicOffset", 1);
  4119. }
  4120. }
  4121. }
  4122. else
  4123. {
  4124. clusterWidth = 1;
  4125. platform = HThorCluster;
  4126. }
  4127. if (agent)
  4128. {
  4129. assertex(!roxie);
  4130. agentQueue.set(getClusterEclAgentQueueName(queue.clear(), name));
  4131. }
  4132. else if (roxie)
  4133. agentQueue.set(getClusterRoxieQueueName(queue.clear(), name));
  4134. // MORE - does this need to be conditional?
  4135. serverQueue.set(getClusterEclCCServerQueueName(queue.clear(), name));
  4136. }
  4137. IStringVal & getName(IStringVal & str) const
  4138. {
  4139. str.set(name.get());
  4140. return str;
  4141. }
  4142. const char *getAlias() const
  4143. {
  4144. return alias;
  4145. }
  4146. IStringVal & getScope(IStringVal & str) const
  4147. {
  4148. str.set(prefix.get());
  4149. return str;
  4150. }
  4151. IStringVal & getAgentQueue(IStringVal & str) const
  4152. {
  4153. str.set(agentQueue);
  4154. return str;
  4155. }
  4156. virtual IStringVal & getServerQueue(IStringVal & str) const
  4157. {
  4158. str.set(serverQueue);
  4159. return str;
  4160. }
  4161. IStringVal & getThorQueue(IStringVal & str) const
  4162. {
  4163. str.set(thorQueue);
  4164. return str;
  4165. }
  4166. unsigned getSize() const
  4167. {
  4168. return clusterWidth;
  4169. }
  4170. virtual ClusterType getPlatform() const
  4171. {
  4172. return platform;
  4173. }
  4174. IStringVal & getRoxieProcess(IStringVal & str) const
  4175. {
  4176. str.set(roxieProcess.get());
  4177. return str;
  4178. }
  4179. const StringArray & getThorProcesses() const
  4180. {
  4181. return thorProcesses;
  4182. }
  4183. const StringArray & getPrimaryThorProcesses() const
  4184. {
  4185. return primaryThorProcesses;
  4186. }
  4187. const SocketEndpointArray & getRoxieServers() const
  4188. {
  4189. return roxieServers;
  4190. }
  4191. unsigned getRoxieRedundancy() const
  4192. {
  4193. return roxieRedundancy;
  4194. }
  4195. unsigned getChannelsPerNode() const
  4196. {
  4197. return channelsPerNode;
  4198. }
  4199. int getRoxieReplicateOffset() const
  4200. {
  4201. return roxieReplicateOffset;
  4202. }
  4203. const char *getLdapUser() const
  4204. {
  4205. return ldapUser.get();
  4206. }
  4207. virtual const char *getLdapPassword() const
  4208. {
  4209. return ldapPassword.str();
  4210. }
  4211. };
  4212. IStringVal &getProcessQueueNames(IStringVal &ret, const char *process, const char *type, const char *suffix)
  4213. {
  4214. if (process)
  4215. {
  4216. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4217. Owned<IConstEnvironment> env = factory->openEnvironment();
  4218. if (env)
  4219. {
  4220. Owned<IPropertyTree> root = &env->getPTree();
  4221. StringBuffer queueNames;
  4222. StringBuffer xpath;
  4223. xpath.appendf("%s[@process=\"%s\"]", type, process);
  4224. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  4225. ForEach(*targets)
  4226. {
  4227. IPropertyTree &target = targets->query();
  4228. if (target.hasProp(xpath))
  4229. {
  4230. if (queueNames.length())
  4231. queueNames.append(',');
  4232. queueNames.append(target.queryProp("@name")).append(suffix);
  4233. }
  4234. }
  4235. ret.set(queueNames);
  4236. }
  4237. }
  4238. return ret;
  4239. }
  4240. #define ROXIE_QUEUE_EXT ".roxie"
  4241. #define THOR_QUEUE_EXT ".thor"
  4242. #define ECLCCSERVER_QUEUE_EXT ".eclserver"
  4243. #define ECLSERVER_QUEUE_EXT ECLCCSERVER_QUEUE_EXT
  4244. #define ECLSCHEDULER_QUEUE_EXT ".eclscheduler"
  4245. #define ECLAGENT_QUEUE_EXT ".agent"
  4246. extern WORKUNIT_API IStringVal &getEclCCServerQueueNames(IStringVal &ret, const char *process)
  4247. {
  4248. return getProcessQueueNames(ret, process, "EclCCServerProcess", ECLCCSERVER_QUEUE_EXT);
  4249. }
  4250. extern WORKUNIT_API IStringVal &getEclServerQueueNames(IStringVal &ret, const char *process)
  4251. {
  4252. return getProcessQueueNames(ret, process, "EclServerProcess", ECLSERVER_QUEUE_EXT); // shares queue name with EclCCServer
  4253. }
  4254. extern WORKUNIT_API IStringVal &getEclSchedulerQueueNames(IStringVal &ret, const char *process)
  4255. {
  4256. return getProcessQueueNames(ret, process, "EclSchedulerProcess", ECLSCHEDULER_QUEUE_EXT); // Shares deployment/config with EclCCServer
  4257. }
  4258. extern WORKUNIT_API IStringVal &getAgentQueueNames(IStringVal &ret, const char *process)
  4259. {
  4260. return getProcessQueueNames(ret, process, "EclAgentProcess", ECLAGENT_QUEUE_EXT);
  4261. }
  4262. extern WORKUNIT_API IStringVal &getRoxieQueueNames(IStringVal &ret, const char *process)
  4263. {
  4264. return getProcessQueueNames(ret, process, "RoxieCluster", ROXIE_QUEUE_EXT);
  4265. }
  4266. extern WORKUNIT_API IStringVal &getThorQueueNames(IStringVal &ret, const char *process)
  4267. {
  4268. return getProcessQueueNames(ret, process, "ThorCluster", THOR_QUEUE_EXT);
  4269. }
  4270. extern WORKUNIT_API StringBuffer &getClusterThorQueueName(StringBuffer &ret, const char *cluster)
  4271. {
  4272. return ret.append(cluster).append(THOR_QUEUE_EXT);
  4273. }
  4274. extern WORKUNIT_API StringBuffer &getClusterThorGroupName(StringBuffer &ret, const char *cluster)
  4275. {
  4276. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4277. Owned<IConstEnvironment> env = factory->openEnvironment();
  4278. if (env)
  4279. {
  4280. Owned<IPropertyTree> root = &env->getPTree();
  4281. StringBuffer path;
  4282. path.append("Software/ThorCluster[@name=\"").append(cluster).append("\"]");
  4283. IPropertyTree * child = root->queryPropTree(path);
  4284. if (child)
  4285. getClusterGroupName(*child, ret);
  4286. }
  4287. return ret;
  4288. }
  4289. extern WORKUNIT_API StringBuffer &getClusterRoxieQueueName(StringBuffer &ret, const char *cluster)
  4290. {
  4291. return ret.append(cluster).append(ROXIE_QUEUE_EXT);
  4292. }
  4293. extern WORKUNIT_API StringBuffer &getClusterEclCCServerQueueName(StringBuffer &ret, const char *cluster)
  4294. {
  4295. return ret.append(cluster).append(ECLCCSERVER_QUEUE_EXT);
  4296. }
  4297. extern WORKUNIT_API StringBuffer &getClusterEclServerQueueName(StringBuffer &ret, const char *cluster)
  4298. {
  4299. return ret.append(cluster).append(ECLSERVER_QUEUE_EXT);
  4300. }
  4301. extern WORKUNIT_API StringBuffer &getClusterEclAgentQueueName(StringBuffer &ret, const char *cluster)
  4302. {
  4303. return ret.append(cluster).append(ECLAGENT_QUEUE_EXT);
  4304. }
  4305. extern WORKUNIT_API IStringIterator *getTargetClusters(const char *processType, const char *processName)
  4306. {
  4307. Owned<CStringArrayIterator> ret = new CStringArrayIterator;
  4308. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4309. Owned<IConstEnvironment> env = factory->openEnvironment();
  4310. if (env)
  4311. {
  4312. Owned<IPropertyTree> root = &env->getPTree();
  4313. StringBuffer xpath;
  4314. xpath.appendf("%s", processType ? processType : "*");
  4315. if (processName && *processName)
  4316. xpath.appendf("[@process=\"%s\"]", processName);
  4317. Owned<IPropertyTreeIterator> targets = root->getElements("Software/Topology/Cluster");
  4318. ForEach(*targets)
  4319. {
  4320. IPropertyTree &target = targets->query();
  4321. if (target.hasProp(xpath))
  4322. {
  4323. ret->append(target.queryProp("@name"));
  4324. }
  4325. }
  4326. }
  4327. return ret.getClear();
  4328. }
  4329. extern WORKUNIT_API bool isProcessCluster(const char *process)
  4330. {
  4331. if (!process || !*process)
  4332. return false;
  4333. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4334. Owned<IConstEnvironment> env = factory->openEnvironment();
  4335. if (!env)
  4336. return false;
  4337. Owned<IPropertyTree> root = &env->getPTree();
  4338. VStringBuffer xpath("Software/*Cluster[@name=\"%s\"]", process);
  4339. return root->hasProp(xpath.str());
  4340. }
  4341. extern WORKUNIT_API bool isProcessCluster(const char *remoteDali, const char *process)
  4342. {
  4343. if (!remoteDali || !*remoteDali)
  4344. return isProcessCluster(process);
  4345. if (!process || !*process)
  4346. return false;
  4347. Owned<INode> remote = createINode(remoteDali, 7070);
  4348. if (!remote)
  4349. return false;
  4350. //Cannot use getEnvironmentFactory() since it is using a remotedali
  4351. VStringBuffer xpath("Environment/Software/*Cluster[@name=\"%s\"]/@name", process);
  4352. try
  4353. {
  4354. Owned<IPropertyTreeIterator> clusters = querySDS().getElementsRaw(xpath, remote, 1000*60*1);
  4355. return clusters->first();
  4356. }
  4357. catch (IException *E)
  4358. {
  4359. StringBuffer msg;
  4360. E->errorMessage(msg);
  4361. DBGLOG("Exception validating cluster %s/%s: %s", remoteDali, xpath.str(), msg.str());
  4362. E->Release();
  4363. }
  4364. return true;
  4365. }
  4366. IConstWUClusterInfo* getTargetClusterInfo(IPropertyTree *environment, IPropertyTree *cluster)
  4367. {
  4368. const char *clustname = cluster->queryProp("@name");
  4369. // MORE - at the moment configenf specifies eclagent and thor queues by (in effect) placing an 'example' thor or eclagent in the topology
  4370. // that uses the queue that will be used.
  4371. // We should and I hope will change that, at which point the code below gets simpler
  4372. StringBuffer prefix(cluster->queryProp("@prefix"));
  4373. prefix.toLowerCase();
  4374. StringBuffer xpath;
  4375. StringBuffer querySetName;
  4376. IPropertyTree *agent = NULL;
  4377. const char *agentName = cluster->queryProp("EclAgentProcess/@process");
  4378. if (agentName)
  4379. {
  4380. xpath.clear().appendf("Software/EclAgentProcess[@name=\"%s\"]", agentName);
  4381. agent = environment->queryPropTree(xpath.str());
  4382. }
  4383. Owned<IPropertyTreeIterator> ti = cluster->getElements("ThorCluster");
  4384. IArrayOf<IPropertyTree> thors;
  4385. ForEach(*ti)
  4386. {
  4387. const char *thorName = ti->query().queryProp("@process");
  4388. if (thorName)
  4389. {
  4390. xpath.clear().appendf("Software/ThorCluster[@name=\"%s\"]", thorName);
  4391. thors.append(*environment->getPropTree(xpath.str()));
  4392. }
  4393. }
  4394. const char *roxieName = cluster->queryProp("RoxieCluster/@process");
  4395. return new CEnvironmentClusterInfo(clustname, prefix, cluster->queryProp("@alias"), agent, thors, queryRoxieProcessTree(environment, roxieName));
  4396. }
  4397. IPropertyTree* getTopologyCluster(Owned<IPropertyTree> &envRoot, const char *clustname)
  4398. {
  4399. if (!clustname || !*clustname)
  4400. return NULL;
  4401. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4402. Owned<IConstEnvironment> env = factory->openEnvironment();
  4403. if (!env)
  4404. return NULL;
  4405. envRoot.setown(&env->getPTree());
  4406. StringBuffer xpath;
  4407. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  4408. return envRoot->getPropTree(xpath.str());
  4409. }
  4410. bool validateTargetClusterName(const char *clustname)
  4411. {
  4412. Owned<IPropertyTree> envRoot;
  4413. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  4414. return (cluster.get()!=NULL);
  4415. }
  4416. IConstWUClusterInfo* getTargetClusterInfo(const char *clustname)
  4417. {
  4418. Owned<IPropertyTree> envRoot;
  4419. Owned<IPropertyTree> cluster = getTopologyCluster(envRoot, clustname);
  4420. if (!cluster)
  4421. return NULL;
  4422. return getTargetClusterInfo(envRoot, cluster);
  4423. }
  4424. unsigned getEnvironmentClusterInfo(CConstWUClusterInfoArray &clusters)
  4425. {
  4426. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4427. Owned<IConstEnvironment> env = factory->openEnvironment();
  4428. if (!env)
  4429. return 0;
  4430. Owned<IPropertyTree> root = &env->getPTree();
  4431. return getEnvironmentClusterInfo(root, clusters);
  4432. }
  4433. unsigned getEnvironmentClusterInfo(IPropertyTree* environmentRoot, CConstWUClusterInfoArray &clusters)
  4434. {
  4435. if (!environmentRoot)
  4436. return 0;
  4437. Owned<IPropertyTreeIterator> clusterIter = environmentRoot->getElements("Software/Topology/Cluster");
  4438. ForEach(*clusterIter)
  4439. {
  4440. IPropertyTree &node = clusterIter->query();
  4441. Owned<IConstWUClusterInfo> cluster = getTargetClusterInfo(environmentRoot, &node);
  4442. clusters.append(*cluster.getClear());
  4443. }
  4444. return clusters.ordinality();
  4445. }
  4446. const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name)
  4447. {
  4448. if (!clustname)
  4449. return NULL;
  4450. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4451. Owned<IConstEnvironment> env = factory->openEnvironment();
  4452. if (!env)
  4453. return NULL;
  4454. Owned<IPropertyTree> root = &env->getPTree();
  4455. StringBuffer xpath;
  4456. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  4457. Owned<IPropertyTree> cluster = root->getPropTree(xpath.str());
  4458. if (!cluster)
  4459. return NULL;
  4460. StringBuffer xpath1;
  4461. xpath1.appendf("%s/@process", processType);
  4462. name.append(cluster->queryProp(xpath1.str()));
  4463. return name.str();
  4464. }
  4465. unsigned getEnvironmentThorClusterNames(StringArray &thorNames, StringArray &groupNames, StringArray &targetNames, StringArray &queueNames)
  4466. {
  4467. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4468. Owned<IConstEnvironment> env = factory->openEnvironment();
  4469. if (!env)
  4470. return 0;
  4471. Owned<IPropertyTree> root = &env->getPTree();
  4472. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  4473. ForEach(*allTargets)
  4474. {
  4475. IPropertyTree &target = allTargets->query();
  4476. const char *targetName = target.queryProp("@name");
  4477. if (targetName && *targetName)
  4478. {
  4479. Owned<IPropertyTreeIterator> thorClusters = target.getElements("ThorCluster");
  4480. ForEach(*thorClusters)
  4481. {
  4482. const char *thorName = thorClusters->query().queryProp("@process");
  4483. VStringBuffer query("Software/ThorCluster[@name=\"%s\"]",thorName);
  4484. IPropertyTree *thorCluster = root->queryPropTree(query.str());
  4485. if (thorCluster)
  4486. {
  4487. const char *groupName = thorCluster->queryProp("@nodeGroup");
  4488. if (!groupName||!*groupName)
  4489. groupName = thorName;
  4490. thorNames.append(thorName);
  4491. groupNames.append(groupName);
  4492. targetNames.append(targetName);
  4493. StringBuffer queueName(targetName);
  4494. queueNames.append(queueName.append(THOR_QUEUE_EXT));
  4495. }
  4496. }
  4497. }
  4498. }
  4499. return thorNames.ordinality();
  4500. }
  4501. unsigned getEnvironmentHThorClusterNames(StringArray &eclAgentNames, StringArray &groupNames, StringArray &targetNames)
  4502. {
  4503. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  4504. Owned<IConstEnvironment> env = factory->openEnvironment();
  4505. if (!env)
  4506. return 0;
  4507. Owned<IPropertyTree> root = &env->getPTree();
  4508. Owned<IPropertyTreeIterator> allEclAgents = root->getElements("Software/EclAgentProcess");
  4509. ForEach(*allEclAgents)
  4510. {
  4511. IPropertyTree &eclAgent = allEclAgents->query();
  4512. const char *eclAgentName = eclAgent.queryProp("@name");
  4513. if (eclAgentName && *eclAgentName)
  4514. {
  4515. Owned<IPropertyTreeIterator> allTargets = root->getElements("Software/Topology/Cluster");
  4516. ForEach(*allTargets)
  4517. {
  4518. IPropertyTree &target = allTargets->query();
  4519. const char *targetName = target.queryProp("@name");
  4520. if (targetName && *targetName)
  4521. {
  4522. StringBuffer xpath;
  4523. xpath.appendf("EclAgentProcess[@process=\"%s\"]", eclAgentName);
  4524. if (target.hasProp(xpath) && !target.hasProp("ThorCluster"))
  4525. {
  4526. StringBuffer groupName("hthor__");
  4527. groupName.append(eclAgentName);
  4528. groupNames.append(groupName);
  4529. eclAgentNames.append(eclAgentName);
  4530. targetNames.append(targetName);
  4531. }
  4532. }
  4533. }
  4534. }
  4535. }
  4536. return eclAgentNames.ordinality();
  4537. }
  4538. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  4539. {
  4540. CriticalBlock block(crit);
  4541. if (p->hasProp("Debug/ForceScope"))
  4542. {
  4543. StringBuffer prefix(p->queryProp("Debug/ForceScope"));
  4544. str.set(prefix.toLowerCase().str());
  4545. }
  4546. else
  4547. {
  4548. Owned <IConstWUClusterInfo> ci = getTargetClusterInfo(p->queryProp("@clusterName"));
  4549. if (ci)
  4550. ci->getScope(str);
  4551. else
  4552. str.clear();
  4553. }
  4554. return str;
  4555. }
  4556. //Queries
  4557. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  4558. {
  4559. CriticalBlock block(crit);
  4560. p->setPropInt("@codeVersion", codeVersion);
  4561. p->setProp("@buildVersion", buildVersion);
  4562. p->setProp("@eclVersion", eclVersion);
  4563. }
  4564. unsigned CLocalWorkUnit::getCodeVersion() const
  4565. {
  4566. CriticalBlock block(crit);
  4567. return p->getPropInt("@codeVersion");
  4568. }
  4569. unsigned CLocalWorkUnit::getWuidVersion() const
  4570. {
  4571. CriticalBlock block(crit);
  4572. return p->getPropInt("@wuidVersion");
  4573. }
  4574. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  4575. {
  4576. CriticalBlock block(crit);
  4577. buildVersion.set(p->queryProp("@buildVersion"));
  4578. eclVersion.set(p->queryProp("@eclVersion"));
  4579. }
  4580. void CLocalWorkUnit::setCloneable(bool value)
  4581. {
  4582. CriticalBlock block(crit);
  4583. p->setPropInt("@cloneable", value);
  4584. }
  4585. void CLocalWorkUnit::setIsClone(bool value)
  4586. {
  4587. CriticalBlock block(crit);
  4588. p->setPropInt("@isClone", value);
  4589. }
  4590. bool CLocalWorkUnit::getCloneable() const
  4591. {
  4592. CriticalBlock block(crit);
  4593. return p->getPropBool("@cloneable", false);
  4594. }
  4595. IUserDescriptor *CLocalWorkUnit::queryUserDescriptor() const
  4596. {
  4597. CriticalBlock block(crit);
  4598. if (!userDesc)
  4599. {
  4600. SCMStringBuffer token, user, password;
  4601. getSecurityToken(token);
  4602. extractToken(token.str(), queryWuid(), user, password);
  4603. userDesc.setown(createUserDescriptor());
  4604. userDesc->set(user.str(), password.str());
  4605. }
  4606. return userDesc;
  4607. }
  4608. bool CLocalWorkUnit::isProtected() const
  4609. {
  4610. CriticalBlock block(crit);
  4611. return p->getPropBool("@protected", false);
  4612. }
  4613. bool CLocalWorkUnit::isPausing() const
  4614. {
  4615. CriticalBlock block(crit);
  4616. if (WUActionPause == getAction())
  4617. {
  4618. switch (getState())
  4619. {
  4620. case WUStateRunning:
  4621. case WUStateAborting:
  4622. return true;
  4623. }
  4624. }
  4625. return false;
  4626. }
  4627. void CLocalWorkUnit::protect(bool protectMode)
  4628. {
  4629. CriticalBlock block(crit);
  4630. p->setPropBool("@protected", protectMode);
  4631. }
  4632. void CLocalWorkUnit::setResultLimit(unsigned value)
  4633. {
  4634. CriticalBlock block(crit);
  4635. p->setPropInt("resultLimit", value);
  4636. }
  4637. unsigned CLocalWorkUnit::getResultLimit() const
  4638. {
  4639. CriticalBlock block(crit);
  4640. return p->getPropInt("resultLimit");
  4641. }
  4642. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  4643. {
  4644. CriticalBlock block(crit);
  4645. str.set(p->queryProp("SNAPSHOT"));
  4646. return str;
  4647. }
  4648. void CLocalWorkUnit::setSnapshot(const char * val)
  4649. {
  4650. CriticalBlock block(crit);
  4651. p->setProp("SNAPSHOT", val);
  4652. }
  4653. const static mapEnums warningSeverityMap[] =
  4654. {
  4655. { SeverityInformation, "info" },
  4656. { SeverityWarning, "warning" },
  4657. { SeverityError, "error" },
  4658. { SeverityAlert, "alert" },
  4659. { SeverityIgnore, "ignore" },
  4660. { SeverityFatal, "fatal" },
  4661. { SeverityUnknown, NULL }
  4662. };
  4663. ErrorSeverity CLocalWorkUnit::getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const
  4664. {
  4665. StringBuffer xpath;
  4666. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  4667. CriticalBlock block(crit);
  4668. IPropertyTree * mapping = p->queryPropTree(xpath);
  4669. if (mapping)
  4670. return (ErrorSeverity) getEnum(mapping, "@severity", warningSeverityMap);
  4671. return defaultSeverity;
  4672. }
  4673. void CLocalWorkUnit::setWarningSeverity(unsigned code, ErrorSeverity severity)
  4674. {
  4675. StringBuffer xpath;
  4676. xpath.append("OnWarnings/OnWarning[@code='").append(code).append("']");
  4677. CriticalBlock block(crit);
  4678. IPropertyTree * mapping = p->queryPropTree(xpath);
  4679. if (!mapping)
  4680. {
  4681. IPropertyTree * onWarnings = ensurePTree(p, "OnWarnings");
  4682. mapping = onWarnings->addPropTree("OnWarning", createPTree());
  4683. mapping->setPropInt("@code", code);
  4684. }
  4685. setEnum(mapping, "@severity", severity, warningSeverityMap);
  4686. }
  4687. static int comparePropTrees(IInterface * const *ll, IInterface * const *rr)
  4688. {
  4689. IPropertyTree *l = (IPropertyTree *) *ll;
  4690. IPropertyTree *r = (IPropertyTree *) *rr;
  4691. return stricmp(l->queryName(), r->queryName());
  4692. };
  4693. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  4694. {
  4695. // Any other values in the WU that could affect generated code should be crc'ed here
  4696. IPropertyTree *tree = p->queryBranch("Debug");
  4697. if (tree)
  4698. {
  4699. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  4700. ICopyArrayOf<IPropertyTree> subs;
  4701. for(sub->first(); sub->isValid(); sub->next())
  4702. subs.append(sub->query());
  4703. subs.sort(comparePropTrees);
  4704. ForEachItemIn(idx, subs)
  4705. {
  4706. const char *name = subs.item(idx).queryName();
  4707. const char *val = subs.item(idx).queryProp(NULL);
  4708. crc = crc32(name, (size32_t)strlen(name), crc);
  4709. if (val)
  4710. crc = crc32(val, (size32_t)strlen(val), crc);
  4711. }
  4712. }
  4713. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  4714. for (plugins->first();plugins->isValid();plugins->next())
  4715. {
  4716. IConstWUPlugin &thisplugin = plugins->query();
  4717. SCMStringBuffer version;
  4718. thisplugin.getPluginVersion(version);
  4719. crc = crc32(version.str(), version.length(), crc);
  4720. }
  4721. return crc;
  4722. }
  4723. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4724. {
  4725. if (!to->hasProp(xpath) && from->hasProp(xpath))
  4726. to->setProp(xpath, from->queryProp(xpath));
  4727. }
  4728. static void setProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4729. {
  4730. if (from->hasProp(xpath))
  4731. to->setProp(xpath, from->queryProp(xpath));
  4732. }
  4733. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  4734. {
  4735. IPropertyTree * match = from->getBranch(xpath);
  4736. if (match)
  4737. to->setPropTree(xpath, match);
  4738. }
  4739. IPropertyTree *CLocalWorkUnit::queryPTree() const
  4740. {
  4741. return p;
  4742. }
  4743. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached, bool all)
  4744. {
  4745. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  4746. if (!from)
  4747. {
  4748. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  4749. if (!fl)
  4750. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  4751. from = fl->c;
  4752. }
  4753. // Need to copy the query, the results, and the graphs from the cached query.
  4754. // The cache is made before the query is executed so there is no need to clear them.
  4755. if (!cached->getCloneable())
  4756. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  4757. const IPropertyTree * fromP = from->p;
  4758. IPropertyTree *pt;
  4759. CriticalBlock block(crit);
  4760. clearCached(false);
  4761. query.clear();
  4762. updateProp(p, fromP, "@jobName");
  4763. copyTree(p, fromP, "Query");
  4764. pt = fromP->getBranch("Application/LibraryModule");
  4765. if (pt)
  4766. {
  4767. ensurePTree(p, "Application");
  4768. p->setPropTree("Application/LibraryModule", pt);
  4769. }
  4770. pt = fromP->queryBranch("Debug");
  4771. if (pt)
  4772. {
  4773. IPropertyTree *curDebug = p->queryPropTree("Debug");
  4774. if (curDebug)
  4775. {
  4776. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  4777. ForEach(*elems)
  4778. {
  4779. IPropertyTree *elem = &elems->query();
  4780. if (!curDebug->hasProp(elem->queryName()))
  4781. curDebug->setPropTree(elem->queryName(),LINK(elem));
  4782. }
  4783. }
  4784. else
  4785. p->setPropTree("Debug", LINK(pt));
  4786. }
  4787. copyTree(p, fromP, "OnWarnings");
  4788. copyTree(p, fromP, "Plugins");
  4789. copyTree(p, fromP, "Libraries");
  4790. copyTree(p, fromP, "Results");
  4791. copyTree(p, fromP, "Graphs");
  4792. copyTree(p, fromP, "Workflow");
  4793. copyTree(p, fromP, "WebServicesInfo");
  4794. if (all)
  4795. {
  4796. // 'all' mode is used when setting up a dali WU from the embedded wu in a workunit dll
  4797. // Merge timing info from both branches
  4798. pt = fromP->getBranch("Timings");
  4799. if (pt)
  4800. {
  4801. IPropertyTree *tgtTimings = ensurePTree(p, "Timings");
  4802. mergePTree(tgtTimings, pt);
  4803. pt->Release();
  4804. }
  4805. pt = fromP->getBranch("Statistics");
  4806. if (pt)
  4807. {
  4808. IPropertyTree *tgtStatistics = ensurePTree(p, "Statistics");
  4809. mergePTree(tgtStatistics, pt);
  4810. pt->Release();
  4811. }
  4812. }
  4813. updateProp(p, fromP, "@clusterName");
  4814. updateProp(p, fromP, "allowedclusters");
  4815. updateProp(p, fromP, "@submitID");
  4816. updateProp(p, fromP, "SNAPSHOT");
  4817. setProp(p, fromP, "@eventScheduledCount");
  4818. //MORE: This is very adhoc. All options that should be cloned should really be in a common branch
  4819. if (all)
  4820. {
  4821. setProp(p, fromP, "PriorityFlag");
  4822. setProp(p, fromP, "@priorityClass");
  4823. setProp(p, fromP, "@protected");
  4824. setProp(p, fromP, "@clusterName");
  4825. updateProp(p, fromP, "@scope");
  4826. }
  4827. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  4828. pt = fromP->getBranch("Variables");
  4829. if (pt)
  4830. {
  4831. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  4832. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  4833. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  4834. {
  4835. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  4836. const char *name = ptSrcVariable->queryProp("@name");
  4837. assertex(name);
  4838. StringBuffer xpath;
  4839. xpath.append("Variable[@name='").append(name).append("']");
  4840. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  4841. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  4842. merged->removeProp("Value"); // except value and status
  4843. merged->setProp("@status", "undefined");
  4844. if (!merged->getPropBool("@isScalar"))
  4845. merged->removeProp("totalRowCount");
  4846. merged->removeProp("rowCount");
  4847. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  4848. if (ptTgtVariable)
  4849. {
  4850. // copy status and Value from what is already set in target
  4851. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  4852. MemoryBuffer value;
  4853. if (ptTgtVariable->getPropBin("Value", value))
  4854. merged->setPropBin("Value", value.length(), value.toByteArray());
  4855. ptTgtVariable->removeProp(xpath.str());
  4856. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  4857. }
  4858. ptTgtVariables->addPropTree("Variable", merged);
  4859. }
  4860. pt->Release();
  4861. }
  4862. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  4863. p->setProp("@buildVersion", fromP->queryProp("@buildVersion"));
  4864. p->setProp("@eclVersion", fromP->queryProp("@eclVersion"));
  4865. p->setProp("@hash", fromP->queryProp("@hash"));
  4866. p->setPropBool("@cloneable", true);
  4867. p->setPropBool("@isClone", true);
  4868. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  4869. Owned<IPropertyTreeIterator> results = p->getElements("Results/Result");
  4870. ForEach(*results)
  4871. {
  4872. CLocalWUResult result(LINK(&results->query()));
  4873. result.setResultStatus(ResultStatusUndefined);
  4874. }
  4875. copyTree(p, fromP, "usedsources"); // field usage
  4876. }
  4877. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  4878. {
  4879. StringBuffer lower;
  4880. lower.append(propname).toLowerCase();
  4881. CriticalBlock block(crit);
  4882. StringBuffer prop("Debug/");
  4883. return p->hasProp(prop.append(lower));
  4884. }
  4885. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  4886. {
  4887. StringBuffer lower;
  4888. lower.append(propname).toLowerCase();
  4889. CriticalBlock block(crit);
  4890. StringBuffer prop("Debug/");
  4891. str.set(p->queryProp(prop.append(lower).str()));
  4892. return str;
  4893. }
  4894. IStringIterator& CLocalWorkUnit::getDebugValues() const
  4895. {
  4896. return getDebugValues(NULL);
  4897. }
  4898. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  4899. {
  4900. CriticalBlock block(crit);
  4901. StringBuffer path("Debug/");
  4902. if (prop)
  4903. {
  4904. StringBuffer lower;
  4905. lower.append(prop).toLowerCase();
  4906. path.append(lower);
  4907. }
  4908. else
  4909. path.append("*");
  4910. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  4911. }
  4912. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  4913. {
  4914. StringBuffer lower;
  4915. lower.append(propname).toLowerCase();
  4916. CriticalBlock block(crit);
  4917. StringBuffer prop("Debug/");
  4918. prop.append(lower);
  4919. return p->getPropInt(prop.str(), defVal);
  4920. }
  4921. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  4922. {
  4923. StringBuffer lower;
  4924. lower.append(propname).toLowerCase();
  4925. CriticalBlock block(crit);
  4926. StringBuffer prop("Debug/");
  4927. prop.append(lower);
  4928. return p->getPropInt64(prop.str(), defVal);
  4929. }
  4930. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  4931. {
  4932. StringBuffer lower;
  4933. lower.append(propname).toLowerCase();
  4934. CriticalBlock block(crit);
  4935. StringBuffer prop("Debug/");
  4936. prop.append(lower);
  4937. return p->getPropBool(prop.str(), defVal);
  4938. }
  4939. IStringIterator *CLocalWorkUnit::getLogs(const char *type, const char *instance) const
  4940. {
  4941. VStringBuffer xpath("Process/%s/", type);
  4942. if (instance)
  4943. xpath.append(instance);
  4944. else
  4945. xpath.append("*");
  4946. CriticalBlock block(crit);
  4947. if (p->getPropInt("@wuidVersion") < 1) // legacy wuid
  4948. {
  4949. // NB: instance unused
  4950. if (streq("EclAgent", type))
  4951. return new CStringPTreeIterator(p->getElements("Debug/eclagentlog"));
  4952. else if (streq("Thor", type))
  4953. return new CStringPTreeIterator(p->getElements("Debug/thorlog*"));
  4954. VStringBuffer xpath("Debug/%s", type);
  4955. return new CStringPTreeIterator(p->getElements(xpath.str()));
  4956. }
  4957. else
  4958. return new CStringPTreeAttrIterator(p->getElements(xpath.str()), "@log");
  4959. }
  4960. IPropertyTreeIterator* CLocalWorkUnit::getProcesses(const char *type, const char *instance) const
  4961. {
  4962. VStringBuffer xpath("Process/%s/", type);
  4963. if (instance)
  4964. xpath.append(instance);
  4965. else
  4966. xpath.append("*");
  4967. CriticalBlock block(crit);
  4968. return p->getElements(xpath.str());
  4969. }
  4970. IStringIterator *CLocalWorkUnit::getProcesses(const char *type) const
  4971. {
  4972. VStringBuffer xpath("Process/%s/*", type);
  4973. CriticalBlock block(crit);
  4974. return new CStringPTreeTagIterator(p->getElements(xpath.str()));
  4975. }
  4976. void CLocalWorkUnit::addProcess(const char *type, const char *instance, unsigned pid, const char *log)
  4977. {
  4978. VStringBuffer processType("Process/%s", type);
  4979. VStringBuffer xpath("%s/%s", processType.str(), instance);
  4980. if (log)
  4981. xpath.appendf("[@log=\"%s\"]", log);
  4982. CriticalBlock block(crit);
  4983. if (!p->hasProp(xpath))
  4984. {
  4985. IPropertyTree *node = ensurePTree(p, processType.str());
  4986. node = node->addPropTree(instance, createPTree());
  4987. node->setProp("@log", log);
  4988. node->setPropInt("@pid", pid);
  4989. }
  4990. }
  4991. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  4992. {
  4993. StringBuffer lower;
  4994. lower.append(propname).toLowerCase();
  4995. CriticalBlock block(crit);
  4996. StringBuffer prop("Debug/");
  4997. prop.append(lower);
  4998. if (overwrite || !p->hasProp(prop.str()))
  4999. {
  5000. // MORE - not sure this line should be needed....
  5001. p->setProp("Debug", "");
  5002. p->setProp(prop.str(), value);
  5003. }
  5004. }
  5005. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  5006. {
  5007. StringBuffer lower;
  5008. lower.append(propname).toLowerCase();
  5009. CriticalBlock block(crit);
  5010. StringBuffer prop("Debug/");
  5011. prop.append(lower);
  5012. if (overwrite || !p->hasProp(prop.str()))
  5013. {
  5014. // MORE - not sure this line should be needed....
  5015. p->setProp("Debug", "");
  5016. p->setPropInt(prop.str(), value);
  5017. }
  5018. }
  5019. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  5020. {
  5021. CriticalBlock block(crit);
  5022. // MORE - not sure this line should be needed....
  5023. p->setProp("Tracing", "");
  5024. StringBuffer prop("Tracing/");
  5025. p->setProp(prop.append(propname).str(), value);
  5026. }
  5027. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  5028. {
  5029. CriticalBlock block(crit);
  5030. StringBuffer prop("Tracing/");
  5031. p->setPropInt(prop.append(propname).str(), value);
  5032. }
  5033. void CLocalWorkUnit::setTracingValueInt64(const char *propname, __int64 value)
  5034. {
  5035. CriticalBlock block(crit);
  5036. VStringBuffer prop("Tracing/%s", propname);
  5037. p->setPropInt64(prop.str(), value);
  5038. }
  5039. IConstWUQuery* CLocalWorkUnit::getQuery() const
  5040. {
  5041. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  5042. CriticalBlock block(crit);
  5043. if (!query)
  5044. {
  5045. IPropertyTree *s = p->getPropTree("Query");
  5046. if (s)
  5047. query.setown(new CLocalWUQuery(s)); // NB takes ownership of 's'
  5048. }
  5049. return query.getLink();
  5050. }
  5051. IWUQuery* CLocalWorkUnit::updateQuery()
  5052. {
  5053. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5054. CriticalBlock block(crit);
  5055. if (!query)
  5056. {
  5057. IPropertyTree *s = p->queryPropTree("Query");
  5058. if (!s)
  5059. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>")); // Is this really desirable (the fetchEntire) ?
  5060. s->Link();
  5061. query.setown(new CLocalWUQuery(s));
  5062. }
  5063. return query.getLink();
  5064. }
  5065. void CLocalWorkUnit::loadPlugins() const
  5066. {
  5067. CriticalBlock block(crit);
  5068. if (!pluginsCached)
  5069. {
  5070. assertex(plugins.length() == 0);
  5071. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  5072. for (r->first(); r->isValid(); r->next())
  5073. {
  5074. IPropertyTree *rp = &r->query();
  5075. rp->Link();
  5076. plugins.append(*new CLocalWUPlugin(rp));
  5077. }
  5078. pluginsCached = true;
  5079. }
  5080. }
  5081. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  5082. {
  5083. CriticalBlock block(crit);
  5084. loadPlugins();
  5085. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  5086. }
  5087. void CLocalWorkUnit::loadLibraries() const
  5088. {
  5089. CriticalBlock block(crit);
  5090. if (!librariesCached)
  5091. {
  5092. assertex(libraries.length() == 0);
  5093. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  5094. ForEach(*r)
  5095. {
  5096. IPropertyTree *rp = &r->query();
  5097. rp->Link();
  5098. libraries.append(*new CLocalWULibrary(rp));
  5099. }
  5100. librariesCached = true;
  5101. }
  5102. }
  5103. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  5104. {
  5105. CriticalBlock block(crit);
  5106. loadLibraries();
  5107. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  5108. }
  5109. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  5110. {
  5111. CriticalBlock block(crit);
  5112. loadLibraries();
  5113. ForEachItemIn(idx, libraries)
  5114. {
  5115. SCMStringBuffer name;
  5116. IConstWULibrary &cur = libraries.item(idx);
  5117. cur.getName(name);
  5118. if (stricmp(name.str(), search)==0)
  5119. return &OLINK(cur);
  5120. }
  5121. return NULL;
  5122. }
  5123. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  5124. {
  5125. str.append("Graph ").append(graphName);
  5126. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  5127. else if (subId) str.append(" - id(").append(subId).append(")");
  5128. return str;
  5129. }
  5130. StringBuffer &formatGraphTimerScope(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  5131. {
  5132. str.append(graphName);
  5133. if (subId) str.append(":sg").append(subId);
  5134. return str;
  5135. }
  5136. bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId)
  5137. {
  5138. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  5139. unsigned len = (size32_t)strlen(label);
  5140. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  5141. return false;
  5142. graphNum = 0;
  5143. subGraphNum = 0;
  5144. subId = 0;
  5145. const char *finger = label+6;
  5146. const char *finger2 = strchr(finger, '-');
  5147. if (NULL == finger2) // just graphName
  5148. graphName.set(finger);
  5149. else
  5150. {
  5151. graphName.set(finger, (size32_t)((finger2-1)-finger));
  5152. finger = finger2+2; // skip '-' and space
  5153. finger2 = strchr(finger, ' ');
  5154. if (finger2)
  5155. {
  5156. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  5157. finger = finger2+2; // skip space and '('
  5158. finger2 = strchr(finger, ')');
  5159. if (finger2)
  5160. subId = atoi_l(finger, (size32_t)(finger2-finger));
  5161. }
  5162. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  5163. {
  5164. finger += 3;
  5165. finger2 = strchr(finger, ')');
  5166. if (finger2)
  5167. subId = atoi_l(finger, (size32_t)(finger2-finger));
  5168. }
  5169. }
  5170. if (graphName && !memicmp(graphName, "graph", 5))
  5171. graphNum = atoi(graphName + 5);
  5172. return true;
  5173. }
  5174. bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId)
  5175. {
  5176. if (!MATCHES_CONST_PREFIX(scope, GraphScopePrefix))
  5177. return false;
  5178. graphNum = atoi(scope + CONST_STRLEN(GraphScopePrefix));
  5179. subGraphId = 0;
  5180. const char * colon = strchr(scope, ':');
  5181. if (!colon)
  5182. {
  5183. graphName.set(scope);
  5184. return true;
  5185. }
  5186. const char * subgraph = colon+1;
  5187. graphName.set(scope, (size32_t)(colon - scope));
  5188. if (MATCHES_CONST_PREFIX(subgraph, SubGraphScopePrefix))
  5189. subGraphId = atoi(subgraph+CONST_STRLEN(SubGraphScopePrefix));
  5190. return true;
  5191. }
  5192. class WorkUnitStatisticsIterator : public CArrayIteratorOf<IConstWUStatistic,IConstWUStatisticIterator>
  5193. {
  5194. typedef CArrayIteratorOf<IConstWUStatistic,IConstWUStatisticIterator> PARENT;
  5195. public:
  5196. WorkUnitStatisticsIterator(const IArray &a, aindex_t start, IInterface *owner, const IStatisticsFilter * _filter)
  5197. : PARENT(a,start, owner), filter(_filter)
  5198. {
  5199. }
  5200. virtual bool first()
  5201. {
  5202. if (!PARENT::first())
  5203. return false;
  5204. if (matchesFilter())
  5205. return true;
  5206. return next();
  5207. }
  5208. virtual bool next()
  5209. {
  5210. loop
  5211. {
  5212. if (!PARENT::next())
  5213. return false;
  5214. if (matchesFilter())
  5215. return true;
  5216. }
  5217. }
  5218. protected:
  5219. bool matchesFilter()
  5220. {
  5221. if (!filter)
  5222. return true;
  5223. return query().matches(filter);
  5224. }
  5225. protected:
  5226. Linked<const IStatisticsFilter> filter;
  5227. };
  5228. 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)
  5229. {
  5230. if (!scope || !*scope) scope = GLOBAL_SCOPE;
  5231. const char * kindName = queryStatisticName(kind);
  5232. StatisticMeasure measure = queryMeasure(kind);
  5233. //creator. scope and name must all be present, and must not contain semi colons.
  5234. assertex(creator && scope);
  5235. CriticalBlock block(crit);
  5236. IPropertyTree * stats = p->queryPropTree("Statistics");
  5237. if (!stats)
  5238. stats = p->addPropTree("Statistics", createPTree("Statistics"));
  5239. IPropertyTree * statTree = NULL;
  5240. if (mergeAction != StatsMergeAppend)
  5241. {
  5242. StringBuffer xpath;
  5243. xpath.append("Statistic[@creator='").append(creator).append("'][@scope='").append(scope).append("'][@kind='").append(kindName).append("']");
  5244. statTree = stats->queryPropTree(xpath.str());
  5245. }
  5246. if (!statTree)
  5247. {
  5248. statTree = stats->addPropTree("Statistic", createPTree("Statistic"));
  5249. statTree->setProp("@creator", creator);
  5250. statTree->setProp("@scope", scope);
  5251. statTree->setProp("@kind", kindName);
  5252. //These items are primarily here to facilitate filtering.
  5253. statTree->setProp("@unit", queryMeasureName(measure));
  5254. statTree->setProp("@c", queryCreatorTypeName(creatorType));
  5255. statTree->setProp("@s", queryScopeTypeName(scopeType));
  5256. statTree->setPropInt64("@ts", getTimeStampNowValue());
  5257. if (optDescription)
  5258. statTree->setProp("@desc", optDescription);
  5259. if (statistics.cached)
  5260. statistics.append(LINK(statTree));
  5261. mergeAction = StatsMergeAppend;
  5262. }
  5263. if (mergeAction != StatsMergeAppend) // RKC->GH Is this right??
  5264. {
  5265. unsigned __int64 oldValue = statTree->getPropInt64("@value", 0);
  5266. unsigned __int64 oldCount = statTree->getPropInt64("@count", 0);
  5267. unsigned __int64 oldMax = statTree->getPropInt64("@max", 0);
  5268. if (oldMax < oldValue)
  5269. oldMax = oldValue;
  5270. statTree->setPropInt64("@value", mergeStatisticValue(oldValue, value, mergeAction));
  5271. statTree->setPropInt64("@count", count + oldCount);
  5272. if (maxValue > oldMax)
  5273. statTree->setPropInt64("@max", maxValue);
  5274. }
  5275. else
  5276. {
  5277. statTree->setPropInt64("@value", value);
  5278. statTree->setPropInt64("@count", count);
  5279. if (maxValue)
  5280. statTree->setPropInt64("@max", maxValue);
  5281. else
  5282. statTree->removeProp("@max");
  5283. }
  5284. if (creatorType==SCTsummary && kind==StTimeElapsed && strsame(scope, GLOBAL_SCOPE))
  5285. {
  5286. StringBuffer t;
  5287. formatTimeCollatable(t, value, false);
  5288. p->setProp("@totalThorTime", t);
  5289. }
  5290. }
  5291. void CLocalWorkUnit::_loadStatistics() const
  5292. {
  5293. statistics.load(p,"Statistics/*");
  5294. }
  5295. IConstWUStatisticIterator& CLocalWorkUnit::getStatistics(const IStatisticsFilter * filter) const
  5296. {
  5297. CriticalBlock block(crit);
  5298. //This should be deleted in version 6.0 when support for 4.x is no longer required
  5299. legacyTimings.load(p,"Timings/*");
  5300. if (legacyTimings.ordinality())
  5301. return *new WorkUnitStatisticsIterator(legacyTimings, 0, (IConstWorkUnit *) this, filter);
  5302. statistics.load(p,"Statistics/*");
  5303. Owned<IConstWUStatisticIterator> localStats = new WorkUnitStatisticsIterator(statistics, 0, (IConstWorkUnit *) this, filter);
  5304. const char * wuid = p->queryName();
  5305. Owned<IConstWUStatisticIterator> graphStats = new CConstGraphProgressStatisticsIterator(wuid, filter);
  5306. return * new CCompoundIteratorOf<IConstWUStatisticIterator, IConstWUStatistic>(localStats, graphStats);
  5307. }
  5308. IConstWUStatistic * CLocalWorkUnit::getStatistic(const char * creator, const char * scope, StatisticKind kind) const
  5309. {
  5310. //MORE: Optimize this....
  5311. StatisticsFilter filter;
  5312. filter.setCreator(creator);
  5313. filter.setScope(scope);
  5314. filter.setKind(kind);
  5315. Owned<IConstWUStatisticIterator> stats = &getStatistics(&filter);
  5316. if (stats->first())
  5317. return LINK(&stats->query());
  5318. return NULL;
  5319. }
  5320. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  5321. {
  5322. CriticalBlock block(crit);
  5323. IConstWUPlugin *existing = getPluginByName(qname);
  5324. if (existing)
  5325. return (IWUPlugin *) existing;
  5326. if (!plugins.length())
  5327. p->addPropTree("Plugins", createPTree("Plugins"));
  5328. IPropertyTree *pl = p->queryPropTree("Plugins");
  5329. IPropertyTree *s = pl->addPropTree("Plugin", createPTree("Plugin"));
  5330. s->Link();
  5331. IWUPlugin* q = new CLocalWUPlugin(s);
  5332. q->Link();
  5333. plugins.append(*q);
  5334. q->setPluginName(qname);
  5335. return q;
  5336. }
  5337. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  5338. {
  5339. CriticalBlock block(crit);
  5340. loadPlugins();
  5341. ForEachItemIn(idx, plugins)
  5342. {
  5343. SCMStringBuffer name;
  5344. IConstWUPlugin &cur = plugins.item(idx);
  5345. cur.getPluginName(name);
  5346. if (stricmp(name.str(), qname)==0)
  5347. {
  5348. cur.Link();
  5349. return &cur;
  5350. }
  5351. }
  5352. return NULL;
  5353. }
  5354. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  5355. {
  5356. CriticalBlock block(crit);
  5357. IConstWULibrary *existing = getLibraryByName(qname);
  5358. if (existing)
  5359. return (IWULibrary *) existing;
  5360. if (!libraries.length())
  5361. p->addPropTree("Libraries", createPTree("Libraries"));
  5362. IPropertyTree *pl = p->queryPropTree("Libraries");
  5363. IPropertyTree *s = pl->addPropTree("Library", createPTree("Library"));
  5364. s->Link();
  5365. IWULibrary* q = new CLocalWULibrary(s);
  5366. q->Link();
  5367. libraries.append(*q);
  5368. q->setName(qname);
  5369. return q;
  5370. }
  5371. void CLocalWorkUnit::_loadExceptions() const
  5372. {
  5373. assertex(exceptions.length() == 0);
  5374. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  5375. for (r->first(); r->isValid(); r->next())
  5376. {
  5377. IPropertyTree *rp = &r->query();
  5378. rp->Link();
  5379. exceptions.append(*new CLocalWUException(rp));
  5380. }
  5381. }
  5382. void CLocalWorkUnit::loadExceptions() const
  5383. {
  5384. CriticalBlock block(crit);
  5385. if (!exceptionsCached)
  5386. {
  5387. _loadExceptions();
  5388. exceptionsCached = true;
  5389. }
  5390. }
  5391. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  5392. {
  5393. CriticalBlock block(crit);
  5394. loadExceptions();
  5395. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  5396. }
  5397. unsigned CLocalWorkUnit::getExceptionCount() const
  5398. {
  5399. CriticalBlock block(crit);
  5400. loadExceptions();
  5401. return exceptions.length();
  5402. }
  5403. void CLocalWorkUnit::clearExceptions()
  5404. {
  5405. CriticalBlock block(crit);
  5406. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5407. exceptions.kill();
  5408. exceptionsCached = true;
  5409. p->removeProp("Exceptions");
  5410. }
  5411. IWUException* CLocalWorkUnit::createException()
  5412. {
  5413. CriticalBlock block(crit);
  5414. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5415. loadExceptions();
  5416. if (!exceptions.length())
  5417. p->addPropTree("Exceptions", createPTree("Exceptions"));
  5418. IPropertyTree *r = p->queryPropTree("Exceptions");
  5419. IPropertyTree *s = r->addPropTree("Exception", createPTree("Exception"));
  5420. s->setPropInt("@sequence", exceptions.ordinality());
  5421. IWUException* q = new CLocalWUException(LINK(s));
  5422. exceptions.append(*LINK(q));
  5423. Owned<IJlibDateTime> now = createDateTimeNow();
  5424. SCMStringBuffer temp;
  5425. now->getString(temp);
  5426. q->setTimeStamp(temp.str());
  5427. return q;
  5428. }
  5429. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  5430. {
  5431. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  5432. CriticalBlock block(crit);
  5433. if (!webServicesInfoCached)
  5434. {
  5435. assertex(!webServicesInfo);
  5436. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  5437. if (s)
  5438. webServicesInfo.setown(new CLocalWUWebServicesInfo(s)); // NB takes ownership of 's'
  5439. webServicesInfoCached = true;
  5440. }
  5441. return webServicesInfo.getLink();
  5442. }
  5443. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  5444. {
  5445. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5446. CriticalBlock block(crit);
  5447. if (!webServicesInfoCached)
  5448. {
  5449. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  5450. if (!s)
  5451. {
  5452. if (create)
  5453. s = p->addPropTree("WebServicesInfo", createPTreeFromXMLString("<WebServicesInfo />"));
  5454. else
  5455. return NULL;
  5456. }
  5457. s->Link();
  5458. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  5459. webServicesInfoCached = true;
  5460. }
  5461. return webServicesInfo.getLink();
  5462. }
  5463. static int compareResults(IInterface * const *ll, IInterface * const *rr)
  5464. {
  5465. CLocalWUResult *l = (CLocalWUResult *) *ll;
  5466. CLocalWUResult *r = (CLocalWUResult *) *rr;
  5467. return l->getResultSequence() - r->getResultSequence();
  5468. }
  5469. void CLocalWorkUnit::_loadResults() const
  5470. {
  5471. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  5472. for (r->first(); r->isValid(); r->next())
  5473. {
  5474. IPropertyTree *rp = &r->query();
  5475. rp->Link();
  5476. results.append(*new CLocalWUResult(rp));
  5477. }
  5478. }
  5479. void CLocalWorkUnit::loadResults() const
  5480. {
  5481. if (!resultsCached)
  5482. {
  5483. assertex(results.length() == 0);
  5484. _loadResults();
  5485. results.sort(compareResults);
  5486. resultsCached = true;
  5487. }
  5488. }
  5489. void CLocalWorkUnit::_loadVariables() const
  5490. {
  5491. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  5492. for (r->first(); r->isValid(); r->next())
  5493. {
  5494. IPropertyTree *rp = &r->query();
  5495. rp->Link();
  5496. variables.append(*new CLocalWUResult(rp));
  5497. }
  5498. }
  5499. void CLocalWorkUnit::loadVariables() const
  5500. {
  5501. if (!variablesCached)
  5502. {
  5503. assertex(variables.length() == 0);
  5504. _loadVariables();
  5505. variablesCached = true;
  5506. }
  5507. }
  5508. void CLocalWorkUnit::_loadTemporaries() const
  5509. {
  5510. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  5511. for (r->first(); r->isValid(); r->next())
  5512. {
  5513. IPropertyTree *rp = &r->query();
  5514. rp->Link();
  5515. temporaries.append(*new CLocalWUResult(rp));
  5516. }
  5517. }
  5518. void CLocalWorkUnit::loadTemporaries() const
  5519. {
  5520. if (!temporariesCached)
  5521. {
  5522. assertex(temporaries.length() == 0);
  5523. _loadTemporaries();
  5524. temporariesCached = true;
  5525. }
  5526. }
  5527. void CLocalWorkUnit::deleteTemporaries()
  5528. {
  5529. CriticalBlock block(crit);
  5530. if (temporariesCached)
  5531. {
  5532. temporaries.kill();
  5533. temporariesCached = false;
  5534. }
  5535. p->removeProp("Temporaries");
  5536. }
  5537. IWUResult* CLocalWorkUnit::createResult()
  5538. {
  5539. CriticalBlock block(crit);
  5540. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5541. loadResults();
  5542. if (!results.length())
  5543. p->addPropTree("Results", createPTree("Results"));
  5544. IPropertyTree *r = p->queryPropTree("Results");
  5545. IPropertyTree *s = r->addPropTree("Result", createPTree());
  5546. s->Link();
  5547. IWUResult* q = new CLocalWUResult(s);
  5548. q->Link();
  5549. results.append(*q);
  5550. return q;
  5551. }
  5552. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  5553. {
  5554. CriticalBlock block(crit);
  5555. IConstWUResult *existing = getResultByName(qname);
  5556. if (existing)
  5557. return (IWUResult *) existing;
  5558. IWUResult* q = createResult();
  5559. q->setResultName(qname);
  5560. return q;
  5561. }
  5562. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  5563. {
  5564. CriticalBlock block(crit);
  5565. IConstWUResult *existing = getResultBySequence(seq);
  5566. if (existing)
  5567. return (IWUResult *) existing;
  5568. IWUResult* q = createResult();
  5569. q->setResultSequence(seq);
  5570. return q;
  5571. }
  5572. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  5573. {
  5574. CriticalBlock block(crit);
  5575. loadResults();
  5576. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  5577. }
  5578. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  5579. {
  5580. CriticalBlock block(crit);
  5581. loadResults();
  5582. ForEachItemIn(idx, results)
  5583. {
  5584. SCMStringBuffer name;
  5585. IConstWUResult &cur = results.item(idx);
  5586. cur.getResultName(name);
  5587. if (stricmp(name.str(), qname)==0)
  5588. {
  5589. cur.Link();
  5590. return &cur;
  5591. }
  5592. }
  5593. return NULL;
  5594. }
  5595. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  5596. {
  5597. CriticalBlock block(crit);
  5598. loadResults();
  5599. ForEachItemIn(idx, results)
  5600. {
  5601. IConstWUResult &cur = results.item(idx);
  5602. if (cur.getResultSequence() == seq)
  5603. {
  5604. cur.Link();
  5605. return &cur;
  5606. }
  5607. }
  5608. return NULL;
  5609. }
  5610. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  5611. {
  5612. CriticalBlock block(crit);
  5613. loadVariables();
  5614. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  5615. }
  5616. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  5617. {
  5618. CriticalBlock block(crit);
  5619. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  5620. return getVariableByName(qname);
  5621. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  5622. return global->getVariableByName(qname);
  5623. }
  5624. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  5625. {
  5626. CriticalBlock block(crit);
  5627. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  5628. return updateVariableByName(qname);
  5629. Owned <IWorkUnit> global = factory->getGlobalWorkUnit(secMgr, secUser);
  5630. return global->updateVariableByName(qname);
  5631. }
  5632. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  5633. {
  5634. CriticalBlock block(crit);
  5635. loadVariables();
  5636. ForEachItemIn(idx, variables)
  5637. {
  5638. SCMStringBuffer name;
  5639. IConstWUResult &cur = variables.item(idx);
  5640. cur.getResultName(name);
  5641. if (stricmp(name.str(), qname)==0)
  5642. {
  5643. cur.Link();
  5644. return &cur;
  5645. }
  5646. }
  5647. return NULL;
  5648. }
  5649. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  5650. {
  5651. CriticalBlock block(crit);
  5652. loadTemporaries();
  5653. ForEachItemIn(idx, temporaries)
  5654. {
  5655. SCMStringBuffer name;
  5656. IConstWUResult &cur = temporaries.item(idx);
  5657. cur.getResultName(name);
  5658. if (stricmp(name.str(), qname)==0)
  5659. {
  5660. cur.Link();
  5661. return &cur;
  5662. }
  5663. }
  5664. return NULL;
  5665. }
  5666. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  5667. {
  5668. CriticalBlock block(crit);
  5669. loadTemporaries();
  5670. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  5671. }
  5672. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  5673. {
  5674. CriticalBlock block(crit);
  5675. IConstWUResult *existing = getTemporaryByName(qname);
  5676. if (existing)
  5677. return (IWUResult *) existing;
  5678. if (!temporaries.length())
  5679. p->addPropTree("Temporaries", createPTree("Temporaries"));
  5680. IPropertyTree *vars = p->queryPropTree("Temporaries");
  5681. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  5682. s->Link();
  5683. IWUResult* q = new CLocalWUResult(s);
  5684. q->Link();
  5685. temporaries.append(*q);
  5686. q->setResultName(qname);
  5687. q->setResultSequence(ResultSequenceInternal);
  5688. return q;
  5689. }
  5690. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  5691. {
  5692. CriticalBlock block(crit);
  5693. IConstWUResult *existing = getVariableByName(qname);
  5694. if (existing)
  5695. return (IWUResult *) existing;
  5696. if (!variables.length())
  5697. p->addPropTree("Variables", createPTree("Variables"));
  5698. IPropertyTree *vars = p->queryPropTree("Variables");
  5699. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  5700. s->Link();
  5701. IWUResult* q = new CLocalWUResult(s);
  5702. q->Link();
  5703. variables.append(*q);
  5704. q->setResultName(qname);
  5705. q->setResultSequence(ResultSequenceStored);
  5706. return q;
  5707. }
  5708. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  5709. {
  5710. CriticalBlock block(crit);
  5711. IPropertyTree *files = p->queryPropTree("Files");
  5712. if (!files) return;
  5713. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  5714. ICopyArrayOf<IPropertyTree> toRemove;
  5715. ForEach (*iter)
  5716. {
  5717. IPropertyTree &file = iter->query();
  5718. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  5719. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  5720. bool needDelete;
  5721. switch(fileKind)
  5722. {
  5723. case WUFileTemporary:
  5724. if(graph==NULL)
  5725. needDelete = true;
  5726. else
  5727. {
  5728. const char *graphOwner = file.queryProp("@graph");
  5729. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  5730. }
  5731. break;
  5732. case WUFileJobOwned:
  5733. needDelete = ((graph==NULL) && deleteJobOwned);
  5734. break;
  5735. case WUFileOwned:
  5736. needDelete = ((graph==NULL) && deleteOwned);
  5737. break;
  5738. default:
  5739. needDelete = false;
  5740. }
  5741. if(needDelete)
  5742. {
  5743. const char *name = file.queryProp("@name");
  5744. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  5745. queryDistributedFileDirectory().removeEntry(name, queryUserDescriptor());
  5746. toRemove.append(file);
  5747. }
  5748. }
  5749. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  5750. }
  5751. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  5752. {
  5753. IDistributedSuperFile *super = file->querySuperFile();
  5754. StringBuffer fname;
  5755. file->getLogicalName(fname);
  5756. if (fname.length())
  5757. {
  5758. StringBuffer path("File[@name=\"");
  5759. path.append(fname).append("\"]");
  5760. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  5761. if (fileTree)
  5762. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  5763. else
  5764. {
  5765. StringBuffer cluster;
  5766. file->getClusterName(0,cluster);
  5767. fileTree = createPTree();
  5768. fileTree->setProp("@name", fname.str());
  5769. fileTree->setProp("@cluster", cluster.str());
  5770. fileTree->setPropInt("@useCount", 1);
  5771. fileTree = filesRead->addPropTree("File", fileTree);
  5772. }
  5773. if (super)
  5774. {
  5775. fileTree->setPropBool("@super", true);
  5776. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  5777. ForEach (*iter)
  5778. {
  5779. IDistributedFile &file = iter->query();
  5780. StringBuffer fname;
  5781. file.getLogicalName(fname);
  5782. Owned<IPropertyTree> subfile = createPTree();
  5783. subfile->setProp("@name", fname.str());
  5784. fileTree->addPropTree("Subfile", subfile.getClear());
  5785. _noteFileRead(&file, filesRead);
  5786. }
  5787. }
  5788. }
  5789. }
  5790. void CLocalWorkUnit::_loadFilesRead() const
  5791. {
  5792. // Nothing to do
  5793. }
  5794. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  5795. {
  5796. if (file)
  5797. {
  5798. CriticalBlock block(crit);
  5799. IPropertyTree *files = p->queryPropTree("FilesRead");
  5800. if (!files)
  5801. files = p->addPropTree("FilesRead", createPTree());
  5802. _noteFileRead(file, files);
  5803. }
  5804. }
  5805. void CLocalWorkUnit::noteFieldUsage(IPropertyTree * fieldUsage)
  5806. {
  5807. if (fieldUsage)
  5808. {
  5809. CriticalBlock block(crit);
  5810. p->addPropTree("usedsources", fieldUsage);
  5811. }
  5812. }
  5813. void CLocalWorkUnit::_loadFilesWritten() const
  5814. {
  5815. // Nothing to do
  5816. }
  5817. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  5818. {
  5819. StringBuffer path("File[@name=\"");
  5820. path.append(fileName).append("\"]");
  5821. if (cluster)
  5822. path.append("[@cluster=\"").append(cluster).append("\"]");
  5823. IPropertyTree *file = files->queryPropTree(path.str());
  5824. if (file) files->removeTree(file);
  5825. file = createPTree();
  5826. file->setProp("@name", fileName);
  5827. if (cluster)
  5828. file->setProp("@cluster", cluster);
  5829. if (graphOwner)
  5830. file->setProp("@graph", graphOwner);
  5831. file->setPropInt("@kind", (unsigned)fileKind);
  5832. if (WUFileTemporary == fileKind)
  5833. file->setPropInt("@usageCount", usageCount);
  5834. files->addPropTree("File", file);
  5835. }
  5836. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  5837. {
  5838. CriticalBlock block(crit);
  5839. IPropertyTree *files = p->queryPropTree("Files");
  5840. if (!files)
  5841. files = p->addPropTree("Files", createPTree());
  5842. if (!clusters)
  5843. ::addFile(files, fileName, NULL, usageCount, fileKind, graphOwner);
  5844. else
  5845. {
  5846. ForEachItemIn(c, *clusters)
  5847. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  5848. }
  5849. }
  5850. void CLocalWorkUnit::releaseFile(const char *fileName)
  5851. {
  5852. StringBuffer path("File[@name=\"");
  5853. path.append(fileName).append("\"]");
  5854. CriticalBlock block(crit);
  5855. IPropertyTree *files = p->queryPropTree("Files");
  5856. if (!files) return;
  5857. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  5858. ForEach (*fiter)
  5859. {
  5860. IPropertyTree *file = &fiter->query();
  5861. unsigned usageCount = file->getPropInt("@usageCount");
  5862. if (usageCount > 1)
  5863. file->setPropInt("@usageCount", usageCount-1);
  5864. else
  5865. {
  5866. StringAttr name(file->queryProp("@name"));
  5867. files->removeTree(file);
  5868. if (!name.isEmpty()&&(1 == usageCount))
  5869. {
  5870. if (queryDistributedFileDirectory().removeEntry(fileName, queryUserDescriptor()))
  5871. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  5872. }
  5873. }
  5874. }
  5875. }
  5876. void CLocalWorkUnit::clearGraphProgress() const
  5877. {
  5878. }
  5879. void CLocalWorkUnit::resetBeforeGeneration()
  5880. {
  5881. CriticalBlock block(crit);
  5882. //Remove all associated files
  5883. Owned<IWUQuery> q = updateQuery();
  5884. q->removeAssociatedFiles();
  5885. //Remove any pre-existing workflow information
  5886. workflowIterator.clear();
  5887. p->removeProp("Workflow");
  5888. }
  5889. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  5890. {
  5891. StringBuffer path("Files/File[@name=\"");
  5892. path.append(fileName).append("\"]/@usageCount");
  5893. CriticalBlock block(crit);
  5894. return p->getPropInt(path.str());
  5895. }
  5896. IConstWUFileUsageIterator * CLocalWorkUnit::getFieldUsage() const
  5897. {
  5898. CriticalBlock block(crit);
  5899. IPropertyTree* fieldUsageTree = p->queryPropTree("usedsources");
  5900. if (!fieldUsageTree)
  5901. return NULL;
  5902. IPropertyTreeIterator* iter = fieldUsageTree->getElements("*");
  5903. return new CConstWUFileUsageIterator(iter);
  5904. }
  5905. bool isFilenameResolved(StringBuffer& filename)
  5906. {
  5907. size32_t length = filename.length();
  5908. // With current implementation, if filename is surrounded by single quotes, it means that the filename was resolved at compile time.
  5909. if (filename.length() >= 2 && filename.charAt(0) == '\'' && filename.charAt(length-1) == '\'')
  5910. return true;
  5911. else
  5912. return false;
  5913. }
  5914. bool CLocalWorkUnit::getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const
  5915. {
  5916. bool scopeLoaded = false;
  5917. SCMStringBuffer defaultScope;
  5918. Owned<IConstWUFileUsageIterator> files = getFieldUsage();
  5919. if (!files)
  5920. return false; // this query was not compiled with recordFieldUsage option.
  5921. ForEach(*files)
  5922. {
  5923. Owned<IConstWUFileUsage> file = files->get();
  5924. StringBuffer filename = file->queryName();
  5925. size32_t length = filename.length();
  5926. if (length == 0)
  5927. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  5928. StringBuffer normalizedFilename;
  5929. // Two cases to handle:
  5930. // 1. Filename was known at compile time, and is surrounded in single quotes (i.e. 'filename').
  5931. // 2. Filename could not be resolved at compile time (i.e. filename is an input to a query),
  5932. // and is a raw expression WITHOUT surrounding single quotes (i.e. STORED('input_filename')).
  5933. if (isFilenameResolved(filename))
  5934. {
  5935. // filename cannot be empty (i.e. empty single quotes '')
  5936. if (length == 2)
  5937. throw MakeStringException(WUERR_InvalidFieldUsage, "Invalid FieldUsage found in WU. Cannot enforce view security.");
  5938. // Remove surrounding single quotes
  5939. StringAttr cleanFilename(filename.str()+1, length-2);
  5940. // When a filename doesn't start with a tilde (~), it means scope is omitted and is relying on a default scope.
  5941. // We need to load a default scope from config and prefix the filename with it.
  5942. if (cleanFilename.str()[0] != '~')
  5943. {
  5944. // loading a default scope from config is expensive, and should be only done once and be reused later.
  5945. if (!scopeLoaded)
  5946. {
  5947. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName);
  5948. if (!clusterInfo)
  5949. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName);
  5950. clusterInfo->getScope(defaultScope);
  5951. scopeLoaded = true;
  5952. }
  5953. normalizedFilename.append(defaultScope.str());
  5954. normalizedFilename.append(cleanFilename.str());
  5955. }
  5956. else
  5957. {
  5958. normalizedFilename.append(cleanFilename);
  5959. }
  5960. }
  5961. else
  5962. {
  5963. // When filename is an unresolved expression, simply treat the expression as a "non-existent" filename.
  5964. // It will have an effect of this query accessing a non-existent filename, and will be denied access unconditionally.
  5965. normalizedFilename.append(filename.str());
  5966. }
  5967. Owned<IConstWUFieldUsageIterator> fields = file->getFields();
  5968. ForEach(*fields)
  5969. {
  5970. Owned<IConstWUFieldUsage> field = fields->get();
  5971. filenames.append(normalizedFilename.str());
  5972. columnnames.append(field->queryName());
  5973. }
  5974. }
  5975. return true;
  5976. }
  5977. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  5978. {
  5979. return p->getPropTree("DiskUsageStats");
  5980. }
  5981. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  5982. {
  5983. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  5984. offset_t maxNodeUsage;
  5985. if (stats)
  5986. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  5987. else
  5988. {
  5989. stats = p->addPropTree("DiskUsageStats", createPTree());
  5990. maxNodeUsage = 0;
  5991. }
  5992. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  5993. {
  5994. // record all details at time of max node usage.
  5995. stats->setPropInt("@minNode", _minNode);
  5996. stats->setPropInt("@maxNode", _maxNode);
  5997. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  5998. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  5999. stats->setPropInt64("@graphId", _graphId);
  6000. if (_avgNodeUsage)
  6001. {
  6002. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  6003. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  6004. stats->setPropInt("@skewHi", _skewHi);
  6005. stats->setPropInt("@skewLo", _skewLo);
  6006. }
  6007. }
  6008. }
  6009. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  6010. {
  6011. CriticalBlock block(crit);
  6012. _loadFilesWritten();
  6013. return * p->getElements("Files/File");
  6014. }
  6015. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  6016. {
  6017. CriticalBlock block(crit);
  6018. _loadFilesRead();
  6019. return * p->getElements("FilesRead/File");
  6020. }
  6021. //=================================================================================================
  6022. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  6023. {
  6024. CriticalBlock block(crit);
  6025. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  6026. return false;
  6027. Owned<IConstWUClusterInfo> newci = getTargetClusterInfo(cluster);
  6028. if (!newci)
  6029. return false;
  6030. StringBuffer currentcluster;
  6031. if (!p->getProp("@clusterName",currentcluster))
  6032. return false;
  6033. Owned<IConstWUClusterInfo> curci = getTargetClusterInfo(currentcluster.str());
  6034. if (!curci)
  6035. return false;
  6036. SCMStringBuffer curqname;
  6037. curci->getThorQueue(curqname);
  6038. const char *wuid = p->queryName();
  6039. void *qi = qs->getQ(curqname.str(),wuid);
  6040. if (!qi)
  6041. return false;
  6042. setClusterName(cluster);
  6043. SCMStringBuffer newqname;
  6044. newci->getThorQueue(newqname);
  6045. qs->putQ(newqname.str(),wuid,qi);
  6046. return true;
  6047. }
  6048. //=================================================================================================
  6049. IPropertyTree *CLocalWorkUnit::getUnpackedTree(bool includeProgress) const
  6050. {
  6051. Owned<IPropertyTree> ret = createPTreeFromIPT(p);
  6052. Owned<IConstWUGraphIterator> graphIter = &getGraphs(GraphTypeAny);
  6053. ForEach(*graphIter)
  6054. {
  6055. IConstWUGraph &graph = graphIter->query();
  6056. Owned<IPropertyTree> graphTree = graph.getXGMMLTree(includeProgress);
  6057. SCMStringBuffer gName;
  6058. graph.getName(gName);
  6059. StringBuffer xpath("Graphs/Graph[@name=\"");
  6060. xpath.append(gName.s).append("\"]/xgmml");
  6061. IPropertyTree *xgmml = ret->queryPropTree(xpath.str());
  6062. if (xgmml) // don't know of any reason it shouldn't exist
  6063. {
  6064. xgmml->removeProp("graphBin");
  6065. xgmml->setPropTree("graph", graphTree.getClear());
  6066. }
  6067. }
  6068. return ret.getClear();
  6069. }
  6070. void CLocalWorkUnit::_loadGraphs(bool heavy) const
  6071. {
  6072. Owned<IPropertyTreeIterator> iter = p->getElements("Graphs/Graph");
  6073. ForEach(*iter)
  6074. {
  6075. IPropertyTree &graph = iter->query();
  6076. graphs.append(*new CLocalWUGraph(*this, LINK(&graph)));
  6077. }
  6078. }
  6079. void CLocalWorkUnit::loadGraphs(bool heavy) const
  6080. {
  6081. if (graphsCached < (heavy ? 2 : 1))
  6082. {
  6083. graphs.kill();
  6084. _loadGraphs(heavy);
  6085. graphsCached = (heavy ? 2 : 1);
  6086. }
  6087. }
  6088. mapEnums graphTypes[] = {
  6089. { GraphTypeAny, "unknown" },
  6090. { GraphTypeProgress, "progress" },
  6091. { GraphTypeEcl, "ECL" },
  6092. { GraphTypeActivities, "activities" },
  6093. { GraphTypeSubProgress, "subgraph" },
  6094. { GraphTypeSize, NULL },
  6095. };
  6096. WUGraphType getGraphTypeFromString(const char* type)
  6097. {
  6098. return (WUGraphType) getEnum(type, graphTypes);
  6099. }
  6100. CLocalWUGraph::CLocalWUGraph(const CLocalWorkUnit &_owner, IPropertyTree *props) : p(props), owner(_owner)
  6101. {
  6102. wuidVersion = owner.getWuidVersion();
  6103. }
  6104. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  6105. {
  6106. str.set(p->queryProp("@name"));
  6107. return str;
  6108. }
  6109. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  6110. {
  6111. if (wuidVersion >= 2)
  6112. {
  6113. str.set(p->queryProp("@label"));
  6114. return str;
  6115. }
  6116. else
  6117. {
  6118. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  6119. str.set(xgmml->queryProp("@label"));
  6120. return str;
  6121. }
  6122. }
  6123. WUGraphState CLocalWUGraph::getState() const
  6124. {
  6125. return owner.queryGraphState(p->queryProp("@name"));
  6126. }
  6127. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  6128. {
  6129. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  6130. if (xgmml)
  6131. {
  6132. StringBuffer x;
  6133. toXML(xgmml, x);
  6134. str.set(x.str());
  6135. }
  6136. return str;
  6137. }
  6138. unsigned CLocalWorkUnit::getGraphCount() const
  6139. {
  6140. CriticalBlock block(crit);
  6141. if (p->hasProp("Graphs"))
  6142. {
  6143. return p->queryPropTree("Graphs")->numChildren();
  6144. }
  6145. return 0;
  6146. }
  6147. unsigned CLocalWorkUnit::getSourceFileCount() const
  6148. {
  6149. CriticalBlock block(crit);
  6150. _loadFilesRead();
  6151. if (p->hasProp("FilesRead"))
  6152. {
  6153. return p->queryPropTree("FilesRead")->numChildren();
  6154. }
  6155. return 0;
  6156. }
  6157. unsigned CLocalWorkUnit::getResultCount() const
  6158. {
  6159. CriticalBlock block(crit);
  6160. if (p->hasProp("Results"))
  6161. {
  6162. return p->queryPropTree("Results")->numChildren();
  6163. }
  6164. return 0;
  6165. }
  6166. unsigned CLocalWorkUnit::getVariableCount() const
  6167. {
  6168. CriticalBlock block(crit);
  6169. if (p->hasProp("Variables"))
  6170. {
  6171. return p->queryPropTree("Variables")->numChildren();
  6172. }
  6173. return 0;
  6174. }
  6175. unsigned CLocalWorkUnit::getApplicationValueCount() const
  6176. {
  6177. CriticalBlock block(crit);
  6178. if (p->hasProp("Application"))
  6179. {
  6180. return p->queryPropTree("Application")->numChildren();
  6181. }
  6182. return 0;
  6183. }
  6184. StringBuffer &appendPTreeOpenTag(StringBuffer &s, IPropertyTree *tree, const char *name, unsigned indent)
  6185. {
  6186. appendXMLOpenTag(s, name, NULL, false);
  6187. Owned<IAttributeIterator> attrs = tree->getAttributes(true);
  6188. if (attrs->first())
  6189. {
  6190. unsigned attributeindent = indent + (size32_t) strlen(name);
  6191. unsigned count = attrs->count();
  6192. bool doindent = false;
  6193. ForEach(*attrs)
  6194. {
  6195. if (doindent)
  6196. s.append('\n').appendN(attributeindent, ' ');
  6197. else if (count > 3)
  6198. doindent = true;
  6199. appendXMLAttr(s, attrs->queryName()+1, attrs->queryValue());
  6200. }
  6201. }
  6202. s.append('>');
  6203. return s;
  6204. }
  6205. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str, bool hidePasswords) const
  6206. {
  6207. CriticalBlock block(crit);
  6208. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  6209. if (!paramTree)
  6210. return str;
  6211. StringBuffer xml;
  6212. if (!hidePasswords)
  6213. toXML(paramTree, xml);
  6214. else
  6215. {
  6216. appendPTreeOpenTag(xml.append(' '), paramTree, "Parameters", 0).append('\n');
  6217. Owned<IPropertyTreeIterator> elems = paramTree->getElements("*");
  6218. ForEach(*elems)
  6219. {
  6220. const char *paramname = elems->query().queryName();
  6221. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  6222. if (p->getPropBool(xpath))
  6223. appendXMLTag(xml.append(" "), paramname, "***").append('\n');
  6224. else
  6225. toXML(&elems->query(), xml, 2);
  6226. }
  6227. appendXMLCloseTag(xml.append(' '), "Parameters").append('\n');
  6228. }
  6229. str.set(xml);
  6230. return str;
  6231. }
  6232. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  6233. {
  6234. CriticalBlock block(crit);
  6235. return p->getPropTree("Parameters");
  6236. }
  6237. void CLocalWorkUnit::setXmlParams(const char *params)
  6238. {
  6239. CriticalBlock block(crit);
  6240. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  6241. }
  6242. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  6243. {
  6244. CriticalBlock block(crit);
  6245. p->setPropTree("Parameters", tree);
  6246. }
  6247. unsigned __int64 CLocalWorkUnit::getHash() const
  6248. {
  6249. CriticalBlock block(crit);
  6250. return p->getPropInt64("@hash");
  6251. }
  6252. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  6253. {
  6254. CriticalBlock block(crit);
  6255. p->setPropInt64("@hash", hash);
  6256. }
  6257. // getGraphs / getGraphsMeta
  6258. // These are basically the same except for the amount of preloading they do, and the type of the iterator they return...
  6259. // If a type other than any is requested, a postfilter is needed.
  6260. template <class T, class U> class CFilteredGraphIteratorOf : public CInterfaceOf<T>
  6261. {
  6262. WUGraphType type;
  6263. Owned<T> base;
  6264. bool match()
  6265. {
  6266. return base->query().getType()==type;
  6267. }
  6268. public:
  6269. CFilteredGraphIteratorOf<T,U>(T *_base, WUGraphType _type)
  6270. : base(_base), type(_type)
  6271. {
  6272. }
  6273. bool first()
  6274. {
  6275. if (!base->first())
  6276. return false;
  6277. if (match())
  6278. return true;
  6279. return next();
  6280. }
  6281. bool next()
  6282. {
  6283. while (base->next())
  6284. if (match())
  6285. return true;
  6286. return false;
  6287. }
  6288. virtual bool isValid()
  6289. {
  6290. return base->isValid();
  6291. }
  6292. U & query()
  6293. {
  6294. return base->query();
  6295. }
  6296. };
  6297. IConstWUGraphMetaIterator& CLocalWorkUnit::getGraphsMeta(WUGraphType type) const
  6298. {
  6299. /* NB: this method should be 'cheap', loadGraphs() creates IConstWUGraph interfaces to the graphs
  6300. * it does not actually pull the graph data. We only use IConstWUGraphMeta here, which never probes the xgmml.
  6301. */
  6302. CriticalBlock block(crit);
  6303. loadGraphs(false);
  6304. IConstWUGraphMetaIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphMetaIterator> (graphs, 0, (IConstWorkUnit *) this);
  6305. if (type!=GraphTypeAny)
  6306. giter = new CFilteredGraphIteratorOf<IConstWUGraphMetaIterator, IConstWUGraphMeta>(giter,type);
  6307. return *giter;
  6308. }
  6309. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  6310. {
  6311. CriticalBlock block(crit);
  6312. loadGraphs(true);
  6313. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  6314. if (type!=GraphTypeAny)
  6315. giter = new CFilteredGraphIteratorOf<IConstWUGraphIterator, IConstWUGraph>(giter, type);
  6316. return *giter;
  6317. }
  6318. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  6319. {
  6320. CriticalBlock block(crit);
  6321. VStringBuffer xpath("Graphs/Graph[@name='%s']", qname);
  6322. // NOTE - this would go wrong if we had other graphs of same name but different type. Ignore for now.
  6323. IPTree *graph = p->queryPropTree(xpath);
  6324. if (graph)
  6325. return new CLocalWUGraph(*this, LINK(graph));
  6326. return NULL;
  6327. }
  6328. void CLocalWorkUnit::createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml)
  6329. {
  6330. CriticalBlock block(crit);
  6331. if (!graphs.length())
  6332. p->addPropTree("Graphs", createPTree("Graphs"));
  6333. IPropertyTree *r = p->queryPropTree("Graphs");
  6334. IPropertyTree *s = r->addPropTree("Graph", createPTree());
  6335. CLocalWUGraph *q = new CLocalWUGraph(*this, LINK(s));
  6336. q->setName(name);
  6337. q->setLabel(label);
  6338. q->setType(type);
  6339. q->setXGMMLTree(xgmml);
  6340. graphs.append(*q);
  6341. }
  6342. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  6343. {
  6344. /* Owned<IRemoteConnection> conn = getProgressConnection();
  6345. if (conn)
  6346. {
  6347. IPTree *progress = conn->queryRoot()->queryPropTree(graphName);
  6348. if (progress)
  6349. return new CConstGraphProgress(p->queryName(), graphName, progress);
  6350. }
  6351. */
  6352. return NULL;
  6353. }
  6354. WUGraphState CLocalWorkUnit::queryGraphState(const char *graphName) const
  6355. {
  6356. throwUnexpected(); // Should only be used for persisted workunits
  6357. }
  6358. WUGraphState CLocalWorkUnit::queryNodeState(const char *graphName, WUGraphIDType nodeId) const
  6359. {
  6360. throwUnexpected(); // Should only be used for persisted workunits
  6361. }
  6362. void CLocalWorkUnit::setGraphState(const char *graphName, WUGraphState state) const
  6363. {
  6364. throwUnexpected(); // Should only be used for persisted workunits
  6365. }
  6366. void CLocalWorkUnit::setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const
  6367. {
  6368. throwUnexpected(); // Should only be used for persisted workunits
  6369. }
  6370. IWUGraphStats *CLocalWorkUnit::updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned subgraph) const
  6371. {
  6372. return new CWuGraphStats(LINK(p), creatorType, creator, graphName, subgraph);
  6373. }
  6374. void CLocalWUGraph::setName(const char *str)
  6375. {
  6376. p->setProp("@name", str);
  6377. }
  6378. void CLocalWUGraph::setLabel(const char *str)
  6379. {
  6380. p->setProp("@label", str);
  6381. }
  6382. void CLocalWUGraph::setXGMML(const char *str)
  6383. {
  6384. setXGMMLTree(createPTreeFromXMLString(str));
  6385. }
  6386. void CLocalWUGraph::setXGMMLTree(IPropertyTree *_graph)
  6387. {
  6388. assertex(strcmp(_graph->queryName(), "graph")==0);
  6389. IPropertyTree *xgmml = p->setPropTree("xgmml", createPTree());
  6390. MemoryBuffer mb;
  6391. _graph->serialize(mb);
  6392. // Note - we could compress further but that would introduce compatibility concerns, so don't bother
  6393. // Cassandra workunit code actually lzw compresses the parent anyway
  6394. xgmml->setPropBin("graphBin", mb.length(), mb.toByteArray());
  6395. graph.setown(_graph);
  6396. }
  6397. static void expandAttributes(IPropertyTree & targetNode, IPropertyTree & progressNode)
  6398. {
  6399. Owned<IAttributeIterator> aIter = progressNode.getAttributes();
  6400. ForEach (*aIter)
  6401. {
  6402. const char *aName = aIter->queryName()+1;
  6403. if (0 != stricmp("id", aName)) // "id" reserved.
  6404. {
  6405. IPropertyTree *att = targetNode.addPropTree("att", createPTree());
  6406. att->setProp("@name", aName);
  6407. att->setProp("@value", aIter->queryValue());
  6408. }
  6409. }
  6410. }
  6411. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  6412. {
  6413. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  6414. if (!graphNode) return;
  6415. unsigned nodeId = rootNode.getPropInt("@id");
  6416. StringBuffer progressNodePath("node[@id=\"");
  6417. progressNodePath.append(nodeId).append("\"]");
  6418. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  6419. if (progressNode)
  6420. {
  6421. expandAttributes(*graphNode, *progressNode);
  6422. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  6423. ForEach (*edges)
  6424. {
  6425. IPropertyTree &edge = edges->query();
  6426. StringBuffer edgePath("edge[@id=\"");
  6427. edgePath.append(edge.queryProp("@id")).append("\"]");
  6428. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  6429. if (graphEdge)
  6430. {
  6431. if (progressV < 1)
  6432. mergePTree(graphEdge, &edge);
  6433. else
  6434. { // must translate to XGMML format
  6435. expandAttributes(*graphEdge, edge);
  6436. // 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)
  6437. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  6438. ForEach (*iter)
  6439. {
  6440. IPropertyTree &t = iter->query();
  6441. IPropertyTree *att = graphEdge->addPropTree("att", createPTree());
  6442. att->setProp("@name", t.queryName());
  6443. att->setProp("@value", t.queryProp(NULL));
  6444. }
  6445. }
  6446. }
  6447. }
  6448. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  6449. ForEach (*nodes)
  6450. {
  6451. IPropertyTree &node = nodes->query();
  6452. StringBuffer nodePath("node[@id=\"");
  6453. nodePath.append(node.queryProp("@id")).append("\"]");
  6454. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  6455. if (_node)
  6456. {
  6457. if (progressV < 1)
  6458. mergePTree(_node, &node);
  6459. else
  6460. { // must translate to XGMML format
  6461. expandAttributes(*_node, node);
  6462. }
  6463. }
  6464. }
  6465. }
  6466. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  6467. ForEach (*iter)
  6468. mergeProgress(iter->query(), progressTree, progressV);
  6469. }
  6470. IPropertyTree * CLocalWUGraph::getXGMMLTreeRaw() const
  6471. {
  6472. return p->getPropTree("xgmml");
  6473. }
  6474. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  6475. {
  6476. if (!graph)
  6477. {
  6478. // NB: although graphBin introduced in wuidVersion==2,
  6479. // daliadmin can retrospectively compress existing graphs, so need to check for all versions
  6480. MemoryBuffer mb;
  6481. if (p->getPropBin("xgmml/graphBin", mb))
  6482. graph.setown(createPTree(mb));
  6483. else
  6484. graph.setown(p->getBranch("xgmml/graph"));
  6485. if (!graph)
  6486. return NULL;
  6487. }
  6488. if (!doMergeProgress)
  6489. return graph.getLink();
  6490. else
  6491. {
  6492. Owned<IPropertyTree> copy = createPTreeFromIPT(graph);
  6493. Owned<IConstWUGraphProgress> progress = owner.getGraphProgress(p->queryProp("@name"));
  6494. if (progress)
  6495. {
  6496. //MORE: Eventually this should directly access the new stats structure
  6497. unsigned progressV = progress->queryFormatVersion();
  6498. Owned<IPropertyTree> progressTree = progress->getProgressTree();
  6499. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  6500. ForEach (*nodeIterator)
  6501. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  6502. }
  6503. return copy.getClear();
  6504. }
  6505. }
  6506. WUGraphType CLocalWUGraph::getType() const
  6507. {
  6508. return (WUGraphType) getEnum(p, "@type", graphTypes);
  6509. }
  6510. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  6511. {
  6512. str.set(p->queryProp("@type"));
  6513. if (!str.length())
  6514. str.set("unknown");
  6515. return str;
  6516. }
  6517. void CLocalWUGraph::setType(WUGraphType _type)
  6518. {
  6519. setEnum(p, "@type", _type, graphTypes);
  6520. }
  6521. //=================================================================================================
  6522. mapEnums queryFileTypes[] = {
  6523. { FileTypeCpp, "cpp" },
  6524. { FileTypeDll, "dll" },
  6525. { FileTypeResText, "res" },
  6526. { FileTypeHintXml, "hint" },
  6527. { FileTypeXml, "xml" },
  6528. { FileTypeSize, NULL },
  6529. };
  6530. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  6531. {
  6532. }
  6533. WUFileType CLocalWUAssociated::getType() const
  6534. {
  6535. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  6536. }
  6537. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  6538. {
  6539. str.set(p->queryProp("@desc"));
  6540. return str;
  6541. }
  6542. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  6543. {
  6544. str.set(p->queryProp("@ip"));
  6545. return str;
  6546. }
  6547. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  6548. {
  6549. str.set(p->queryProp("@filename"));
  6550. return str;
  6551. }
  6552. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  6553. {
  6554. str.set(pathTail(p->queryProp("@filename")));
  6555. return str;
  6556. }
  6557. unsigned CLocalWUAssociated::getCrc() const
  6558. {
  6559. return p->getPropInt("@crc", 0);
  6560. }
  6561. unsigned CLocalWUAssociated::getMinActivityId() const
  6562. {
  6563. return p->getPropInt("@minActivity", 0);
  6564. }
  6565. unsigned CLocalWUAssociated::getMaxActivityId() const
  6566. {
  6567. return p->getPropInt("@maxActivity", 0);
  6568. }
  6569. //=================================================================================================
  6570. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  6571. {
  6572. associatedCached = false;
  6573. }
  6574. mapEnums queryTypes[] = {
  6575. { QueryTypeUnknown, "unknown" },
  6576. { QueryTypeEcl, "ECL" },
  6577. { QueryTypeSql, "SQL" },
  6578. { QueryTypeXml, "XML" },
  6579. { QueryTypeAttribute, "Attribute" },
  6580. { QueryTypeSize, NULL },
  6581. };
  6582. WUQueryType CLocalWUQuery::getQueryType() const
  6583. {
  6584. return (WUQueryType) getEnum(p, "@type", queryTypes);
  6585. }
  6586. void CLocalWUQuery::setQueryType(WUQueryType qt)
  6587. {
  6588. setEnum(p, "@type", qt, queryTypes);
  6589. }
  6590. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  6591. {
  6592. str.set(p->queryProp("Text"));
  6593. return str;
  6594. }
  6595. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  6596. {
  6597. const char * text = p->queryProp("ShortText");
  6598. if (text)
  6599. str.set(text);
  6600. else
  6601. {
  6602. text = p->queryProp("Text");
  6603. if (isArchiveQuery(text))
  6604. {
  6605. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive);
  6606. const char * path = xml->queryProp("Query/@attributePath");
  6607. if (path)
  6608. {
  6609. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  6610. if (resolved)
  6611. str.set(resolved->queryProp(NULL));
  6612. }
  6613. else
  6614. str.set(xml->queryProp("Query"));
  6615. }
  6616. else
  6617. str.set(text);
  6618. }
  6619. return str;
  6620. }
  6621. bool CLocalWUQuery::isArchive() const
  6622. {
  6623. if (p->hasProp("@isArchive"))
  6624. return p->getPropBool("@isArchive");
  6625. const char *text = p->queryProp("Text");
  6626. return isArchiveQuery(text);
  6627. }
  6628. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  6629. {
  6630. str.set(p->queryProp("@name"));
  6631. return str;
  6632. }
  6633. IStringVal & CLocalWUQuery::getQueryMainDefinition(IStringVal & str) const
  6634. {
  6635. str.set(p->queryProp("@main"));
  6636. return str;
  6637. }
  6638. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  6639. {
  6640. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  6641. if (entry)
  6642. entry->getNameTail(str);
  6643. return str;
  6644. }
  6645. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  6646. {
  6647. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  6648. if (entry)
  6649. entry->getName(str);
  6650. return str;
  6651. }
  6652. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  6653. {
  6654. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  6655. if (entry)
  6656. entry->getName(str);
  6657. return str;
  6658. }
  6659. unsigned CLocalWUQuery::getQueryDllCrc() const
  6660. {
  6661. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  6662. if (entry)
  6663. return entry->getCrc();
  6664. return 0;
  6665. }
  6666. void CLocalWUQuery::setQueryText(const char *text)
  6667. {
  6668. p->setProp("Text", text);
  6669. bool isArchive = isArchiveQuery(text);
  6670. if (isArchive)
  6671. {
  6672. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive);
  6673. const char * path = xml->queryProp("Query/@attributePath");
  6674. if (path)
  6675. {
  6676. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  6677. if (resolved)
  6678. p->setProp("ShortText", resolved->queryProp(NULL));
  6679. }
  6680. else
  6681. p->setProp("ShortText", xml->queryProp("Query"));
  6682. }
  6683. p->setPropBool("@isArchive", isArchive);
  6684. }
  6685. void CLocalWUQuery::setQueryName(const char *qname)
  6686. {
  6687. p->setProp("@name", qname);
  6688. }
  6689. void CLocalWUQuery::setQueryMainDefinition(const char * str)
  6690. {
  6691. p->setProp("@main", str);
  6692. }
  6693. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity)
  6694. {
  6695. CriticalBlock block(crit);
  6696. loadAssociated();
  6697. if (!associated.length())
  6698. p->addPropTree("Associated", createPTree("Associated"));
  6699. IPropertyTree *pl = p->queryPropTree("Associated");
  6700. IPropertyTree *s = pl->addPropTree("File", createPTree("File"));
  6701. setEnum(s, "@type", type, queryFileTypes);
  6702. s->setProp("@filename", name);
  6703. s->setProp("@ip", ip);
  6704. s->setProp("@desc", desc);
  6705. if (crc)
  6706. s->setPropInt("@crc", crc);
  6707. if (minActivity)
  6708. s->setPropInt("@minActivity", minActivity);
  6709. if (maxActivity)
  6710. s->setPropInt("@maxActivity", maxActivity);
  6711. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  6712. associated.append(*q);
  6713. }
  6714. void CLocalWUQuery::removeAssociatedFile(WUFileType type, const char * name, const char * desc)
  6715. {
  6716. CriticalBlock block(crit);
  6717. associatedCached = false;
  6718. associated.kill();
  6719. StringBuffer xpath;
  6720. xpath.append("Associated/File");
  6721. if (type)
  6722. xpath.append("[@type=\"").append(getEnumText(type, queryFileTypes)).append("\"]");
  6723. if (name)
  6724. xpath.append("[@filename=\"").append(name).append("\"]");
  6725. if (desc)
  6726. xpath.append("[@desc=\"").append(desc).append("\"]");
  6727. p->removeProp(xpath.str());
  6728. }
  6729. void CLocalWUQuery::removeAssociatedFiles()
  6730. {
  6731. associatedCached = false;
  6732. associated.kill();
  6733. p->removeProp("Associated");
  6734. }
  6735. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  6736. {
  6737. CriticalBlock block(crit);
  6738. loadAssociated();
  6739. ForEachItemIn(idx, associated)
  6740. {
  6741. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  6742. if (cur.getType() == type)
  6743. {
  6744. if (index-- == 0)
  6745. return &OLINK(cur);
  6746. }
  6747. }
  6748. return NULL;
  6749. }
  6750. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  6751. {
  6752. const char * name = p->queryProp(propname);
  6753. if (name)
  6754. {
  6755. IPropertyTree *s = createPTree("File");
  6756. setEnum(s, "@type", type, queryFileTypes);
  6757. s->setProp("@filename", name);
  6758. if (crc)
  6759. s->setPropInt("@crc", crc);
  6760. associated.append(*new CLocalWUAssociated(s));
  6761. }
  6762. }
  6763. void CLocalWUQuery::loadAssociated() const
  6764. {
  6765. CriticalBlock block(crit);
  6766. if (!associatedCached)
  6767. {
  6768. assertex(associated.length() == 0);
  6769. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  6770. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  6771. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  6772. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  6773. for (r->first(); r->isValid(); r->next())
  6774. {
  6775. IPropertyTree *rp = &r->query();
  6776. rp->Link();
  6777. associated.append(*new CLocalWUAssociated(rp));
  6778. }
  6779. associatedCached = true;
  6780. }
  6781. }
  6782. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  6783. {
  6784. CriticalBlock block(crit);
  6785. loadAssociated();
  6786. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  6787. }
  6788. //========================================================================================
  6789. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  6790. {
  6791. }
  6792. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  6793. {
  6794. str.set(p->queryProp("@module"));
  6795. return str;
  6796. }
  6797. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  6798. {
  6799. str.set(p->queryProp("@attribute"));
  6800. return str;
  6801. }
  6802. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  6803. {
  6804. str.set(p->queryProp("@defaultName"));
  6805. return str;
  6806. }
  6807. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  6808. {
  6809. return (unsigned) p->getPropInt("@crc");
  6810. }
  6811. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  6812. {
  6813. if (!name)
  6814. {
  6815. StringBuffer ws_info;
  6816. ws_info.appendf("<%s ", p->queryName());
  6817. Owned<IAttributeIterator> attrs = p->getAttributes();
  6818. for(attrs->first(); attrs->isValid(); attrs->next())
  6819. {
  6820. const char *name = attrs->queryName()+1;
  6821. const char *value = attrs->queryValue();
  6822. ws_info.appendf("%s='%s' ", name, value);
  6823. }
  6824. ws_info.append("> \n");
  6825. Owned<IPropertyTreeIterator> info = p->getElements("*");
  6826. ForEach(*info)
  6827. {
  6828. IPropertyTree &item = info->query();
  6829. const char *name = item.queryName();
  6830. if (name)
  6831. {
  6832. MemoryBuffer mb;
  6833. bool isbin = p->isBinary(name);
  6834. if (isbin)
  6835. {
  6836. p->getPropBin(name,mb);
  6837. if (mb.length())
  6838. {
  6839. unsigned len = 0;
  6840. mb.read(len);
  6841. StringBuffer encodedString;
  6842. StringBuffer val(len, (const char *) mb.readDirect(len));
  6843. encodeXML(val, encodedString);
  6844. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  6845. }
  6846. }
  6847. else
  6848. {
  6849. StringBuffer tmp;
  6850. toXML(&item, tmp);
  6851. ws_info.append(tmp.str());
  6852. }
  6853. }
  6854. }
  6855. ws_info.appendf("</%s>", p->queryName());
  6856. str.setLen(ws_info.str(), ws_info.length());
  6857. }
  6858. else
  6859. {
  6860. MemoryBuffer mb;
  6861. p->getPropBin(name,mb);
  6862. if (mb.length())
  6863. {
  6864. unsigned len;
  6865. mb.read(len);
  6866. str.setLen((const char *) mb.readDirect(len), len);
  6867. }
  6868. }
  6869. return str;
  6870. }
  6871. IStringVal& CLocalWUWebServicesInfo::getText(const char *name, IStringVal &str) const
  6872. {
  6873. str.set(p->queryProp(name));
  6874. return str;
  6875. }
  6876. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  6877. {
  6878. p->setProp("@module", mname);
  6879. }
  6880. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  6881. {
  6882. p->setProp("@attribute", aname);
  6883. }
  6884. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  6885. {
  6886. p->setProp("@defaultName", dname);
  6887. }
  6888. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  6889. {
  6890. p->setPropInt("@crc", crc);
  6891. }
  6892. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  6893. {
  6894. MemoryBuffer m;
  6895. unsigned len = (size32_t)strlen(info);
  6896. serializeLPString(len, info, m);
  6897. p->setPropBin(name, m.length(), m.toByteArray());
  6898. }
  6899. void CLocalWUWebServicesInfo::setText(const char *name, const char *info)
  6900. {
  6901. p->setProp(name, info);
  6902. }
  6903. //========================================================================================
  6904. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  6905. {
  6906. }
  6907. mapEnums resultStatuses[] = {
  6908. { ResultStatusUndefined, "undefined" },
  6909. { ResultStatusCalculated, "calculated" },
  6910. { ResultStatusSupplied, "supplied" },
  6911. { ResultStatusFailed, "failed" },
  6912. { ResultStatusPartial, "partial" },
  6913. { ResultStatusSize, NULL }
  6914. };
  6915. WUResultStatus CLocalWUResult::getResultStatus() const
  6916. {
  6917. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  6918. }
  6919. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  6920. {
  6921. str.set(p->queryProp("@name"));
  6922. return str;
  6923. }
  6924. int CLocalWUResult::getResultSequence() const
  6925. {
  6926. return p->getPropInt("@sequence", -1);
  6927. }
  6928. bool CLocalWUResult::isResultScalar() const
  6929. {
  6930. return p->getPropInt("@isScalar", 1) != 0;
  6931. }
  6932. bool findSize(int size, IntArray &sizes)
  6933. {
  6934. ForEachItemIn(idx, sizes)
  6935. {
  6936. if (sizes.item(idx)==size)
  6937. return true;
  6938. }
  6939. return false;
  6940. }
  6941. void CLocalWUResult::getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const
  6942. {
  6943. MemoryBuffer schema;
  6944. p->getPropBin("SchemaRaw", schema);
  6945. if (schema.length())
  6946. {
  6947. for (;;)
  6948. {
  6949. StringAttr name;
  6950. schema.read(name);
  6951. if (*schema.readDirect(0)==type_void)
  6952. break;
  6953. names.append(*new StringAttrItem(name));
  6954. types.append(*deserializeType(schema)); // MORE - nested records!
  6955. }
  6956. schema.skip(1);
  6957. if (schema.length() != schema.getPos())
  6958. {
  6959. unsigned eclLen;
  6960. schema.read(eclLen);
  6961. const char * schemaData = (const char *)schema.readDirect(eclLen);
  6962. if (eclText)
  6963. {
  6964. eclText->setLen(schemaData, eclLen);
  6965. if ((eclLen == 0) && names.ordinality())
  6966. {
  6967. const char * firstName = names.item(0).text;
  6968. StringBuffer temp;
  6969. temp.append("RECORD ");
  6970. types.item(0).getECLType(temp);
  6971. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  6972. eclText->set(temp.str());
  6973. }
  6974. }
  6975. }
  6976. }
  6977. }
  6978. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  6979. {
  6980. ForEachItemIn(idx, types)
  6981. {
  6982. StringAttrItem &name = names.item(idx);
  6983. ITypeInfo &type = types.item(idx);
  6984. unsigned size = type.getSize();
  6985. switch(type.getTypeCode())
  6986. {
  6987. case type_data:
  6988. if (size==UNKNOWN_LENGTH)
  6989. {
  6990. if (in.remaining() < sizeof(int))
  6991. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  6992. in.read(size);
  6993. }
  6994. outputXmlData(size, in.readDirect(size), name.text, out);
  6995. break;
  6996. case type_string:
  6997. if (size==UNKNOWN_LENGTH)
  6998. {
  6999. if (in.remaining() < sizeof(int))
  7000. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  7001. in.read(size);
  7002. }
  7003. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  7004. break;
  7005. case type_varstring:
  7006. {
  7007. if (size == UNKNOWN_LENGTH)
  7008. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  7009. const char * text = (const char *) in.readDirect(size);
  7010. outputXmlString((size32_t)strlen(text), text, name.text, out);
  7011. break;
  7012. }
  7013. case type_unicode:
  7014. {
  7015. unsigned len = type.getStringLen();
  7016. if (size==UNKNOWN_LENGTH)
  7017. in.read(len);
  7018. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  7019. }
  7020. break;
  7021. case type_utf8:
  7022. {
  7023. unsigned len = type.getStringLen();
  7024. if (size==UNKNOWN_LENGTH)
  7025. {
  7026. in.read(len);
  7027. size = rtlUtf8Size(len, in.readDirect(0));
  7028. }
  7029. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  7030. }
  7031. break;
  7032. case type_qstring:
  7033. {
  7034. unsigned len = type.getStringLen();
  7035. if (size==UNKNOWN_LENGTH)
  7036. in.read(len);
  7037. unsigned outlen;
  7038. char *outstr;
  7039. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  7040. outputXmlString(outlen, outstr, name.text, out);
  7041. free(outstr);
  7042. break;
  7043. }
  7044. case type_int:
  7045. case type_swapint:
  7046. if (type.isSigned())
  7047. {
  7048. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  7049. unsigned __int64 cval8 = 0;
  7050. //MORE: I think this is wrong - swapped doesn't mean little/big/
  7051. if (type.isSwappedEndian())
  7052. {
  7053. unsigned idx = 0;
  7054. if (raw[idx] & 0x80)
  7055. cval8 = (__int64)-1;
  7056. while (size--)
  7057. cval8 = (cval8 << 8) | raw[idx++];
  7058. }
  7059. else
  7060. {
  7061. if (raw[size-1] & 0x80)
  7062. cval8 = (__int64)-1;
  7063. while (size--)
  7064. cval8 = (cval8 << 8) | raw[size];
  7065. }
  7066. outputXmlInt((__int64) cval8, name.text, out);
  7067. }
  7068. else
  7069. {
  7070. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  7071. unsigned __int64 cval8 = 0;
  7072. if (type.isSwappedEndian())
  7073. {
  7074. unsigned idx = 0;
  7075. while (size--)
  7076. cval8 = (cval8 << 8) | raw[idx++];
  7077. }
  7078. else
  7079. {
  7080. while (size--)
  7081. cval8 = (cval8 << 8) | raw[size];
  7082. }
  7083. outputXmlUInt(cval8, name.text, out);
  7084. }
  7085. break;
  7086. case type_boolean:
  7087. bool cvalb;
  7088. in.read(cvalb);
  7089. outputXmlBool(cvalb, name.text, out);
  7090. break;
  7091. case type_decimal:
  7092. if (type.isSigned())
  7093. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  7094. else
  7095. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  7096. break;
  7097. case type_real:
  7098. double cvald;
  7099. switch(size)
  7100. {
  7101. case 4:
  7102. float cvalf;
  7103. in.read(cvalf);
  7104. cvald = cvalf;
  7105. break;
  7106. case 8:
  7107. in.read(cvald);
  7108. break;
  7109. }
  7110. outputXmlReal(cvald, name.text, out);
  7111. break;
  7112. default:
  7113. assertex(!"unexpected type in raw record");
  7114. break;
  7115. }
  7116. }
  7117. }
  7118. IStringVal& CLocalWUResult::getResultXml(IStringVal &str, bool hidePassword) const
  7119. {
  7120. TypeInfoArray types;
  7121. StringAttrArray names;
  7122. getSchema(types, names);
  7123. StringBuffer xml;
  7124. const char * name = p->queryProp("@name");
  7125. if (name)
  7126. xml.appendf("<Dataset name=\'%s\'>\n", name);
  7127. else
  7128. xml.append("<Dataset>\n");
  7129. if (hidePassword && p->getPropBool("Format/@password"))
  7130. {
  7131. xml.append(" <Row>");
  7132. appendXMLTag(xml, name, "****");
  7133. xml.append("</Row>\n");
  7134. }
  7135. else if (p->hasProp("Value"))
  7136. {
  7137. MemoryBuffer raw;
  7138. p->getPropBin("Value", raw);
  7139. unsigned __int64 numrows = getResultRowCount();
  7140. while (numrows--)
  7141. {
  7142. xml.append(" <Row>");
  7143. readRow(xml, raw, types, names);
  7144. xml.append("</Row>\n");
  7145. }
  7146. }
  7147. else if (p->hasProp("xmlValue"))
  7148. {
  7149. xml.append(" <Row>");
  7150. appendXMLTag(xml, name, p->queryProp("xmlValue"));
  7151. xml.append("</Row>\n");
  7152. }
  7153. xml.append("</Dataset>\n");
  7154. str.set(xml.str());
  7155. return str;
  7156. }
  7157. IProperties *CLocalWUResult::queryResultXmlns()
  7158. {
  7159. CriticalBlock block(crit);
  7160. if (xmlns)
  7161. return xmlns;
  7162. xmlns.setown(createProperties());
  7163. Owned<IAttributeIterator> it = p->getAttributes();
  7164. unsigned prefixLen = strlen("@xmlns");
  7165. ForEach(*it)
  7166. {
  7167. const char *name = it->queryName();
  7168. if (!strncmp("@xmlns", name, prefixLen))
  7169. {
  7170. if (name[prefixLen]==':') //normal case
  7171. xmlns->setProp(name+prefixLen+1, it->queryValue());
  7172. else if (!name[prefixLen]) //special case, unprefixed namespace
  7173. xmlns->setProp("xmlns", it->queryValue());
  7174. }
  7175. }
  7176. return xmlns;
  7177. }
  7178. unsigned CLocalWUResult::getResultFetchSize() const
  7179. {
  7180. return p->getPropInt("fetchSize", 100);
  7181. }
  7182. __int64 CLocalWUResult::getResultTotalRowCount() const
  7183. {
  7184. return p->getPropInt64("totalRowCount", -1);
  7185. }
  7186. __int64 CLocalWUResult::getResultRowCount() const
  7187. {
  7188. return p->getPropInt64("rowCount", 0);
  7189. }
  7190. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  7191. {
  7192. ecl.set(p->queryProp("datasetEcl"));
  7193. defs.set(p->queryProp("datasetEclDefs"));
  7194. }
  7195. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  7196. {
  7197. val.set(p->queryProp("logicalName"));
  7198. return val;
  7199. }
  7200. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  7201. {
  7202. ecl.set(p->queryProp("keyField"));
  7203. return ecl;
  7204. }
  7205. unsigned CLocalWUResult::getResultRequestedRows() const
  7206. {
  7207. return p->getPropInt("requestedRows", 1);
  7208. }
  7209. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  7210. {
  7211. TypeInfoArray types;
  7212. StringAttrArray names;
  7213. getSchema(types, names, &str);
  7214. return str;
  7215. }
  7216. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  7217. {
  7218. str.set(p->queryProp("@recordSizeEntry"));
  7219. return str;
  7220. }
  7221. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  7222. {
  7223. str.set(p->queryProp("@transformerEntry"));
  7224. return str;
  7225. }
  7226. __int64 CLocalWUResult::getResultRowLimit() const
  7227. {
  7228. return p->getPropInt64("@rowLimit");
  7229. }
  7230. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  7231. {
  7232. str.set(p->queryProp("@tempFilename"));
  7233. return str;
  7234. }
  7235. IStringVal& CLocalWUResult::getResultFieldOpt(const char *name, IStringVal &str) const
  7236. {
  7237. str.clear();
  7238. if (!name || !*name)
  7239. return str;
  7240. IPropertyTree *format = p->queryPropTree("Format");
  7241. if (!format)
  7242. return str;
  7243. VStringBuffer xpath("@%s", name);
  7244. str.set(format->queryProp(xpath));
  7245. return str;
  7246. }
  7247. void CLocalWUResult::setResultStatus(WUResultStatus status)
  7248. {
  7249. setEnum(p, "@status", status, resultStatuses);
  7250. if (status==ResultStatusUndefined)
  7251. {
  7252. p->removeProp("Value");
  7253. p->removeProp("totalRowCount");
  7254. p->removeProp("rowCount");
  7255. p->removeProp("@format");
  7256. p->removeProp("@tempFileNmae");
  7257. p->removeProp("logicalName");
  7258. }
  7259. }
  7260. void CLocalWUResult::setResultName(const char *s)
  7261. {
  7262. p->setProp("@name", s);
  7263. }
  7264. void CLocalWUResult::setResultSequence(unsigned seq)
  7265. {
  7266. p->setPropInt("@sequence", seq);
  7267. }
  7268. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  7269. {
  7270. p->setPropBin("SchemaRaw", size, schema);
  7271. }
  7272. void CLocalWUResult::setResultXmlns(const char *prefix, const char *uri)
  7273. {
  7274. StringBuffer xpath("@xmlns");
  7275. if (prefix && *prefix)
  7276. xpath.append(':').append(prefix);
  7277. p->setProp(xpath, uri);
  7278. }
  7279. void CLocalWUResult::setResultFieldOpt(const char *name, const char *value)
  7280. {
  7281. if (!name || !*name)
  7282. return;
  7283. IPropertyTree *format = ensurePTree(p, "Format");
  7284. VStringBuffer xpath("@%s", name);
  7285. format->setProp(xpath, value);
  7286. }
  7287. void CLocalWUResult::setResultScalar(bool isScalar)
  7288. {
  7289. p->setPropInt("@isScalar", (int) isScalar);
  7290. if (isScalar)
  7291. setResultTotalRowCount(1);
  7292. }
  7293. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  7294. {
  7295. p->setPropBin("Value", len, data);
  7296. setResultStatus(ResultStatusSupplied);
  7297. setResultFormat(format);
  7298. }
  7299. void CLocalWUResult::setResultFormat(WUResultFormat format)
  7300. {
  7301. switch (format)
  7302. {
  7303. case ResultFormatXml:
  7304. p->setProp("@format","xml");
  7305. break;
  7306. case ResultFormatXmlSet:
  7307. p->setProp("@format","xmlSet");
  7308. break;
  7309. case ResultFormatCsv:
  7310. p->setProp("@format","csv");
  7311. break;
  7312. default:
  7313. p->removeProp("@format");
  7314. break;
  7315. }
  7316. }
  7317. void CLocalWUResult::setResultXML(const char *val)
  7318. {
  7319. p->setProp("xmlValue", val);
  7320. }
  7321. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  7322. {
  7323. p->appendPropBin("Value", len, data);
  7324. setResultStatus(ResultStatusPartial);
  7325. const char *existingFormat = p->queryProp("@format");
  7326. const char *formatStr = NULL;
  7327. switch (format)
  7328. {
  7329. case ResultFormatXml:
  7330. formatStr = "xml";
  7331. break;
  7332. case ResultFormatXmlSet:
  7333. formatStr = "xmlSet";
  7334. break;
  7335. case ResultFormatCsv:
  7336. formatStr = "csv";
  7337. break;
  7338. default:
  7339. p->removeProp("@format");
  7340. break;
  7341. }
  7342. if (format)
  7343. {
  7344. if (existingFormat)
  7345. {
  7346. if (0 != stricmp(formatStr, existingFormat))
  7347. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  7348. }
  7349. else
  7350. p->setProp("@format", formatStr);
  7351. }
  7352. }
  7353. void CLocalWUResult::setResultFetchSize(unsigned rows)
  7354. {
  7355. p->setPropInt("fetchSize", rows);
  7356. }
  7357. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  7358. {
  7359. p->setPropInt64("totalRowCount", rows);
  7360. }
  7361. void CLocalWUResult::setResultRowCount(__int64 rows)
  7362. {
  7363. p->setPropInt64("rowCount", rows);
  7364. }
  7365. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  7366. {
  7367. p->setProp("datasetEcl", ecl);
  7368. p->setProp("datasetEclDefs", defs);
  7369. }
  7370. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  7371. {
  7372. p->setProp("logicalName", logicalName);
  7373. }
  7374. void CLocalWUResult::setResultKeyField(const char *ecl)
  7375. {
  7376. p->setProp("keyField", ecl);
  7377. }
  7378. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  7379. {
  7380. p->setPropInt("requestedRows", rows);
  7381. }
  7382. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  7383. {
  7384. p->setProp("@recordSizeEntry", entry);
  7385. }
  7386. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  7387. {
  7388. p->setProp("@transformerEntry", entry);
  7389. }
  7390. void CLocalWUResult::setResultRowLimit(__int64 value)
  7391. {
  7392. p->setPropInt64("@rowLimit", value);
  7393. }
  7394. void CLocalWUResult::setResultFilename(const char * name)
  7395. {
  7396. p->setProp("@tempFilename", name);
  7397. }
  7398. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  7399. __int64 CLocalWUResult::getResultInt() const
  7400. {
  7401. __int64 result = 0;
  7402. MemoryBuffer s;
  7403. p->getPropBin("Value", s);
  7404. if (s.length())
  7405. s.read(result);
  7406. else
  7407. result = p->getPropInt64("xmlValue");
  7408. return result;
  7409. }
  7410. bool CLocalWUResult::getResultBool() const
  7411. {
  7412. bool result = false;
  7413. MemoryBuffer s;
  7414. p->getPropBin("Value", s);
  7415. if (s.length())
  7416. s.read(result);
  7417. else
  7418. result = p->getPropBool("xmlValue");
  7419. return result;
  7420. }
  7421. double CLocalWUResult::getResultReal() const
  7422. {
  7423. double result = 0;
  7424. MemoryBuffer s;
  7425. p->getPropBin("Value", s);
  7426. if (s.length())
  7427. s.read(result);
  7428. else
  7429. {
  7430. const char *xmlVal = p->queryProp("xmlValue");
  7431. if (xmlVal)
  7432. result = atof(xmlVal);
  7433. }
  7434. return result;
  7435. }
  7436. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  7437. {
  7438. MemoryBuffer s;
  7439. p->getPropBin("Value", s);
  7440. if (s.length())
  7441. {
  7442. assertex(s.length() == len);
  7443. s.read(len, val);
  7444. }
  7445. else
  7446. {
  7447. const char *xmlVal = p->queryProp("xmlValue");
  7448. if (xmlVal)
  7449. {
  7450. Decimal d;
  7451. d.setString(strlen(xmlVal), xmlVal);
  7452. if (isSigned)
  7453. d.getDecimal(len, precision, val);
  7454. else
  7455. d.getUDecimal(len, precision, val);
  7456. }
  7457. else
  7458. memset(val, 0, len);
  7459. }
  7460. }
  7461. IStringVal& CLocalWUResult::getResultString(IStringVal & str, bool hidePassword) const
  7462. {
  7463. if (hidePassword && p->getPropBool("@password"))
  7464. {
  7465. str.set("****");
  7466. return str;
  7467. }
  7468. MemoryBuffer s;
  7469. p->getPropBin("Value", s);
  7470. if (s.length())
  7471. {
  7472. unsigned len;
  7473. s.read(len);
  7474. str.setLen((const char *) s.readDirect(len), len);
  7475. }
  7476. else
  7477. {
  7478. p->getPropBin("xmlValue", s);
  7479. if (p->isBinary("xmlValue"))
  7480. str.setLen(s.toByteArray(), s.length());
  7481. else
  7482. {
  7483. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  7484. str.set(ascii);
  7485. rtlFree(ascii);
  7486. }
  7487. }
  7488. return str;
  7489. }
  7490. WUResultFormat CLocalWUResult::getResultFormat() const
  7491. {
  7492. const char * format = p->queryProp("@format");
  7493. if (!format)
  7494. return ResultFormatRaw;
  7495. else if (strcmp(format, "xml") == 0)
  7496. return ResultFormatXml;
  7497. else if (strcmp(format, "xmlSet") == 0)
  7498. return ResultFormatXmlSet;
  7499. else if (strcmp(format, "csv") == 0)
  7500. return ResultFormatCsv;
  7501. else
  7502. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  7503. }
  7504. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7505. {
  7506. MemoryBuffer s;
  7507. p->getPropBin("Value", s);
  7508. unsigned len = s.length();
  7509. if (len)
  7510. {
  7511. WUResultFormat format = getResultFormat();
  7512. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  7513. {
  7514. if (!xmlTransformer)
  7515. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  7516. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  7517. }
  7518. else if (format == ResultFormatCsv)
  7519. {
  7520. if (!csvTransformer)
  7521. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  7522. csvTransformer->transform(data, len, s.readDirect(len), true);
  7523. }
  7524. else
  7525. data.setLen(s.readDirect(len), len);
  7526. }
  7527. else
  7528. data.clear();
  7529. return data;
  7530. }
  7531. unsigned CLocalWUResult::getResultHash() const
  7532. {
  7533. MemoryBuffer s;
  7534. p->getPropBin("Value", s);
  7535. unsigned len = s.length();
  7536. const byte * data = (const byte *)s.toByteArray();
  7537. return ~hashc(data, len, ~0);
  7538. }
  7539. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  7540. {
  7541. MemoryBuffer s;
  7542. p->getPropBin("Value", s);
  7543. if (s.length())
  7544. {
  7545. unsigned len;
  7546. s.read(len);
  7547. data.setLen(s.readDirect(len*2), len*2);
  7548. }
  7549. else
  7550. {
  7551. StringBuffer utf8;
  7552. if (p->getProp("xmlValue", utf8))
  7553. {
  7554. unsigned outlen;
  7555. UChar *out;
  7556. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  7557. data.setLen(out, outlen*2);
  7558. rtlFree(out);
  7559. }
  7560. else
  7561. data.clear();
  7562. }
  7563. return data;
  7564. }
  7565. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7566. {
  7567. WUResultFormat format = getResultFormat();
  7568. if (format == ResultFormatRaw)
  7569. {
  7570. //MORE: This should not load the whole property...
  7571. MemoryBuffer s;
  7572. p->getPropBin("Value", s);
  7573. return s.length();
  7574. }
  7575. else
  7576. {
  7577. MemoryBuffer temp;
  7578. MemoryBuffer2IDataVal adaptor(temp);
  7579. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  7580. return temp.length();
  7581. }
  7582. }
  7583. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  7584. {
  7585. WUResultFormat format = getResultFormat();
  7586. if (format != ResultFormatRaw)
  7587. {
  7588. MemoryBuffer temp;
  7589. MemoryBuffer2IDataVal adaptor(temp);
  7590. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  7591. unsigned len = temp.length();
  7592. if (from > len) from = len;
  7593. if (from + length > len) length = len - from;
  7594. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  7595. return data;
  7596. }
  7597. else
  7598. {
  7599. //MORE: This should not load the whole property, and should be different from the code above...
  7600. MemoryBuffer s;
  7601. p->getPropBin("Value", s);
  7602. unsigned len = s.length();
  7603. if (from > len) from = len;
  7604. if (from + length > len) length = len - from;
  7605. data.setLen(s.readDirect(len) + from, (size32_t)length);
  7606. return data;
  7607. }
  7608. }
  7609. bool CLocalWUResult::getResultIsAll() const
  7610. {
  7611. return p->getPropBool("@isAll", false);
  7612. }
  7613. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  7614. void CLocalWUResult::setResultInt(__int64 val)
  7615. {
  7616. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  7617. MemoryBuffer m;
  7618. serializeInt8(val, m);
  7619. p->setPropBin("Value", m.length(), m.toByteArray());
  7620. setResultRowCount(1);
  7621. setResultTotalRowCount(1);
  7622. }
  7623. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  7624. {
  7625. setResultInt((__int64) val);
  7626. }
  7627. void CLocalWUResult::setResultReal(double val)
  7628. {
  7629. // Note: we always serialize scalar real results as real8, and schema must reflect this
  7630. MemoryBuffer m;
  7631. serializeReal8(val, m);
  7632. p->setPropBin("Value", m.length(), m.toByteArray());
  7633. setResultRowCount(1);
  7634. setResultTotalRowCount(1);
  7635. }
  7636. void CLocalWUResult::setResultBool(bool val)
  7637. {
  7638. MemoryBuffer m;
  7639. serializeBool(val, m);
  7640. p->setPropBin("Value", m.length(), m.toByteArray());
  7641. setResultRowCount(1);
  7642. setResultTotalRowCount(1);
  7643. }
  7644. void CLocalWUResult::setResultString(const char *val, unsigned len)
  7645. {
  7646. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  7647. MemoryBuffer m;
  7648. serializeLPString(len, val, m);
  7649. p->setPropBin("Value", m.length(), m.toByteArray());
  7650. setResultRowCount(1);
  7651. setResultTotalRowCount(1);
  7652. }
  7653. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  7654. {
  7655. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  7656. MemoryBuffer m;
  7657. m.append(len).append(len*2, val);
  7658. p->setPropBin("Value", m.length(), m.toByteArray());
  7659. setResultRowCount(1);
  7660. setResultTotalRowCount(1);
  7661. }
  7662. void CLocalWUResult::setResultData(const void *val, unsigned len)
  7663. {
  7664. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  7665. MemoryBuffer m;
  7666. serializeLPString(len, (const char *)val, m);
  7667. p->setPropBin("Value", m.length(), m.toByteArray());
  7668. setResultRowCount(1);
  7669. setResultTotalRowCount(1);
  7670. }
  7671. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  7672. {
  7673. // Note: serialized as data but with length known from schema
  7674. MemoryBuffer m;
  7675. serializeFixedData(len, val, m);
  7676. p->setPropBin("Value", m.length(), m.toByteArray());
  7677. setResultRowCount(1);
  7678. setResultTotalRowCount(1);
  7679. }
  7680. void CLocalWUResult::setResultRow(unsigned len, const void * data)
  7681. {
  7682. p->setPropBin("Value", len, data);
  7683. setResultRowCount(1);
  7684. setResultTotalRowCount(1);
  7685. setResultFormat(ResultFormatRaw);
  7686. }
  7687. void CLocalWUResult::setResultIsAll(bool value)
  7688. {
  7689. p->setPropBool("@isAll", value);
  7690. }
  7691. //==========================================================================================
  7692. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  7693. {
  7694. }
  7695. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  7696. {
  7697. str.set(p->queryProp("@dllname"));
  7698. return str;
  7699. }
  7700. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  7701. {
  7702. str.set(p->queryProp("@version"));
  7703. return str;
  7704. }
  7705. void CLocalWUPlugin::setPluginName(const char *str)
  7706. {
  7707. p->setProp("@dllname", str);
  7708. }
  7709. void CLocalWUPlugin::setPluginVersion(const char *str)
  7710. {
  7711. p->setProp("@version", str);
  7712. }
  7713. //==========================================================================================
  7714. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  7715. {
  7716. }
  7717. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  7718. {
  7719. str.set(p->queryProp("@name"));
  7720. return str;
  7721. }
  7722. void CLocalWULibrary::setName(const char *str)
  7723. {
  7724. p->setProp("@name", str);
  7725. }
  7726. //==========================================================================================
  7727. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  7728. {
  7729. }
  7730. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  7731. {
  7732. str.set(p->queryProp("@source"));
  7733. return str;
  7734. }
  7735. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  7736. {
  7737. str.set(p->queryProp(NULL));
  7738. return str;
  7739. }
  7740. unsigned CLocalWUException::getExceptionCode() const
  7741. {
  7742. return p->getPropInt("@code", 0);
  7743. }
  7744. ErrorSeverity CLocalWUException::getSeverity() const
  7745. {
  7746. return (ErrorSeverity)p->getPropInt("@severity", SeverityError);
  7747. }
  7748. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  7749. {
  7750. dt.set(p->queryProp("@time"));
  7751. return dt;
  7752. }
  7753. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  7754. {
  7755. str.set(p->queryProp("@filename"));
  7756. return str;
  7757. }
  7758. unsigned CLocalWUException::getExceptionLineNo() const
  7759. {
  7760. return p->getPropInt("@row", 0);
  7761. }
  7762. unsigned CLocalWUException::getExceptionColumn() const
  7763. {
  7764. return p->getPropInt("@col", 0);
  7765. }
  7766. unsigned CLocalWUException::getSequence() const
  7767. {
  7768. return p->getPropInt("@sequence", 0);
  7769. }
  7770. void CLocalWUException::setExceptionSource(const char *str)
  7771. {
  7772. p->setProp("@source", str);
  7773. }
  7774. void CLocalWUException::setExceptionMessage(const char *str)
  7775. {
  7776. p->setProp(NULL, str);
  7777. }
  7778. void CLocalWUException::setExceptionCode(unsigned code)
  7779. {
  7780. p->setPropInt("@code", code);
  7781. }
  7782. void CLocalWUException::setSeverity(ErrorSeverity level)
  7783. {
  7784. p->setPropInt("@severity", level);
  7785. }
  7786. void CLocalWUException::setTimeStamp(const char *str)
  7787. {
  7788. p->setProp("@time", str);
  7789. }
  7790. void CLocalWUException::setExceptionFileName(const char *str)
  7791. {
  7792. p->setProp("@filename", str);
  7793. }
  7794. void CLocalWUException::setExceptionLineNo(unsigned r)
  7795. {
  7796. p->setPropInt("@row", r);
  7797. }
  7798. void CLocalWUException::setExceptionColumn(unsigned c)
  7799. {
  7800. p->setPropInt("@col", c);
  7801. }
  7802. //==========================================================================================
  7803. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props, unsigned child) : p(props)
  7804. {
  7805. StringAttrBuilder propPath(prop);
  7806. propPath.append("*[").append(child).append("]");
  7807. }
  7808. const char * CLocalWUAppValue::queryApplication() const
  7809. {
  7810. return p->queryName();
  7811. }
  7812. const char * CLocalWUAppValue::queryName() const
  7813. {
  7814. IPropertyTree* val=p->queryPropTree(prop.str());
  7815. if(val)
  7816. return val->queryName();
  7817. return ""; // Should not happen in normal usage
  7818. }
  7819. const char * CLocalWUAppValue::queryValue() const
  7820. {
  7821. return p->queryProp(prop.str());
  7822. }
  7823. //==========================================================================================
  7824. CLocalWUStatistic::CLocalWUStatistic(IPropertyTree *props) : p(props)
  7825. {
  7826. }
  7827. IStringVal & CLocalWUStatistic::getCreator(IStringVal & str) const
  7828. {
  7829. const char * creator = p->queryProp("@creator");
  7830. str.set(creator);
  7831. return str;
  7832. }
  7833. IStringVal & CLocalWUStatistic::getDescription(IStringVal & str, bool createDefault) const
  7834. {
  7835. const char * desc = p->queryProp("@desc");
  7836. if (desc)
  7837. {
  7838. str.set(desc); // legacy and in case it is overridden
  7839. }
  7840. else if (createDefault)
  7841. {
  7842. StatisticKind kind = getKind();
  7843. assertex(kind != StKindNone);
  7844. const char * scope = p->queryProp("@scope");
  7845. assertex(scope);
  7846. //Clean up the format of the scope when converting it to a description
  7847. StringBuffer descriptionText;
  7848. if (streq(scope, GLOBAL_SCOPE))
  7849. {
  7850. const char * creator = p->queryProp("@creator");
  7851. descriptionText.append(creator).append(":");
  7852. queryLongStatisticName(descriptionText, kind);
  7853. }
  7854. else
  7855. {
  7856. loop
  7857. {
  7858. char c = *scope++;
  7859. if (!c)
  7860. break;
  7861. if (c == ':')
  7862. descriptionText.append(": ");
  7863. else
  7864. descriptionText.append(c);
  7865. }
  7866. if (kind != StTimeElapsed)
  7867. queryLongStatisticName(descriptionText.append(": "), kind);
  7868. }
  7869. str.set(descriptionText);
  7870. }
  7871. else
  7872. str.clear();
  7873. return str;
  7874. }
  7875. IStringVal & CLocalWUStatistic::getType(IStringVal & str) const
  7876. {
  7877. StatisticKind kind = getKind();
  7878. if (kind != StKindNone)
  7879. str.set(queryStatisticName(kind));
  7880. return str;
  7881. }
  7882. IStringVal & CLocalWUStatistic::getFormattedValue(IStringVal & str) const
  7883. {
  7884. StringBuffer formatted;
  7885. formatStatistic(formatted, getValue(), getMeasure());
  7886. str.set(formatted);
  7887. return str;
  7888. }
  7889. StatisticCreatorType CLocalWUStatistic::getCreatorType() const
  7890. {
  7891. return queryCreatorType(p->queryProp("@c"));
  7892. }
  7893. StatisticScopeType CLocalWUStatistic::getScopeType() const
  7894. {
  7895. return queryScopeType(p->queryProp("@s"));
  7896. }
  7897. StatisticKind CLocalWUStatistic::getKind() const
  7898. {
  7899. return queryStatisticKind(p->queryProp("@kind"));
  7900. }
  7901. IStringVal & CLocalWUStatistic::getScope(IStringVal & str) const
  7902. {
  7903. const char * scope = p->queryProp("@scope");
  7904. str.set(scope);
  7905. return str;
  7906. }
  7907. StatisticMeasure CLocalWUStatistic::getMeasure() const
  7908. {
  7909. return queryMeasure(p->queryProp("@unit"));
  7910. }
  7911. unsigned __int64 CLocalWUStatistic::getValue() const
  7912. {
  7913. return p->getPropInt64("@value", 0);
  7914. }
  7915. unsigned __int64 CLocalWUStatistic::getCount() const
  7916. {
  7917. return p->getPropInt64("@count", 0);
  7918. }
  7919. unsigned __int64 CLocalWUStatistic::getMax() const
  7920. {
  7921. return p->getPropInt64("@max", 0);
  7922. }
  7923. unsigned __int64 CLocalWUStatistic::getTimestamp() const
  7924. {
  7925. return p->getPropInt64("@ts", 0);
  7926. }
  7927. bool CLocalWUStatistic::matches(const IStatisticsFilter * filter) const
  7928. {
  7929. if (!filter)
  7930. return true;
  7931. const char * creator = p->queryProp("@creator");
  7932. const char * scope = p->queryProp("@scope");
  7933. return filter->matches(getCreatorType(), creator, getScopeType(), scope, getMeasure(), getKind());
  7934. }
  7935. //==========================================================================================
  7936. CLocalWULegacyTiming::CLocalWULegacyTiming(IPropertyTree *props) : p(props)
  7937. {
  7938. }
  7939. IStringVal & CLocalWULegacyTiming::getCreator(IStringVal & str) const
  7940. {
  7941. str.clear();
  7942. return str;
  7943. }
  7944. IStringVal & CLocalWULegacyTiming::getDescription(IStringVal & str, bool createDefault) const
  7945. {
  7946. str.set(p->queryProp("@name"));
  7947. return str;
  7948. }
  7949. IStringVal & CLocalWULegacyTiming::getType(IStringVal & str) const
  7950. {
  7951. str.set(queryStatisticName(StTimeElapsed));
  7952. return str;
  7953. }
  7954. IStringVal & CLocalWULegacyTiming::getFormattedValue(IStringVal & str) const
  7955. {
  7956. StringBuffer formatted;
  7957. formatStatistic(formatted, getValue(), getMeasure());
  7958. str.set(formatted);
  7959. return str;
  7960. }
  7961. StatisticCreatorType CLocalWULegacyTiming::getCreatorType() const
  7962. {
  7963. return SCTunknown;
  7964. }
  7965. StatisticScopeType CLocalWULegacyTiming::getScopeType() const
  7966. {
  7967. return SSTnone;
  7968. }
  7969. StatisticKind CLocalWULegacyTiming::getKind() const
  7970. {
  7971. return StTimeElapsed;
  7972. }
  7973. IStringVal & CLocalWULegacyTiming::getScope(IStringVal & str) const
  7974. {
  7975. str.clear();
  7976. return str;
  7977. }
  7978. StatisticMeasure CLocalWULegacyTiming::getMeasure() const
  7979. {
  7980. return SMeasureTimeNs;
  7981. }
  7982. unsigned __int64 CLocalWULegacyTiming::getValue() const
  7983. {
  7984. return p->getPropInt64("@duration", 0) * 1000000;
  7985. }
  7986. unsigned __int64 CLocalWULegacyTiming::getCount() const
  7987. {
  7988. return p->getPropInt64("@count", 0);
  7989. }
  7990. unsigned __int64 CLocalWULegacyTiming::getMax() const
  7991. {
  7992. return p->getPropInt64("@max", 0);
  7993. }
  7994. unsigned __int64 CLocalWULegacyTiming::getTimestamp() const
  7995. {
  7996. return 0;
  7997. }
  7998. bool CLocalWULegacyTiming::matches(const IStatisticsFilter * filter) const
  7999. {
  8000. if (!filter)
  8001. return true;
  8002. const char * creator = p->queryProp("@creator");
  8003. const char * scope = p->queryProp("@scope");
  8004. return filter->matches(SCTall, NULL, SSTall, NULL, getMeasure(), getKind());
  8005. }
  8006. //==========================================================================================
  8007. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit(const char *xml)
  8008. {
  8009. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit((ISecManager *) NULL, NULL);
  8010. if (xml)
  8011. cw->loadPTree(createPTreeFromXMLString(xml));
  8012. else
  8013. {
  8014. Owned<IPropertyTree> p = createPTree("W_LOCAL");
  8015. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  8016. cw->loadPTree(p.getClear());
  8017. }
  8018. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  8019. return ret;
  8020. }
  8021. void exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, IIOStream &out, unsigned extraXmlFlags)
  8022. {
  8023. const char *name = p->queryName();
  8024. if (!name)
  8025. name = "__unnamed__";
  8026. StringBuffer temp;
  8027. writeStringToStream(out, appendPTreeOpenTag(temp, p, name, 1));
  8028. Owned<IPropertyTreeIterator> elems = p->getElements("*", iptiter_sort);
  8029. ForEach(*elems)
  8030. {
  8031. IPropertyTree &elem = elems->query();
  8032. if (streq(elem.queryName(), "Parameters"))
  8033. {
  8034. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Parameters", 2).append('\n'));
  8035. Owned<IPropertyTreeIterator> params = elem.getElements("*", iptiter_sort);
  8036. ForEach(*params)
  8037. {
  8038. IPropertyTree &param = params->query();
  8039. const char *paramname = param.queryName();
  8040. VStringBuffer xpath("Variables/Variable[@name='%s']/Format/@password", paramname);
  8041. if (p->getPropBool(xpath))
  8042. writeStringToStream(out, appendXMLTag(temp.clear().append(" "), paramname, "****").append('\n'));
  8043. else
  8044. {
  8045. toXML(&param, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  8046. }
  8047. }
  8048. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Parameters").append('\n'));
  8049. }
  8050. else if (streq(elem.queryName(), "Variables"))
  8051. {
  8052. writeStringToStream(out, appendPTreeOpenTag(temp.clear().append(' '), &elem, "Variables", 2).append('\n'));
  8053. Owned<IPropertyTreeIterator> vars = elem.getElements("*", iptiter_sort);
  8054. ForEach(*vars)
  8055. {
  8056. Owned<IPropertyTree> var = LINK(&vars->query());
  8057. if (var->getPropBool("Format/@password"))
  8058. {
  8059. var.setown(createPTreeFromIPT(var)); //copy and remove password values
  8060. var->removeProp("Value");
  8061. var->removeProp("xmlValue");
  8062. }
  8063. toXML(var, out, 2, XML_Format|XML_SortTags|extraXmlFlags);
  8064. }
  8065. writeStringToStream(out, appendXMLCloseTag(temp.clear().append(' '), "Variables").append('\n'));
  8066. }
  8067. else
  8068. toXML(&elem, out, 1, XML_Format|XML_SortTags|extraXmlFlags);
  8069. }
  8070. writeStringToStream(out, appendXMLCloseTag(temp.clear(), name));
  8071. }
  8072. StringBuffer &exportWorkUnitToXMLWithHiddenPasswords(IPropertyTree *p, StringBuffer &str)
  8073. {
  8074. class CAdapter : public CInterface, implements IIOStream
  8075. {
  8076. StringBuffer &out;
  8077. public:
  8078. IMPLEMENT_IINTERFACE;
  8079. CAdapter(StringBuffer &_out) : out(_out) { }
  8080. virtual void flush() { }
  8081. virtual size32_t read(size32_t len, void * data) { UNIMPLEMENTED; return 0; }
  8082. virtual size32_t write(size32_t len, const void * data) { out.append(len, (const char *)data); return len; }
  8083. } adapter(str);
  8084. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), adapter, 0);
  8085. return str;
  8086. }
  8087. void exportWorkUnitToXMLFileWithHiddenPasswords(IPropertyTree *p, const char *filename, unsigned extraXmlFlags)
  8088. {
  8089. OwnedIFile ifile = createIFile(filename);
  8090. OwnedIFileIO ifileio = ifile->open(IFOcreate);
  8091. Owned<IIOStream> stream = createIOStream(ifileio);
  8092. exportWorkUnitToXMLWithHiddenPasswords(p->queryBranch(NULL), *stream, extraXmlFlags);
  8093. }
  8094. extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords)
  8095. {
  8096. // MORE - queryPTree isn't really safe without holding CLocalWorkUnit::crit - really need to move these functions into CLocalWorkunit
  8097. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  8098. if (ewu)
  8099. {
  8100. Linked<IPropertyTree> p;
  8101. if (unpack||includeProgress)
  8102. p.setown(ewu->getUnpackedTree(includeProgress));
  8103. else
  8104. p.set(ewu->queryPTree());
  8105. if (hidePasswords && p->hasProp("Variables/Variable[Format/@password]"))
  8106. return exportWorkUnitToXMLWithHiddenPasswords(p, str);
  8107. toXML(p, str, 0, XML_Format|XML_SortTags);
  8108. }
  8109. else
  8110. str.append("Unrecognized workunit format");
  8111. return str;
  8112. }
  8113. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords)
  8114. {
  8115. const IExtendedWUInterface *ewu = queryExtendedWU(wu);
  8116. if (ewu)
  8117. {
  8118. Linked<IPropertyTree> p;
  8119. if (unpack||includeProgress)
  8120. p.setown(ewu->getUnpackedTree(includeProgress));
  8121. else
  8122. p.set(ewu->queryPTree());
  8123. if (hidePasswords && p->hasProp("Variables/Variable[Format/@password]"))
  8124. return exportWorkUnitToXMLFileWithHiddenPasswords(p, filename, extraXmlFlags);
  8125. saveXML(filename, p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  8126. }
  8127. else
  8128. throw makeStringException(0, "Unrecognized workunit format");
  8129. }
  8130. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  8131. {
  8132. MemoryBuffer buffer;
  8133. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  8134. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  8135. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  8136. assertex(workunit);
  8137. SCMStringBuffer token;
  8138. createToken(wuid, username, password, token);
  8139. workunit->setSecurityToken(token.str());
  8140. StringAttr clusterName(workunit->queryClusterName());
  8141. if (!clusterName.length())
  8142. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  8143. workunit->commit();
  8144. workunit.clear();
  8145. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  8146. if (!clusterInfo)
  8147. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName.str());
  8148. SCMStringBuffer serverQueue;
  8149. clusterInfo->getServerQueue(serverQueue);
  8150. assertex(serverQueue.length());
  8151. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  8152. if (!queue.get())
  8153. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  8154. IJobQueueItem *item = createJobQueueItem(wuid);
  8155. queue->enqueue(item);
  8156. }
  8157. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  8158. {
  8159. StringBuffer xpath("/WorkUnitAborts/");
  8160. xpath.append(wuid);
  8161. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  8162. acon->queryRoot()->setPropInt(NULL, 1);
  8163. }
  8164. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  8165. {
  8166. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  8167. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  8168. }
  8169. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  8170. {
  8171. if (!checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  8172. return;
  8173. abortWorkUnit(wuid);
  8174. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  8175. if(!cw)
  8176. return;
  8177. WorkunitUpdate wu(&cw->lock());
  8178. const char *abortBy = secuser.getName();
  8179. if (abortBy && *abortBy)
  8180. wu->setTracingValue("AbortBy", abortBy);
  8181. wu->setTracingValueInt64("AbortTimeStamp", getTimeStampNowValue());
  8182. }
  8183. extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  8184. {
  8185. if (secmgr && secuser)
  8186. return secSubmitWorkUnit(wuid, *secmgr, *secuser);
  8187. if (secuser)
  8188. return submitWorkUnit(wuid, secuser->getName(), secuser->credentials().getPassword());
  8189. submitWorkUnit(wuid, "", "");
  8190. }
  8191. extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser)
  8192. {
  8193. if (secmgr && secuser)
  8194. return secAbortWorkUnit(wuid, *secmgr, *secuser);
  8195. abortWorkUnit(wuid);
  8196. }
  8197. bool CLocalWorkUnit::hasWorkflow() const
  8198. {
  8199. return p->hasProp("Workflow");
  8200. }
  8201. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  8202. {
  8203. CriticalBlock block(crit);
  8204. if (p->hasProp("@eventScheduledCount"))
  8205. return p->getPropInt("@eventScheduledCount", 0);
  8206. else
  8207. return p->getPropInt("Workflow/@eventScheduledCount", 0); // Legacy location for this setting
  8208. }
  8209. void CLocalWorkUnit::incEventScheduledCount()
  8210. {
  8211. CriticalBlock block(crit);
  8212. p->setPropInt("@eventScheduledCount", queryEventScheduledCount()+1);
  8213. }
  8214. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  8215. {
  8216. CriticalBlock block(crit);
  8217. return p->queryPropTree("Workflow");
  8218. }
  8219. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  8220. {
  8221. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8222. CriticalBlock block(crit);
  8223. if(!workflowIteratorCached)
  8224. {
  8225. assertex(!workflowIterator);
  8226. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  8227. if(s)
  8228. workflowIterator.setown(createWorkflowItemIterator(s));
  8229. workflowIteratorCached = true;
  8230. }
  8231. return workflowIterator.getLink();
  8232. }
  8233. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  8234. {
  8235. unsigned count = 0;
  8236. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  8237. for(iter->first(); iter->isValid(); iter->next())
  8238. count++;
  8239. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  8240. for(iter->first(); iter->isValid(); iter->next())
  8241. array->addClone(iter->query());
  8242. return array.getLink();
  8243. }
  8244. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  8245. {
  8246. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8247. CriticalBlock block(crit);
  8248. workflowIterator.clear();
  8249. workflowIteratorCached = false;
  8250. IPropertyTree * s = p->queryPropTree("Workflow");
  8251. if(!s)
  8252. s = p->addPropTree("Workflow", createPTree("Workflow"));
  8253. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  8254. }
  8255. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  8256. {
  8257. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8258. CriticalBlock block(crit);
  8259. if(!workflowIterator)
  8260. {
  8261. IPropertyTree * s = p->queryPropTree("Workflow");
  8262. if(!s)
  8263. s = p->addPropTree("Workflow", createPTree("Workflow"));
  8264. workflowIterator.setown(createWorkflowItemIterator(s));
  8265. workflowIteratorCached = true;
  8266. }
  8267. return workflowIterator.getLink();
  8268. }
  8269. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  8270. {
  8271. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  8272. Owned<IWorkflowItem> item;
  8273. for(iter->first(); iter->isValid(); iter->next())
  8274. {
  8275. item.setown(iter->get());
  8276. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  8277. }
  8278. workflowIterator.clear();
  8279. workflowIteratorCached = false;
  8280. }
  8281. void CLocalWorkUnit::resetWorkflow()
  8282. {
  8283. if (hasWorkflow())
  8284. {
  8285. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  8286. Owned<IWorkflowItem> wf;
  8287. for(iter->first(); iter->isValid(); iter->next())
  8288. {
  8289. wf.setown(iter->get());
  8290. wf->reset();
  8291. }
  8292. workflowIterator.clear();
  8293. workflowIteratorCached = false;
  8294. }
  8295. }
  8296. void CLocalWorkUnit::schedule()
  8297. {
  8298. CriticalBlock block(crit);
  8299. if(queryEventScheduledCount() == 0) return;
  8300. switch(getState())
  8301. {
  8302. case WUStateCompleted:
  8303. setState(WUStateWait);
  8304. break;
  8305. case WUStateFailed:
  8306. case WUStateArchived:
  8307. case WUStateAborting:
  8308. case WUStateAborted:
  8309. case WUStateScheduled:
  8310. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  8311. }
  8312. StringBuffer rootPath;
  8313. rootPath.append("/Schedule/").append(queryClusterName());
  8314. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  8315. Owned<IPropertyTree> root = conn->getRoot();
  8316. if(!root->hasChildren())
  8317. {
  8318. StringBuffer addPath;
  8319. addPath.append("/Schedulers/").append(queryClusterName());
  8320. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  8321. }
  8322. char const * wuid = p->queryName();
  8323. StringBuffer xpath("*/*/");
  8324. ncnameEscape(wuid, xpath);
  8325. bool more;
  8326. do more = root->removeProp(xpath.str()); while(more);
  8327. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  8328. Owned<IWorkflowEvent> event;
  8329. Owned<IPropertyTree> branch1, branch2;
  8330. for(iter->first(); iter->isValid(); iter->next())
  8331. {
  8332. event.setown(iter->query()->getScheduleEvent());
  8333. if(!event) continue;
  8334. ncnameEscape(event->queryName(), xpath.clear());
  8335. ensurePTree(root, xpath.str());
  8336. branch1.setown(root->getPropTree(xpath.str()));
  8337. ncnameEscape(event->queryText(), xpath.clear());
  8338. ensurePTree(branch1, xpath.str());
  8339. branch2.setown(branch1->getPropTree(xpath.str()));
  8340. ncnameEscape(wuid, xpath.clear());
  8341. ensurePTree(branch2, xpath.str());
  8342. }
  8343. }
  8344. void CLocalWorkUnit::deschedule()
  8345. {
  8346. if(queryEventScheduledCount() == 0) return;
  8347. if(getState() == WUStateWait)
  8348. setState(WUStateCompleted);
  8349. doDescheduleWorkkunit(p->queryName());
  8350. }
  8351. mapEnums localFileUploadTypes[] = {
  8352. { UploadTypeFileSpray, "FileSpray" },
  8353. { UploadTypeWUResult, "WUResult" },
  8354. { UploadTypeWUResultCsv, "WUResultCsv" },
  8355. { UploadTypeWUResultXml, "WUResultXml" },
  8356. { UploadTypeSize, NULL }
  8357. };
  8358. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  8359. {
  8360. public:
  8361. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  8362. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  8363. {
  8364. tree.setown(createPTree());
  8365. tree->setPropInt("@id", id);
  8366. setEnum(tree, "@type", type, localFileUploadTypes);
  8367. tree->setProp("@source", source);
  8368. tree->setProp("@destination", destination);
  8369. if (eventTag)
  8370. tree->setProp("@eventTag", eventTag);
  8371. }
  8372. IMPLEMENT_IINTERFACE;
  8373. IPropertyTree * getTree() { return tree.getLink(); }
  8374. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  8375. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  8376. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  8377. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  8378. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  8379. private:
  8380. Owned<IPropertyTree> tree;
  8381. };
  8382. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  8383. {
  8384. public:
  8385. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  8386. IMPLEMENT_IINTERFACE;
  8387. bool first() { return iter->first(); }
  8388. bool isValid() { return iter->isValid(); }
  8389. bool next() { return iter->next(); }
  8390. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  8391. private:
  8392. Owned<IPropertyTree> tree;
  8393. Owned<IPropertyTreeIterator> iter;
  8394. };
  8395. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  8396. {
  8397. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  8398. CriticalBlock block(crit);
  8399. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  8400. if(s)
  8401. return new CLocalFileUploadIterator(s.getClear());
  8402. else
  8403. return NULL;
  8404. }
  8405. bool CLocalWorkUnit::requiresLocalFileUpload() const
  8406. {
  8407. SCMStringBuffer dest;
  8408. Owned<IConstWUResult> result;
  8409. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  8410. if(!iter)
  8411. return false;
  8412. for(iter->first(); iter->isValid(); iter->next())
  8413. {
  8414. Owned<IConstLocalFileUpload> upload(iter->get());
  8415. switch(upload->queryType())
  8416. {
  8417. case UploadTypeWUResult:
  8418. case UploadTypeWUResultCsv:
  8419. case UploadTypeWUResultXml:
  8420. upload->getDestination(dest);
  8421. result.setown(getResultByName(dest.str()));
  8422. if(!result)
  8423. return true;
  8424. break;
  8425. default:
  8426. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  8427. }
  8428. }
  8429. return false;
  8430. }
  8431. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  8432. {
  8433. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  8434. CriticalBlock block(crit);
  8435. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  8436. if(!s)
  8437. s = p->addPropTree("LocalFileUploads", createPTree());
  8438. unsigned id = s->numChildren();
  8439. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  8440. s->addPropTree("LocalFileUpload", upload->getTree());
  8441. return id;
  8442. }
  8443. IStringVal & CLocalWorkUnit::getAbortBy(IStringVal & str) const
  8444. {
  8445. CriticalBlock block(crit);
  8446. str.set(p->queryProp("Tracing/AbortBy"));
  8447. return str;
  8448. }
  8449. unsigned __int64 CLocalWorkUnit::getAbortTimeStamp() const
  8450. {
  8451. CriticalBlock block(crit);
  8452. return p->getPropInt64("Tracing/AbortTimeStamp", 0);
  8453. }
  8454. #if 0
  8455. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  8456. {
  8457. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  8458. unsigned deps = 0;
  8459. Owned<IWorkflowDependencyIterator> diter;
  8460. switch(cwf->queryWfid())
  8461. {
  8462. case 1:
  8463. assertex(!cwf->isScheduled());
  8464. assertex(cwf->queryType() == WFTypeNormal);
  8465. assertex(cwf->queryState() == WFStateNull);
  8466. diter.setown(cwf->getDependencies());
  8467. for(diter->first(); diter->isValid(); diter->next())
  8468. deps++;
  8469. assertex(deps==0);
  8470. okay[0] = true;
  8471. break;
  8472. case 2:
  8473. assertex(!cwf->isScheduled());
  8474. assertex(cwf->queryType() == WFTypeRecovery);
  8475. assertex(cwf->queryState() == WFStateSkip);
  8476. okay[1] = true;
  8477. break;
  8478. case 3:
  8479. assertex(cwf->queryContingencyFor() == 4);
  8480. okay[2] = true;
  8481. break;
  8482. case 4:
  8483. assertex(cwf->isScheduled());
  8484. assertex(cwf->queryType() == WFTypeNormal);
  8485. assertex(cwf->queryState() == WFStateReqd);
  8486. assertex(cwf->querySuccess() == 0);
  8487. assertex(cwf->queryFailure() == 3);
  8488. assertex(cwf->queryRecovery() == 2);
  8489. assertex(cwf->queryRetriesAllowed() == 10);
  8490. assertex(cwf->queryRetriesRemaining() == 10);
  8491. diter.setown(cwf->getDependencies());
  8492. for(diter->first(); diter->isValid(); diter->next())
  8493. {
  8494. dep[diter->query()-1] = true;
  8495. deps++;
  8496. }
  8497. assertex(deps==2);
  8498. assertex(dep[0]);
  8499. assertex(dep[1]);
  8500. okay[3] = true;
  8501. break;
  8502. case 5:
  8503. assertex(cwf->isScheduled());
  8504. assertex(!cwf->isScheduledNow());
  8505. assertex(cwf->querySchedulePriority() == 75);
  8506. assertex(cwf->queryScheduleCount() == 5);
  8507. assertex(cwf->queryScheduleCountRemaining() == 5);
  8508. okay[4] = true;
  8509. break;
  8510. case 6:
  8511. assertex(cwf->isScheduled());
  8512. assertex(!cwf->isScheduledNow());
  8513. assertex(cwf->querySchedulePriority() == 25);
  8514. assertex(!cwf->hasScheduleCount());
  8515. okay[5] = true;
  8516. break;
  8517. default:
  8518. assertex(!"unknown wfid in test");
  8519. }
  8520. }
  8521. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  8522. {
  8523. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  8524. switch(rwf->queryWfid())
  8525. {
  8526. case 1:
  8527. case 2:
  8528. case 3:
  8529. okay[rwf->queryWfid()-1] = true;
  8530. break;
  8531. case 4:
  8532. {
  8533. unsigned tries = 0;
  8534. while(rwf->testAndDecRetries())
  8535. tries++;
  8536. assertex(tries == 10);
  8537. assertex(rwf->queryRetriesRemaining() == 0);
  8538. rwf->setState(WFStateFail);
  8539. assertex(rwf->queryState() == WFStateFail);
  8540. rwf->reset();
  8541. assertex(rwf->queryRetriesRemaining() == 10);
  8542. assertex(rwf->queryState() == WFStateReqd);
  8543. }
  8544. okay[3] = true;
  8545. break;
  8546. case 5:
  8547. {
  8548. assertex(rwf->queryScheduleCountRemaining() == 5);
  8549. unsigned count = 0;
  8550. do count++; while(rwf->decAndTestScheduleCountRemaining());
  8551. assertex(count == 5);
  8552. assertex(rwf->queryScheduleCountRemaining() == 0);
  8553. rwf->reset();
  8554. assertex(rwf->queryScheduleCountRemaining() == 5);
  8555. }
  8556. okay[4] = true;
  8557. break;
  8558. case 6:
  8559. {
  8560. assertex(!rwf->hasScheduleCount());
  8561. unsigned count;
  8562. for(count=0; count<20; count++)
  8563. assertex(rwf->decAndTestScheduleCountRemaining());
  8564. }
  8565. okay[5] = true;
  8566. break;
  8567. default:
  8568. assertex(!"unknown wfid in test");
  8569. }
  8570. }
  8571. void testWorkflow()
  8572. {
  8573. DBGLOG("workunit.cpp : testWorkflow");
  8574. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  8575. Owned<IWorkflowItem> wf;
  8576. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  8577. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  8578. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  8579. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  8580. wf->setScheduledNow();
  8581. wf->addDependency(1);
  8582. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  8583. wf->setScheduledOn("test", "foo*");
  8584. wf->setSchedulePriority(75);
  8585. wf->setScheduleCount(5);
  8586. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  8587. wf->setScheduledOn("test", "bar*");
  8588. wf->setSchedulePriority(25);
  8589. unsigned const n = 6;
  8590. bool okay[n];
  8591. bool dep[n];
  8592. unsigned i;
  8593. for(i=0; i<n; i++)
  8594. okay[i] = dep[i] = 0;
  8595. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  8596. for(citer->first(); citer->isValid(); citer->next())
  8597. testConstWorkflow(citer->query(), okay, dep);
  8598. for(i=0; i<n; i++)
  8599. {
  8600. assertex(okay[i]);
  8601. okay[i] = false;
  8602. }
  8603. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  8604. for(miter->first(); miter->isValid(); miter->next())
  8605. {
  8606. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  8607. testRuntimeWorkflow(rwf, okay);
  8608. }
  8609. for(i=0; i<n; i++)
  8610. {
  8611. assertex(okay[i]);
  8612. okay[i] = dep[i] = false;
  8613. }
  8614. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  8615. unsigned wfid;
  8616. for(wfid = 1; array->isValid(wfid); wfid++)
  8617. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  8618. for(i=0; i<n; i++)
  8619. {
  8620. assertex(okay[i]);
  8621. okay[i] = false;
  8622. }
  8623. for(wfid = 1; array->isValid(wfid); wfid++)
  8624. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  8625. for(i=0; i<n; i++)
  8626. {
  8627. assertex(okay[i]);
  8628. okay[i] = false;
  8629. }
  8630. }
  8631. #endif
  8632. //------------------------------------------------------------------------------------------
  8633. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, bool returnOnWaitState)
  8634. {
  8635. return factory->waitForWorkUnit(wuid, (unsigned) timeout, false, returnOnWaitState);
  8636. }
  8637. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, bool returnOnWaitState)
  8638. {
  8639. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  8640. return waitForWorkUnitToComplete(wuid, timeout, returnOnWaitState);
  8641. return WUStateUnknown;
  8642. }
  8643. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  8644. {
  8645. switch(factory->waitForWorkUnit(wuid, (unsigned) timeout, true, true))
  8646. {
  8647. case WUStateCompiled:
  8648. case WUStateCompleted:
  8649. case WUStateWait:
  8650. case WUStateUploadingFiles:
  8651. return true;
  8652. default:
  8653. return false;
  8654. }
  8655. }
  8656. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  8657. {
  8658. if (checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  8659. return waitForWorkUnitToCompile(wuid, timeout);
  8660. return false;
  8661. }
  8662. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  8663. {
  8664. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, &secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  8665. {
  8666. Owned<IConstWorkUnit> wu = factory->openWorkUnit(wuid, &secmgr, &secuser);
  8667. SCMStringBuffer ip;
  8668. unsigned port;
  8669. port = wu->getDebugAgentListenerPort();
  8670. wu->getDebugAgentListenerIP(ip);
  8671. SocketEndpoint debugEP(ip.str(), port);
  8672. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  8673. unsigned len = (size32_t)strlen(command);
  8674. unsigned revlen = len;
  8675. _WINREV(revlen);
  8676. socket->write(&revlen, sizeof(revlen));
  8677. socket->write(command, len);
  8678. for (;;)
  8679. {
  8680. socket->read(&len, sizeof(len));
  8681. _WINREV(len);
  8682. if (len == 0)
  8683. break;
  8684. if (len & 0x80000000)
  8685. {
  8686. throwUnexpected();
  8687. }
  8688. char * mem = (char*) response.reserve(len);
  8689. socket->read(mem, len);
  8690. }
  8691. return true;
  8692. }
  8693. return false;
  8694. }
  8695. void getSimpleResultType(IWUResult *r, Owned<ITypeInfo> &type)
  8696. {
  8697. TypeInfoArray types;
  8698. StringAttrArray names;
  8699. r->getSchema(types, names, NULL);
  8700. if (types.ordinality()==1)
  8701. type.set(&types.item(0));
  8702. }
  8703. bool isSuppliedParamScalar(IWUResult *r, IPropertyTree &curVal, Owned<ITypeInfo> &type)
  8704. {
  8705. if (!r->isResultScalar())
  8706. return false;
  8707. if (!curVal.hasChildren())
  8708. return true;
  8709. getSimpleResultType(r, type);
  8710. return type && type->isScalar();
  8711. }
  8712. void updateSuppliedXmlParams(IWorkUnit * w)
  8713. {
  8714. Owned<const IPropertyTree> params = w->getXmlParams();
  8715. if (!params)
  8716. return;
  8717. Owned<IPropertyTreeIterator> elems = params->getElements("*");
  8718. ForEach(*elems)
  8719. {
  8720. IPropertyTree & curVal = elems->query();
  8721. const char *name = curVal.queryName();
  8722. Owned<IWUResult> r = updateWorkUnitResult(w, name, -1);
  8723. if (r)
  8724. {
  8725. Owned<ITypeInfo> type;
  8726. StringBuffer s;
  8727. if (isSuppliedParamScalar(r, curVal, type))
  8728. {
  8729. curVal.getProp(".", s);
  8730. r->setResultXML(s);
  8731. r->setResultStatus(ResultStatusSupplied);
  8732. }
  8733. else
  8734. {
  8735. toXML(&curVal, s);
  8736. if (!type)
  8737. getSimpleResultType(r, type);
  8738. bool isSet = (type && type->getTypeCode()==type_set);
  8739. r->setResultRaw(s.length(), s.str(), isSet ? ResultFormatXmlSet : ResultFormatXml);
  8740. }
  8741. }
  8742. else
  8743. DBGLOG("WARNING: no matching variable in workunit for input parameter %s", name);
  8744. }
  8745. }
  8746. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  8747. {
  8748. switch ((int)sequence)
  8749. {
  8750. case ResultSequenceStored:
  8751. return w->updateVariableByName(name);
  8752. case ResultSequencePersist:
  8753. return w->updateGlobalByName(name);
  8754. case ResultSequenceInternal:
  8755. case ResultSequenceOnce:
  8756. return w->updateTemporaryByName(name);
  8757. default:
  8758. return w->updateResultBySequence(sequence);
  8759. }
  8760. }
  8761. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  8762. {
  8763. switch ((int)sequence)
  8764. {
  8765. case ResultSequenceStored:
  8766. return w->getVariableByName(name);
  8767. case ResultSequencePersist:
  8768. return w->getGlobalByName(name);
  8769. case ResultSequenceInternal:
  8770. case ResultSequenceOnce:
  8771. return w->getTemporaryByName(name);
  8772. default:
  8773. if (name && name[0])
  8774. return w->getResultByName(name);//name takes precedence over sequence
  8775. else
  8776. return w->getResultBySequence(sequence);
  8777. }
  8778. }
  8779. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  8780. {
  8781. if (wuid) {
  8782. char prefchar;
  8783. unsigned year,month,day,hour,min,sec;
  8784. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  8785. time.set(year, month, day, hour, min, sec, 0, true);
  8786. // time.setDate(year, month, day);
  8787. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  8788. return true;
  8789. }
  8790. }
  8791. return false;
  8792. }
  8793. extern WORKUNIT_API IStringVal& createToken(const char *wuid, const char *user, const char *password, IStringVal &str)
  8794. {
  8795. StringBuffer wu, token("X");
  8796. wu.append(wuid).append(';').append(user).append(';').append(password);
  8797. encrypt(token,wu.str());
  8798. str.set(token.str());
  8799. return str;
  8800. }
  8801. // This will be replaced by something more secure!
  8802. extern WORKUNIT_API void extractToken(const char *token, const char *wuid, IStringVal &user, IStringVal &password)
  8803. {
  8804. if (token && *token)
  8805. {
  8806. StringBuffer wu;
  8807. decrypt(wu, token+1);
  8808. const char *finger = strchr(wu.str(),';');
  8809. if (finger && strnicmp(wuid, wu.str(), finger-wu.str())==0)
  8810. {
  8811. const char *finger1 = strchr(++finger,';');
  8812. if(finger1)
  8813. {
  8814. user.setLen(finger, (size32_t)(finger1-finger));
  8815. finger1++;
  8816. password.setLen(finger1, (size32_t)(wu.str() + wu.length() - finger1));
  8817. return;
  8818. }
  8819. }
  8820. throw MakeStringException(WUERR_InvalidSecurityToken, "Invalid call to extractToken");
  8821. }
  8822. }
  8823. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  8824. {
  8825. return (WUState) getEnum(state, states);
  8826. }
  8827. const LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  8828. class CWorkflowScheduleConnection : implements IWorkflowScheduleConnection, public CInterface
  8829. {
  8830. public:
  8831. CWorkflowScheduleConnection(char const * wuid)
  8832. {
  8833. basexpath.append("/WorkflowSchedule/").append(wuid);
  8834. flagxpath.append(basexpath.str()).append("/Active");
  8835. }
  8836. IMPLEMENT_IINTERFACE;
  8837. virtual void lock()
  8838. {
  8839. LOG(MCschedconn, "Locking base schedule connection");
  8840. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  8841. if(!baseconn)
  8842. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  8843. }
  8844. virtual void unlock()
  8845. {
  8846. LOG(MCschedconn, "Unlocking base schedule connection");
  8847. baseconn.clear();
  8848. }
  8849. virtual void setActive()
  8850. {
  8851. LOG(MCschedconn, "Setting active flag in schedule connection");
  8852. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  8853. if(!flagconn)
  8854. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  8855. }
  8856. virtual void resetActive()
  8857. {
  8858. LOG(MCschedconn, "Resetting active flag in schedule connection");
  8859. flagconn.clear();
  8860. }
  8861. virtual bool queryActive()
  8862. {
  8863. return baseconn->queryRoot()->hasProp("Active");
  8864. }
  8865. virtual bool pull(IWorkflowItemArray * workflow)
  8866. {
  8867. assertex(baseconn);
  8868. Owned<IPropertyTree> root = baseconn->getRoot();
  8869. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  8870. if(!eventQueue) return false;
  8871. if(!eventQueue->hasProp("Item")) return false;
  8872. {
  8873. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  8874. Owned<IPropertyTree> eventItem;
  8875. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  8876. Owned<IRuntimeWorkflowItem> wfItem;
  8877. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  8878. {
  8879. eventItem.setown(&eventItems->get());
  8880. const char * eventName = eventItem->queryProp("@name");
  8881. const char * eventText = eventItem->queryProp("@text");
  8882. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  8883. {
  8884. wfItem.setown(wfItems->get());
  8885. if(wfItem->queryState() != WFStateWait)
  8886. continue;
  8887. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  8888. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  8889. continue;
  8890. wfItem->setEvent(eventName, eventText);
  8891. wfItem->setState(WFStateReqd);
  8892. resetDependentsState(workflow, *wfItem);
  8893. }
  8894. }
  8895. }
  8896. bool more;
  8897. do
  8898. more = eventQueue->removeProp("Item");
  8899. while(more);
  8900. return true;
  8901. }
  8902. virtual void push(char const * name, char const * text)
  8903. {
  8904. assertex(baseconn);
  8905. Owned<IPropertyTree> root = baseconn->getRoot();
  8906. ensurePTree(root, "EventQueue");
  8907. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  8908. Owned<IPropertyTree> eventItem = createPTree();
  8909. eventItem->setProp("@name", name);
  8910. eventItem->setProp("@text", text);
  8911. eventQueue->addPropTree("Item", eventItem.getLink());
  8912. }
  8913. virtual void remove()
  8914. {
  8915. if (baseconn)
  8916. {
  8917. baseconn->close(true);
  8918. baseconn.clear();
  8919. }
  8920. }
  8921. private:
  8922. void resetItemStateAndDependents(IWorkflowItemArray * workflow, unsigned wfid) const
  8923. {
  8924. if (wfid)
  8925. resetItemStateAndDependents(workflow, workflow->queryWfid(wfid));
  8926. }
  8927. void resetItemStateAndDependents(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  8928. {
  8929. switch(item.queryState())
  8930. {
  8931. case WFStateDone:
  8932. case WFStateFail:
  8933. {
  8934. item.setState(WFStateNull);
  8935. resetItemStateAndDependents(workflow, item.queryPersistWfid());
  8936. resetDependentsState(workflow, item);
  8937. break;
  8938. }
  8939. }
  8940. }
  8941. void resetDependentsState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  8942. {
  8943. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  8944. for(iter->first(); iter->isValid(); iter->next())
  8945. {
  8946. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  8947. resetItemStateAndDependents(workflow, dep);
  8948. }
  8949. }
  8950. private:
  8951. StringBuffer basexpath;
  8952. StringBuffer flagxpath;
  8953. Owned<IRemoteConnection> baseconn;
  8954. Owned<IRemoteConnection> flagconn;
  8955. };
  8956. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  8957. {
  8958. return new CWorkflowScheduleConnection(wuid);
  8959. }
  8960. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu)
  8961. {
  8962. return QUERYINTERFACE(wu, IExtendedWUInterface);
  8963. }
  8964. extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu)
  8965. {
  8966. return QUERYINTERFACE(wu, const IExtendedWUInterface);
  8967. }
  8968. extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, ErrorSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column)
  8969. {
  8970. Owned<IWUException> we = wu->createException();
  8971. we->setSeverity(severity);
  8972. we->setExceptionMessage(text);
  8973. if (source)
  8974. we->setExceptionSource(source);
  8975. if (code)
  8976. we->setExceptionCode(code);
  8977. if (filename)
  8978. we->setExceptionFileName(filename);
  8979. if (lineno)
  8980. {
  8981. we->setExceptionLineNo(lineno);
  8982. if (column)
  8983. we->setExceptionColumn(lineno);
  8984. }
  8985. }
  8986. const char * skipLeadingXml(const char * text)
  8987. {
  8988. if (!text)
  8989. return NULL;
  8990. //skip utf8 BOM, probably excessive
  8991. if (memcmp(text, UTF8_BOM, 3) == 0)
  8992. text += 3;
  8993. loop
  8994. {
  8995. if (isspace(*text))
  8996. text++;
  8997. else if (text[0] == '<' && text[1] == '?')
  8998. {
  8999. text += 2;
  9000. loop
  9001. {
  9002. if (!*text) break;
  9003. if (text[0] == '?' && text[1] == '>')
  9004. {
  9005. text += 2;
  9006. break;
  9007. }
  9008. text++;
  9009. }
  9010. }
  9011. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  9012. {
  9013. text += 4;
  9014. loop
  9015. {
  9016. if (!*text) break;
  9017. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  9018. {
  9019. text += 3;
  9020. break;
  9021. }
  9022. text++;
  9023. }
  9024. }
  9025. else
  9026. break;
  9027. }
  9028. return text;
  9029. }
  9030. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  9031. {
  9032. text = skipLeadingXml(text);
  9033. if (!text)
  9034. return false;
  9035. const char * archivePrefix = "<Archive";
  9036. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  9037. }
  9038. extern WORKUNIT_API bool isQueryManifest(const char * text)
  9039. {
  9040. text = skipLeadingXml(text);
  9041. if (!text)
  9042. return false;
  9043. const char * manifestPrefix = "<Manifest";
  9044. return memicmp(text, manifestPrefix, strlen(manifestPrefix)) == 0;
  9045. }
  9046. //------------------------------------------------------------------------------
  9047. // Named Alias helper function
  9048. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  9049. {
  9050. StringBuffer xpath;
  9051. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  9052. return queryRegistry->getPropTree(xpath);
  9053. }
  9054. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  9055. {
  9056. StringBuffer xpath;
  9057. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  9058. return queryRegistry->getPropTree(xpath);
  9059. }
  9060. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  9061. {
  9062. StringBuffer lcId(id);
  9063. lcId.toLowerCase();
  9064. StringBuffer xpath;
  9065. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  9066. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  9067. ForEach(*iter)
  9068. {
  9069. queryRegistry->removeProp(xpath.str());
  9070. }
  9071. }
  9072. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot)
  9073. {
  9074. StringBuffer lcName(name);
  9075. lcName.toLowerCase();
  9076. StringBuffer xpath;
  9077. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  9078. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  9079. unsigned seq = 1;
  9080. ForEach(*iter)
  9081. {
  9082. IPropertyTree &item = iter->query();
  9083. const char *thisWuid = item.queryProp("@wuid");
  9084. if (strieq(wuid, thisWuid))
  9085. return &item;
  9086. unsigned thisSeq = item.getPropInt("@seq");
  9087. if (thisSeq >= seq)
  9088. seq = thisSeq + 1;
  9089. }
  9090. StringBuffer id;
  9091. id.append(lcName).append(".").append(seq);
  9092. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive);
  9093. newEntry->setProp("@name", lcName);
  9094. newEntry->setProp("@wuid", wuid);
  9095. newEntry->setProp("@dll", dll);
  9096. newEntry->setProp("@id", id);
  9097. newEntry->setPropInt("@seq", seq);
  9098. if (library)
  9099. newEntry->setPropBool("@isLibrary", true);
  9100. if (userid && *userid)
  9101. newEntry->setProp("@publishedBy", userid);
  9102. if (snapshot && *snapshot)
  9103. newEntry->setProp("@snapshot", snapshot);
  9104. return queryRegistry->addPropTree("Query", newEntry);
  9105. }
  9106. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  9107. {
  9108. StringBuffer lcId(id);
  9109. lcId.toLowerCase();
  9110. clearAliases(queryRegistry, lcId);
  9111. StringBuffer xpath;
  9112. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  9113. queryRegistry->removeProp(xpath);
  9114. }
  9115. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  9116. {
  9117. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  9118. if (!match)
  9119. return;
  9120. clearAliases(queryRegistry, match->queryProp("@id"));
  9121. queryRegistry->removeTree(match);
  9122. }
  9123. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  9124. {
  9125. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  9126. if (!match)
  9127. return;
  9128. clearAliases(queryRegistry, match->queryProp("@id"));
  9129. queryRegistry->removeTree(match);
  9130. }
  9131. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  9132. {
  9133. clearAliases(queryRegistry, id);
  9134. }
  9135. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  9136. {
  9137. StringBuffer lcName(name);
  9138. lcName.toLowerCase();
  9139. StringBuffer xpath;
  9140. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  9141. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  9142. if (!match)
  9143. {
  9144. IPropertyTree * newEntry = createPTree("Alias");
  9145. newEntry->setProp("@name", lcName);
  9146. match = queryRegistry->addPropTree("Alias", newEntry);
  9147. }
  9148. match->setProp("@id", value);
  9149. }
  9150. extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid)
  9151. {
  9152. if (!queryRegistry || !queryid)
  9153. return NULL;
  9154. StringBuffer xpath;
  9155. xpath.append("Query[@id=\"").append(queryid).append("\"]");
  9156. return queryRegistry->getPropTree(xpath);
  9157. }
  9158. extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly)
  9159. {
  9160. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  9161. return getQueryById(queryRegistry, queryid);
  9162. }
  9163. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  9164. {
  9165. if (!queryRegistry || !alias)
  9166. return NULL;
  9167. StringBuffer xpath;
  9168. unsigned cnt = 0;
  9169. StringBuffer lc(alias);
  9170. const char * search = lc.toLowerCase().str();
  9171. loop
  9172. {
  9173. xpath.set("Alias[@name='").append(search).append("']/@id");
  9174. const char * queryId = queryRegistry->queryProp(xpath);
  9175. if (!queryId)
  9176. break;
  9177. //Check for too many alias indirections.
  9178. if (cnt++ > 10)
  9179. return NULL;
  9180. search = lc.set(queryId).toLowerCase().str();
  9181. }
  9182. return getQueryById(queryRegistry, search);
  9183. }
  9184. extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly)
  9185. {
  9186. Owned<IPropertyTree> queryRegistry = getQueryRegistry(queryset, readonly);
  9187. return resolveQueryAlias(queryRegistry, alias);
  9188. }
  9189. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend, const char *userid)
  9190. {
  9191. StringBuffer lcId(id);
  9192. lcId.toLowerCase();
  9193. StringBuffer xpath;
  9194. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  9195. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  9196. if (tree)
  9197. {
  9198. if (tree->getPropBool("@suspended", false) == suspend)
  9199. return;
  9200. if (suspend)
  9201. {
  9202. tree->addPropBool("@suspended", true);
  9203. if (userid && *userid)
  9204. tree->addProp("@suspendedBy", userid);
  9205. }
  9206. else
  9207. {
  9208. tree->removeProp("@suspended");
  9209. tree->removeProp("@suspendedBy");
  9210. }
  9211. }
  9212. else
  9213. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  9214. }
  9215. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  9216. {
  9217. if (queryComment)
  9218. {
  9219. StringBuffer lcId(id);
  9220. lcId.toLowerCase();
  9221. StringBuffer xpath;
  9222. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  9223. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  9224. if (tree)
  9225. tree->setProp("@queryComment", queryComment);
  9226. else
  9227. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  9228. }
  9229. }
  9230. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  9231. {
  9232. Owned<IRemoteConnection> conn = querySDS().connect("/QuerySets", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  9233. if (conn)
  9234. return conn->getRoot();
  9235. else
  9236. return NULL;
  9237. }
  9238. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries)
  9239. {
  9240. if (!queryTree || !libraries)
  9241. return;
  9242. if (queryTree->hasProp("@libCount")) //already added
  9243. return;
  9244. unsigned libCount=0;
  9245. ForEach(*libraries)
  9246. {
  9247. IConstWULibrary &library = libraries->query();
  9248. SCMStringBuffer libname;
  9249. if (!library.getName(libname).length())
  9250. continue;
  9251. queryTree->addProp("Library", libname.str());
  9252. libCount++;
  9253. }
  9254. queryTree->setPropInt("@libCount", libCount);
  9255. }
  9256. extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw)
  9257. {
  9258. Owned<IConstWULibraryIterator> libraries = &cw->getLibraries();
  9259. checkAddLibrariesToQueryEntry(queryTree, libraries);
  9260. }
  9261. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  9262. {
  9263. //Only lock the branch for the target we're interested in.
  9264. StringBuffer xpath;
  9265. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  9266. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  9267. if (conn)
  9268. return conn->getRoot();
  9269. if (readonly)
  9270. return NULL;
  9271. //Lock the QuerySets in case another thread/client wants to check/add the same QuerySet.
  9272. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  9273. //Re-check if the QuerySet has been added between checking the 1st time and gaining the globalLock.
  9274. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  9275. if (conn)
  9276. return conn->getRoot();
  9277. conn.setown(querySDS().connect("/QuerySets/QuerySet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  9278. if (!conn)
  9279. throwUnexpected();
  9280. IPropertyTree * root = conn->queryRoot();
  9281. root->setProp("@id",wsEclId);
  9282. conn->commit();
  9283. return LINK(root);
  9284. }
  9285. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  9286. {
  9287. StringBuffer xpath;
  9288. StringBuffer lcName(name);
  9289. lcName.toLowerCase();
  9290. // see if "name" already exists
  9291. xpath.append("Package[@id='").append(name).append("']");
  9292. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  9293. if (pkgTree)
  9294. {
  9295. if (overWrite)
  9296. packageRegistry->removeTree(pkgTree);
  9297. else
  9298. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  9299. }
  9300. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  9301. tree->setProp("@id", lcName);
  9302. return tree;
  9303. }
  9304. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  9305. {
  9306. StringBuffer lcId(id);
  9307. lcId.toLowerCase();
  9308. StringBuffer xpath;
  9309. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  9310. packageRegistry->removeProp(xpath);
  9311. }
  9312. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  9313. {
  9314. //Only lock the branch for the target we're interested in.
  9315. StringBuffer xpath;
  9316. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  9317. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  9318. if (conn)
  9319. return conn->getRoot();
  9320. if (readonly)
  9321. return NULL;
  9322. //Lock the PackageSets in case another thread/client wants to check/add the same PackageSet.
  9323. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  9324. //Re-check if the PackageSet has been added between checking the 1st time and gaining the globalLock.
  9325. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  9326. if (conn)
  9327. return conn->getRoot();
  9328. conn.setown(querySDS().connect("/PackageSets/PackageSet", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_ADD, SDS_LOCK_TIMEOUT));
  9329. if (!conn)
  9330. throwUnexpected();
  9331. IPropertyTree* root = conn->queryRoot();
  9332. root->setProp("@id",wsEclId);
  9333. conn->commit();
  9334. return LINK(root);
  9335. }
  9336. void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  9337. {
  9338. StringBuffer cleanQueryName;
  9339. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  9340. SCMStringBuffer dllName;
  9341. Owned<IConstWUQuery> q = workunit->getQuery();
  9342. q->getQueryDllName(dllName);
  9343. if (!dllName.length())
  9344. throw MakeStringException(WUERR_InvalidDll, "Cannot deploy query - no associated dll.");
  9345. StringBuffer currentTargetClusterType;
  9346. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  9347. SCMStringBuffer targetClusterType;
  9348. workunit->getDebugValue("targetclustertype", targetClusterType);
  9349. SCMStringBuffer snapshot;
  9350. workunit->getSnapshot(snapshot);
  9351. if (currentTargetClusterType.length() < 1)
  9352. {
  9353. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  9354. }
  9355. else
  9356. {
  9357. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  9358. {
  9359. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  9360. }
  9361. }
  9362. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, workunit->queryWuid(), dllName.str(), isLibrary(workunit), userid, snapshot.str());
  9363. Owned<IConstWULibraryIterator> libraries = &workunit->getLibraries();
  9364. checkAddLibrariesToQueryEntry(newEntry, libraries);
  9365. newQueryId.append(newEntry->queryProp("@id"));
  9366. workunit->setIsQueryService(true); //will check querysets before delete
  9367. workunit->commit();
  9368. activateQuery(queryRegistry, activateOption, queryName, newQueryId, userid);
  9369. }
  9370. void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid)
  9371. {
  9372. StringBuffer cleanQueryName;
  9373. appendUtf8XmlName(cleanQueryName, strlen(queryName), queryName);
  9374. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  9375. {
  9376. Owned<IPropertyTree> prevQuery = resolveQueryAlias(queryRegistry, cleanQueryName);
  9377. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  9378. if (prevQuery && !streq(queryId, prevQuery->queryProp("@id")))
  9379. {
  9380. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  9381. setQuerySuspendedState(queryRegistry, prevQuery->queryProp("@id"), true, userid);
  9382. else
  9383. removeNamedQuery(queryRegistry, prevQuery->queryProp("@id"));
  9384. }
  9385. }
  9386. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  9387. setQueryAlias(queryRegistry, cleanQueryName, queryId);
  9388. }
  9389. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid)
  9390. {
  9391. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  9392. addQueryToQuerySet(workunit, queryRegistry, queryName, activateOption, newQueryId, userid);
  9393. }
  9394. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  9395. {
  9396. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9397. StringBuffer xpath;
  9398. xpath.appendf("Alias[@name='%s']", alias);
  9399. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  9400. return queryRegistry->removeTree(t);
  9401. }
  9402. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  9403. {
  9404. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  9405. setQueryAlias(queryRegistry, alias, id);
  9406. }
  9407. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid)
  9408. {
  9409. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9410. setQuerySuspendedState(queryRegistry, id, suspend, userid);
  9411. }
  9412. void deleteQuerySetQuery(const char *querySetName, const char *id)
  9413. {
  9414. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9415. removeNamedQuery(queryRegistry, id);
  9416. }
  9417. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  9418. {
  9419. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9420. clearAliases(queryRegistry, id);
  9421. }
  9422. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  9423. {
  9424. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9425. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  9426. }
  9427. const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id)
  9428. {
  9429. if (!queryRegistry)
  9430. return NULL;
  9431. StringBuffer xpath;
  9432. xpath.appendf("Query[@wuid='%s']", wuid);
  9433. if (queryName && *queryName)
  9434. xpath.appendf("[@name='%s']", queryName);
  9435. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  9436. if (q)
  9437. {
  9438. id.set(q->queryProp("@id"));
  9439. }
  9440. return id.str();
  9441. }
  9442. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id)
  9443. {
  9444. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  9445. return queryIdFromQuerySetWuid(queryRegistry, wuid, queryName, id);
  9446. }
  9447. extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset)
  9448. {
  9449. Owned<IConstWULibraryIterator> wulibraries = &cw.getLibraries();
  9450. ForEach(*wulibraries)
  9451. {
  9452. SCMStringBuffer libname;
  9453. IConstWULibrary &wulibrary = wulibraries->query();
  9454. wulibrary.getName(libname);
  9455. if (names.contains(libname.str()) || unresolved.contains(libname.str()))
  9456. continue;
  9457. Owned<IPropertyTree> query = resolveQueryAlias(queryset, libname.str());
  9458. if (query && query->getPropBool("@isLibrary"))
  9459. {
  9460. const char *wuid = query->queryProp("@wuid");
  9461. Owned<IConstWorkUnit> libcw = workunitFactory.openWorkUnit(wuid);
  9462. if (libcw)
  9463. {
  9464. names.appendUniq(libname.str());
  9465. gatherLibraryNames(names, unresolved, workunitFactory, *libcw, queryset);
  9466. continue;
  9467. }
  9468. }
  9469. unresolved.appendUniq(libname.str());
  9470. }
  9471. }
  9472. bool looksLikeAWuid(const char * wuid, const char firstChar)
  9473. {
  9474. if (!wuid)
  9475. return false;
  9476. if (wuid[0] != firstChar)
  9477. return false;
  9478. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  9479. return false;
  9480. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  9481. return false;
  9482. return (wuid[9]=='-');
  9483. }
  9484. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  9485. {
  9486. IPropertyTree * module = archive;
  9487. const char * dot = strrchr(path, '.');
  9488. StringBuffer xpath;
  9489. if (dot)
  9490. {
  9491. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  9492. module = archive->queryPropTree(xpath);
  9493. path = dot+1;
  9494. }
  9495. else
  9496. module = archive->queryPropTree("Module[@key='']");
  9497. if (!module)
  9498. return NULL;
  9499. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  9500. return module->queryPropTree(xpath);
  9501. }
  9502. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity, unsigned maxActivity)
  9503. {
  9504. StringBuffer hostname;
  9505. queryHostIP().getIpText(hostname);
  9506. StringBuffer fullPathname;
  9507. makeAbsolutePath(name, fullPathname);
  9508. query->addAssociatedFile(type, fullPathname, hostname, description, crc, minActivity, maxActivity);
  9509. }
  9510. extern WORKUNIT_API void descheduleWorkunit(char const * wuid)
  9511. {
  9512. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  9513. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  9514. if(workunit)
  9515. workunit->deschedule();
  9516. else
  9517. doDescheduleWorkkunit(wuid);
  9518. }
  9519. extern WORKUNIT_API void updateWorkunitTimeStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value)
  9520. {
  9521. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, description, value, 1, 0, StatsMergeReplace);
  9522. }
  9523. extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer)
  9524. {
  9525. StringBuffer scope;
  9526. for (unsigned i = 0; i < timer->numSections(); i++)
  9527. {
  9528. StatisticScopeType scopeType= timer->getScopeType(i);
  9529. timer->getScope(i, scope.clear());
  9530. StatisticKind kind = timer->getTimerType(i);
  9531. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, timer->getTime(i), timer->getCount(i), timer->getMaxTime(i), StatsMergeReplace);
  9532. }
  9533. }
  9534. extern WORKUNIT_API void getWorkunitTotalTime(IConstWorkUnit* workunit, const char* creator, unsigned __int64 & totalTimeNs, unsigned __int64 & totalThisTimeNs)
  9535. {
  9536. StatisticsFilter summaryTimeFilter(SCTsummary, creator, SSTglobal, GLOBAL_SCOPE, SMeasureTimeNs, StTimeElapsed);
  9537. Owned<IConstWUStatistic> totalThorTime = getStatistic(workunit, summaryTimeFilter);
  9538. Owned<IConstWUStatistic> totalThisThorTime = workunit->getStatistic(queryStatisticsComponentName(), GLOBAL_SCOPE, StTimeElapsed);
  9539. if (totalThorTime)
  9540. totalTimeNs = totalThorTime->getValue();
  9541. else
  9542. totalTimeNs = 0;
  9543. if (totalThisThorTime)
  9544. totalThisTimeNs = totalThisThorTime->getValue();
  9545. else
  9546. totalThisTimeNs = 0;
  9547. }
  9548. extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind)
  9549. {
  9550. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, getTimeStampNowValue(), 1, 0, StatsMergeAppend);
  9551. }
  9552. IConstWUStatistic * getStatistic(IConstWorkUnit * wu, const IStatisticsFilter & filter)
  9553. {
  9554. Owned<IConstWUStatisticIterator> iter = &wu->getStatistics(&filter);
  9555. if (iter->first())
  9556. return &OLINK(iter->query());
  9557. return NULL;
  9558. }
  9559. class GlobalStatisticGatherer : public CInterfaceOf<IStatisticGatherer>
  9560. {
  9561. public:
  9562. GlobalStatisticGatherer(IWorkUnit * _wu) : wu(_wu) {}
  9563. virtual void beginScope(const StatsScopeId & id)
  9564. {
  9565. prevLenStack.append(scope.length());
  9566. if (scope.length())
  9567. scope.append(":");
  9568. id.getScopeText(scope);
  9569. scopeTypeStack.append(id.queryScopeType());
  9570. }
  9571. virtual void beginSubGraphScope(unsigned id)
  9572. {
  9573. StatsScopeId scopeId(SSTsubgraph, id);
  9574. beginScope(scopeId);
  9575. }
  9576. virtual void beginActivityScope(unsigned id)
  9577. {
  9578. StatsScopeId scopeId(SSTactivity, id);
  9579. beginScope(scopeId);
  9580. }
  9581. virtual void beginEdgeScope(unsigned id, unsigned oid)
  9582. {
  9583. StatsScopeId scopeId(SSTedge, id, oid);
  9584. beginScope(scopeId);
  9585. }
  9586. virtual void endScope()
  9587. {
  9588. scope.setLength(prevLenStack.popGet());
  9589. scopeTypeStack.pop();
  9590. }
  9591. virtual void addStatistic(StatisticKind kind, unsigned __int64 value)
  9592. {
  9593. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  9594. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, StatsMergeAppend);
  9595. }
  9596. virtual void updateStatistic(StatisticKind kind, unsigned __int64 value, StatsMergeAction mergeAction)
  9597. {
  9598. StatisticScopeType scopeType = scopeTypeStack.ordinality() ? (StatisticScopeType)scopeTypeStack.tos() : SSTglobal;
  9599. wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, NULL, value, 1, 0, mergeAction);
  9600. }
  9601. virtual IStatisticCollection * getResult()
  9602. {
  9603. return NULL;
  9604. }
  9605. protected:
  9606. Linked<IWorkUnit> wu;
  9607. StringBuffer scope;
  9608. UnsignedArray prevLenStack;
  9609. UnsignedArray scopeTypeStack;
  9610. };
  9611. IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu)
  9612. {
  9613. return new GlobalStatisticGatherer(wu);
  9614. }
  9615. extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly)
  9616. {
  9617. if (!wuid || !*wuid)
  9618. return NULL;
  9619. VStringBuffer path("/GraphProgress/%s", wuid);
  9620. Owned<IRemoteConnection> conn = querySDS().connect(path.str(),myProcessSession(),readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  9621. if (conn)
  9622. return conn->getRoot();
  9623. else
  9624. return NULL;
  9625. }