workunit.cpp 349 KB

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