workunit.cpp 288 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #include "jlib.hpp"
  15. #include "workunit.hpp"
  16. #include "jprop.hpp"
  17. #include "jmisc.hpp"
  18. #include "jexcept.hpp"
  19. #include "jiter.ipp"
  20. #include "jptree.hpp"
  21. #include "jtime.ipp"
  22. #include "jencrypt.hpp"
  23. #include "eclrtl.hpp"
  24. #include "deftype.hpp"
  25. #include <time.h>
  26. #include "mpbase.hpp"
  27. #include "daclient.hpp"
  28. #include "dadfs.hpp"
  29. #include "dafdesc.hpp"
  30. #include "dasds.hpp"
  31. #include "danqs.hpp"
  32. #include "dautils.hpp"
  33. #include "dllserver.hpp"
  34. #include "thorhelper.hpp"
  35. #include "workflow.hpp"
  36. #include "nbcd.hpp"
  37. #include "seclib.hpp"
  38. #include "wuerror.hpp"
  39. #include "wujobq.hpp"
  40. #define GLOBAL_WORKUNIT "global"
  41. #define SDS_LOCK_TIMEOUT (5*60*1000) // 5mins, 30s a bit short
  42. static int workUnitTraceLevel = 1;
  43. static StringBuffer &getXPath(StringBuffer &wuRoot, const char *wuid)
  44. {
  45. // MORE - can fold in the date
  46. return wuRoot.append("/WorkUnits/").append(wuid);
  47. }
  48. //To be called by eclserver, but esp etc. won't know, so we need to store it.
  49. static StringBuffer & appendLibrarySuffix(StringBuffer & suffix)
  50. {
  51. #ifdef _WIN32
  52. suffix.append("W");
  53. #else
  54. suffix.append("L");
  55. #endif
  56. #ifdef __64BIT__
  57. suffix.append("64");
  58. #else
  59. suffix.append("32");
  60. #endif
  61. return suffix;
  62. }
  63. typedef MapStringTo<bool> UniqueScopes;
  64. static void wuAccessError(const char *username, const char *action, const char *wuscope, const char *wuid, bool excpt, bool log)
  65. {
  66. StringBuffer err;
  67. err.append("Workunit Access Denied - action: ").append(action).append(" user:").append(username ? username : "<Unknown>");
  68. if (wuid)
  69. err.append(" workunit:").append(wuid);
  70. if (wuscope)
  71. err.append(" scope:").append(wuscope);
  72. //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
  73. SYSLOG(AUDIT_TYPE_ACCESS_FAILURE, err.str());
  74. if (log)
  75. LOG(MCuserError, "%s", err.str());
  76. if (excpt)
  77. throw MakeStringException(WUERR_AccessError, "%s", err.str());
  78. }
  79. static bool checkWuScopeSecAccess(const char *wuscope, ISecManager &secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  80. {
  81. bool ret=(!secuser) ? true : (secmgr.authorizeEx(RT_WORKUNIT_SCOPE, *secuser, wuscope)>=required);
  82. if (!ret && (log || excpt))
  83. wuAccessError(secuser ? secuser->getName() : NULL, action, wuscope, NULL, excpt, log);
  84. return ret;
  85. }
  86. static bool checkWuScopeListSecAccess(const char *wuscope, ISecResourceList *scopes, int required, const char *action, bool excpt, bool log)
  87. {
  88. if (!scopes)
  89. return true;
  90. bool ret=true;
  91. if (wuscope)
  92. {
  93. Owned<ISecResource> res=scopes->getResource(wuscope);
  94. if (!res || res->getAccessFlags()<required)
  95. ret=false;
  96. }
  97. else
  98. {
  99. for (int seq=0; ret && seq<scopes->count(); seq++)
  100. {
  101. ISecResource *res=scopes->queryResource(seq);
  102. if (res && res->getAccessFlags()<required)
  103. return false;
  104. }
  105. }
  106. if (!ret && (log || excpt))
  107. wuAccessError(NULL, action, wuscope, NULL, excpt, log);
  108. return ret;
  109. }
  110. static bool checkWuSecAccess(IConstWorkUnit &cw, ISecManager &secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  111. {
  112. SCMStringBuffer wuscope;
  113. bool ret=(!secuser) ? true : (secmgr.authorizeEx(RT_WORKUNIT_SCOPE, *secuser, cw.getWuScope(wuscope).str())>=required);
  114. if (!ret && (log || excpt))
  115. {
  116. SCMStringBuffer wuid;
  117. wuAccessError(secuser ? secuser->getName() : NULL, action, wuscope.str(), cw.getWuid(wuid).str(), excpt, log);
  118. }
  119. return ret;
  120. }
  121. static bool checkWuSecAccess(const char *wuid, ISecManager &secmgr, ISecUser *secuser, int required, const char *action, bool excpt, bool log)
  122. {
  123. StringBuffer wuRoot;
  124. Owned<IRemoteConnection> conn = querySDS().connect(getXPath(wuRoot, wuid).str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  125. if (conn)
  126. {
  127. Owned<IPropertyTree> ptree=conn->getRoot();
  128. return checkWuScopeSecAccess(ptree->queryProp("@scope"), secmgr, secuser, required, action, excpt, log);
  129. }
  130. return false;
  131. }
  132. #define PROGRESS_FORMAT_V 2
  133. class CConstGraphProgress : public CInterface, implements IConstWUGraphProgress
  134. {
  135. class CGraphProgress : public CInterface, implements IWUGraphProgress
  136. {
  137. CConstGraphProgress &parent;
  138. public:
  139. IMPLEMENT_IINTERFACE;
  140. CGraphProgress(CConstGraphProgress &_parent) : parent(_parent)
  141. {
  142. parent.lockWrite();
  143. }
  144. ~CGraphProgress()
  145. {
  146. parent.unlock();
  147. }
  148. virtual IPropertyTree * queryProgressTree() { return parent.queryProgressTree(); }
  149. virtual WUGraphState queryGraphState() { return parent.queryGraphState(); }
  150. virtual WUGraphState queryNodeState(WUGraphIDType nodeId) { return parent.queryNodeState(nodeId); }
  151. virtual IWUGraphProgress * update() { return parent.update(); }
  152. virtual unsigned queryFormatVersion() { return parent.queryFormatVersion(); }
  153. virtual IPropertyTree & updateEdge(WUGraphIDType nodeId, const char *edgeId)
  154. {
  155. return parent.updateEdge(nodeId, edgeId);
  156. }
  157. virtual IPropertyTree & updateNode(WUGraphIDType nodeId, WUNodeIDType id)
  158. {
  159. return parent.updateNode(nodeId, id);
  160. }
  161. virtual void setGraphState(WUGraphState state)
  162. {
  163. parent.setGraphState(state);
  164. }
  165. virtual void setNodeState(WUGraphIDType nodeId, WUGraphState state)
  166. {
  167. parent.setNodeState(nodeId, state);
  168. }
  169. };
  170. IPropertyTree &updateElement(WUGraphIDType nodeId, const char *elemName, const char *id)
  171. {
  172. IPropertyTree *elem = NULL;
  173. if (!connectedWrite) lockWrite();
  174. StringBuffer path;
  175. path.append("node[@id=\"").append(nodeId).append("\"]");
  176. IPropertyTree *node = progress->queryPropTree(path.str());
  177. if (!node)
  178. {
  179. node = progress->addPropTree("node", createPTree());
  180. node->setPropInt("@id", (int)nodeId);
  181. elem = node->addPropTree(elemName, createPTree());
  182. elem->setProp("@id", id);
  183. }
  184. else
  185. {
  186. path.clear().append(elemName).append("[@id=\"").append(id).append("\"]");
  187. elem = node->queryPropTree(path.str());
  188. if (!elem)
  189. {
  190. elem = node->addPropTree(elemName, createPTree());
  191. elem->setProp("@id", id);
  192. }
  193. }
  194. return *elem;
  195. }
  196. public:
  197. IMPLEMENT_IINTERFACE;
  198. static void deleteWuidProgress(const char *wuid)
  199. {
  200. StringBuffer path("/GraphProgress/");
  201. path.append(wuid);
  202. Owned<IRemoteConnection> conn = querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  203. if (conn)
  204. conn->close(true);
  205. }
  206. CConstGraphProgress(const char *_wuid, const char *_graphName) : wuid(_wuid), graphName(_graphName)
  207. {
  208. rootPath.append("/GraphProgress/").append(wuid).append('/').append(graphName).append('/');
  209. connected = connectedWrite = false;
  210. formatVersion = 0;
  211. }
  212. void connect()
  213. {
  214. conn.clear();
  215. packProgress(wuid,false);
  216. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_READ|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  217. progress = conn->queryRoot();
  218. formatVersion = progress->getPropInt("@format");
  219. connected = true;
  220. }
  221. void lockWrite()
  222. {
  223. if (connectedWrite) return;
  224. // JCSMORE - look at using changeMode here.
  225. if (conn)
  226. conn.clear();
  227. else
  228. packProgress(wuid,false);
  229. conn.setown(querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  230. progress = conn->queryRoot();
  231. if (!progress->hasChildren()) // i.e. blank.
  232. {
  233. formatVersion = PROGRESS_FORMAT_V;
  234. progress->setPropInt("@format", PROGRESS_FORMAT_V);
  235. }
  236. else
  237. formatVersion = progress->getPropInt("@format");
  238. connected = connectedWrite = true;
  239. }
  240. void unlock()
  241. {
  242. connected = false;
  243. connectedWrite = false;
  244. conn.clear();
  245. }
  246. IPropertyTree &updateNode(WUGraphIDType nodeId, WUNodeIDType id)
  247. {
  248. StringBuffer s;
  249. return updateElement(nodeId, "node", s.append(id).str());
  250. }
  251. IPropertyTree &updateEdge(WUGraphIDType nodeId, const char *edgeId)
  252. {
  253. return updateElement(nodeId, "edge", edgeId);
  254. }
  255. static bool getRunningGraph(const char *wuid, IStringVal &graphName, WUGraphIDType &subId)
  256. {
  257. StringBuffer path;
  258. Owned<IRemoteConnection> conn = querySDS().connect(path.append("/GraphProgress/").append(wuid).str(), myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  259. if (!conn) return false;
  260. const char *name = conn->queryRoot()->queryProp("Running/@graph");
  261. if (name)
  262. {
  263. graphName.set(name);
  264. subId = conn->queryRoot()->getPropInt64("Running/@subId");
  265. return true;
  266. }
  267. else
  268. return false;
  269. }
  270. void setGraphState(WUGraphState state)
  271. {
  272. progress->setPropInt("@_state", (unsigned)state);
  273. }
  274. void setNodeState(WUGraphIDType nodeId, WUGraphState state)
  275. {
  276. if (!connectedWrite) lockWrite();
  277. StringBuffer path;
  278. path.append("node[@id=\"").append(nodeId).append("\"]");
  279. IPropertyTree *node = progress->queryPropTree(path.str());
  280. if (!node)
  281. {
  282. node = progress->addPropTree("node", createPTree());
  283. node->setPropInt("@id", (int)nodeId);
  284. }
  285. node->setPropInt("@_state", (unsigned)state);
  286. switch (state)
  287. {
  288. case WUGraphRunning:
  289. {
  290. StringBuffer path;
  291. Owned<IRemoteConnection> conn = querySDS().connect(path.append("/GraphProgress/").append(wuid).str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  292. IPropertyTree *running = conn->queryRoot()->setPropTree("Running", createPTree());
  293. running->setProp("@graph", graphName);
  294. running->setPropInt64("@subId", nodeId);
  295. break;
  296. }
  297. case WUGraphComplete:
  298. {
  299. StringBuffer path;
  300. Owned<IRemoteConnection> conn = querySDS().connect(path.append("/GraphProgress/").append(wuid).str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  301. conn->queryRoot()->removeProp("Running"); // only one thing running at any given time and one thing with lockWrite access
  302. break;
  303. }
  304. }
  305. }
  306. virtual IPropertyTree * queryProgressTree()
  307. {
  308. if (!connected) connect();
  309. return progress;
  310. }
  311. virtual WUGraphState queryGraphState()
  312. {
  313. return (WUGraphState)queryProgressTree()->getPropInt("@_state", (unsigned)WUGraphUnknown);
  314. }
  315. virtual WUGraphState queryNodeState(WUGraphIDType nodeId)
  316. {
  317. StringBuffer path;
  318. path.append("node[@id=\"").append(nodeId).append("\"]/@_state");
  319. return (WUGraphState)queryProgressTree()->getPropInt(path.str(), (unsigned)WUGraphUnknown);
  320. }
  321. virtual IWUGraphProgress * update()
  322. {
  323. return new CGraphProgress(*this);
  324. }
  325. virtual unsigned queryFormatVersion()
  326. {
  327. if (!connected) connect();
  328. return formatVersion;
  329. }
  330. static bool packProgress(const char *wuid,bool pack)
  331. {
  332. StringBuffer path;
  333. path.append("/GraphProgress/").append(wuid);
  334. Owned<IRemoteConnection> conn(querySDS().connect(path.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT));
  335. if (!conn)
  336. return false;
  337. Owned<IPropertyTree> newt;
  338. MemoryBuffer buf;
  339. IPropertyTree *root = conn->queryRoot();
  340. if (root->getPropBin("Packed",buf)) {
  341. if (pack)
  342. return true;
  343. newt.setown(createPTree(buf));
  344. IPropertyTree *running = root->queryPropTree("Running");
  345. if (running)
  346. newt->setPropTree("Running",createPTreeFromIPT(running));
  347. }
  348. else {
  349. if (!pack)
  350. return true;
  351. newt.setown(createPTree(wuid));
  352. IPropertyTree *running = root->queryPropTree("Running");
  353. if (running) {
  354. newt->setPropTree("Running",createPTreeFromIPT(running));
  355. root->removeTree(running);
  356. }
  357. root->serialize(buf);
  358. newt->setPropBin("Packed",buf.length(),buf.bufferBase());
  359. }
  360. root->setPropTree(NULL,newt.getClear());
  361. return true;
  362. }
  363. private:
  364. Owned<IRemoteConnection> conn;
  365. IPropertyTree* progress;
  366. StringAttr wuid, graphName;
  367. StringBuffer rootPath;
  368. bool connected, connectedWrite;
  369. unsigned formatVersion;
  370. };
  371. class CLocalWUTimeStamp : public CInterface, implements IConstWUTimeStamp
  372. {
  373. Owned<IPropertyTree> p;
  374. public:
  375. IMPLEMENT_IINTERFACE;
  376. CLocalWUTimeStamp(IPropertyTree *p);
  377. virtual IStringVal & getApplication(IStringVal & str) const;
  378. virtual IStringVal & getEvent(IStringVal & str) const;
  379. virtual IStringVal & getDate(IStringVal & dt) const;
  380. };
  381. class CLocalWUAppValue : public CInterface, implements IConstWUAppValue
  382. {
  383. Owned<IPropertyTree> p;
  384. StringBuffer prop;
  385. public:
  386. IMPLEMENT_IINTERFACE;
  387. CLocalWUAppValue(IPropertyTree *p,unsigned child);
  388. virtual IStringVal & getApplication(IStringVal & str) const;
  389. virtual IStringVal & getName(IStringVal & str) const;
  390. virtual IStringVal & getValue(IStringVal & dt) const;
  391. };
  392. template <typename T, typename IT> struct CachedTags
  393. {
  394. CachedTags(): cached(false) {}
  395. void load(IPropertyTree* p,const char* xpath)
  396. {
  397. if (!cached)
  398. {
  399. assertex(tags.length() == 0);
  400. Owned<IPropertyTreeIterator> r = p->getElements(xpath);
  401. for (r->first(); r->isValid(); r->next())
  402. {
  403. IPropertyTree *rp = &r->query();
  404. rp->Link();
  405. tags.append(*new T(rp));
  406. }
  407. cached = true;
  408. }
  409. }
  410. operator IArrayOf<IT>&() { return tags; }
  411. void kill()
  412. {
  413. cached = false;
  414. tags.kill();
  415. }
  416. bool cached;
  417. IArrayOf<IT> tags;
  418. };
  419. template <> struct CachedTags<CLocalWUAppValue, IConstWUAppValue>
  420. {
  421. CachedTags(): cached(false) {}
  422. void load(IPropertyTree* p,const char* xpath)
  423. {
  424. if (!cached)
  425. {
  426. assertex(tags.length() == 0);
  427. Owned<IPropertyTreeIterator> r = p->getElements(xpath);
  428. for (r->first(); r->isValid(); r->next())
  429. {
  430. IPropertyTree *rp = &r->query();
  431. Owned<IPropertyTreeIterator> v = rp->getElements("*");
  432. unsigned pos = 1;
  433. for (v->first(); v->isValid(); v->next())
  434. {
  435. rp->Link();
  436. tags.append(*new CLocalWUAppValue(rp,pos++));
  437. }
  438. }
  439. cached = true;
  440. }
  441. }
  442. operator IArrayOf<IConstWUAppValue>&() { return tags; }
  443. void kill()
  444. {
  445. cached = false;
  446. tags.kill();
  447. }
  448. bool cached;
  449. IArrayOf<IConstWUAppValue> tags;
  450. };
  451. class CLocalWorkUnit : public CInterface, implements IConstWorkUnit , implements ISDSSubscription, implements IExtendedWUInterface
  452. {
  453. friend StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str);
  454. friend void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags);
  455. // NOTE - order is important - we need to construct connection before p and (especially) destruct after p
  456. Owned<IRemoteConnection> connection;
  457. Owned<IPropertyTree> p;
  458. bool dirty;
  459. bool connectAtRoot;
  460. mutable bool abortDirty;
  461. mutable bool abortState;
  462. mutable CriticalSection crit;
  463. mutable Owned<IWUQuery> query;
  464. mutable Owned<IWUWebServicesInfo> webServicesInfo;
  465. mutable Owned<IWURoxieQueryInfo> roxieQueryInfo;
  466. mutable Owned<IWorkflowItemIterator> workflowIterator;
  467. mutable bool workflowIteratorCached;
  468. mutable bool resultsCached;
  469. mutable bool temporariesCached;
  470. mutable bool variablesCached;
  471. mutable bool exceptionsCached;
  472. mutable bool pluginsCached;
  473. mutable bool librariesCached;
  474. mutable bool activitiesCached;
  475. mutable bool webServicesInfoCached;
  476. mutable bool roxieQueryInfoCached;
  477. mutable IArrayOf<IWUActivity> activities;
  478. mutable IArrayOf<IWUPlugin> plugins;
  479. mutable IArrayOf<IWULibrary> libraries;
  480. mutable IArrayOf<IWUException> exceptions;
  481. mutable IArrayOf<IWUGraph> graphs;
  482. mutable IArrayOf<IWUResult> results;
  483. mutable IArrayOf<IWUResult> temporaries;
  484. mutable IArrayOf<IWUResult> variables;
  485. mutable CachedTags<CLocalWUTimeStamp,IConstWUTimeStamp> timestamps;
  486. mutable CachedTags<CLocalWUAppValue,IConstWUAppValue> appvalues;
  487. mutable Owned<IUserDescriptor> userDesc;
  488. Mutex locked;
  489. Owned<ISecManager> secMgr;
  490. Owned<ISecUser> secUser;
  491. mutable Owned<IPropertyTree> cachedGraphs;
  492. public:
  493. IMPLEMENT_IINTERFACE;
  494. CLocalWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser, const char *parentWuid = NULL);
  495. CLocalWorkUnit(IRemoteConnection *_conn, IPropertyTree* root, ISecManager *secmgr, ISecUser *secuser);
  496. ~CLocalWorkUnit();
  497. CLocalWorkUnit(const char *dummyWuid, const char *parentWuid, ISecManager *secmgr, ISecUser *secuser);
  498. ISecManager *querySecMgr(){return secMgr.get();}
  499. ISecUser *querySecUser(){return secUser.get();}
  500. void setSecIfcs(ISecManager *mgr, ISecUser*usr){secMgr.set(mgr); secUser.set(usr);}
  501. virtual bool aborting() const;
  502. virtual void forceReload();
  503. virtual WUAction getAction() const;
  504. virtual IStringVal& getActionEx(IStringVal & str) const;
  505. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const;
  506. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const;
  507. virtual IConstWUAppValueIterator & getApplicationValues() const;
  508. virtual bool hasWorkflow() const;
  509. virtual unsigned queryEventScheduledCount() const;
  510. virtual IPropertyTree * queryWorkflowTree() const;
  511. virtual IConstWorkflowItemIterator * getWorkflowItems() const;
  512. virtual IWorkflowItemArray * getWorkflowClone() const;
  513. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const;
  514. virtual bool requiresLocalFileUpload() const;
  515. virtual bool getIsQueryService() const;
  516. virtual IStringVal & getClusterName(IStringVal & str) const;
  517. virtual unsigned getCombineQueries() const;
  518. virtual WUCompareMode getCompareMode() const;
  519. virtual IStringVal & getCustomerId(IStringVal & str) const;
  520. virtual bool hasDebugValue(const char * propname) const;
  521. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const;
  522. virtual IStringIterator & getDebugValues() const;
  523. virtual IStringIterator & getDebugValues(const char *prop) const;
  524. virtual int getDebugValueInt(const char * propname, int defVal) const;
  525. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const;
  526. virtual bool getDebugValueBool(const char * propname, bool defVal) const;
  527. virtual unsigned getExceptionCount() const;
  528. virtual IConstWUExceptionIterator & getExceptions() const;
  529. virtual IConstWUResult * getGlobalByName(const char * name) const;
  530. virtual unsigned getGraphCount() const;
  531. virtual unsigned getSourceFileCount() const;
  532. virtual unsigned getResultCount() const;
  533. virtual unsigned getVariableCount() const;
  534. virtual unsigned getTimerCount() const;
  535. virtual unsigned getApplicationValueCount() const;
  536. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const;
  537. virtual IConstWUGraph * getGraph(const char *name) const;
  538. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const;
  539. virtual IStringVal & getJobName(IStringVal & str) const;
  540. virtual IStringVal & getParentWuid(IStringVal & str) const;
  541. virtual IConstWUPlugin * getPluginByName(const char * name) const;
  542. virtual IConstWUPluginIterator & getPlugins() const;
  543. virtual IConstWULibraryIterator & getLibraries() const;
  544. virtual WUPriorityClass getPriority() const;
  545. virtual int getPriorityLevel() const;
  546. virtual int getPriorityValue() const;
  547. virtual IConstWUQuery * getQuery() const;
  548. virtual bool getRescheduleFlag() const;
  549. virtual IConstWUResult * getResultByName(const char * name) const;
  550. virtual IConstWUResult * getResultBySequence(unsigned seq) const;
  551. virtual unsigned getResultLimit() const;
  552. virtual IConstWUResultIterator & getResults() const;
  553. virtual IConstWUActivityIterator& getActivities() const;
  554. virtual IConstWUActivity* getActivity(__int64 id) const;
  555. virtual IStringVal & getScope(IStringVal & str) const;
  556. virtual IStringVal & getSecurityToken(IStringVal & str) const;
  557. virtual WUState getState() const;
  558. virtual IStringVal & getStateEx(IStringVal & str) const;
  559. virtual __int64 getAgentSession() const;
  560. virtual unsigned getAgentPID() const;
  561. virtual IStringVal & getStateDesc(IStringVal & str) const;
  562. virtual IConstWUResult * getTemporaryByName(const char * name) const;
  563. virtual IConstWUResultIterator & getTemporaries() const;
  564. virtual unsigned getTimerCount(const char * timerName, const char * instance) const;
  565. virtual unsigned getTimerDuration(const char * timerName, const char * instance) const;
  566. virtual IStringIterator & getTimers() const;
  567. virtual IConstWUTimeStampIterator & getTimeStamps() const;
  568. virtual IConstWUWebServicesInfo * getWebServicesInfo() const;
  569. virtual IConstWURoxieQueryInfo * getRoxieQueryInfo() const;
  570. virtual IStringVal & getXmlParams(IStringVal & params) const;
  571. virtual const IPropertyTree *getXmlParams() const;
  572. virtual unsigned __int64 getHash() const;
  573. virtual bool getWuDate(unsigned & year, unsigned & month, unsigned& day);
  574. virtual IStringVal & getSnapshot(IStringVal & str) const;
  575. virtual IStringVal & getTimeStamp(const char * name, const char * instance, IStringVal & str) const;
  576. virtual IStringVal & getUser(IStringVal & str) const;
  577. virtual IStringVal & getWuScope(IStringVal & str) const;
  578. virtual IConstWUResult * getVariableByName(const char * name) const;
  579. virtual IConstWUResultIterator & getVariables() const;
  580. virtual IStringVal & getWuid(IStringVal & str) const;
  581. virtual bool getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const;
  582. virtual bool isProtected() const;
  583. virtual bool isPausing() const;
  584. virtual bool isBilled() const;
  585. virtual IWorkUnit& lock();
  586. virtual bool reload();
  587. virtual void requestAbort();
  588. virtual void subscribe(WUSubscribeOptions options);
  589. virtual unsigned calculateHash(unsigned prevHash);
  590. virtual void copyWorkUnit(IConstWorkUnit *cached);
  591. virtual unsigned queryFileUsage(const char *filename) const;
  592. virtual bool getCloneable() const;
  593. virtual IUserDescriptor * getUserDescriptor() const;
  594. virtual unsigned getCodeVersion() const;
  595. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const;
  596. virtual IPropertyTree * getDiskUsageStats();
  597. virtual IPropertyTreeIterator & getFileIterator() const;
  598. virtual bool archiveWorkUnit(const char *base,bool del,bool ignoredllerrors,bool deleteOwned);
  599. virtual void packWorkUnit(bool pack=true);
  600. virtual IDateTime & getTimeScheduled(IDateTime &val) const;
  601. virtual IPropertyTreeIterator & getFilesReadIterator() const;
  602. virtual void protect(bool protectMode);
  603. virtual IConstWULibrary * getLibraryByName(const char * name) const;
  604. virtual unsigned getDebugAgentListenerPort() const;
  605. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const;
  606. void clearExceptions();
  607. void commit();
  608. IWUException *createException();
  609. void setTimeStamp(const char *name, const char *instance, const char *event);
  610. void addTimeStamp(const char * name, const char * instance, const char *event);
  611. void setAction(WUAction action);
  612. void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite);
  613. void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite);
  614. void incEventScheduledCount();
  615. void setIsQueryService(bool value);
  616. void setCloneable(bool value);
  617. void setIsClone(bool value);
  618. void setClusterName(const char * value);
  619. void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion);
  620. void setCombineQueries(unsigned combine);
  621. void setCompareMode(WUCompareMode value);
  622. void setCustomerId(const char * value);
  623. void setDebugValue(const char * propname, const char * value, bool overwrite);
  624. void setDebugValueInt(const char * propname, int value, bool overwrite);
  625. void setJobName(const char * value);
  626. void setPriority(WUPriorityClass cls);
  627. void setPriorityLevel(int level);
  628. void setRescheduleFlag(bool value);
  629. void setResultLimit(unsigned value);
  630. void setState(WUState state);
  631. void setStateEx(const char * text);
  632. void setAgentSession(__int64 sessionId);
  633. void setAgentPID(unsigned pid);
  634. void setSecurityToken(const char *value);
  635. void setTimerInfo(const char * name, const char * instance, unsigned ms, unsigned count, unsigned max);
  636. void setTracingValue(const char * propname, const char * value);
  637. void setTracingValueInt(const char * propname, int value);
  638. void setUser(const char * value);
  639. void setWuScope(const char * value);
  640. void setBilled(bool billed);
  641. void setSnapshot(const char * value);
  642. void setTimeStamp(const char *application, const char *instance, const char *event, bool add);
  643. void setDebugAgentListenerPort(unsigned port);
  644. void setDebugAgentListenerIP(const char * ip);
  645. void setXmlParams(const char *params);
  646. void setXmlParams(IPropertyTree *tree);
  647. void setHash(unsigned __int64 hash);
  648. IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor);
  649. IWorkflowItemIterator * updateWorkflowItems();
  650. void syncRuntimeWorkflow(IWorkflowItemArray * array);
  651. void resetWorkflow();
  652. void schedule();
  653. void deschedule();
  654. unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag);
  655. IWUResult * updateGlobalByName(const char * name);
  656. IWUGraph * updateGraph(const char * name);
  657. IWUQuery * updateQuery();
  658. IWUWebServicesInfo* updateWebServicesInfo(bool create);
  659. IWURoxieQueryInfo* updateRoxieQueryInfo(const char *wuid, const char *roxieClusterName);
  660. IWUActivity* updateActivity(__int64 id);
  661. IWUPlugin * updatePluginByName(const char * name);
  662. IWULibrary * updateLibraryByName(const char * name);
  663. IWUResult * updateResultByName(const char * name);
  664. IWUResult * updateResultBySequence(unsigned seq);
  665. IWUResult * updateTemporaryByName(const char * name);
  666. IWUResult * updateVariableByName(const char * name);
  667. void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner);
  668. void noteFileRead(IDistributedFile *file);
  669. void releaseFile(const char *fileName);
  670. void clearGraphProgress();
  671. void resetBeforeGeneration();
  672. void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned);
  673. void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId);
  674. void setTimeScheduled(const IDateTime &val);
  675. // ILocalWorkUnit - used for debugging etc
  676. void loadXML(const char *xml);
  677. void serialize(MemoryBuffer &tgt);
  678. void deserialize(MemoryBuffer &src);
  679. IWorkUnit &lockRemote(bool commit);
  680. void unlockRemote(bool closing);
  681. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen=0, const void *valueData=NULL);
  682. void abort();
  683. void cleanupAndDelete(bool deldll,bool deleteOwned);
  684. bool switchThorQueue(const char *cluster, IQueueSwitcher *qs);
  685. void setAllowedClusters(const char *value);
  686. IStringVal & getAllowedClusters(IStringVal & str) const;
  687. void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const;
  688. void setAllowAutoQueueSwitch(bool val);
  689. bool getAllowAutoQueueSwitch() const;
  690. void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash);
  691. private:
  692. void init();
  693. IWUGraph *createGraph();
  694. IWUResult *createResult();
  695. void loadGraphs() const;
  696. void loadResults() const;
  697. void loadTemporaries() const;
  698. void loadVariables() const;
  699. void loadExceptions() const;
  700. void loadPlugins() const;
  701. void loadLibraries() const;
  702. void loadClusters() const;
  703. void loadActivities() const;
  704. void unsubscribe();
  705. void checkAgentRunning(WUState & state);
  706. // MORE - the two could be a bit more similar...
  707. class CWorkUnitWatcher : public CInterface, implements ISDSSubscription
  708. {
  709. ISDSSubscription *parent; // not linked - it links me
  710. SubscriptionId change;
  711. bool sub;
  712. public:
  713. IMPLEMENT_IINTERFACE;
  714. CWorkUnitWatcher(ISDSSubscription *_parent, const char *wuid, bool _sub) : parent(_parent), sub(_sub)
  715. {
  716. StringBuffer wuRoot;
  717. getXPath(wuRoot, wuid);
  718. change = querySDS().subscribe(wuRoot.str(), *this, sub);
  719. }
  720. ~CWorkUnitWatcher()
  721. {
  722. assertex(change==0);
  723. }
  724. bool watchingChildren()
  725. {
  726. return sub;
  727. }
  728. void unsubscribe()
  729. {
  730. querySDS().unsubscribe(change);
  731. change = 0;
  732. }
  733. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  734. {
  735. parent->notify(id, xpath, flags, valueLen, valueData);
  736. }
  737. };
  738. class CWorkUnitAbortWatcher : public CInterface, implements ISDSSubscription
  739. {
  740. CLocalWorkUnit *parent; // not linked - it links me
  741. SubscriptionId abort;
  742. public:
  743. IMPLEMENT_IINTERFACE;
  744. CWorkUnitAbortWatcher(CLocalWorkUnit *_parent, const char *wuid) : parent(_parent)
  745. {
  746. StringBuffer wuRoot;
  747. wuRoot.append("/WorkUnitAborts/").append(wuid);
  748. abort = querySDS().subscribe(wuRoot.str(), *this);
  749. }
  750. ~CWorkUnitAbortWatcher()
  751. {
  752. assertex(abort==0);
  753. }
  754. void unsubscribe()
  755. {
  756. querySDS().unsubscribe(abort);
  757. abort = 0;
  758. }
  759. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  760. {
  761. parent->abort();
  762. }
  763. };
  764. Owned<CWorkUnitAbortWatcher> abortWatcher;
  765. Owned<CWorkUnitWatcher> changeWatcher;
  766. void ensureGraphsUnpacked ()
  767. {
  768. IPropertyTree *t = p->queryPropTree("PackedGraphs");
  769. MemoryBuffer buf;
  770. if (t&&t->getPropBin(NULL,buf)) {
  771. cachedGraphs.clear();
  772. IPropertyTree *st = createPTree(buf);
  773. if (st) {
  774. p->setPropTree("Graphs",st);
  775. p->removeTree(t);
  776. }
  777. }
  778. }
  779. };
  780. class CLockedWorkUnit : public CInterface, implements ILocalWorkUnit, implements IExtendedWUInterface
  781. {
  782. public:
  783. Owned<CLocalWorkUnit> c;
  784. IMPLEMENT_IINTERFACE;
  785. CLockedWorkUnit(CLocalWorkUnit *_c) : c(_c) {}
  786. ~CLockedWorkUnit()
  787. {
  788. if (workUnitTraceLevel > 1)
  789. {
  790. StringAttr x;
  791. StringAttrAdaptor strval(x);
  792. getWuid(strval);
  793. PrintLog("Releasing locked workunit %s", x.get());
  794. }
  795. if (c)
  796. c->unlockRemote(c->IsShared());
  797. }
  798. void setSecIfcs(ISecManager *mgr, ISecUser*usr){c->setSecIfcs(mgr, usr);}
  799. virtual IConstWorkUnit * unlock()
  800. {
  801. c->unlockRemote(c->IsShared());
  802. return c.getClear();
  803. }
  804. virtual bool aborting() const
  805. { return c->aborting(); }
  806. virtual void forceReload()
  807. { UNIMPLEMENTED; }
  808. virtual WUAction getAction() const
  809. { return c->getAction(); }
  810. virtual IStringVal& getActionEx(IStringVal & str) const
  811. { return c->getActionEx(str); }
  812. virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const
  813. { return c->getApplicationValue(application, propname, str); }
  814. virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const
  815. { return c->getApplicationValueInt(application, propname, defVal); }
  816. virtual IConstWUAppValueIterator & getApplicationValues() const
  817. { return c->getApplicationValues(); }
  818. virtual bool hasWorkflow() const
  819. { return c->hasWorkflow(); }
  820. virtual unsigned queryEventScheduledCount() const
  821. { return c->queryEventScheduledCount(); }
  822. virtual IPropertyTree * queryWorkflowTree() const
  823. { return c->queryWorkflowTree(); }
  824. virtual IConstWorkflowItemIterator * getWorkflowItems() const
  825. { return c->getWorkflowItems(); }
  826. virtual IWorkflowItemArray * getWorkflowClone() const
  827. { return c->getWorkflowClone(); }
  828. virtual bool requiresLocalFileUpload() const
  829. { return c->requiresLocalFileUpload(); }
  830. virtual IConstLocalFileUploadIterator * getLocalFileUploads() const
  831. { return c->getLocalFileUploads(); }
  832. virtual bool getIsQueryService() const
  833. { return c->getIsQueryService(); }
  834. virtual bool getCloneable() const
  835. { return c->getCloneable(); }
  836. virtual IUserDescriptor * getUserDescriptor() const
  837. { return c->getUserDescriptor(); }
  838. virtual IStringVal & getClusterName(IStringVal & str) const
  839. { return c->getClusterName(str); }
  840. virtual unsigned getCodeVersion() const
  841. { return c->getCodeVersion(); }
  842. virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  843. { c->getBuildVersion(buildVersion, eclVersion); }
  844. virtual unsigned getCombineQueries() const
  845. { return c->getCombineQueries(); }
  846. virtual WUCompareMode getCompareMode() const
  847. { return c->getCompareMode(); }
  848. virtual IStringVal & getCustomerId(IStringVal & str) const
  849. { return c->getCustomerId(str); }
  850. virtual bool hasDebugValue(const char * propname) const
  851. { return c->hasDebugValue(propname); }
  852. virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const
  853. { return c->getDebugValue(propname, str); }
  854. virtual int getDebugValueInt(const char * propname, int defVal) const
  855. { return c->getDebugValueInt(propname, defVal); }
  856. virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const
  857. { return c->getDebugValueInt64(propname, defVal); }
  858. virtual bool getDebugValueBool(const char * propname, bool defVal) const
  859. { return c->getDebugValueBool(propname, defVal); }
  860. virtual IStringIterator & getDebugValues() const
  861. { return c->getDebugValues(NULL); }
  862. virtual IStringIterator & getDebugValues(const char *prop) const
  863. { return c->getDebugValues(prop); }
  864. virtual unsigned getExceptionCount() const
  865. { return c->getExceptionCount(); }
  866. virtual IConstWUExceptionIterator & getExceptions() const
  867. { return c->getExceptions(); }
  868. virtual unsigned getGraphCount() const
  869. { return c->getGraphCount(); }
  870. virtual unsigned getSourceFileCount() const
  871. { return c->getSourceFileCount(); }
  872. virtual unsigned getResultCount() const
  873. { return c->getResultCount(); }
  874. virtual unsigned getVariableCount() const
  875. { return c->getVariableCount(); }
  876. virtual unsigned getTimerCount() const
  877. { return c->getTimerCount(); }
  878. virtual unsigned getApplicationValueCount() const
  879. { return c->getApplicationValueCount(); }
  880. virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const
  881. { return c->getGraphs(type); }
  882. virtual IConstWUGraph * getGraph(const char *name) const
  883. { return c->getGraph(name); }
  884. virtual IConstWUGraphProgress * getGraphProgress(const char * name) const
  885. { return c->getGraphProgress(name); }
  886. virtual IStringVal & getJobName(IStringVal & str) const
  887. { return c->getJobName(str); }
  888. virtual IStringVal & getParentWuid(IStringVal & str) const
  889. { return c->getParentWuid(str); }
  890. virtual IConstWUPlugin * getPluginByName(const char * name) const
  891. { return c->getPluginByName(name); }
  892. virtual IConstWUPluginIterator & getPlugins() const
  893. { return c->getPlugins(); }
  894. virtual IConstWULibrary* getLibraryByName(const char *name) const
  895. { return c->getLibraryByName(name); }
  896. virtual IConstWULibraryIterator & getLibraries() const
  897. { return c->getLibraries(); }
  898. virtual WUPriorityClass getPriority() const
  899. { return c->getPriority(); }
  900. virtual int getPriorityLevel() const
  901. { return c->getPriorityLevel(); }
  902. virtual int getPriorityValue() const
  903. { return c->getPriorityValue(); }
  904. virtual IConstWUQuery * getQuery() const
  905. { return c->getQuery(); }
  906. virtual IConstWUWebServicesInfo * getWebServicesInfo() const
  907. { return c->getWebServicesInfo(); }
  908. virtual IConstWURoxieQueryInfo* getRoxieQueryInfo() const
  909. { return c->getRoxieQueryInfo(); }
  910. virtual bool getRescheduleFlag() const
  911. { return c->getRescheduleFlag(); }
  912. virtual IConstWUResult * getResultByName(const char * name) const
  913. { return c->getResultByName(name); }
  914. virtual IConstWUResult * getResultBySequence(unsigned seq) const
  915. { return c->getResultBySequence(seq); }
  916. virtual unsigned getResultLimit() const
  917. { return c->getResultLimit(); }
  918. virtual IConstWUResultIterator & getResults() const
  919. { return c->getResults(); }
  920. virtual IConstWUActivityIterator & getActivities() const
  921. { return c->getActivities(); }
  922. virtual IConstWUActivity * getActivity(__int64 id) const
  923. { return c->getActivity(id); }
  924. virtual IStringVal & getScope(IStringVal & str) const
  925. { return c->getScope(str); }
  926. virtual IStringVal & getSecurityToken(IStringVal & str) const
  927. { return c->getSecurityToken(str); }
  928. virtual WUState getState() const
  929. { return c->getState(); }
  930. virtual IStringVal & getStateEx(IStringVal & str) const
  931. { return c->getStateEx(str); }
  932. virtual __int64 getAgentSession() const
  933. { return c->getAgentSession(); }
  934. virtual unsigned getAgentPID() const
  935. { return c->getAgentPID(); }
  936. virtual IStringVal & getStateDesc(IStringVal & str) const
  937. { return c->getStateDesc(str); }
  938. virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const
  939. { return c->getRunningGraph(graphName, subId); }
  940. virtual unsigned getTimerCount(const char * timerName, const char * instance) const
  941. { return c->getTimerCount(timerName, instance); }
  942. virtual unsigned getTimerDuration(const char * timerName, const char * instance) const
  943. { return c->getTimerDuration(timerName, instance); }
  944. virtual IStringVal & getTimeStamp(const char * name, const char * instance, IStringVal & str) const
  945. { return c->getTimeStamp(name, instance, str); }
  946. virtual IStringIterator & getTimers() const
  947. { return c->getTimers(); }
  948. virtual IConstWUTimeStampIterator & getTimeStamps() const
  949. { return c->getTimeStamps(); }
  950. virtual bool getWuDate(unsigned & year, unsigned & month, unsigned& day)
  951. { return c->getWuDate(year,month,day);}
  952. virtual IStringVal & getSnapshot(IStringVal & str) const
  953. { return c->getSnapshot(str); }
  954. virtual IStringVal & getUser(IStringVal & str) const
  955. { return c->getUser(str); }
  956. virtual IStringVal & getWuScope(IStringVal & str) const
  957. { return c->getWuScope(str); }
  958. virtual IStringVal & getWuid(IStringVal & str) const
  959. { return c->getWuid(str); }
  960. virtual IConstWUResult * getGlobalByName(const char * name) const
  961. { return c->getGlobalByName(name); }
  962. virtual IConstWUResult * getTemporaryByName(const char * name) const
  963. { return c->getTemporaryByName(name); }
  964. virtual IConstWUResultIterator & getTemporaries() const
  965. { return c->getTemporaries(); }
  966. virtual IConstWUResult * getVariableByName(const char * name) const
  967. { return c->getVariableByName(name); }
  968. virtual IConstWUResultIterator & getVariables() const
  969. { return c->getVariables(); }
  970. virtual bool isProtected() const
  971. { return c->isProtected(); }
  972. virtual bool isPausing() const
  973. { return c->isPausing(); }
  974. virtual bool isBilled() const
  975. { return c->isBilled(); }
  976. virtual IWorkUnit & lock()
  977. { ((CInterface *)this)->Link(); return (IWorkUnit &) *this; }
  978. virtual bool reload()
  979. { UNIMPLEMENTED; }
  980. virtual void subscribe(WUSubscribeOptions options)
  981. { c->subscribe(options); }
  982. virtual void requestAbort()
  983. { c->requestAbort(); }
  984. virtual unsigned calculateHash(unsigned prevHash)
  985. { return c->calculateHash(prevHash); }
  986. virtual void copyWorkUnit(IConstWorkUnit *cached)
  987. { c->copyWorkUnit(cached); }
  988. virtual bool archiveWorkUnit(const char *base,bool del,bool deldll,bool deleteOwned)
  989. { return c->archiveWorkUnit(base,del,deldll,deleteOwned); }
  990. virtual void packWorkUnit(bool pack)
  991. { c->packWorkUnit(pack); }
  992. virtual unsigned queryFileUsage(const char *filename) const
  993. { return c->queryFileUsage(filename); }
  994. virtual IDateTime & getTimeScheduled(IDateTime &val) const
  995. { return c->getTimeScheduled(val); }
  996. virtual unsigned getDebugAgentListenerPort() const
  997. { return c->getDebugAgentListenerPort(); }
  998. virtual IStringVal & getDebugAgentListenerIP(IStringVal &ip) const
  999. { return c->getDebugAgentListenerIP(ip); }
  1000. virtual IStringVal & getXmlParams(IStringVal & params) const
  1001. { return c->getXmlParams(params); }
  1002. virtual const IPropertyTree *getXmlParams() const
  1003. { return c->getXmlParams(); }
  1004. virtual unsigned __int64 getHash() const
  1005. { return c->getHash(); }
  1006. virtual void clearExceptions()
  1007. { c->clearExceptions(); }
  1008. virtual void commit()
  1009. { c->commit(); }
  1010. virtual IWUException * createException()
  1011. { return c->createException(); }
  1012. virtual void setTimeStamp(const char * name, const char * instance, const char *event)
  1013. { c->setTimeStamp(name, instance, event); }
  1014. virtual void addTimeStamp(const char * name, const char * instance, const char *event)
  1015. { c->addTimeStamp(name, instance, event); }
  1016. virtual void protect(bool protectMode)
  1017. { c->protect(protectMode); }
  1018. virtual void setBilled(bool billed)
  1019. { c->setBilled(billed); }
  1020. virtual void setAction(WUAction action)
  1021. { c->setAction(action); }
  1022. virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite)
  1023. { c->setApplicationValue(application, propname, value, overwrite); }
  1024. virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite)
  1025. { c->setApplicationValueInt(application, propname, value, overwrite); }
  1026. virtual void incEventScheduledCount()
  1027. { c->incEventScheduledCount(); }
  1028. virtual void setIsQueryService(bool value)
  1029. { c->setIsQueryService(value); }
  1030. virtual void setCloneable(bool value)
  1031. { c->setCloneable(value); }
  1032. virtual void setIsClone(bool value)
  1033. { c->setIsClone(value); }
  1034. virtual void setClusterName(const char * value)
  1035. { c->setClusterName(value); }
  1036. virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion)
  1037. { c->setCodeVersion(version, buildVersion, eclVersion); }
  1038. virtual void setCombineQueries(unsigned combine)
  1039. { c->setCombineQueries(combine); }
  1040. virtual void setCompareMode(WUCompareMode value)
  1041. { c->setCompareMode(value); }
  1042. virtual void setCustomerId(const char * value)
  1043. { c->setCustomerId(value); }
  1044. virtual void setDebugValue(const char * propname, const char * value, bool overwrite)
  1045. { c->setDebugValue(propname, value, overwrite); }
  1046. virtual void setDebugValueInt(const char * propname, int value, bool overwrite)
  1047. { c->setDebugValueInt(propname, value, overwrite); }
  1048. virtual void setJobName(const char * value)
  1049. { c->setJobName(value); }
  1050. virtual void setPriority(WUPriorityClass cls)
  1051. { c->setPriority(cls); }
  1052. virtual void setPriorityLevel(int level)
  1053. { c->setPriorityLevel(level); }
  1054. virtual void setRescheduleFlag(bool value)
  1055. { c->setRescheduleFlag(value); }
  1056. virtual void setResultLimit(unsigned value)
  1057. { c->setResultLimit(value); }
  1058. virtual void setSecurityToken(const char *value)
  1059. { c->setSecurityToken(value); }
  1060. virtual void setState(WUState state)
  1061. { c->setState(state); }
  1062. virtual void setStateEx(const char * text)
  1063. { c->setStateEx(text); }
  1064. virtual void setAgentSession(__int64 sessionId)
  1065. { c->setAgentSession(sessionId); }
  1066. virtual void setAgentPID(unsigned pid)
  1067. { c->setAgentPID(pid); }
  1068. virtual void setTimerInfo(const char * name, const char * instance, unsigned ms, unsigned count, unsigned max)
  1069. { c->setTimerInfo(name, instance, ms, count, max); }
  1070. virtual void setTracingValue(const char * propname, const char * value)
  1071. { c->setTracingValue(propname, value); }
  1072. virtual void setTracingValueInt(const char * propname, int value)
  1073. { c->setTracingValueInt(propname, value); }
  1074. virtual void setUser(const char * value)
  1075. { c->setUser(value); }
  1076. virtual void setWuScope(const char * value)
  1077. {
  1078. if (value && *value)
  1079. {
  1080. ISecManager *secmgr=c->querySecMgr();
  1081. ISecUser *secusr=c->querySecUser();
  1082. if (!secmgr || !secusr)
  1083. throw MakeStringException(WUERR_SecurityNotAvailable, "Trying to change workunit scope without security interfaces available");
  1084. if (checkWuScopeSecAccess(value, *secmgr, secusr, SecAccess_Write, "Change Scope", true, true))
  1085. c->setWuScope(value);
  1086. }
  1087. }
  1088. virtual IWorkflowItem* addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  1089. { return c->addWorkflowItem(wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor); }
  1090. virtual void syncRuntimeWorkflow(IWorkflowItemArray * array)
  1091. { c->syncRuntimeWorkflow(array); }
  1092. virtual IWorkflowItemIterator * updateWorkflowItems()
  1093. { return c->updateWorkflowItems(); }
  1094. virtual void resetWorkflow()
  1095. { c->resetWorkflow(); }
  1096. virtual void schedule()
  1097. { c->schedule(); }
  1098. virtual void deschedule()
  1099. { c->deschedule(); }
  1100. virtual unsigned addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  1101. { return c->addLocalFileUpload(type, source, destination, eventTag); }
  1102. virtual IWUResult * updateGlobalByName(const char * name)
  1103. { return c->updateGlobalByName(name); }
  1104. virtual IWUGraph * updateGraph(const char * name)
  1105. { return c->updateGraph(name); }
  1106. virtual IWUQuery * updateQuery()
  1107. { return c->updateQuery(); }
  1108. virtual IWUWebServicesInfo * updateWebServicesInfo(bool create)
  1109. { return c->updateWebServicesInfo(create); }
  1110. virtual IWURoxieQueryInfo * updateRoxieQueryInfo(const char *wuid, const char *roxieClusterName)
  1111. { return c->updateRoxieQueryInfo(wuid, roxieClusterName); }
  1112. virtual IWUActivity * updateActivity(__int64 id)
  1113. { return c->updateActivity(id); }
  1114. virtual IWUPlugin * updatePluginByName(const char * name)
  1115. { return c->updatePluginByName(name); }
  1116. virtual IWULibrary * updateLibraryByName(const char * name)
  1117. { return c->updateLibraryByName(name); }
  1118. virtual IWUResult * updateResultByName(const char * name)
  1119. { return c->updateResultByName(name); }
  1120. virtual IWUResult * updateResultBySequence(unsigned seq)
  1121. { return c->updateResultBySequence(seq); }
  1122. virtual IWUResult * updateTemporaryByName(const char * name)
  1123. { return c->updateTemporaryByName(name); }
  1124. virtual IWUResult * updateVariableByName(const char * name)
  1125. { return c->updateVariableByName(name); }
  1126. virtual void addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  1127. { c->addFile(fileName, clusters, usageCount, fileKind, graphOwner); }
  1128. virtual void noteFileRead(IDistributedFile *file)
  1129. { c->noteFileRead(file); }
  1130. virtual void releaseFile(const char *fileName)
  1131. { c->releaseFile(fileName); }
  1132. virtual void clearGraphProgress()
  1133. { c->clearGraphProgress(); }
  1134. virtual void resetBeforeGeneration()
  1135. { c->resetBeforeGeneration(); }
  1136. virtual void deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  1137. { c->deleteTempFiles(graph, deleteOwned, deleteJobOwned); }
  1138. virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId)
  1139. { c->addDiskUsageStats(avgNodeUsage, minNode, minNodeUsage, maxNode, maxNodeUsage, graphId); }
  1140. virtual IPropertyTree * getDiskUsageStats()
  1141. { return c->getDiskUsageStats(); }
  1142. virtual IPropertyTreeIterator & getFileIterator() const
  1143. { return c->getFileIterator(); }
  1144. virtual IPropertyTreeIterator & getFilesReadIterator() const
  1145. { return c->getFilesReadIterator(); }
  1146. virtual void setSnapshot(const char * value)
  1147. { c->setSnapshot(value); }
  1148. virtual void setTimeScheduled(const IDateTime &val)
  1149. { c->setTimeScheduled(val); }
  1150. virtual void setDebugAgentListenerPort(unsigned port)
  1151. { c->setDebugAgentListenerPort(port); }
  1152. virtual void setDebugAgentListenerIP(const char * ip)
  1153. { c->setDebugAgentListenerIP(ip); }
  1154. virtual void setXmlParams(const char *params)
  1155. { c->setXmlParams(params); }
  1156. virtual void setXmlParams(IPropertyTree *tree)
  1157. { c->setXmlParams(tree); }
  1158. virtual void setHash(unsigned __int64 hash)
  1159. { c->setHash(hash); }
  1160. // ILocalWorkUnit - used for debugging etc
  1161. virtual void loadXML(const char *xml)
  1162. { c->loadXML(xml); }
  1163. virtual void serialize(MemoryBuffer &tgt)
  1164. { c->serialize(tgt); }
  1165. virtual void deserialize(MemoryBuffer &src)
  1166. { c->deserialize(src); }
  1167. virtual bool switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  1168. { return c->switchThorQueue(cluster,qs); }
  1169. virtual void setAllowedClusters(const char *value)
  1170. { c->setAllowedClusters(value); }
  1171. virtual IStringVal& getAllowedClusters(IStringVal &str) const
  1172. { return c->getAllowedClusters(str); }
  1173. virtual void remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  1174. { c->remoteCheckAccess(user,writeaccess); }
  1175. virtual void setAllowAutoQueueSwitch(bool val)
  1176. { c->setAllowAutoQueueSwitch(val); }
  1177. virtual bool getAllowAutoQueueSwitch() const
  1178. { return c->getAllowAutoQueueSwitch(); }
  1179. virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  1180. { c->setLibraryInformation(name, interfaceHash, definitionHash); }
  1181. virtual void setResultInt(const char * name, unsigned sequence, __int64 val)
  1182. {
  1183. Owned<IWUResult> r = updateResult(name, sequence);
  1184. if (r)
  1185. {
  1186. r->setResultInt(val);
  1187. r->setResultStatus(ResultStatusCalculated);
  1188. }
  1189. }
  1190. virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val)
  1191. {
  1192. Owned<IWUResult> r = updateResult(name, sequence);
  1193. if (r)
  1194. {
  1195. r->setResultUInt(val);
  1196. r->setResultStatus(ResultStatusCalculated);
  1197. }
  1198. }
  1199. virtual void setResultReal(const char *name, unsigned sequence, double val)
  1200. {
  1201. Owned<IWUResult> r = updateResult(name, sequence);
  1202. if (r)
  1203. {
  1204. r->setResultReal(val);
  1205. r->setResultStatus(ResultStatusCalculated);
  1206. }
  1207. }
  1208. virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val)
  1209. {
  1210. setResultString(stepname, sequence, strlen(val), val);
  1211. }
  1212. virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val)
  1213. {
  1214. setResultUnicode(stepname, sequence, rtlUnicodeStrlen(val), val);
  1215. }
  1216. virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val)
  1217. {
  1218. doSetResultString(type_string, stepname, sequence, len, val);
  1219. }
  1220. virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val)
  1221. {
  1222. doSetResultString(type_data, stepname, sequence, len, (const char *)val);
  1223. }
  1224. virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val)
  1225. {
  1226. Owned<IWUResult> r = updateResult(name, sequence);
  1227. if (r)
  1228. {
  1229. r->setResultRaw(len, val, ResultFormatRaw);
  1230. r->setResultStatus(ResultStatusCalculated);
  1231. }
  1232. }
  1233. virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *)
  1234. {
  1235. Owned<IWUResult> r = updateResult(name, sequence);
  1236. if (r)
  1237. {
  1238. r->setResultIsAll(isAll);
  1239. r->setResultRaw(len, val, ResultFormatRaw);
  1240. r->setResultStatus(ResultStatusCalculated);
  1241. }
  1242. }
  1243. virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val)
  1244. {
  1245. Owned<IWUResult> r = updateResult(name, sequence);
  1246. if (r)
  1247. {
  1248. r->setResultUnicode((char const *)val, len);
  1249. r->setResultStatus(ResultStatusCalculated);
  1250. }
  1251. }
  1252. virtual void setResultBool(const char *name, unsigned sequence, bool val)
  1253. {
  1254. Owned<IWUResult> r = updateResult(name, sequence);
  1255. if (r)
  1256. {
  1257. r->setResultBool(val);
  1258. r->setResultStatus(ResultStatusCalculated);
  1259. }
  1260. }
  1261. virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val)
  1262. {
  1263. Owned<IWUResult> r = updateResult(name, sequence);
  1264. if (r)
  1265. {
  1266. r->setResultDecimal(val, len);
  1267. r->setResultStatus(ResultStatusCalculated);
  1268. }
  1269. }
  1270. virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend)
  1271. {
  1272. Owned<IWUResult> r = updateResult(name, sequence);
  1273. if (r)
  1274. {
  1275. __int64 totalRows = numRows;
  1276. if (extend)
  1277. {
  1278. totalRows += r->getResultRowCount();
  1279. r->addResultRaw(len, val, ResultFormatRaw);
  1280. }
  1281. else
  1282. r->setResultRaw(len, val, ResultFormatRaw);
  1283. r->setResultStatus(ResultStatusCalculated);
  1284. r->setResultRowCount(totalRows);
  1285. r->setResultTotalRowCount(totalRows);
  1286. }
  1287. }
  1288. protected:
  1289. IWUResult *updateResult(const char *name, unsigned sequence)
  1290. {
  1291. Owned <IWUResult> result = updateWorkUnitResult(this, name, sequence);
  1292. if (result)
  1293. {
  1294. SCMStringBuffer rname;
  1295. if (!result->getResultName(rname).length())
  1296. result->setResultName(name);
  1297. }
  1298. return result.getClear();
  1299. }
  1300. void doSetResultString(type_t type, const char *name, unsigned sequence, int len, const char *val)
  1301. {
  1302. Owned<IWUResult> r = updateResult(name, sequence);
  1303. if (r)
  1304. {
  1305. r->setResultString(val, len);
  1306. r->setResultStatus(ResultStatusCalculated);
  1307. }
  1308. }
  1309. };
  1310. class CLocalWUAssociated : public CInterface, implements IConstWUAssociatedFile
  1311. {
  1312. Owned<IPropertyTree> p;
  1313. public:
  1314. IMPLEMENT_IINTERFACE;
  1315. CLocalWUAssociated(IPropertyTree *p);
  1316. virtual WUFileType getType() const;
  1317. virtual IStringVal & getDescription(IStringVal & ret) const;
  1318. virtual IStringVal & getIp(IStringVal & ret) const;
  1319. virtual IStringVal & getName(IStringVal & ret) const;
  1320. virtual IStringVal & getNameTail(IStringVal & ret) const;
  1321. virtual unsigned getCrc() const;
  1322. };
  1323. class CLocalWUQuery : public CInterface, implements IWUQuery
  1324. {
  1325. Owned<IPropertyTree> p;
  1326. mutable IArrayOf<IConstWUAssociatedFile> associated;
  1327. mutable CriticalSection crit;
  1328. mutable bool associatedCached;
  1329. private:
  1330. void addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const;
  1331. void loadAssociated() const;
  1332. public:
  1333. IMPLEMENT_IINTERFACE;
  1334. CLocalWUQuery(IPropertyTree *p);
  1335. virtual WUQueryType getQueryType() const;
  1336. virtual IStringVal& getQueryText(IStringVal &str) const;
  1337. virtual IStringVal& getQueryShortText(IStringVal &str) const;
  1338. virtual IStringVal& getQueryName(IStringVal &str) const;
  1339. virtual IStringVal& getQueryDllName(IStringVal &str) const;
  1340. virtual unsigned getQueryDllCrc() const;
  1341. virtual IStringVal& getQueryCppName(IStringVal &str) const;
  1342. virtual IStringVal& getQueryResTxtName(IStringVal &str) const;
  1343. virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const;
  1344. virtual IConstWUAssociatedFileIterator& getAssociatedFiles() const;
  1345. virtual void setQueryType(WUQueryType qt);
  1346. virtual void setQueryText(const char *pstr);
  1347. virtual void setQueryName(const char *);
  1348. virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc);
  1349. virtual void removeAssociatedFiles();
  1350. };
  1351. class CLocalWUWebServicesInfo : public CInterface, implements IWUWebServicesInfo
  1352. {
  1353. Owned<IPropertyTree> p;
  1354. mutable CriticalSection crit;
  1355. private:
  1356. public:
  1357. IMPLEMENT_IINTERFACE;
  1358. CLocalWUWebServicesInfo(IPropertyTree *p);
  1359. virtual IStringVal& getModuleName(IStringVal &str) const;
  1360. virtual IStringVal& getAttributeName(IStringVal &str) const;
  1361. virtual IStringVal& getDefaultName(IStringVal &str) const;
  1362. virtual IStringVal& getInfo(const char *name, IStringVal &str) const;
  1363. virtual unsigned getWebServicesCRC() const;
  1364. virtual void setModuleName(const char *);
  1365. virtual void setAttributeName(const char *);
  1366. virtual void setDefaultName(const char *);
  1367. virtual void setInfo(const char *name, const char *info);
  1368. virtual void setWebServicesCRC(unsigned);
  1369. };
  1370. class CLocalWURoxieQueryInfo : public CInterface, implements IWURoxieQueryInfo
  1371. {
  1372. Owned<IPropertyTree> p;
  1373. mutable CriticalSection crit;
  1374. private:
  1375. public:
  1376. IMPLEMENT_IINTERFACE;
  1377. CLocalWURoxieQueryInfo(IPropertyTree *p);
  1378. virtual IStringVal& getQueryInfo(IStringVal &str) const;
  1379. virtual IStringVal& getDefaultPackageInfo(IStringVal &str) const;
  1380. virtual IStringVal& getRoxieClusterName(IStringVal &str) const;
  1381. virtual IStringVal& getWuid(IStringVal &str) const;
  1382. virtual void setQueryInfo(const char *info);
  1383. virtual void setDefaultPackageInfo(const char *, int len);
  1384. virtual void setRoxieClusterName(const char *str);
  1385. virtual void setWuid(const char *str);
  1386. };
  1387. class CLocalWUResult : public CInterface, implements IWUResult
  1388. {
  1389. friend class CLocalWorkUnit;
  1390. Owned<IPropertyTree> p;
  1391. void getSchema(TypeInfoArray &types, StringAttrArray &names, IStringVal * ecl=NULL) const;
  1392. public:
  1393. IMPLEMENT_IINTERFACE;
  1394. CLocalWUResult(IPropertyTree *props);
  1395. ~CLocalWUResult() { try { p.clear(); } catch (IException *E) {E->Release();}}
  1396. virtual WUResultStatus getResultStatus() const;
  1397. virtual IStringVal& getResultName(IStringVal &str) const;
  1398. virtual int getResultSequence() const;
  1399. virtual bool isResultScalar() const;
  1400. virtual IStringVal& getResultXml(IStringVal &str) const;
  1401. virtual unsigned getResultFetchSize() const;
  1402. virtual __int64 getResultTotalRowCount() const;
  1403. virtual __int64 getResultRowCount() const;
  1404. virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const;
  1405. virtual IStringVal& getResultLogicalName(IStringVal &ecl) const;
  1406. virtual IStringVal& getResultKeyField(IStringVal& ecl) const;
  1407. virtual unsigned getResultRequestedRows() const;
  1408. virtual __int64 getResultInt() const;
  1409. virtual bool getResultBool() const;
  1410. virtual double getResultReal() const;
  1411. virtual IStringVal& getResultString(IStringVal & str) const;
  1412. virtual IDataVal& getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1413. virtual IDataVal& getResultUnicode(IDataVal & data) const;
  1414. virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const;
  1415. virtual IStringVal& getResultEclSchema(IStringVal & str) const;
  1416. virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1417. virtual IDataVal& getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const;
  1418. virtual IStringVal& getResultRecordSizeEntry(IStringVal & str) const;
  1419. virtual IStringVal& getResultTransformerEntry(IStringVal & str) const;
  1420. virtual __int64 getResultRowLimit() const;
  1421. virtual IStringVal& getResultFilename(IStringVal & str) const;
  1422. virtual WUResultFormat getResultFormat() const;
  1423. virtual unsigned getResultHash() const;
  1424. virtual bool getResultIsAll() const;
  1425. // interface IWUResult
  1426. virtual void setResultStatus(WUResultStatus status);
  1427. virtual void setResultName(const char *name);
  1428. virtual void setResultSequence(unsigned seq);
  1429. virtual void setResultSchemaRaw(unsigned len, const void *schema);
  1430. virtual void setResultScalar(bool isScalar);
  1431. virtual void setResultRaw(unsigned len, const void *xml, WUResultFormat format);
  1432. virtual void setResultFetchSize(unsigned rows); // 0 means file-loaded
  1433. virtual void setResultTotalRowCount(__int64 rows); // -1 means unknown
  1434. virtual void setResultRowCount(__int64 rows);
  1435. virtual void setResultDataset(const char *ecl, const char *defs);
  1436. virtual void setResultLogicalName(const char *logicalName);
  1437. virtual void setResultKeyField(const char * name);
  1438. virtual void setResultRequestedRows(unsigned req);
  1439. virtual void setResultRecordSizeEntry(const char * val);
  1440. virtual void setResultTransformerEntry(const char * val);
  1441. virtual void setResultInt(__int64 val);
  1442. virtual void setResultReal(double val);
  1443. virtual void setResultBool(bool val);
  1444. virtual void setResultString(const char * val, unsigned length);
  1445. virtual void setResultUnicode(const void * val, unsigned length);
  1446. virtual void setResultData(const void * val, unsigned length);
  1447. virtual void setResultDecimal(const void * val, unsigned length);
  1448. virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format);
  1449. virtual void setResultRowLimit(__int64 value);
  1450. virtual void setResultFilename(const char * name);
  1451. virtual void setResultUInt(unsigned __int64 val);
  1452. virtual void setResultIsAll(bool value);
  1453. virtual void setResultFormat(WUResultFormat format);
  1454. virtual void setResultXML(const char *val);
  1455. };
  1456. class CLocalWUPlugin : public CInterface, implements IWUPlugin
  1457. {
  1458. Owned<IPropertyTree> p;
  1459. public:
  1460. IMPLEMENT_IINTERFACE;
  1461. CLocalWUPlugin(IPropertyTree *p);
  1462. virtual IStringVal& getPluginName(IStringVal &str) const;
  1463. virtual IStringVal& getPluginVersion(IStringVal &str) const;
  1464. virtual bool getPluginThor() const;
  1465. virtual bool getPluginHole() const;
  1466. virtual void setPluginName(const char *str);
  1467. virtual void setPluginVersion(const char *str);
  1468. virtual void setPluginThor(bool on);
  1469. virtual void setPluginHole(bool on);
  1470. };
  1471. class CLocalWULibrary : public CInterface, implements IWULibrary
  1472. {
  1473. Owned<IPropertyTree> p;
  1474. public:
  1475. IMPLEMENT_IINTERFACE;
  1476. CLocalWULibrary(IPropertyTree *p);
  1477. virtual IStringVal & getName(IStringVal & str) const;
  1478. virtual IConstWULibraryActivityIterator * getActivities() const;
  1479. virtual void setName(const char * str);
  1480. virtual void addActivity(unsigned id);
  1481. };
  1482. class CLocalWUGraph : public CInterface, implements IWUGraph
  1483. {
  1484. Owned<IPropertyTree> p;
  1485. mutable Linked<IConstWUGraphProgress> progress;
  1486. StringAttr wuid;
  1487. void mergeProgress(IPropertyTree &tree, IPropertyTree &progressTree, const unsigned &progressV) const;
  1488. public:
  1489. IMPLEMENT_IINTERFACE;
  1490. CLocalWUGraph(IPropertyTree *p, const char *wuid);
  1491. virtual IStringVal & getXGMML(IStringVal & ret, bool mergeProgress) const;
  1492. virtual IStringVal & getDOT(IStringVal & ret) const;
  1493. virtual IStringVal & getName(IStringVal & ret) const;
  1494. virtual IStringVal & getLabel(IStringVal & ret) const;
  1495. virtual IStringVal & getTypeName(IStringVal & ret) const;
  1496. virtual WUGraphType getType() const;
  1497. virtual IPropertyTree * getXGMMLTree(bool mergeProgress) const;
  1498. virtual bool isValid() const;
  1499. virtual void setName(const char *str);
  1500. virtual void setType(WUGraphType type);
  1501. virtual void setXGMML(const char *str);
  1502. virtual void setXGMMLTree(IPropertyTree * tree);
  1503. };
  1504. class CLocalWUActivity : public CInterface, implements IWUActivity
  1505. {
  1506. Owned<IPropertyTree> p;
  1507. public:
  1508. IMPLEMENT_IINTERFACE;
  1509. CLocalWUActivity(IPropertyTree *p, __int64 id = 0);
  1510. virtual __int64 getId() const;
  1511. virtual unsigned getKind() const;
  1512. virtual IStringVal & getHelper(IStringVal & ret) const;
  1513. virtual void setKind(unsigned id);
  1514. virtual void setHelper(const char * str);
  1515. };
  1516. class CLocalWUException : public CInterface, implements IWUException
  1517. {
  1518. Owned<IPropertyTree> p;
  1519. public:
  1520. IMPLEMENT_IINTERFACE;
  1521. CLocalWUException(IPropertyTree *p);
  1522. virtual IStringVal& getExceptionSource(IStringVal &str) const;
  1523. virtual IStringVal& getExceptionMessage(IStringVal &str) const;
  1524. virtual unsigned getExceptionCode() const;
  1525. virtual WUExceptionSeverity getSeverity() const;
  1526. virtual IStringVal & getTimeStamp(IStringVal & dt) const;
  1527. virtual IStringVal & getExceptionFileName(IStringVal & str) const;
  1528. virtual unsigned getExceptionLineNo() const;
  1529. virtual unsigned getExceptionColumn() const;
  1530. virtual void setExceptionSource(const char *str);
  1531. virtual void setExceptionMessage(const char *str);
  1532. virtual void setExceptionCode(unsigned code);
  1533. virtual void setSeverity(WUExceptionSeverity level);
  1534. virtual void setTimeStamp(const char * dt);
  1535. virtual void setExceptionFileName(const char *str);
  1536. virtual void setExceptionLineNo(unsigned r);
  1537. virtual void setExceptionColumn(unsigned c);
  1538. };
  1539. //==========================================================================================
  1540. struct mapEnums { int val; const char *str; };
  1541. const char *getEnumText(int value, mapEnums *map)
  1542. {
  1543. const char *defval = map->str;
  1544. while (map->str)
  1545. {
  1546. if (value==map->val)
  1547. return map->str;
  1548. map++;
  1549. }
  1550. assertex(!"Unexpected value in setEnum");
  1551. return defval;
  1552. }
  1553. void setEnum(IPropertyTree *p, const char *propname, int value, mapEnums *map)
  1554. {
  1555. const char *defval = map->str;
  1556. while (map->str)
  1557. {
  1558. if (value==map->val)
  1559. {
  1560. p->setProp(propname, map->str);
  1561. return;
  1562. }
  1563. map++;
  1564. }
  1565. assertex(!"Unexpected value in setEnum");
  1566. p->setProp(propname, defval);
  1567. }
  1568. static int getEnum(const char *v, mapEnums *map)
  1569. {
  1570. if (v)
  1571. {
  1572. while (map->str)
  1573. {
  1574. if (stricmp(v, map->str)==0)
  1575. return map->val;
  1576. map++;
  1577. }
  1578. assertex(!"Unexpected value in getEnum");
  1579. }
  1580. return 0;
  1581. }
  1582. static int getEnum(IPropertyTree *p, const char *propname, mapEnums *map)
  1583. {
  1584. return getEnum(p->queryProp(propname),map);
  1585. }
  1586. //==========================================================================================
  1587. class CConstWUArrayIterator : public CInterface, implements IConstWorkUnitIterator
  1588. {
  1589. IArrayOf<IConstWorkUnit> w;
  1590. CArrayIteratorOf<IConstWorkUnit,IConstWorkUnitIterator> it;
  1591. public:
  1592. IMPLEMENT_IINTERFACE;
  1593. CConstWUArrayIterator(IRemoteConnection *conn, IArrayOf<IPropertyTree> &trees, ISecManager *secmgr=NULL, ISecUser *secuser=NULL)
  1594. : it(w)
  1595. {
  1596. ForEachItemIn(i,trees) {
  1597. IPropertyTree &tree = trees.item(i);
  1598. tree.Link();
  1599. w.append(*(IConstWorkUnit *) new CLocalWorkUnit(LINK(conn), &tree, secmgr, secuser));
  1600. }
  1601. }
  1602. bool first() { return it.first(); }
  1603. bool isValid() { return it.isValid(); }
  1604. bool next() { return it.next(); }
  1605. IConstWorkUnit & query() { return it.query();}
  1606. };
  1607. //==========================================================================================
  1608. class CStringArrayIterator : public CInterface, implements IStringIterator
  1609. {
  1610. StringArray strings;
  1611. unsigned idx;
  1612. public:
  1613. IMPLEMENT_IINTERFACE;
  1614. CStringArrayIterator() { idx = 0; };
  1615. void append(const char *str) { strings.append(str); }
  1616. virtual bool first() { idx = 0; return strings.isItem(idx); }
  1617. virtual bool next() { idx ++; return strings.isItem(idx); }
  1618. virtual bool isValid() { return strings.isItem(idx); }
  1619. virtual IStringVal & str(IStringVal &s) { s.set(strings.item(idx)); return s; }
  1620. };
  1621. class CCachedJobNameIterator : public CInterface, implements IStringIterator
  1622. {
  1623. Owned<IPropertyTreeIterator> it;
  1624. public:
  1625. IMPLEMENT_IINTERFACE;
  1626. CCachedJobNameIterator(IPropertyTreeIterator *p) : it(p) {};
  1627. virtual bool first() { return it->first(); }
  1628. virtual bool next() { return it->next(); }
  1629. virtual bool isValid() { return it->isValid(); }
  1630. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()+1); return s; }
  1631. };
  1632. class CEmptyStringIterator : public CInterface, implements IStringIterator
  1633. {
  1634. public:
  1635. IMPLEMENT_IINTERFACE;
  1636. virtual bool first() { return false; }
  1637. virtual bool next() { return false; }
  1638. virtual bool isValid() { return false; }
  1639. virtual IStringVal & str(IStringVal &s) { s.clear(); return s; }
  1640. };
  1641. mapEnums sortFields[] =
  1642. {
  1643. { WUSFuser, "@submitID" },
  1644. { WUSFcluster, "@clusterName" },
  1645. { WUSFjob, "@jobName" },
  1646. { WUSFstate, "@state" },
  1647. { WUSFpriority, "@priorityClass" },
  1648. { WUSFprotected, "@protected" },
  1649. { WUSFwuid, "@" },
  1650. { WUSFfileread, "FilesRead/File/@name" },
  1651. { WUSFroxiecluster, "RoxieQueryInfo/@roxieClusterName" },
  1652. { WUSFbatchloginid, "Application/Dispatcher/FTPUserID" },
  1653. { WUSFbatchcustomername, "Application/Dispatcher/CustomerName" },
  1654. { WUSFbatchpriority, "Application/Dispatcher/JobPriority" },
  1655. { WUSFbatchinputreccount, "Application/Dispatcher/InputRecords" },
  1656. { WUSFbatchtimeuploaded, "Application/Dispatcher/TimeUploaded" },
  1657. { WUSFbatchtimecompleted, "Application/Dispatcher/TimeCompleted" },
  1658. { WUSFbatchmachine, "Application/Dispatcher/Machine" },
  1659. { WUSFbatchinputfile, "Application/Dispatcher/InputFileName" },
  1660. { WUSFbatchoutputfile, "Application/Dispatcher/OutputFileName" },
  1661. { WUSFtotalthortime, "Timings/Timing[@name='Total thor time']/@duration" },
  1662. { WUSFterm, NULL }
  1663. };
  1664. class asyncRemoveDllWorkItem: public CInterface, implements IWorkQueueItem // class only used in asyncRemoveDll
  1665. {
  1666. StringAttr name;
  1667. unsigned version;
  1668. bool removeDlls;
  1669. bool removeDirectory;
  1670. public:
  1671. IMPLEMENT_IINTERFACE;
  1672. asyncRemoveDllWorkItem(const char * _name, bool _removeDlls, bool _removeDirectory)
  1673. : name(_name)
  1674. {
  1675. removeDlls = _removeDlls;
  1676. removeDirectory = _removeDirectory;
  1677. }
  1678. void execute()
  1679. {
  1680. PROGLOG("WU removeDll %s",name.get());
  1681. queryDllServer().removeDll(name,removeDlls,removeDirectory);
  1682. }
  1683. };
  1684. class CWorkUnitFactory : public CInterface, implements IWorkUnitFactory, implements IDaliClientShutdown
  1685. {
  1686. Owned<IWorkQueueThread> deletedllworkq;
  1687. public:
  1688. IMPLEMENT_IINTERFACE;
  1689. CWorkUnitFactory()
  1690. {
  1691. // Assumes dali client configuration has already been done
  1692. sdsManager = &querySDS();
  1693. session = myProcessSession();
  1694. deletedllworkq.setown(createWorkQueueThread());
  1695. addShutdownHook(*this);
  1696. }
  1697. ~CWorkUnitFactory()
  1698. {
  1699. removeShutdownHook(*this);
  1700. // deletepool->joinAll();
  1701. }
  1702. void clientShutdown();
  1703. SessionId startSession()
  1704. {
  1705. // Temporary placeholder until startSession is implemented
  1706. #ifdef _WIN32
  1707. return GetTickCount();
  1708. #else
  1709. struct timeval tm;
  1710. gettimeofday(&tm,NULL);
  1711. return tm.tv_usec;
  1712. #endif
  1713. }
  1714. IWorkUnit* ensureNamedWorkUnit(const char *name)
  1715. {
  1716. if (workUnitTraceLevel > 1)
  1717. PrintLog("ensureNamedWorkUnit created %s", name);
  1718. StringBuffer wuRoot;
  1719. getXPath(wuRoot, name);
  1720. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  1721. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  1722. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit(conn, (ISecManager *)NULL, NULL, (const char *)NULL);
  1723. return &cw->lockRemote(false);
  1724. }
  1725. virtual IWorkUnit* createNamedWorkUnit(const char *wuid,const char *parentWuid, const char *app, const char *user)
  1726. {
  1727. StringBuffer wuRoot;
  1728. getXPath(wuRoot, wuid);
  1729. IRemoteConnection *conn;
  1730. if (queryDaliServerVersion().compare("2.0") >= 0)
  1731. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE_UNIQUE, SDS_LOCK_TIMEOUT);
  1732. else
  1733. conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  1734. conn->queryRoot()->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  1735. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit(conn, (ISecManager*)NULL, NULL, parentWuid);
  1736. IWorkUnit* ret = &cw->lockRemote(false);
  1737. ret->setDebugValue("CREATED_BY", app, true);
  1738. ret->setDebugValue("CREATED_FOR", user, true);
  1739. if (user)
  1740. cw->setWuScope(user);
  1741. return ret;
  1742. }
  1743. virtual IWorkUnit* createWorkUnit(const char *parentWuid, const char *app, const char *user)
  1744. {
  1745. StringBuffer wuid("W");
  1746. char result[32];
  1747. time_t ltime;
  1748. time( &ltime );
  1749. tm *today = localtime( &ltime ); // MORE - this is not threadsafe. But I probably don't care that much!
  1750. strftime(result, sizeof(result), "%Y%m%d-%H%M%S", today);
  1751. wuid.append(result);
  1752. if (queryDaliServerVersion().compare("2.0") < 0)
  1753. wuid.append('-').append(startSession());
  1754. if (workUnitTraceLevel > 1)
  1755. PrintLog("createWorkUnit created %s", wuid.str());
  1756. IWorkUnit* ret = createNamedWorkUnit(wuid.str(),parentWuid, app, user);
  1757. if (workUnitTraceLevel > 1)
  1758. {
  1759. SCMStringBuffer wuidName;
  1760. ret->getWuid(wuidName);
  1761. PrintLog("createWorkUnit created %s", wuidName.str());
  1762. }
  1763. ret->addTimeStamp("workunit", NULL, "Created");
  1764. return ret;
  1765. }
  1766. bool secDeleteWorkUnit(const char * wuid, ISecManager *secmgr, ISecUser *secuser, bool raiseexceptions)
  1767. {
  1768. if (workUnitTraceLevel > 1)
  1769. PrintLog("deleteWorkUnit %s", wuid);
  1770. StringBuffer wuRoot;
  1771. getXPath(wuRoot, wuid);
  1772. IRemoteConnection *conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  1773. if (!conn)
  1774. {
  1775. if (workUnitTraceLevel > 0)
  1776. PrintLog("deleteWorkUnit %s not found", wuid);
  1777. return false;
  1778. }
  1779. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit(conn, secmgr, secuser); // takes ownership of conn
  1780. if (secmgr && !checkWuSecAccess(*cw.get(), *secmgr, secuser, SecAccess_Full, "delete", true, true)) {
  1781. if (raiseexceptions) {
  1782. // perhaps raise exception here?
  1783. }
  1784. return false;
  1785. }
  1786. if (raiseexceptions) {
  1787. try
  1788. {
  1789. cw->cleanupAndDelete(true,true);
  1790. }
  1791. catch (IException *E)
  1792. {
  1793. StringBuffer s;
  1794. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during deleteWorkUnit: ").append(wuid).str());
  1795. E->Release();
  1796. return false;
  1797. }
  1798. }
  1799. else
  1800. cw->cleanupAndDelete(true,true);
  1801. return true;
  1802. }
  1803. virtual bool deleteWorkUnitEx(const char * wuid)
  1804. {
  1805. return secDeleteWorkUnit(wuid,NULL,NULL,true);
  1806. }
  1807. virtual bool deleteWorkUnit(const char * wuid)
  1808. {
  1809. return secDeleteWorkUnit(wuid,NULL,NULL,false);
  1810. }
  1811. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner)
  1812. {
  1813. // Not sure what to do about customerID vs user etc
  1814. StringBuffer path("*");
  1815. if (owner && *owner)
  1816. path.append("[@submitID=\"").append(owner).append("\"]");
  1817. return getWorkUnitsByXPath(path.str());
  1818. }
  1819. virtual IConstWorkUnitIterator * getWorkUnitsByState(WUState state);
  1820. virtual IConstWorkUnitIterator * getWorkUnitsByECL(const char* ecl)
  1821. {
  1822. StringBuffer path("*");
  1823. if (ecl && *ecl)
  1824. path.append("[Query/Text=~\"*").append(ecl).append("*\"]");
  1825. return getWorkUnitsByXPath(path.str());
  1826. }
  1827. virtual IConstWorkUnitIterator * getWorkUnitsByCluster(const char* cluster)
  1828. {
  1829. StringBuffer path("*");
  1830. if (cluster && *cluster)
  1831. path.append("[@clusterName=\"").append(cluster).append("\"]");
  1832. return getWorkUnitsByXPath(path.str());
  1833. }
  1834. virtual IConstWorkUnitIterator * getChildWorkUnits(const char *parent)
  1835. {
  1836. StringBuffer path("*[@parent=\"");
  1837. path.append(parent).append("\"]");
  1838. return getWorkUnitsByXPath(path.str());
  1839. }
  1840. virtual IConstWorkUnit* secOpenWorkUnit(const char *wuid, bool lock, ISecManager *secmgr=NULL, ISecUser *secuser=NULL)
  1841. {
  1842. if (workUnitTraceLevel > 1)
  1843. PrintLog("openWorkUnit %s", wuid);
  1844. StringBuffer wuRoot;
  1845. getXPath(wuRoot, wuid);
  1846. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, lock ? RTM_LOCK_READ|RTM_LOCK_SUB : 0, SDS_LOCK_TIMEOUT);
  1847. if (conn)
  1848. {
  1849. CLocalWorkUnit *wu = new CLocalWorkUnit(conn, secmgr, secuser);
  1850. if (secmgr && wu)
  1851. {
  1852. if (!checkWuSecAccess(*wu, *secmgr, secuser, SecAccess_Read, "opening", true, true))
  1853. {
  1854. delete wu;
  1855. return NULL;
  1856. }
  1857. }
  1858. return wu;
  1859. }
  1860. else
  1861. {
  1862. if (workUnitTraceLevel > 0)
  1863. PrintLog("openWorkUnit %s not found", wuid);
  1864. return NULL;
  1865. }
  1866. }
  1867. virtual IConstWorkUnit* openWorkUnit(const char *wuid, bool lock)
  1868. {
  1869. return secOpenWorkUnit(wuid, lock);
  1870. }
  1871. virtual IWorkUnit* secUpdateWorkUnit(const char *wuid, ISecManager *secmgr=NULL, ISecUser *secuser=NULL)
  1872. {
  1873. if (workUnitTraceLevel > 1)
  1874. PrintLog("updateWorkUnit %s", wuid);
  1875. StringBuffer wuRoot;
  1876. getXPath(wuRoot, wuid);
  1877. IRemoteConnection* conn = sdsManager->connect(wuRoot.str(), session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  1878. if (conn)
  1879. {
  1880. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit(conn, secmgr, secuser);
  1881. if (secmgr && cw)
  1882. {
  1883. if (!checkWuSecAccess(*cw.get(), *secmgr, secuser, SecAccess_Write, "updating", true, true))
  1884. return NULL;
  1885. }
  1886. return &cw->lockRemote(false);
  1887. }
  1888. else
  1889. {
  1890. if (workUnitTraceLevel > 0)
  1891. PrintLog("updateWorkUnit %s not found", wuid);
  1892. return NULL;
  1893. }
  1894. }
  1895. virtual IWorkUnit* updateWorkUnit(const char *wuid)
  1896. {
  1897. return secUpdateWorkUnit(wuid);
  1898. }
  1899. virtual int setTracingLevel(int newLevel)
  1900. {
  1901. if (newLevel)
  1902. PrintLog("Setting workunit trace level to %d", newLevel);
  1903. int level = workUnitTraceLevel;
  1904. workUnitTraceLevel = newLevel;
  1905. return level;
  1906. }
  1907. IConstWorkUnitIterator * getWorkUnitsByXPath(const char *xpath)
  1908. {
  1909. return getWorkUnitsByXPath(xpath,NULL,NULL);
  1910. }
  1911. void descheduleAllWorkUnits()
  1912. {
  1913. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  1914. if(!conn) return;
  1915. Owned<IPropertyTree> root(conn->queryRoot()->getBranch("."));
  1916. KeptAtomTable entries;
  1917. Owned<IPropertyTreeIterator> iter(root->getElements("*/*/*/*"));
  1918. StringBuffer wuid;
  1919. for(iter->first(); iter->isValid(); iter->next())
  1920. {
  1921. char const * entry = iter->query().queryName();
  1922. if(!entries.find(entry))
  1923. {
  1924. entries.addAtom(entry);
  1925. ncnameUnescape(entry, wuid.clear());
  1926. Owned<IWorkUnit> wu = updateWorkUnit(wuid);
  1927. if(wu && (wu->getState() == WUStateWait))
  1928. wu->setState(WUStateCompleted);
  1929. }
  1930. }
  1931. bool more;
  1932. do more = root->removeProp("*"); while(more);
  1933. }
  1934. IConstWorkUnitIterator * getWorkUnitsByXPath(const char *xpath, ISecManager *secmgr, ISecUser *secuser)
  1935. {
  1936. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  1937. if (conn)
  1938. {
  1939. CDaliVersion serverVersionNeeded("3.2");
  1940. Owned<IPropertyTreeIterator> iter(queryDaliServerVersion().compare(serverVersionNeeded) < 0 ?
  1941. conn->queryRoot()->getElements(xpath) :
  1942. conn->getElements(xpath));
  1943. return new CConstWUIterator(conn, NULL, iter, secmgr, secuser);
  1944. }
  1945. else
  1946. return NULL;
  1947. }
  1948. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  1949. WUSortField *filters, // NULL or list of fields to folteron (terminated by WUSFterm)
  1950. const void *filterbuf, // (appended) string values for filters
  1951. unsigned startoffset,
  1952. unsigned maxnum,
  1953. const char *queryowner,
  1954. __int64 *cachehint,
  1955. ISecManager *secmgr,
  1956. ISecUser *secuser)
  1957. {
  1958. class cScopeChecker: implements ISortedElementsTreeFilter
  1959. {
  1960. UniqueScopes done;
  1961. ISecManager *secmgr;
  1962. ISecUser *secuser;
  1963. public:
  1964. cScopeChecker(ISecManager *_secmgr,ISecUser *_secuser)
  1965. {
  1966. secmgr = _secmgr;
  1967. secuser = _secuser;
  1968. }
  1969. bool isOK(IPropertyTree &tree)
  1970. {
  1971. const char *scopename = tree.queryProp("@scope");
  1972. if (!scopename||!*scopename)
  1973. return true;
  1974. const bool *b = done.getValue(scopename);
  1975. if (b)
  1976. return *b;
  1977. bool ret = checkWuScopeSecAccess(scopename,*secmgr,secuser,SecAccess_Read,"iterating",false,false);
  1978. done.setValue(scopename,ret);
  1979. return ret;
  1980. }
  1981. } sc(secmgr,secuser);
  1982. StringBuffer query("*");
  1983. StringBuffer so;
  1984. StringAttr namefilterlo;
  1985. StringAttr namefilterhi;
  1986. if (filters) {
  1987. const char *fv = (const char *)filterbuf;
  1988. for (unsigned i=0;filters[i]!=WUSFterm;i++) {
  1989. int fmt = filters[i];
  1990. int subfmt = (fmt&0xff);
  1991. if (subfmt==WUSFwuid)
  1992. namefilterlo.set(fv);
  1993. else if (subfmt==WUSFwuidhigh)
  1994. namefilterhi.set(fv);
  1995. else {
  1996. query.append('[').append(getEnumText(subfmt,sortFields)).append('=');
  1997. if (fmt&WUSFnocase)
  1998. query.append('?');
  1999. if (fmt&WUSFwild)
  2000. query.append('~');
  2001. query.append('"').append(fv).append("\"]");
  2002. }
  2003. fv = fv + strlen(fv)+1;
  2004. }
  2005. }
  2006. if (sortorder) {
  2007. for (unsigned i=0;sortorder[i]!=WUSFterm;i++) {
  2008. if (so.length())
  2009. so.append(',');
  2010. int fmt = sortorder[i];
  2011. if (fmt&WUSFreverse)
  2012. so.append('-');
  2013. if (fmt&WUSFnocase)
  2014. so.append('~');
  2015. if (fmt&WUSFnumeric)
  2016. so.append('#');
  2017. so.append(getEnumText(fmt&0xff,sortFields));
  2018. }
  2019. }
  2020. IArrayOf<IPropertyTree> results;
  2021. Owned<IRemoteConnection> conn=getElementsPaged( "WorkUnits", query.str(), so.length()?so.str():NULL,startoffset,maxnum,
  2022. secmgr?&sc:NULL,queryowner,cachehint,namefilterlo.get(),namefilterhi.get(),results);
  2023. return new CConstWUArrayIterator(conn, results, secmgr, secuser);
  2024. }
  2025. IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  2026. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2027. const void *filterbuf, // (appended) string values for filters
  2028. unsigned startoffset,
  2029. unsigned maxnum,
  2030. const char *queryowner,
  2031. __int64 *cachehint)
  2032. {
  2033. return getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,queryowner,cachehint, NULL, NULL);
  2034. }
  2035. virtual unsigned numWorkUnits()
  2036. {
  2037. Owned<IRemoteConnection> conn = sdsManager->connect("/WorkUnits", session, 0, SDS_LOCK_TIMEOUT);
  2038. if (!conn)
  2039. return 0;
  2040. IPropertyTree *root = conn->queryRoot();
  2041. return root->numChildren();
  2042. }
  2043. virtual unsigned numWorkUnitsFiltered(WUSortField *filters,
  2044. const void *filterbuf,
  2045. ISecManager *secmgr,
  2046. ISecUser *secuser)
  2047. {
  2048. Owned<IConstWorkUnitIterator> iter = getWorkUnitsSorted( NULL,filters,filterbuf,0,0x7fffffff,NULL,NULL,secmgr,secuser);
  2049. // this is rather slow but necessarily so (for security check)
  2050. unsigned ret = 0;
  2051. ForEach(*iter)
  2052. ret++;
  2053. return ret;
  2054. }
  2055. virtual unsigned numWorkUnitsFiltered(WUSortField *filters,const void *filterbuf)
  2056. {
  2057. if (!filters)
  2058. return numWorkUnits();
  2059. return numWorkUnitsFiltered(filters,filterbuf,NULL,NULL);
  2060. }
  2061. void asyncRemoveDll(const char * name, bool removeDlls, bool removeDirectory)
  2062. {
  2063. deletedllworkq->post(new asyncRemoveDllWorkItem(name,removeDlls,removeDirectory));
  2064. }
  2065. ISDSManager *sdsManager;
  2066. SessionId session;
  2067. ISecManager *secMgr;
  2068. private:
  2069. void deleteChildren(IPropertyTree *root, const char *wuid)
  2070. {
  2071. StringBuffer kids("*[@parent=\"");
  2072. kids.append(wuid).append("\"]");
  2073. Owned<IPropertyTreeIterator> it = root->getElements(kids.str());
  2074. ForEach (*it)
  2075. {
  2076. deleteChildren(root, it->query().queryName());
  2077. }
  2078. root->removeProp(wuid);
  2079. }
  2080. class CConstWUIterator : public CInterface, implements IConstWorkUnitIterator
  2081. {
  2082. IArrayOf<IConstWorkUnit> w;
  2083. CArrayIteratorOf<IConstWorkUnit,IConstWorkUnitIterator> it;
  2084. public:
  2085. IMPLEMENT_IINTERFACE;
  2086. CConstWUIterator() : it(w)
  2087. {
  2088. }
  2089. CConstWUIterator(IRemoteConnection *conn, IPropertyTree *, IPropertyTreeIterator *_it, ISecManager *secmgr=NULL, ISecUser *secuser=NULL) : it(w)
  2090. {
  2091. UniqueScopes us;
  2092. Owned<ISecResourceList> scopes;
  2093. if (secmgr /* && secmgr->authTypeRequired(RT_WORKUNIT_SCOPE) tbd */)
  2094. {
  2095. scopes.setown(secmgr->createResourceList("wuscopes"));
  2096. for (_it->first(); _it->isValid(); _it->next())
  2097. {
  2098. const char *scopename = _it->query().queryProp("@scope");
  2099. if (scopename && *scopename && !us.getValue(scopename))
  2100. {
  2101. scopes->addResource(scopename);
  2102. us.setValue(scopename, true);
  2103. }
  2104. }
  2105. if (scopes->count())
  2106. {
  2107. secmgr->authorizeEx(RT_WORKUNIT_SCOPE, *secuser, scopes);
  2108. if (checkWuScopeListSecAccess(NULL, scopes, SecAccess_Read, "iterating", false, false))
  2109. scopes.clear(); //if no scopes restricted, no need to check later
  2110. }
  2111. else
  2112. scopes.clear();
  2113. }
  2114. for (_it->first(); _it->isValid(); _it->next())
  2115. {
  2116. IPropertyTree *rp = &_it->query();
  2117. const char *scopename=rp->queryProp("@scope");
  2118. if (!scopename || !*scopename || !scopes || checkWuScopeListSecAccess(rp->queryProp("@scope"), scopes, SecAccess_Read, "iterating", false, false))
  2119. w.append(*(IConstWorkUnit *) new CLocalWorkUnit(LINK(conn), LINK(rp), secmgr, secuser));
  2120. }
  2121. }
  2122. bool first() { return it.first(); }
  2123. bool isValid() { return it.isValid(); }
  2124. bool next() { return it.next(); }
  2125. IConstWorkUnit & query() { return it.query();}
  2126. };
  2127. IRemoteConnection* connect(const char *xpath, unsigned flags)
  2128. {
  2129. return sdsManager->connect(xpath, session, flags, SDS_LOCK_TIMEOUT);
  2130. }
  2131. };
  2132. static Owned<CWorkUnitFactory> factory;
  2133. void CWorkUnitFactory::clientShutdown()
  2134. {
  2135. factory.clear();
  2136. }
  2137. void clientShutdownWorkUnit()
  2138. {
  2139. factory.clear();
  2140. }
  2141. extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory()
  2142. {
  2143. if (!factory)
  2144. factory.setown(new CWorkUnitFactory());
  2145. return factory.getLink();
  2146. }
  2147. class CSecureWorkUnitFactory : public CInterface, implements IWorkUnitFactory
  2148. {
  2149. public:
  2150. IMPLEMENT_IINTERFACE;
  2151. CSecureWorkUnitFactory(ISecManager &secmgr, ISecUser &secuser)
  2152. {
  2153. if (!factory)
  2154. factory.setown(new CWorkUnitFactory());
  2155. secMgr.set(&secmgr);
  2156. secUser.set(&secuser);
  2157. }
  2158. virtual IWorkUnit* createNamedWorkUnit(const char *wuid,const char *parentWuid, const char *app, const char *user)
  2159. {
  2160. checkWuScopeSecAccess(user, *secMgr.get(), secUser.get(), SecAccess_Write, "Create", true, true);
  2161. IWorkUnit *wu=factory->createNamedWorkUnit(wuid, parentWuid, app, user);
  2162. if (wu)
  2163. {
  2164. CLockedWorkUnit* lw = dynamic_cast<CLockedWorkUnit*>(wu);
  2165. if (lw)
  2166. lw->setSecIfcs(secMgr.get(), secUser.get());
  2167. }
  2168. return wu;
  2169. }
  2170. virtual IWorkUnit* createWorkUnit(const char *parentWuid, const char *app, const char *user)
  2171. {
  2172. checkWuScopeSecAccess(user, *secMgr.get(), secUser.get(), SecAccess_Write, "Create", true, true);
  2173. IWorkUnit *wu=factory->createWorkUnit(parentWuid, app, user);
  2174. if (wu)
  2175. {
  2176. CLockedWorkUnit* lw = dynamic_cast<CLockedWorkUnit*>(wu);
  2177. if (lw)
  2178. lw->setSecIfcs(secMgr.get(), secUser.get());
  2179. }
  2180. return wu;
  2181. }
  2182. virtual bool deleteWorkUnitEx(const char * wuid)
  2183. {
  2184. return factory->secDeleteWorkUnit(wuid, secMgr.get(), secUser.get(), true);
  2185. }
  2186. virtual bool deleteWorkUnit(const char * wuid)
  2187. {
  2188. return factory->secDeleteWorkUnit(wuid, secMgr.get(), secUser.get(), false);
  2189. }
  2190. virtual IConstWorkUnit* openWorkUnit(const char *wuid, bool lock)
  2191. {
  2192. return factory->secOpenWorkUnit(wuid, lock, secMgr.get(), secUser.get());
  2193. }
  2194. virtual IWorkUnit* updateWorkUnit(const char *wuid)
  2195. {
  2196. return factory->secUpdateWorkUnit(wuid, secMgr.get(), secUser.get());
  2197. }
  2198. //make cached workunits a non secure pass through for now.
  2199. virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner)
  2200. {
  2201. // Not sure what to do about customerID vs user etc
  2202. StringBuffer path("*");
  2203. if (owner && *owner)
  2204. path.append("[@submitID=\"").append(owner).append("\"]");
  2205. return factory->getWorkUnitsByXPath(path.str(), secMgr.get(), secUser.get());
  2206. }
  2207. virtual IConstWorkUnitIterator * getWorkUnitsByState(WUState state);
  2208. virtual IConstWorkUnitIterator * getWorkUnitsByECL(const char* ecl)
  2209. {
  2210. return factory->getWorkUnitsByECL(ecl);
  2211. }
  2212. virtual IConstWorkUnitIterator * getWorkUnitsByCluster(const char* cluster)
  2213. {
  2214. return factory->getWorkUnitsByCluster(cluster);
  2215. }
  2216. virtual IConstWorkUnitIterator * getWorkUnitsByXPath(const char * xpath)
  2217. {
  2218. return factory->getWorkUnitsByXPath(xpath, secMgr.get(), secUser.get());
  2219. }
  2220. virtual void descheduleAllWorkUnits()
  2221. {
  2222. factory->descheduleAllWorkUnits();
  2223. }
  2224. virtual IConstWorkUnitIterator * getChildWorkUnits(const char *parent)
  2225. {
  2226. StringBuffer path("*[@parent=\"");
  2227. path.append(parent).append("\"]");
  2228. return factory->getWorkUnitsByXPath(path.str(), secMgr.get(), secUser.get());
  2229. }
  2230. virtual int setTracingLevel(int newLevel)
  2231. {
  2232. return factory->setTracingLevel(newLevel);
  2233. }
  2234. virtual IConstWorkUnitIterator* getWorkUnitsSorted( WUSortField *sortorder, // list of fields to sort by (terminated by WUSFterm)
  2235. WUSortField *filters, // NULL or list of fields to filter on (terminated by WUSFterm)
  2236. const void *filterbuf, // (appended) string values for filters
  2237. unsigned startoffset,
  2238. unsigned maxnum,
  2239. const char *queryowner,
  2240. __int64 *cachehint)
  2241. {
  2242. return factory->getWorkUnitsSorted(sortorder,filters,filterbuf,startoffset,maxnum,queryowner,cachehint, secMgr.get(), secUser.get());
  2243. }
  2244. virtual unsigned numWorkUnits()
  2245. {
  2246. return factory->numWorkUnits();
  2247. }
  2248. virtual unsigned numWorkUnitsFiltered(WUSortField *filters,
  2249. const void *filterbuf)
  2250. {
  2251. return factory->numWorkUnitsFiltered(filters,filterbuf,secMgr.get(), secUser.get());
  2252. }
  2253. private:
  2254. Owned<CWorkUnitFactory> base_factory;
  2255. Owned<ISecManager> secMgr;
  2256. Owned<ISecUser> secUser;
  2257. };
  2258. extern WORKUNIT_API IWorkUnitFactory * getSecWorkUnitFactory(ISecManager &secmgr, ISecUser &secuser)
  2259. {
  2260. return new CSecureWorkUnitFactory(secmgr, secuser);
  2261. }
  2262. //==========================================================================================
  2263. class CStringPTreeIterator : public CInterface, implements IStringIterator
  2264. {
  2265. Owned<IPropertyTreeIterator> it;
  2266. public:
  2267. IMPLEMENT_IINTERFACE;
  2268. CStringPTreeIterator(IPropertyTreeIterator *p) : it(p) {};
  2269. virtual bool first() { return it->first(); }
  2270. virtual bool next() { return it->next(); }
  2271. virtual bool isValid() { return it->isValid(); }
  2272. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(NULL)); return s; }
  2273. };
  2274. class CStringPTreeTagIterator : public CInterface, implements IStringIterator
  2275. {
  2276. Owned<IPropertyTreeIterator> it;
  2277. public:
  2278. IMPLEMENT_IINTERFACE;
  2279. CStringPTreeTagIterator(IPropertyTreeIterator *p) : it(p) {};
  2280. virtual bool first() { return it->first(); }
  2281. virtual bool next() { return it->next(); }
  2282. virtual bool isValid() { return it->isValid(); }
  2283. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryName()); return s; }
  2284. };
  2285. class CStringPTreeAttrIterator : public CInterface, implements IStringIterator
  2286. {
  2287. Owned<IPropertyTreeIterator> it;
  2288. StringAttr name;
  2289. public:
  2290. IMPLEMENT_IINTERFACE;
  2291. CStringPTreeAttrIterator(IPropertyTreeIterator *p, const char *_name) : it(p), name(_name) {};
  2292. virtual bool first() { return it->first(); }
  2293. virtual bool next() { return it->next(); }
  2294. virtual bool isValid() { return it->isValid(); }
  2295. virtual IStringVal & str(IStringVal &s) { s.set(it->query().queryProp(name)); return s; }
  2296. };
  2297. //==========================================================================================
  2298. CLocalWorkUnit::CLocalWorkUnit(IRemoteConnection *_conn, ISecManager *secmgr, ISecUser *secuser, const char *parentWuid) : connection(_conn)
  2299. {
  2300. connectAtRoot = true;
  2301. init();
  2302. p.setown(connection->getRoot());
  2303. if (parentWuid)
  2304. p->setProp("@parent", parentWuid);
  2305. secMgr.set(secmgr);
  2306. secUser.set(secuser);
  2307. }
  2308. CLocalWorkUnit::CLocalWorkUnit(IRemoteConnection *_conn, IPropertyTree* root, ISecManager *secmgr, ISecUser *secuser) : connection(_conn)
  2309. {
  2310. connectAtRoot = false;
  2311. init();
  2312. p.setown(root);
  2313. secMgr.set(secmgr);
  2314. secUser.set(secuser);
  2315. }
  2316. void CLocalWorkUnit::init()
  2317. {
  2318. p.clear();
  2319. cachedGraphs.clear();
  2320. workflowIterator.clear();
  2321. query.clear();
  2322. graphs.kill();
  2323. results.kill();
  2324. variables.kill();
  2325. plugins.kill();
  2326. libraries.kill();
  2327. activities.kill();
  2328. exceptions.kill();
  2329. temporaries.kill();
  2330. roxieQueryInfo.clear();
  2331. webServicesInfo.clear();
  2332. workflowIteratorCached = false;
  2333. resultsCached = false;
  2334. temporariesCached = false;
  2335. variablesCached = false;
  2336. exceptionsCached = false;
  2337. pluginsCached = false;
  2338. librariesCached = false;
  2339. activitiesCached = false;
  2340. webServicesInfoCached = false;
  2341. roxieQueryInfoCached = false;
  2342. dirty = false;
  2343. abortDirty = true;
  2344. abortState = false;
  2345. }
  2346. // Dummy workunit support
  2347. CLocalWorkUnit::CLocalWorkUnit(const char *_wuid, const char *parentWuid, ISecManager *secmgr, ISecUser *secuser)
  2348. {
  2349. connectAtRoot = true;
  2350. init();
  2351. p.setown(createPTree(_wuid));
  2352. p->setProp("@xmlns:xsi", "http://www.w3.org/1999/XMLSchema-instance");
  2353. if (parentWuid)
  2354. p->setProp("@parentWuid", parentWuid);
  2355. secMgr.set(secmgr);
  2356. secUser.set(secuser);
  2357. }
  2358. CLocalWorkUnit::~CLocalWorkUnit()
  2359. {
  2360. if (workUnitTraceLevel > 1)
  2361. {
  2362. PrintLog("Releasing workunit %s mode %x", p->queryName(), connection ? connection->queryMode() :0);
  2363. }
  2364. try
  2365. {
  2366. unsubscribe();
  2367. query.clear();
  2368. webServicesInfo.clear();
  2369. roxieQueryInfo.clear();
  2370. workflowIterator.clear();
  2371. activities.kill();
  2372. plugins.kill();
  2373. libraries.kill();
  2374. exceptions.kill();
  2375. graphs.kill();
  2376. results.kill();
  2377. temporaries.kill();
  2378. variables.kill();
  2379. timestamps.kill();
  2380. appvalues.kill();
  2381. userDesc.clear();
  2382. secMgr.clear();
  2383. secUser.clear();
  2384. cachedGraphs.clear();
  2385. p.clear();
  2386. connection.clear();
  2387. }
  2388. catch (IException *E) { LOG(MCexception(E, MSGCLS_warning), E, "Exception during ~CLocalWorkUnit"); E->Release(); }
  2389. }
  2390. void CLocalWorkUnit::cleanupAndDelete(bool deldll,bool deleteOwned)
  2391. {
  2392. TIME_SECTION("WUDELETE cleanupAndDelete total");
  2393. // Delete any related things in SDS etc that might otherwise be forgotten
  2394. assertex(connectAtRoot); // make sure we don't delete entire workunit tree!
  2395. if (p->getPropBool("@protected", false))
  2396. throw MakeStringException(WUERR_WorkunitProtected, "%s: Workunit is protected",p->queryName());
  2397. switch (getState())
  2398. {
  2399. case WUStateAborted:
  2400. case WUStateCompleted:
  2401. case WUStateFailed:
  2402. case WUStateArchived:
  2403. break;
  2404. case WUStateCompiled:
  2405. if (getAction()==WUActionRun || getAction()==WUActionUnknown)
  2406. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active",p->queryName());
  2407. break;
  2408. case WUStateWait:
  2409. throw MakeStringException(WUERR_WorkunitScheduled, "%s: Workunit is scheduled, not deleting",p->queryName());
  2410. default:
  2411. throw MakeStringException(WUERR_WorkunitActive, "%s: Workunit is active",p->queryName());
  2412. break;
  2413. }
  2414. try
  2415. {
  2416. //Move any service aliases
  2417. if (getIsQueryService())
  2418. {
  2419. Owned<IPropertyTree> registry = getQueryRegistry(p->queryProp("@clusterName"), false);
  2420. if (registry)
  2421. removeWuidFromNamedQueries(registry, p->queryName());
  2422. }
  2423. if (deldll && !p->getPropBool("@isClone", false))
  2424. {
  2425. Owned<IConstWUQuery> q = getQuery();
  2426. if (q)
  2427. {
  2428. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  2429. SCMStringBuffer name;
  2430. ForEach(*iter)
  2431. {
  2432. IConstWUAssociatedFile & cur = iter->query();
  2433. cur.getName(name);
  2434. bool removeDir = (cur.getType() == FileTypeDll); // this is to keep the code the same as before, but I don't know why it only does it for the dll.
  2435. factory->asyncRemoveDll(name.str(), true, removeDir);
  2436. }
  2437. }
  2438. }
  2439. StringBuffer apath;
  2440. // PROGLOG("wuid dll files removed");
  2441. {
  2442. apath.append("/WorkUnitAborts/").append(p->queryName());
  2443. Owned<IRemoteConnection> acon = factory->sdsManager->connect(apath.str(), factory->session, RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, SDS_LOCK_TIMEOUT);
  2444. acon.clear();
  2445. }
  2446. // PROGLOG("wuid WorkUnitAborts entry removed");
  2447. deleteTempFiles(NULL, deleteOwned, true); // all, any remaining.
  2448. }
  2449. catch(IException *E)
  2450. {
  2451. StringBuffer s;
  2452. LOG(MCexception(E, MSGCLS_warning), E, s.append("Exception during cleanupAndDelete: ").append(p->queryName()).str());
  2453. E->Release();
  2454. }
  2455. catch (...)
  2456. {
  2457. WARNLOG("Unknown exception during cleanupAndDelete: %s", p->queryName());
  2458. }
  2459. CConstGraphProgress::deleteWuidProgress(p->queryName());
  2460. connection->close(true);
  2461. PROGLOG("WUID %s removed",p->queryName());
  2462. connection.clear();
  2463. }
  2464. void CLocalWorkUnit::setTimeScheduled(const IDateTime &val)
  2465. {
  2466. SCMStringBuffer strval;
  2467. val.getGmtString(strval);
  2468. p->setProp("@timescheduled",strval.str());
  2469. }
  2470. IDateTime & CLocalWorkUnit::getTimeScheduled(IDateTime &val) const
  2471. {
  2472. StringBuffer str;
  2473. p->getProp("@timescheduled",str);
  2474. if(str.length())
  2475. val.setGmtString(str.str());
  2476. return val;
  2477. }
  2478. bool modifyAndWriteWorkUnitXML(char const * wuid, StringBuffer & buf, StringBuffer & extra, IFileIO * fileio)
  2479. {
  2480. // kludge in extra chunks of XML such as GraphProgress and GeneratedDlls
  2481. if(extra.length())
  2482. {
  2483. size32_t l = (size32_t)strlen(wuid);
  2484. size32_t p = buf.length()-l-4; // bit of a kludge
  2485. assertex(memcmp(buf.str()+p+2,wuid,l)==0);
  2486. StringAttr tail(buf.str()+p);
  2487. buf.setLength(p);
  2488. buf.append(extra);
  2489. buf.append(tail);
  2490. }
  2491. return (fileio->write(0,buf.length(),buf.str()) == buf.length());
  2492. }
  2493. bool CLocalWorkUnit::archiveWorkUnit(const char *base,bool del,bool ignoredllerrors,bool deleteOwned)
  2494. {
  2495. CriticalBlock block(crit);
  2496. StringBuffer path(base);
  2497. if (!p)
  2498. return false;
  2499. const char *wuid = p->queryName();
  2500. if (!wuid||!*wuid)
  2501. return false;
  2502. addPathSepChar(path).append(wuid).append(".xml");
  2503. Owned<IFile> file = createIFile(path.str());
  2504. if (!file)
  2505. return false;
  2506. Owned<IFileIO> fileio = file->open(IFOcreate);
  2507. if (!fileio)
  2508. return false;
  2509. StringBuffer buf;
  2510. exportWorkUnitToXML(this, buf);
  2511. StringBuffer extraWorkUnitXML;
  2512. StringBuffer xpath("/GraphProgress/");
  2513. xpath.append(wuid);
  2514. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2515. if (conn) {
  2516. Owned<IPropertyTree> tmp = createPTree("GraphProgress");
  2517. mergePTree(tmp,conn->queryRoot());
  2518. toXML(tmp,extraWorkUnitXML,1,XML_Format);
  2519. conn->close();
  2520. }
  2521. Owned<IConstWUQuery> q = getQuery();
  2522. if (!q) {
  2523. if(!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  2524. return false;
  2525. if (del) {
  2526. if (getState()==WUStateUnknown)
  2527. setState(WUStateArchived); // to allow delete
  2528. cleanupAndDelete(false,deleteOwned); // no query, may as well delete
  2529. }
  2530. return false;
  2531. }
  2532. Owned<IConstWUAssociatedFileIterator> iter = &q->getAssociatedFiles();
  2533. SCMStringBuffer name;
  2534. Owned<IException> exception;
  2535. Owned<IDllLocation> loc;
  2536. StringBuffer dst, locpath;
  2537. Owned<IPropertyTree> generatedDlls = createPTree("GeneratedDlls");
  2538. ForEach(*iter) {
  2539. IConstWUAssociatedFile & cur = iter->query();
  2540. cur.getName(name);
  2541. if (name.length()) {
  2542. Owned<IDllEntry> entry = queryDllServer().getEntry(name.str());
  2543. if (entry.get()) {
  2544. Owned<IPropertyTree> generatedDllBranch = createPTree();
  2545. generatedDllBranch->setProp("@name", entry->queryName());
  2546. generatedDllBranch->setProp("@kind", entry->queryKind());
  2547. bool removeDllFiles = true;
  2548. exception.clear();
  2549. try
  2550. {
  2551. loc.setown(entry->getBestLocation()); //throws exception if no readable locations
  2552. }
  2553. catch(IException * e)
  2554. {
  2555. exception.setown(e);
  2556. loc.setown(entry->getBestLocationCandidate()); //this will be closest of the unreadable locations
  2557. }
  2558. RemoteFilename filename;
  2559. loc->getDllFilename(filename);
  2560. if(!exception)
  2561. {
  2562. Owned<IFile> srcfile = createIFile(filename);
  2563. addPathSepChar(dst.clear().append(base));
  2564. filename.getTail(dst);
  2565. Owned<IFile> dstfile = createIFile(dst.str());
  2566. try
  2567. {
  2568. copyFile(dstfile,srcfile);
  2569. makeAbsolutePath(dstfile->queryFilename(), locpath.clear());
  2570. }
  2571. catch(IException * e)
  2572. {
  2573. exception.setown(e);
  2574. }
  2575. }
  2576. if(exception)
  2577. {
  2578. if(ignoredllerrors)
  2579. {
  2580. EXCLOG(exception.get(), "archiveWorkUnit (copying associated file)");
  2581. //copy failed, so store original (best) location and don't delete the files
  2582. filename.getRemotePath(locpath.clear());
  2583. removeDllFiles = false;
  2584. }
  2585. else
  2586. {
  2587. throw exception.getLink();
  2588. }
  2589. }
  2590. generatedDllBranch->setProp("@location", locpath.str());
  2591. generatedDlls->addPropTree("GeneratedDll", generatedDllBranch.getClear());
  2592. if (del) {
  2593. bool removeDir = (cur.getType() == FileTypeDll); // copied from cleanupAndDelete code, above
  2594. if (!p->getPropBool("@isClone", false)) // Leak to protect against cloned WUs
  2595. entry->remove(removeDllFiles, removeDir);
  2596. }
  2597. }
  2598. }
  2599. }
  2600. iter.clear();
  2601. if(generatedDlls->numChildren())
  2602. toXML(generatedDlls, extraWorkUnitXML, 1, XML_Format);
  2603. if(!modifyAndWriteWorkUnitXML(wuid, buf, extraWorkUnitXML, fileio))
  2604. return false;
  2605. if (del) {
  2606. //setState(WUStateArchived); // this isn't useful as about to delete it!
  2607. q.clear();
  2608. //deldll false as should have deleted all those we successfully copied, and archived and removed SDS entries, above
  2609. cleanupAndDelete(false, deleteOwned);
  2610. }
  2611. return true;
  2612. }
  2613. void CLocalWorkUnit::packWorkUnit(bool pack)
  2614. {
  2615. // only packs Graph info currently
  2616. CriticalBlock block(crit);
  2617. if (!p)
  2618. return;
  2619. const char *wuid = p->queryName();
  2620. if (!wuid||!*wuid)
  2621. return;
  2622. if (pack) {
  2623. if (!p->hasProp("PackedGraphs")) {
  2624. cachedGraphs.clear();
  2625. IPropertyTree *t = p->queryPropTree("Graphs");
  2626. if (t) {
  2627. MemoryBuffer buf;
  2628. t->serialize(buf);
  2629. p->setPropBin("PackedGraphs",buf.length(),buf.bufferBase());
  2630. p->removeTree(t);
  2631. }
  2632. }
  2633. }
  2634. else {
  2635. ensureGraphsUnpacked();
  2636. }
  2637. CConstGraphProgress::packProgress(wuid,pack);
  2638. }
  2639. IPropertyTree * pruneBranch(IPropertyTree * from, char const * xpath)
  2640. {
  2641. Owned<IPropertyTree> ret;
  2642. IPropertyTree * branch = from->queryPropTree(xpath);
  2643. if(branch) {
  2644. ret.setown(createPTreeFromIPT(branch));
  2645. from->removeTree(branch);
  2646. }
  2647. return ret.getClear();
  2648. }
  2649. bool restoreWorkUnit(const char *base,const char *wuid)
  2650. {
  2651. StringBuffer path(base);
  2652. if (!wuid||!*wuid)
  2653. return false;
  2654. addPathSepChar(path).append(wuid).append(".xml");
  2655. Owned<IFile> file = createIFile(path.str());
  2656. if (!file)
  2657. return false;
  2658. Owned<IFileIO> fileio = file->open(IFOread);
  2659. if (!fileio)
  2660. return false;
  2661. Owned<IPropertyTree> pt = createPTree(*fileio);
  2662. if (!pt)
  2663. return false;
  2664. CDateTime dt;
  2665. dt.setNow();
  2666. StringBuffer dts;
  2667. dt.getString(dts);
  2668. pt->setProp("@restoredDate", dts.str());
  2669. Owned<IRemoteConnection> conn = querySDS().connect("/WorkUnits", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  2670. if (!conn) {
  2671. ERRLOG("restoreWorkUnit could not connect to /WorkUnits");
  2672. return false;
  2673. }
  2674. IPropertyTree *root = conn->queryRoot();
  2675. if (root->hasProp(wuid)) {
  2676. ERRLOG("restoreWorkUnit WUID %s already exists",wuid);
  2677. return false;
  2678. }
  2679. Owned<IPropertyTree> gprogress = pruneBranch(pt, "GraphProgress[1]");
  2680. Owned<IPropertyTree> generatedDlls = pruneBranch(pt, "GeneratedDlls[1]");
  2681. root->setPropTree(wuid,pt.getClear());
  2682. conn.clear();
  2683. // now kludge back GraphProgress and GeneratedDlls
  2684. if (gprogress) {
  2685. StringBuffer xpath("/GraphProgress/");
  2686. conn.setown(querySDS().connect("/GraphProgress", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  2687. if (conn) {
  2688. IPropertyTree *groot = conn->queryRoot();
  2689. if (groot->hasProp(wuid)) {
  2690. ERRLOG("restoreWorkUnit WUID %s graphprogress already exists, removing",wuid);
  2691. groot->removeProp(wuid);
  2692. }
  2693. groot->setPropTree(wuid,gprogress.getClear());
  2694. }
  2695. }
  2696. if(generatedDlls)
  2697. {
  2698. Owned<IPropertyTreeIterator> dlls = generatedDlls->getElements("GeneratedDll");
  2699. for(dlls->first(); dlls->isValid(); dlls->next())
  2700. {
  2701. IPropertyTree & dll = dlls->query();
  2702. char const * name = dll.queryProp("@name");
  2703. char const * kind = dll.queryProp("@kind");
  2704. char const * location = dll.queryProp("@location");
  2705. Owned<IDllEntry> got = queryDllServer().getEntry(name);
  2706. if(!got)
  2707. queryDllServer().registerDll(name, kind, location);
  2708. }
  2709. }
  2710. return true;
  2711. }
  2712. void CLocalWorkUnit::loadXML(const char *xml)
  2713. {
  2714. CriticalBlock block(crit);
  2715. init();
  2716. assertex(xml);
  2717. p.setown(createPTreeFromXMLString(xml));
  2718. }
  2719. void CLocalWorkUnit::serialize(MemoryBuffer &tgt)
  2720. {
  2721. CriticalBlock block(crit);
  2722. StringBuffer x;
  2723. tgt.append(exportWorkUnitToXML(this, x).str());
  2724. }
  2725. void CLocalWorkUnit::deserialize(MemoryBuffer &src)
  2726. {
  2727. CriticalBlock block(crit);
  2728. StringAttr value;
  2729. src.read(value);
  2730. loadXML(value);
  2731. }
  2732. void CLocalWorkUnit::notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  2733. {
  2734. dirty = true;
  2735. }
  2736. void CLocalWorkUnit::abort()
  2737. {
  2738. abortDirty = true;
  2739. }
  2740. void CLocalWorkUnit::requestAbort()
  2741. {
  2742. CriticalBlock block(crit);
  2743. abortWorkUnit(p->queryName());
  2744. }
  2745. void CLocalWorkUnit::subscribe(WUSubscribeOptions options)
  2746. {
  2747. CriticalBlock block(crit);
  2748. bool subscribeAbort = false;
  2749. bool subscribeChange = false;
  2750. bool needChildren = true;
  2751. switch (options)
  2752. {
  2753. case SubscribeOptionAbort:
  2754. subscribeAbort = true;
  2755. break;
  2756. case SubscribeOptionRunningState:
  2757. needChildren = false;
  2758. case SubscribeOptionAnyState:
  2759. subscribeAbort = true;
  2760. subscribeChange = true;
  2761. break;
  2762. case SubscribeOptionProgress:
  2763. case SubscribeOptionAll:
  2764. subscribeChange = true;
  2765. break;
  2766. }
  2767. if (subscribeChange)
  2768. {
  2769. if (changeWatcher && changeWatcher->watchingChildren() != needChildren)
  2770. {
  2771. changeWatcher->unsubscribe();
  2772. changeWatcher.clear();
  2773. }
  2774. if (!changeWatcher)
  2775. {
  2776. changeWatcher.setown(new CWorkUnitWatcher(this, p->queryName(), needChildren));
  2777. dirty = true;
  2778. }
  2779. }
  2780. if (subscribeAbort && !abortWatcher)
  2781. {
  2782. abortWatcher.setown(new CWorkUnitAbortWatcher(this, p->queryName()));
  2783. abortDirty = true;
  2784. }
  2785. }
  2786. #if 0 // I don't think this is used (I grepped the source), am leaving here just in case I've missed somewhere (PG)
  2787. WUState CLocalWorkUnit::waitComplete(int timeout, bool returnOnWaitState)
  2788. {
  2789. class WorkUnitWaiter : public CInterface, implements ISDSSubscription, implements IAbortHandler
  2790. {
  2791. Semaphore changed;
  2792. CLocalWorkUnit *parent;
  2793. public:
  2794. IMPLEMENT_IINTERFACE;
  2795. WorkUnitWaiter(CLocalWorkUnit *_parent) : parent(_parent) { aborted = false; };
  2796. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  2797. {
  2798. parent->notify(id, xpath, flags, valueLen, valueData);
  2799. changed.signal();
  2800. }
  2801. bool wait(unsigned timeout)
  2802. {
  2803. return changed.wait(timeout) && !aborted;
  2804. }
  2805. bool onAbort()
  2806. {
  2807. aborted = true;
  2808. changed.signal();
  2809. return false;
  2810. }
  2811. bool aborted;
  2812. } waiter(this);
  2813. Owned<CWorkUnitWatcher> w = new CWorkUnitWatcher(&waiter, p->queryName(), false);
  2814. LocalIAbortHandler abortHandler(waiter);
  2815. forceReload(); // or may miss changes that already happened, between load of wu and now.
  2816. unsigned start = msTick();
  2817. WUState ret;
  2818. loop
  2819. {
  2820. ret = getState();
  2821. switch (ret)
  2822. {
  2823. case WUStateWait:
  2824. if(!returnOnWaitState)
  2825. break;
  2826. //fall thru
  2827. case WUStateCompleted:
  2828. case WUStateFailed:
  2829. case WUStateAborted:
  2830. w->unsubscribe();
  2831. return ret;
  2832. }
  2833. unsigned waited = msTick() - start;
  2834. if (timeout==-1)
  2835. {
  2836. waiter.wait(20000);
  2837. if (waiter.aborted)
  2838. {
  2839. ret = WUStateUnknown; // MORE - throw an exception?
  2840. break;
  2841. }
  2842. }
  2843. else if (waited > timeout || !waiter.wait(timeout-waited))
  2844. {
  2845. ret = WUStateUnknown; // MORE - throw an exception?
  2846. break;
  2847. }
  2848. reload();
  2849. }
  2850. w->unsubscribe();
  2851. return ret;
  2852. }
  2853. #endif
  2854. void CLocalWorkUnit::forceReload()
  2855. {
  2856. dirty = true;
  2857. reload();
  2858. }
  2859. bool CLocalWorkUnit::reload()
  2860. {
  2861. CriticalBlock block(crit);
  2862. if (dirty)
  2863. {
  2864. if (!connectAtRoot)
  2865. {
  2866. StringBuffer wuRoot;
  2867. getXPath(wuRoot, p->queryName());
  2868. IRemoteConnection *newconn = factory->sdsManager->connect(wuRoot.str(), factory->session, 0, SDS_LOCK_TIMEOUT);
  2869. if (!newconn)
  2870. throw MakeStringException(WUERR_ConnectFailed, "Could not connect to workunit %s (deleted?)",p->queryName());
  2871. connection.setown(newconn);
  2872. connectAtRoot = true;
  2873. }
  2874. else
  2875. connection->reload();
  2876. init();
  2877. p.setown(connection->getRoot());
  2878. return true;
  2879. }
  2880. return false;
  2881. }
  2882. void CLocalWorkUnit::unsubscribe()
  2883. {
  2884. CriticalBlock block(crit);
  2885. if (abortWatcher)
  2886. {
  2887. abortWatcher->unsubscribe();
  2888. abortWatcher.clear();
  2889. }
  2890. if (changeWatcher)
  2891. {
  2892. changeWatcher->unsubscribe();
  2893. changeWatcher.clear();
  2894. }
  2895. }
  2896. void CLocalWorkUnit::unlockRemote(bool commit)
  2897. {
  2898. CriticalBlock block(crit);
  2899. MTIME_SECTION(timer, "WorkUnit_unlockRemote");
  2900. locked.unlock();
  2901. if (commit)
  2902. {
  2903. try
  2904. {
  2905. assertex(connectAtRoot);
  2906. setTimeStamp("workunit", NULL, "Modified",false);
  2907. try { connection->commit(); }
  2908. catch (IException *e)
  2909. {
  2910. EXCLOG(e, "Error during workunit commit");
  2911. connection->rollback();
  2912. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  2913. throw;
  2914. }
  2915. connection->changeMode(0, SDS_LOCK_TIMEOUT);
  2916. }
  2917. catch (IException *E)
  2918. {
  2919. StringBuffer s;
  2920. PrintLog("Failed to release write lock on workunit: %s", E->errorMessage(s).str());
  2921. throw;
  2922. }
  2923. }
  2924. }
  2925. IWorkUnit &CLocalWorkUnit::lockRemote(bool commit)
  2926. {
  2927. if (secMgr)
  2928. checkWuSecAccess(*this, *secMgr.get(), secUser.get(), SecAccess_Write, "write lock", true, true);
  2929. locked.lock();
  2930. CriticalBlock block(crit);
  2931. MTIME_SECTION(timer, "WorkUnit_lockRemote");
  2932. if (commit)
  2933. {
  2934. try
  2935. {
  2936. StringBuffer wuRoot;
  2937. getXPath(wuRoot, p->queryName());
  2938. if (connection&&connectAtRoot)
  2939. connection->changeMode(RTM_LOCK_WRITE,SDS_LOCK_TIMEOUT);
  2940. else
  2941. connection.setown(factory->sdsManager->connect(wuRoot.str(), factory->session, RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  2942. if (!connection)
  2943. throw MakeStringException(WUERR_LockFailed, "Failed to get connection for xpath %s", wuRoot.str());
  2944. connectAtRoot = true;
  2945. init();
  2946. p.setown(connection->getRoot());
  2947. }
  2948. catch (IException *E)
  2949. {
  2950. StringBuffer s;
  2951. PrintLog("Failed to get write lock on workunit: %s", E->errorMessage(s).str());
  2952. locked.unlock();
  2953. throw;
  2954. }
  2955. }
  2956. return *new CLockedWorkUnit(LINK(this));
  2957. }
  2958. void CLocalWorkUnit::commit()
  2959. {
  2960. CriticalBlock block(crit);
  2961. assertex(connectAtRoot);
  2962. if (connection)
  2963. connection->commit();
  2964. }
  2965. IWorkUnit& CLocalWorkUnit::lock()
  2966. {
  2967. return lockRemote(true);
  2968. }
  2969. IStringVal& CLocalWorkUnit::getWuid(IStringVal &str) const
  2970. {
  2971. CriticalBlock block(crit);
  2972. str.set(p->queryName());
  2973. return str;
  2974. }
  2975. unsigned CLocalWorkUnit::getDebugAgentListenerPort() const
  2976. {
  2977. CriticalBlock block(crit);
  2978. return p->getPropInt("@DebugListenerPort", 0);
  2979. }
  2980. void CLocalWorkUnit::setDebugAgentListenerPort(unsigned port)
  2981. {
  2982. CriticalBlock block(crit);
  2983. p->setPropInt("@DebugListenerPort", port);
  2984. }
  2985. IStringVal& CLocalWorkUnit::getDebugAgentListenerIP(IStringVal &ip) const
  2986. {
  2987. CriticalBlock block(crit);
  2988. ip.set(p->queryProp("@DebugListenerIP"));
  2989. return ip;
  2990. }
  2991. void CLocalWorkUnit::setDebugAgentListenerIP(const char * ip)
  2992. {
  2993. CriticalBlock block(crit);
  2994. p->setProp("@DebugListenerIP", ip);
  2995. }
  2996. IStringVal& CLocalWorkUnit::getSecurityToken(IStringVal &str) const
  2997. {
  2998. CriticalBlock block(crit);
  2999. str.set(p->queryProp("@token"));
  3000. return str;
  3001. }
  3002. void CLocalWorkUnit::setSecurityToken(const char *value)
  3003. {
  3004. CriticalBlock block(crit);
  3005. p->setProp("@token", value);
  3006. }
  3007. bool CLocalWorkUnit::getRunningGraph(IStringVal &graphName, WUGraphIDType &subId) const
  3008. {
  3009. return CConstGraphProgress::getRunningGraph(p->queryName(), graphName, subId);
  3010. }
  3011. void CLocalWorkUnit::setJobName(const char *value)
  3012. {
  3013. CriticalBlock block(crit);
  3014. p->setProp("@jobName", value);
  3015. }
  3016. IStringVal& CLocalWorkUnit::getJobName(IStringVal &str) const
  3017. {
  3018. CriticalBlock block(crit);
  3019. str.set(p->queryProp("@jobName"));
  3020. return str;
  3021. }
  3022. void CLocalWorkUnit::setClusterName(const char *value)
  3023. {
  3024. CriticalBlock block(crit);
  3025. p->setProp("@clusterName", value);
  3026. }
  3027. IStringVal& CLocalWorkUnit::getClusterName(IStringVal &str) const
  3028. {
  3029. CriticalBlock block(crit);
  3030. str.set(p->queryProp("@clusterName"));
  3031. return str;
  3032. }
  3033. void CLocalWorkUnit::setAllowedClusters(const char *value)
  3034. {
  3035. setDebugValue("allowedclusters",value, true);
  3036. }
  3037. IStringVal& CLocalWorkUnit::getAllowedClusters(IStringVal &str) const
  3038. {
  3039. CriticalBlock block(crit);
  3040. getDebugValue("allowedclusters",str);
  3041. if (str.length()!=0)
  3042. return str;
  3043. str.set(p->queryProp("@clusterName"));
  3044. return str;
  3045. }
  3046. void CLocalWorkUnit::setAllowAutoQueueSwitch(bool val)
  3047. {
  3048. setDebugValueInt("allowautoqueueswitch",val?1:0,true);
  3049. }
  3050. bool CLocalWorkUnit::getAllowAutoQueueSwitch() const
  3051. {
  3052. CriticalBlock block(crit);
  3053. return getDebugValueBool("allowautoqueueswitch",false);
  3054. }
  3055. void CLocalWorkUnit::setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash)
  3056. {
  3057. StringBuffer suffix;
  3058. if (name && *name)
  3059. setApplicationValue("LibraryModule", "name", name, true);
  3060. setApplicationValueInt("LibraryModule", "interfaceHash", interfaceHash, true);
  3061. setApplicationValueInt("LibraryModule", "definitionHash", definitionHash, true);
  3062. setApplicationValue("LibraryModule", "platform", appendLibrarySuffix(suffix).str(), true);
  3063. }
  3064. void CLocalWorkUnit::remoteCheckAccess(IUserDescriptor *user, bool writeaccess) const
  3065. {
  3066. unsigned auditflags = DALI_LDAP_AUDIT_REPORT|DALI_LDAP_READ_WANTED;
  3067. if (writeaccess)
  3068. auditflags |= DALI_LDAP_WRITE_WANTED;
  3069. int perm = 255;
  3070. const char *scopename = p->queryProp("@scope");
  3071. if (scopename&&*scopename) {
  3072. Owned<IUserDescriptor> tmpuser;
  3073. if (!user) {
  3074. tmpuser.setown(getUserDescriptor()); // probably not that useful as presumably owner has access
  3075. user = tmpuser.get();
  3076. }
  3077. perm = querySessionManager().getPermissionsLDAP("workunit",scopename,user,auditflags);
  3078. if (perm<0) {
  3079. if (perm==-1)
  3080. perm = 255;
  3081. else
  3082. perm = 0;
  3083. }
  3084. }
  3085. IDFS_Exception *e = NULL;
  3086. if (!HASREADPERMISSION(perm)) {
  3087. SCMStringBuffer wuid;
  3088. getWuid(wuid);
  3089. throw MakeStringException(WUERR_WorkunitAccessDenied, "Read access denied for workunit %s",wuid.s.str());
  3090. }
  3091. if (writeaccess&&!HASWRITEPERMISSION(perm)) {
  3092. SCMStringBuffer wuid;
  3093. getWuid(wuid);
  3094. throw MakeStringException(WUERR_WorkunitAccessDenied, "Write access denied for workunit %s",wuid.s.str());
  3095. }
  3096. }
  3097. IStringVal& CLocalWorkUnit::getParentWuid(IStringVal &str) const
  3098. {
  3099. CriticalBlock block(crit);
  3100. str.set(p->queryProp("@parent"));
  3101. return str;
  3102. }
  3103. void CLocalWorkUnit::setUser(const char * value)
  3104. {
  3105. CriticalBlock block(crit);
  3106. p->setProp("@submitID", value);
  3107. }
  3108. IStringVal& CLocalWorkUnit::getUser(IStringVal &str) const
  3109. {
  3110. CriticalBlock block(crit);
  3111. str.set(p->queryProp("@submitID"));
  3112. return str;
  3113. }
  3114. void CLocalWorkUnit::setWuScope(const char * value)
  3115. {
  3116. CriticalBlock block(crit);
  3117. p->setProp("@scope", value);
  3118. }
  3119. IStringVal& CLocalWorkUnit::getWuScope(IStringVal &str) const
  3120. {
  3121. CriticalBlock block(crit);
  3122. str.set(p->queryProp("@scope"));
  3123. return str;
  3124. }
  3125. void CLocalWorkUnit::setCustomerId(const char * value)
  3126. {
  3127. CriticalBlock block(crit);
  3128. p->setProp("CustomerID", value);
  3129. }
  3130. IStringVal& CLocalWorkUnit::getCustomerId(IStringVal &str) const
  3131. {
  3132. CriticalBlock block(crit);
  3133. str.set(p->queryProp("CustomerID"));
  3134. return str;
  3135. }
  3136. mapEnums priorityClasses[] = {
  3137. { PriorityClassUnknown, "unknown" },
  3138. { PriorityClassLow, "low" },
  3139. { PriorityClassNormal, "normal" },
  3140. { PriorityClassHigh, "high" },
  3141. { PriorityClassSize, NULL },
  3142. };
  3143. void CLocalWorkUnit::setPriority(WUPriorityClass cls)
  3144. {
  3145. CriticalBlock block(crit);
  3146. setEnum(p, "@priorityClass", cls, priorityClasses);
  3147. }
  3148. WUPriorityClass CLocalWorkUnit::getPriority() const
  3149. {
  3150. CriticalBlock block(crit);
  3151. return (WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses);
  3152. }
  3153. mapEnums states[] = {
  3154. { WUStateUnknown, "unknown" },
  3155. { WUStateCompiled, "compiled" },
  3156. { WUStateRunning, "running" },
  3157. { WUStateCompleted, "completed" },
  3158. { WUStateFailed, "failed" },
  3159. { WUStateArchived, "archived" },
  3160. { WUStateAborting, "aborting" },
  3161. { WUStateAborted, "aborted" },
  3162. { WUStateBlocked, "blocked" },
  3163. { WUStateSubmitted, "submitted" },
  3164. { WUStateScheduled, "scheduled" },
  3165. { WUStateCompiling, "compiling" },
  3166. { WUStateWait, "wait" },
  3167. { WUStateUploadingFiles, "uploading_files" },
  3168. { WUStateDebugPaused, "debugging" },
  3169. { WUStateDebugRunning, "debug_running" },
  3170. { WUStatePaused, "paused" },
  3171. { WUStateSize, NULL }
  3172. };
  3173. IConstWorkUnitIterator * CWorkUnitFactory::getWorkUnitsByState(WUState state)
  3174. {
  3175. StringBuffer path("*");
  3176. path.append("[@state=\"").append(getEnumText(state, states)).append("\"]");
  3177. return getWorkUnitsByXPath(path.str());
  3178. }
  3179. IConstWorkUnitIterator * CSecureWorkUnitFactory::getWorkUnitsByState(WUState state)
  3180. {
  3181. StringBuffer path("*");
  3182. path.append("[@state=\"").append(getEnumText(state, states)).append("\"]");
  3183. return factory->getWorkUnitsByXPath(path.str(), secMgr.get(), secUser.get());
  3184. }
  3185. void CLocalWorkUnit::setState(WUState value)
  3186. {
  3187. CriticalBlock block(crit);
  3188. if (value==WUStateAborted || value==WUStatePaused || value==WUStateCompleted || value==WUStateFailed || value==WUStateSubmitted || value==WUStateWait)
  3189. {
  3190. if (abortWatcher)
  3191. {
  3192. abortWatcher->unsubscribe();
  3193. abortWatcher.clear();
  3194. }
  3195. StringBuffer apath;
  3196. apath.append("/WorkUnitAborts/").append(p->queryName());
  3197. if(factory)
  3198. {
  3199. Owned<IRemoteConnection> acon = factory->sdsManager->connect(apath.str(), factory->session, RTM_LOCK_WRITE|RTM_LOCK_SUB, SDS_LOCK_TIMEOUT);
  3200. if (acon)
  3201. acon->close(true);
  3202. }
  3203. }
  3204. setEnum(p, "@state", value, states);
  3205. if (getDebugValueBool("monitorWorkunit", false))
  3206. {
  3207. switch(value)
  3208. {
  3209. case WUStateAborted:
  3210. FLLOG(MCoperatorWarning, "Workunit %s aborted", p->queryName());
  3211. break;
  3212. case WUStateCompleted:
  3213. FLLOG(MCoperatorProgress, "Workunit %s completed", p->queryName());
  3214. break;
  3215. case WUStateFailed:
  3216. FLLOG(MCoperatorProgress, "Workunit %s failed", p->queryName());
  3217. break;
  3218. }
  3219. }
  3220. p->removeProp("@stateEx");
  3221. }
  3222. void CLocalWorkUnit::setStateEx(const char * text)
  3223. {
  3224. CriticalBlock block(crit);
  3225. p->setProp("@stateEx", text);
  3226. }
  3227. void CLocalWorkUnit::setAgentSession(__int64 sessionId)
  3228. {
  3229. CriticalBlock block(crit);
  3230. p->setPropInt64("@agentSession", sessionId);
  3231. }
  3232. void CLocalWorkUnit::setAgentPID(unsigned pid)
  3233. {
  3234. CriticalBlock block(crit);
  3235. p->setPropInt("@agentPID", pid);
  3236. }
  3237. bool CLocalWorkUnit::aborting() const
  3238. {
  3239. CriticalBlock block(crit);
  3240. if (abortDirty)
  3241. {
  3242. if (factory)
  3243. {
  3244. StringBuffer apath;
  3245. apath.append("/WorkUnitAborts/").append(p->queryName());
  3246. Owned<IRemoteConnection> acon = factory->sdsManager->connect(apath.str(), factory->session, 0, SDS_LOCK_TIMEOUT);
  3247. if (acon)
  3248. abortState = acon->queryRoot()->getPropInt(NULL)!=0;
  3249. else
  3250. abortState = false;
  3251. }
  3252. abortDirty = false;
  3253. }
  3254. return abortState;
  3255. }
  3256. bool CLocalWorkUnit::getIsQueryService() const
  3257. {
  3258. CriticalBlock block(crit);
  3259. return p->getPropBool("@isQueryService", false);
  3260. }
  3261. void CLocalWorkUnit::setIsQueryService(bool value)
  3262. {
  3263. CriticalBlock block(crit);
  3264. p->setPropBool("@isQueryService", value);
  3265. }
  3266. void CLocalWorkUnit::checkAgentRunning(WUState & state)
  3267. {
  3268. if (queryDaliServerVersion().compare("2.1")<0)
  3269. return;
  3270. switch(state)
  3271. {
  3272. case WUStateRunning:
  3273. case WUStateDebugPaused:
  3274. case WUStateDebugRunning:
  3275. case WUStateBlocked:
  3276. case WUStateAborting:
  3277. case WUStateCompiling:
  3278. case WUStatePaused:
  3279. {
  3280. SessionId agent = getAgentSession();
  3281. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  3282. {
  3283. forceReload();
  3284. state = (WUState) getEnum(p, "@state", states);
  3285. bool isecl=state==WUStateCompiling;
  3286. if (aborting())
  3287. state = WUStateAborted;
  3288. else if (state==WUStateRunning || state==WUStatePaused || state==WUStateDebugPaused || state==WUStateDebugRunning || state==WUStateBlocked || state==WUStateCompiling)
  3289. state = WUStateFailed;
  3290. else
  3291. return;
  3292. WARNLOG("checkAgentRunning terminated: %"I64F"d state = %d",(__int64)agent,(int)state);
  3293. Owned<IWorkUnit> w = &lock();
  3294. w->setState(state);
  3295. Owned<IWUException> e = w->createException();
  3296. WUAction action = w->getAction();
  3297. switch (action)
  3298. {
  3299. case WUActionPause:
  3300. case WUActionPauseNow:
  3301. case WUActionResume:
  3302. w->setAction(WUActionUnknown);
  3303. }
  3304. if(isecl)
  3305. {
  3306. e->setExceptionCode(1001);
  3307. e->setExceptionMessage("EclServer terminated unexpectedly");
  3308. }
  3309. else
  3310. {
  3311. e->setExceptionCode(1000);
  3312. e->setExceptionMessage("Workunit terminated unexpectedly");
  3313. }
  3314. }
  3315. }
  3316. }
  3317. }
  3318. WUState CLocalWorkUnit::getState() const
  3319. {
  3320. CriticalBlock block(crit);
  3321. WUState state = (WUState) getEnum(p, "@state", states);
  3322. switch (state)
  3323. {
  3324. case WUStateRunning:
  3325. case WUStateDebugPaused:
  3326. case WUStateDebugRunning:
  3327. case WUStateBlocked:
  3328. case WUStateCompiling:
  3329. if (aborting())
  3330. state = WUStateAborting;
  3331. break;
  3332. case WUStateSubmitted:
  3333. if (aborting())
  3334. state = WUStateAborted;
  3335. break;
  3336. }
  3337. const_cast<CLocalWorkUnit *>(this)->checkAgentRunning(state); //need const_cast as will change state if agent has died
  3338. return state;
  3339. }
  3340. IStringVal& CLocalWorkUnit::getStateEx(IStringVal & str) const
  3341. {
  3342. CriticalBlock block(crit);
  3343. str.set(p->queryProp("@stateEx"));
  3344. return str;
  3345. }
  3346. __int64 CLocalWorkUnit::getAgentSession() const
  3347. {
  3348. CriticalBlock block(crit);
  3349. return p->getPropInt64("@agentSession", -1);
  3350. }
  3351. unsigned CLocalWorkUnit::getAgentPID() const
  3352. {
  3353. CriticalBlock block(crit);
  3354. return p->getPropInt("@agentPID", -1);
  3355. }
  3356. IStringVal& CLocalWorkUnit::getStateDesc(IStringVal &str) const
  3357. {
  3358. // MORE - not sure about this - may prefer a separate interface
  3359. CriticalBlock block(crit);
  3360. try
  3361. {
  3362. str.set(getEnumText(getState(), states));
  3363. }
  3364. catch (...)
  3365. {
  3366. str.set("???");
  3367. }
  3368. return str;
  3369. }
  3370. mapEnums actions[] = {
  3371. { WUActionUnknown, "unknown" },
  3372. { WUActionCompile, "compile" },
  3373. { WUActionCheck, "check" },
  3374. { WUActionRun, "run" },
  3375. { WUActionExecuteExisting, "execute" },
  3376. { WUActionPause, "pause" },
  3377. { WUActionPauseNow, "pausenow" },
  3378. { WUActionResume, "resume" },
  3379. { WUActionSize, NULL },
  3380. };
  3381. void CLocalWorkUnit::setAction(WUAction value)
  3382. {
  3383. CriticalBlock block(crit);
  3384. setEnum(p, "Action", value, actions);
  3385. }
  3386. WUAction CLocalWorkUnit::getAction() const
  3387. {
  3388. CriticalBlock block(crit);
  3389. return (WUAction) getEnum(p, "Action", actions);
  3390. }
  3391. IStringVal& CLocalWorkUnit::getActionEx(IStringVal & str) const
  3392. {
  3393. CriticalBlock block(crit);
  3394. str.set(p->queryProp("Action"));
  3395. return str;
  3396. }
  3397. IStringVal& CLocalWorkUnit::getApplicationValue(const char *app, const char *propname, IStringVal &str) const
  3398. {
  3399. CriticalBlock block(crit);
  3400. StringBuffer prop("Application/");
  3401. prop.append(app).append('/').append(propname);
  3402. str.set(p->queryProp(prop.str()));
  3403. return str;
  3404. }
  3405. int CLocalWorkUnit::getApplicationValueInt(const char *app, const char *propname, int defVal) const
  3406. {
  3407. CriticalBlock block(crit);
  3408. StringBuffer prop("Application/");
  3409. prop.append(app).append('/').append(propname);
  3410. return p->getPropInt(prop.str(), defVal);
  3411. }
  3412. IConstWUAppValueIterator& CLocalWorkUnit::getApplicationValues() const
  3413. {
  3414. CriticalBlock block(crit);
  3415. appvalues.load(p,"Application/*");
  3416. return *new CArrayIteratorOf<IConstWUAppValue,IConstWUAppValueIterator> (appvalues, 0, (IConstWorkUnit *) this);
  3417. }
  3418. void CLocalWorkUnit::setApplicationValue(const char *app, const char *propname, const char *value, bool overwrite)
  3419. {
  3420. CriticalBlock block(crit);
  3421. StringBuffer prop("Application/");
  3422. prop.append(app).append('/').append(propname);
  3423. if (overwrite || !p->hasProp(prop.str()))
  3424. {
  3425. // MORE - not sure these lines should be needed....
  3426. StringBuffer sp;
  3427. p->setProp(sp.append("Application").str(), "");
  3428. p->setProp(sp.append('/').append(app).str(), "");
  3429. p->setProp(prop.str(), value);
  3430. }
  3431. }
  3432. void CLocalWorkUnit::setApplicationValueInt(const char *app, const char *propname, int value, bool overwrite)
  3433. {
  3434. CriticalBlock block(crit);
  3435. StringBuffer prop("Application/");
  3436. prop.append(app).append('/').append(propname);
  3437. if (overwrite || !p->hasProp(prop.str()))
  3438. {
  3439. // MORE - not sure these lines should be needed....
  3440. StringBuffer sp;
  3441. p->setProp(sp.append("Application").str(), "");
  3442. p->setProp(sp.append('/').append(app).str(), "");
  3443. p->setPropInt(prop.str(), value);
  3444. }
  3445. }
  3446. void CLocalWorkUnit::setPriorityLevel(int level)
  3447. {
  3448. CriticalBlock block(crit);
  3449. p->setPropInt("PriorityFlag", level);
  3450. }
  3451. int CLocalWorkUnit::getPriorityLevel() const
  3452. {
  3453. CriticalBlock block(crit);
  3454. return p->getPropInt("PriorityFlag");
  3455. }
  3456. int CLocalWorkUnit::getPriorityValue() const
  3457. {
  3458. CriticalBlock block(crit);
  3459. int priority = p->getPropInt("PriorityFlag");
  3460. switch((WUPriorityClass) getEnum(p, "@priorityClass", priorityClasses))
  3461. {
  3462. case PriorityClassLow:
  3463. priority -= 100;
  3464. break;
  3465. case PriorityClassHigh:
  3466. priority += 100;
  3467. break;
  3468. }
  3469. return priority;
  3470. }
  3471. void CLocalWorkUnit::setRescheduleFlag(bool value)
  3472. {
  3473. CriticalBlock block(crit);
  3474. p->setPropInt("RescheduleFlag", (int) value);
  3475. }
  3476. bool CLocalWorkUnit::getRescheduleFlag() const
  3477. {
  3478. CriticalBlock block(crit);
  3479. return p->getPropInt("RescheduleFlag") != 0;
  3480. }
  3481. class NullIStringIterator : public CInterface, extends IStringIterator
  3482. {
  3483. public:
  3484. IMPLEMENT_IINTERFACE;
  3485. bool first() { return false; }
  3486. bool next() { return false; }
  3487. bool isValid() { return false; }
  3488. IStringVal & str(IStringVal & str) { return str; }
  3489. };
  3490. class CEnvironmentClusterInfo: public CInterface, implements IConstWUClusterInfo
  3491. {
  3492. StringAttr name;
  3493. StringAttr serverQueue;
  3494. StringAttr agentQueue;
  3495. StringAttr thorQueue;
  3496. StringAttr prefix;
  3497. StringAttr platform;
  3498. StringAttr querySetName;
  3499. unsigned clusterWidth;
  3500. public:
  3501. IMPLEMENT_IINTERFACE;
  3502. CEnvironmentClusterInfo(const char *_name, const char *_prefix, const char *_querySetName, IPropertyTree *agent, IArrayOf<IPropertyTree> &thors, IPropertyTree *roxie)
  3503. : name(_name), prefix(_prefix), querySetName(_querySetName)
  3504. {
  3505. StringBuffer queue;
  3506. if (thors.ordinality())
  3507. {
  3508. thorQueue.set(queue.clear().append(name).append(".thor"));
  3509. clusterWidth = 0;
  3510. bool lcr = false;
  3511. ForEachItemIn(i,thors)
  3512. {
  3513. IPropertyTree &thor = thors.item(i);
  3514. unsigned ts = thor.getPropInt("@slaves");
  3515. if (clusterWidth && (ts!=clusterWidth))
  3516. throw MakeStringException(WUERR_MismatchClusterSize,"CEnvironmentClusterInfo: mismatched thor sizes in cluster");
  3517. clusterWidth = ts;
  3518. bool islcr = thor.getPropBool("@LCR");
  3519. if (i==0)
  3520. lcr = islcr;
  3521. else if (lcr!=islcr)
  3522. throw MakeStringException(WUERR_MismatchThorType,"CEnvironmentClusterInfo: mismatched thor LCR in cluster");
  3523. }
  3524. platform.set(lcr ? "thorlcr" : "thor");
  3525. }
  3526. else if (roxie)
  3527. {
  3528. clusterWidth = roxie->getPropInt("@numChannels", 1);
  3529. platform.set("roxie");
  3530. }
  3531. else
  3532. {
  3533. clusterWidth = 1;
  3534. platform.set("hthor");
  3535. }
  3536. if (agent)
  3537. agentQueue.set(queue.clear().append(name).append(".agent"));
  3538. // MORE - does this need to be conditional?
  3539. serverQueue.set(queue.clear().append(name).append(".eclserver"));
  3540. }
  3541. IStringVal & getName(IStringVal & str) const
  3542. {
  3543. str.set(name.get());
  3544. return str;
  3545. }
  3546. IStringVal & getScope(IStringVal & str) const
  3547. {
  3548. str.set(prefix.get());
  3549. return str;
  3550. }
  3551. IStringVal & getAgentQueue(IStringVal & str) const
  3552. {
  3553. str.set(agentQueue);
  3554. return str;
  3555. }
  3556. virtual IStringVal & getServerQueue(IStringVal & str) const
  3557. {
  3558. str.set(serverQueue);
  3559. return str;
  3560. }
  3561. IStringVal & getThorQueue(IStringVal & str) const
  3562. {
  3563. str.set(thorQueue);
  3564. return str;
  3565. }
  3566. unsigned getSize() const
  3567. {
  3568. return clusterWidth;
  3569. }
  3570. virtual IStringVal & getPlatform(IStringVal & str) const
  3571. {
  3572. str.set(platform);
  3573. return str;
  3574. }
  3575. IStringVal & getQuerySetName(IStringVal & str) const
  3576. {
  3577. str.set(querySetName.get());
  3578. return str;
  3579. }
  3580. };
  3581. IStringVal &getProcessQueueNames(IStringVal &ret, const char *process, const char *type, const char *suffix)
  3582. {
  3583. if (process)
  3584. {
  3585. Owned<IRemoteConnection> conn = querySDS().connect("Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  3586. if (conn)
  3587. {
  3588. StringBuffer queueNames;
  3589. StringBuffer xpath;
  3590. xpath.appendf("%s[@process=\"%s\"]", type, process);
  3591. Owned<IPropertyTreeIterator> targets = conn->queryRoot()->getElements("Software/Topology/Cluster");
  3592. ForEach(*targets)
  3593. {
  3594. IPropertyTree &target = targets->query();
  3595. if (target.hasProp(xpath))
  3596. {
  3597. if (queueNames.length())
  3598. queueNames.append(',');
  3599. queueNames.append(target.queryProp("@name")).append(suffix);
  3600. }
  3601. }
  3602. ret.set(queueNames);
  3603. }
  3604. }
  3605. return ret;
  3606. }
  3607. extern WORKUNIT_API IStringVal &getEclCCServerQueueNames(IStringVal &ret, const char *process)
  3608. {
  3609. return getProcessQueueNames(ret, process, "EclCCServerProcess", ".eclserver");
  3610. }
  3611. extern WORKUNIT_API IStringVal &getEclServerQueueNames(IStringVal &ret, const char *process)
  3612. {
  3613. return getProcessQueueNames(ret, process, "EclServerProcess", ".eclserver"); // shares queue name with EclCCServer
  3614. }
  3615. extern WORKUNIT_API IStringVal &getEclSchedulerQueueNames(IStringVal &ret, const char *process)
  3616. {
  3617. return getProcessQueueNames(ret, process, "EclCCServerProcess", ".eclscheduler"); // Shares deployment/config with EclCCServer
  3618. }
  3619. extern WORKUNIT_API IStringVal &getAgentQueueNames(IStringVal &ret, const char *process)
  3620. {
  3621. return getProcessQueueNames(ret, process, "EclAgentProcess", ".agent");
  3622. }
  3623. extern WORKUNIT_API IStringVal &getThorQueueNames(IStringVal &ret, const char *process)
  3624. {
  3625. return getProcessQueueNames(ret, process, "ThorCluster", ".thor");
  3626. }
  3627. extern WORKUNIT_API IStringIterator *getTargetClusters(const char *processType, const char *processName)
  3628. {
  3629. Owned<IRemoteConnection> conn = querySDS().connect("Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  3630. Owned<CStringArrayIterator> ret = new CStringArrayIterator;
  3631. if (conn)
  3632. {
  3633. StringBuffer xpath;
  3634. xpath.appendf("%s", processType ? processType : "*");
  3635. if (processName)
  3636. xpath.appendf("[@process=\"%s\"]", processName);
  3637. Owned<IPropertyTreeIterator> targets = conn->queryRoot()->getElements("Software/Topology/Cluster");
  3638. ForEach(*targets)
  3639. {
  3640. IPropertyTree &target = targets->query();
  3641. if (target.hasProp(xpath))
  3642. {
  3643. ret->append(target.queryProp("@name"));
  3644. }
  3645. }
  3646. }
  3647. return ret.getClear();
  3648. }
  3649. IConstWUClusterInfo* getTargetClusterInfo(const char *clustname)
  3650. {
  3651. if (!clustname)
  3652. return NULL;
  3653. Owned<IRemoteConnection> conn = querySDS().connect("Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  3654. if (!conn)
  3655. return NULL;
  3656. StringBuffer xpath;
  3657. // MORE - at the moment configenf specifies eclagent and thor queues by (in effect) placing an 'example' thor or eclagent in the topology
  3658. // that uses the queue that will be used.
  3659. // We should and I hope will change that, at which point the code below gets simpler
  3660. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  3661. Owned<IPropertyTree> cluster = conn->queryRoot()->getPropTree(xpath.str());
  3662. if (!cluster)
  3663. return NULL;
  3664. StringBuffer prefix(cluster->queryProp("@prefix"));
  3665. prefix.toLowerCase();
  3666. StringBuffer querySetName;
  3667. IPropertyTree *agent = NULL;
  3668. const char *agentName = cluster->queryProp("EclAgentProcess/@process");
  3669. if (agentName)
  3670. {
  3671. xpath.clear().appendf("Software/EclAgentProcess[@name=\"%s\"]", agentName);
  3672. agent = conn->queryRoot()->queryPropTree(xpath.str());
  3673. }
  3674. Owned<IPropertyTreeIterator> ti = cluster->getElements("ThorCluster");
  3675. IArrayOf<IPropertyTree> thors;
  3676. ForEach(*ti)
  3677. {
  3678. const char *thorName = ti->query().queryProp("@process");
  3679. if (thorName)
  3680. {
  3681. xpath.clear().appendf("Software/ThorCluster[@name=\"%s\"]", thorName);
  3682. thors.append(*conn->queryRoot()->getPropTree(xpath.str()));
  3683. }
  3684. }
  3685. IPropertyTree *roxie = NULL;
  3686. const char *roxieName = cluster->queryProp("RoxieCluster/@process");
  3687. if (roxieName)
  3688. {
  3689. xpath.clear().appendf("Software/RoxieCluster[@name=\"%s\"]", roxieName);
  3690. roxie = conn->queryRoot()->queryPropTree(xpath.str());
  3691. querySetName.clear().append(roxieName);
  3692. }
  3693. if (querySetName.length() == 0)
  3694. querySetName.append(clustname);
  3695. return new CEnvironmentClusterInfo(clustname, prefix, querySetName, agent, thors, roxie);
  3696. }
  3697. const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name)
  3698. {
  3699. if (!clustname)
  3700. return NULL;
  3701. Owned<IRemoteConnection> conn = querySDS().connect("Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  3702. if (!conn)
  3703. return NULL;
  3704. StringBuffer xpath;
  3705. xpath.appendf("Software/Topology/Cluster[@name=\"%s\"]", clustname);
  3706. Owned<IPropertyTree> cluster = conn->queryRoot()->getPropTree(xpath.str());
  3707. if (!cluster)
  3708. return NULL;
  3709. StringBuffer xpath1;
  3710. xpath1.appendf("%s/@process", processType);
  3711. name.append(cluster->queryProp(xpath1.str()));
  3712. return name.str();
  3713. }
  3714. unsigned getEnvironmentThorClusterNames(StringArray &clusternames, StringArray &groupnames, StringArray &qnames)
  3715. {
  3716. Owned<IRemoteConnection> conn = querySDS().connect("Environment", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  3717. if (!conn)
  3718. return 0;
  3719. Owned<IPropertyTreeIterator> iter = conn->queryRoot()->getElements("Software/Topology/EclServerProcess/Cluster");
  3720. ForEach(*iter) {
  3721. IPropertyTree &tc = iter->query();
  3722. // I think we want the name here but it isn't exactly clear
  3723. const char *cname = tc.queryProp("@name");
  3724. if (cname&&*cname) {
  3725. Owned<IPropertyTreeIterator> iter2 = tc.getElements("ThorCluster");
  3726. ForEach(*iter2) {
  3727. IPropertyTree &tc2 = iter2->query();
  3728. StringBuffer query;
  3729. const char *pname = tc2.queryProp("@process");
  3730. query.appendf("Software/ThorCluster[@name=\"%s\"]",pname);
  3731. IPropertyTree *t = conn->queryRoot()->queryPropTree(query.str());
  3732. if (t) {
  3733. const char *qname = t->queryProp("@queueName");
  3734. if (!qname||!*qname)
  3735. qname = pname;
  3736. const char *gname = t->queryProp("@nodeGroup");
  3737. if (!gname||!*gname)
  3738. gname = pname;
  3739. clusternames.append(cname);
  3740. groupnames.append(gname);
  3741. qnames.append(qname);
  3742. }
  3743. }
  3744. }
  3745. }
  3746. return clusternames.ordinality();
  3747. }
  3748. IStringVal& CLocalWorkUnit::getScope(IStringVal &str) const
  3749. {
  3750. CriticalBlock block(crit);
  3751. if (p->hasProp("Debug/ForceScope"))
  3752. {
  3753. StringBuffer prefix(p->queryProp("Debug/ForceScope"));
  3754. str.set(prefix.toLowerCase().str());
  3755. }
  3756. else
  3757. {
  3758. Owned <IConstWUClusterInfo> ci = getTargetClusterInfo(p->queryProp("@clusterName"));
  3759. if (ci)
  3760. ci->getScope(str);
  3761. else
  3762. str.clear();
  3763. }
  3764. return str;
  3765. }
  3766. //Queries
  3767. void CLocalWorkUnit::setCodeVersion(unsigned codeVersion, const char * buildVersion, const char * eclVersion)
  3768. {
  3769. CriticalBlock block(crit);
  3770. p->setPropInt("@codeVersion", codeVersion);
  3771. p->setProp("@buildVersion", buildVersion);
  3772. p->setProp("@eclVersion", eclVersion);
  3773. }
  3774. unsigned CLocalWorkUnit::getCodeVersion() const
  3775. {
  3776. CriticalBlock block(crit);
  3777. return p->getPropInt("@codeVersion");
  3778. }
  3779. void CLocalWorkUnit::getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const
  3780. {
  3781. CriticalBlock block(crit);
  3782. buildVersion.set(p->queryProp("@buildVersion"));
  3783. eclVersion.set(p->queryProp("@eclVersion"));
  3784. }
  3785. void CLocalWorkUnit::setCloneable(bool value)
  3786. {
  3787. CriticalBlock block(crit);
  3788. p->setPropInt("@cloneable", value);
  3789. }
  3790. void CLocalWorkUnit::setIsClone(bool value)
  3791. {
  3792. CriticalBlock block(crit);
  3793. p->setPropInt("@isClone", value);
  3794. }
  3795. bool CLocalWorkUnit::getCloneable() const
  3796. {
  3797. CriticalBlock block(crit);
  3798. return p->getPropBool("@cloneable", false);
  3799. }
  3800. IUserDescriptor *CLocalWorkUnit::getUserDescriptor() const
  3801. {
  3802. CriticalBlock block(crit);
  3803. if (!userDesc)
  3804. {
  3805. SCMStringBuffer token, user, password;
  3806. getSecurityToken(token);
  3807. SCMStringBuffer wuid;
  3808. getWuid(wuid);
  3809. extractToken(token.str(), wuid.str(), user, password);
  3810. userDesc.setown(createUserDescriptor());
  3811. userDesc->set(user.str(), password.str());
  3812. }
  3813. return LINK(userDesc);
  3814. }
  3815. void CLocalWorkUnit::setCombineQueries(unsigned combine)
  3816. {
  3817. CriticalBlock block(crit);
  3818. p->setPropInt("COMBINE_QUERIES", combine);
  3819. }
  3820. unsigned CLocalWorkUnit::getCombineQueries() const
  3821. {
  3822. CriticalBlock block(crit);
  3823. return p->getPropInt("COMBINE_QUERIES");
  3824. }
  3825. bool CLocalWorkUnit::isProtected() const
  3826. {
  3827. CriticalBlock block(crit);
  3828. return p->getPropBool("@protected", false);
  3829. }
  3830. bool CLocalWorkUnit::isPausing() const
  3831. {
  3832. CriticalBlock block(crit);
  3833. if (WUActionPause == getAction())
  3834. {
  3835. switch (getState())
  3836. {
  3837. case WUStateRunning:
  3838. case WUStateAborting:
  3839. return true;
  3840. }
  3841. }
  3842. return false;
  3843. }
  3844. void CLocalWorkUnit::protect(bool protectMode)
  3845. {
  3846. CriticalBlock block(crit);
  3847. p->setPropBool("@protected", protectMode);
  3848. }
  3849. bool CLocalWorkUnit::isBilled() const
  3850. {
  3851. CriticalBlock block(crit);
  3852. return p->getPropBool("@billed", false);
  3853. }
  3854. void CLocalWorkUnit::setBilled(bool value)
  3855. {
  3856. CriticalBlock block(crit);
  3857. p->setPropBool("@billed", value);
  3858. }
  3859. void CLocalWorkUnit::setResultLimit(unsigned value)
  3860. {
  3861. CriticalBlock block(crit);
  3862. p->setPropInt("resultLimit", value);
  3863. }
  3864. unsigned CLocalWorkUnit::getResultLimit() const
  3865. {
  3866. CriticalBlock block(crit);
  3867. return p->getPropInt("resultLimit");
  3868. }
  3869. void CLocalWorkUnit::setCompareMode(WUCompareMode value)
  3870. {
  3871. CriticalBlock block(crit);
  3872. p->setPropInt("comparemode", (int)value);
  3873. }
  3874. WUCompareMode CLocalWorkUnit::getCompareMode() const
  3875. {
  3876. CriticalBlock block(crit);
  3877. return (WUCompareMode) p->getPropInt("comparemode");
  3878. }
  3879. IStringVal & CLocalWorkUnit::getSnapshot(IStringVal & str) const
  3880. {
  3881. CriticalBlock block(crit);
  3882. str.set(p->queryProp("SNAPSHOT"));
  3883. return str;
  3884. }
  3885. void CLocalWorkUnit::setSnapshot(const char * val)
  3886. {
  3887. CriticalBlock block(crit);
  3888. p->setProp("SNAPSHOT", val);
  3889. }
  3890. static int comparePropTrees(IInterface **ll, IInterface **rr)
  3891. {
  3892. IPropertyTree *l = (IPropertyTree *) *ll;
  3893. IPropertyTree *r = (IPropertyTree *) *rr;
  3894. return stricmp(l->queryName(), r->queryName());
  3895. };
  3896. unsigned CLocalWorkUnit::calculateHash(unsigned crc)
  3897. {
  3898. // Any other values in the WU that could affect generated code should be crc'ed here
  3899. IPropertyTree *tree = p->queryBranch("Debug");
  3900. if (tree)
  3901. {
  3902. Owned<IPropertyTreeIterator> sub = tree->getElements("*");
  3903. ICopyArrayOf<IPropertyTree> subs;
  3904. for(sub->first(); sub->isValid(); sub->next())
  3905. subs.append(sub->query());
  3906. subs.sort(comparePropTrees);
  3907. ForEachItemIn(idx, subs)
  3908. {
  3909. const char *name = subs.item(idx).queryName();
  3910. const char *val = subs.item(idx).queryProp(NULL);
  3911. crc = crc32(name, (size32_t)strlen(name), crc);
  3912. if (val)
  3913. crc = crc32(val, (size32_t)strlen(val), crc);
  3914. }
  3915. }
  3916. Owned<IConstWUPluginIterator> plugins = &getPlugins();
  3917. for (plugins->first();plugins->isValid();plugins->next())
  3918. {
  3919. IConstWUPlugin &thisplugin = plugins->query();
  3920. SCMStringBuffer version;
  3921. thisplugin.getPluginVersion(version);
  3922. crc = crc32(version.str(), version.length(), crc);
  3923. }
  3924. return crc;
  3925. }
  3926. static void updateProp(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  3927. {
  3928. if (!to->hasProp(xpath) && from->hasProp(xpath))
  3929. to->setProp(xpath, from->queryProp(xpath));
  3930. }
  3931. static void copyTree(IPropertyTree * to, const IPropertyTree * from, const char * xpath)
  3932. {
  3933. IPropertyTree * match = from->getBranch(xpath);
  3934. if (match)
  3935. to->setPropTree(xpath, match);
  3936. }
  3937. void CLocalWorkUnit::copyWorkUnit(IConstWorkUnit *cached)
  3938. {
  3939. CLocalWorkUnit *from = QUERYINTERFACE(cached, CLocalWorkUnit);
  3940. if (!from)
  3941. {
  3942. CLockedWorkUnit *fl = QUERYINTERFACE(cached, CLockedWorkUnit);
  3943. if (!fl)
  3944. throw MakeStringException(WUERR_InternalUnknownImplementation, "Cached workunit not created using workunit dll");
  3945. from = fl->c;
  3946. }
  3947. // Need to copy the query, the results, and the graphs from the cached query.
  3948. // The cache is made before the query is executed so there is no need to clear them.
  3949. if (!cached->getCloneable())
  3950. throw MakeStringException(WUERR_CannotCloneWorkunit, "Source work unit not marked as clonable");
  3951. const IPropertyTree * fromP = from->p;
  3952. IPropertyTree *pt;
  3953. CriticalBlock block(crit);
  3954. query.clear();
  3955. updateProp(p, fromP, "@jobName");
  3956. copyTree(p, fromP, "Query");
  3957. pt = fromP->getBranch("Application/LibraryModule");
  3958. if (pt)
  3959. {
  3960. ensurePTree(p, "Application");
  3961. p->setPropTree("Application/LibraryModule", pt);
  3962. }
  3963. pt = fromP->queryBranch("Debug");
  3964. if (pt)
  3965. {
  3966. IPropertyTree *curDebug = p->queryPropTree("Debug");
  3967. if (curDebug)
  3968. {
  3969. Owned<IPropertyTreeIterator> elems = pt->getElements("*");
  3970. ForEach(*elems)
  3971. {
  3972. IPropertyTree *elem = &elems->query();
  3973. if (!curDebug->hasProp(elem->queryName()))
  3974. curDebug->setPropTree(elem->queryName(),LINK(elem));
  3975. }
  3976. }
  3977. else
  3978. p->setPropTree("Debug", LINK(pt));
  3979. }
  3980. copyTree(p, fromP, "Plugins");
  3981. copyTree(p, fromP, "Libraries");
  3982. copyTree(p, fromP, "Results");
  3983. copyTree(p, fromP, "Graphs");
  3984. copyTree(p, fromP, "Workflow");
  3985. updateProp(p, fromP, "@clusterName");
  3986. updateProp(p, fromP, "allowedclusters");
  3987. updateProp(p, fromP, "@submitID");
  3988. updateProp(p, fromP, "CustomerID");
  3989. //Variables may have been set up as parameters to the query - so need to preserve any values that were supplied.
  3990. pt = fromP->getBranch("Variables");
  3991. if (pt)
  3992. {
  3993. IPropertyTree *ptTgtVariables = ensurePTree(p, "Variables");
  3994. Owned<IPropertyTreeIterator> ptiVariable = pt->getElements("Variable");
  3995. for (ptiVariable->first(); ptiVariable->isValid(); ptiVariable->next())
  3996. {
  3997. IPropertyTree *ptSrcVariable = &ptiVariable->query();
  3998. const char *name = ptSrcVariable->queryProp("@name");
  3999. assertex(name);
  4000. StringBuffer xpath;
  4001. xpath.append("Variable[@name='").append(name).append("']");
  4002. IPropertyTree *ptTgtVariable = ptTgtVariables->queryPropTree(xpath.str());
  4003. IPropertyTree *merged = createPTreeFromIPT(ptSrcVariable); // clone entire source info...
  4004. merged->removeProp("Value"); // except value and status
  4005. merged->setProp("@status", "undefined");
  4006. if (!merged->getPropBool("@isScalar"))
  4007. merged->removeProp("totalRowCount");
  4008. merged->removeProp("rowCount");
  4009. // If there are any other fields that get set ONLY by eclagent, strip them out here...
  4010. if (ptTgtVariable)
  4011. {
  4012. // copy status and Value from what is already set in target
  4013. merged->setProp("@status", ptTgtVariable->queryProp("@status"));
  4014. MemoryBuffer value;
  4015. if (ptTgtVariable->getPropBin("Value", value))
  4016. merged->setPropBin("Value", value.length(), value.toByteArray());
  4017. ptTgtVariable->removeProp(xpath.str());
  4018. // If there are any other fields in a variable that get set by ws_ecl before submitting, copy them across here...
  4019. }
  4020. ptTgtVariables->addPropTree("Variable", merged);
  4021. }
  4022. pt->Release();
  4023. }
  4024. p->setProp("@codeVersion", fromP->queryProp("@codeVersion"));
  4025. p->setPropBool("@cloneable", true);
  4026. p->setPropBool("@isClone", true);
  4027. resetWorkflow(); // the source Workflow section may have had some parts already executed...
  4028. // resetResults(); // probably should be resetting the results as well... rather than waiting for the rerun to overwrite them
  4029. }
  4030. bool CLocalWorkUnit::hasDebugValue(const char *propname) const
  4031. {
  4032. StringBuffer lower;
  4033. lower.append(propname).toLowerCase();
  4034. CriticalBlock block(crit);
  4035. StringBuffer prop("Debug/");
  4036. return p->hasProp(prop.append(lower));
  4037. }
  4038. IStringVal& CLocalWorkUnit::getDebugValue(const char *propname, IStringVal &str) const
  4039. {
  4040. StringBuffer lower;
  4041. lower.append(propname).toLowerCase();
  4042. CriticalBlock block(crit);
  4043. StringBuffer prop("Debug/");
  4044. str.set(p->queryProp(prop.append(lower).str()));
  4045. return str;
  4046. }
  4047. IStringIterator& CLocalWorkUnit::getDebugValues() const
  4048. {
  4049. return getDebugValues(NULL);
  4050. }
  4051. IStringIterator& CLocalWorkUnit::getDebugValues(const char *prop) const
  4052. {
  4053. CriticalBlock block(crit);
  4054. StringBuffer path("Debug/");
  4055. if (prop)
  4056. {
  4057. StringBuffer lower;
  4058. lower.append(prop).toLowerCase();
  4059. path.append(lower);
  4060. }
  4061. else
  4062. path.append("*");
  4063. return *new CStringPTreeTagIterator(p->getElements(path.str()));
  4064. }
  4065. int CLocalWorkUnit::getDebugValueInt(const char *propname, int defVal) const
  4066. {
  4067. StringBuffer lower;
  4068. lower.append(propname).toLowerCase();
  4069. CriticalBlock block(crit);
  4070. StringBuffer prop("Debug/");
  4071. prop.append(lower);
  4072. return p->getPropInt(prop.str(), defVal);
  4073. }
  4074. __int64 CLocalWorkUnit::getDebugValueInt64(const char *propname, __int64 defVal) const
  4075. {
  4076. StringBuffer lower;
  4077. lower.append(propname).toLowerCase();
  4078. CriticalBlock block(crit);
  4079. StringBuffer prop("Debug/");
  4080. prop.append(lower);
  4081. return p->getPropInt64(prop.str(), defVal);
  4082. }
  4083. bool CLocalWorkUnit::getDebugValueBool(const char * propname, bool defVal) const
  4084. {
  4085. StringBuffer lower;
  4086. lower.append(propname).toLowerCase();
  4087. CriticalBlock block(crit);
  4088. StringBuffer prop("Debug/");
  4089. prop.append(lower);
  4090. return p->getPropBool(prop.str(), defVal);
  4091. }
  4092. void CLocalWorkUnit::setDebugValue(const char *propname, const char *value, bool overwrite)
  4093. {
  4094. StringBuffer lower;
  4095. lower.append(propname).toLowerCase();
  4096. CriticalBlock block(crit);
  4097. StringBuffer prop("Debug/");
  4098. prop.append(lower);
  4099. if (overwrite || !p->hasProp(prop.str()))
  4100. {
  4101. // MORE - not sure this line should be needed....
  4102. p->setProp("Debug", "");
  4103. p->setProp(prop.str(), value);
  4104. }
  4105. }
  4106. void CLocalWorkUnit::setDebugValueInt(const char *propname, int value, bool overwrite)
  4107. {
  4108. StringBuffer lower;
  4109. lower.append(propname).toLowerCase();
  4110. CriticalBlock block(crit);
  4111. StringBuffer prop("Debug/");
  4112. prop.append(lower);
  4113. if (overwrite || !p->hasProp(prop.str()))
  4114. {
  4115. // MORE - not sure this line should be needed....
  4116. p->setProp("Debug", "");
  4117. p->setPropInt(prop.str(), value);
  4118. }
  4119. }
  4120. void CLocalWorkUnit::setTracingValue(const char *propname, const char *value)
  4121. {
  4122. CriticalBlock block(crit);
  4123. // MORE - not sure this line should be needed....
  4124. p->setProp("Tracing", "");
  4125. StringBuffer prop("Tracing/");
  4126. p->setProp(prop.append(propname).str(), value);
  4127. }
  4128. void CLocalWorkUnit::setTracingValueInt(const char *propname, int value)
  4129. {
  4130. CriticalBlock block(crit);
  4131. StringBuffer prop("Tracing/");
  4132. p->setPropInt(prop.append(propname).str(), value);
  4133. }
  4134. IConstWUQuery* CLocalWorkUnit::getQuery() const
  4135. {
  4136. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  4137. CriticalBlock block(crit);
  4138. if (!query)
  4139. {
  4140. IPropertyTree *s = p->getPropTree("Query");
  4141. if (s)
  4142. query.setown(new CLocalWUQuery(s));
  4143. }
  4144. return query.getLink();
  4145. }
  4146. IWUQuery* CLocalWorkUnit::updateQuery()
  4147. {
  4148. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4149. CriticalBlock block(crit);
  4150. if (!query)
  4151. {
  4152. IPropertyTree *s = p->queryPropTree("Query");
  4153. if (!s)
  4154. s = p->addPropTree("Query", createPTreeFromXMLString("<Query fetchEntire='1'/>"));
  4155. s->Link();
  4156. query.setown(new CLocalWUQuery(s));
  4157. }
  4158. return query.getLink();
  4159. }
  4160. void CLocalWorkUnit::loadPlugins() const
  4161. {
  4162. CriticalBlock block(crit);
  4163. if (!pluginsCached)
  4164. {
  4165. assertex(plugins.length() == 0);
  4166. Owned<IPropertyTreeIterator> r = p->getElements("Plugins/Plugin");
  4167. for (r->first(); r->isValid(); r->next())
  4168. {
  4169. IPropertyTree *rp = &r->query();
  4170. rp->Link();
  4171. plugins.append(*new CLocalWUPlugin(rp));
  4172. }
  4173. pluginsCached = true;
  4174. }
  4175. }
  4176. IConstWUPluginIterator& CLocalWorkUnit::getPlugins() const
  4177. {
  4178. CriticalBlock block(crit);
  4179. loadPlugins();
  4180. return *new CArrayIteratorOf<IConstWUPlugin,IConstWUPluginIterator> (plugins, 0, (IConstWorkUnit *) this);
  4181. }
  4182. void CLocalWorkUnit::loadLibraries() const
  4183. {
  4184. CriticalBlock block(crit);
  4185. if (!librariesCached)
  4186. {
  4187. assertex(libraries.length() == 0);
  4188. Owned<IPropertyTreeIterator> r = p->getElements("Libraries/Library");
  4189. ForEach(*r)
  4190. {
  4191. IPropertyTree *rp = &r->query();
  4192. rp->Link();
  4193. libraries.append(*new CLocalWULibrary(rp));
  4194. }
  4195. librariesCached = true;
  4196. }
  4197. }
  4198. IConstWULibraryIterator& CLocalWorkUnit::getLibraries() const
  4199. {
  4200. CriticalBlock block(crit);
  4201. loadLibraries();
  4202. return *new CArrayIteratorOf<IConstWULibrary,IConstWULibraryIterator> (libraries, 0, (IConstWorkUnit *) this);
  4203. }
  4204. IConstWULibrary * CLocalWorkUnit::getLibraryByName(const char * search) const
  4205. {
  4206. CriticalBlock block(crit);
  4207. loadLibraries();
  4208. ForEachItemIn(idx, libraries)
  4209. {
  4210. SCMStringBuffer name;
  4211. IConstWULibrary &cur = libraries.item(idx);
  4212. cur.getName(name);
  4213. if (stricmp(name.str(), search)==0)
  4214. return &OLINK(cur);
  4215. }
  4216. return NULL;
  4217. }
  4218. unsigned CLocalWorkUnit::getTimerDuration(const char *name, const char *_unused) const
  4219. {
  4220. CriticalBlock block(crit);
  4221. StringBuffer pname;
  4222. pname.appendf("Timings/Timing[@name=\"%s\"]/@duration", name);
  4223. return p->getPropInt(pname.str(), 0);
  4224. }
  4225. unsigned CLocalWorkUnit::getTimerCount(const char *name, const char *_unused) const
  4226. {
  4227. CriticalBlock block(crit);
  4228. StringBuffer pname;
  4229. pname.appendf("Timings/Timing[@name=\"%s\"]/@count", name);
  4230. return p->getPropInt(pname.str(), 0);
  4231. }
  4232. IStringIterator& CLocalWorkUnit::getTimers() const
  4233. {
  4234. CriticalBlock block(crit);
  4235. return *new CStringPTreeAttrIterator(p->getElements("Timings/Timing"), "@name");
  4236. }
  4237. StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum, unsigned __int64 subId)
  4238. {
  4239. str.append("Graph ").append(graphName);
  4240. if (subGraphNum) str.append(" - ").append(subGraphNum).append(" (").append(subId).append(")");
  4241. else if (subId) str.append(" - id(").append(subId).append(")");
  4242. return str;
  4243. }
  4244. bool parseGraphTimerLabel(const char *label, StringBuffer &graphName, unsigned &subGraphNum, unsigned __int64 &subId)
  4245. {
  4246. // expects format: "Graph <graphname>[ - <subgraphnum> (<subgraphid>)]"
  4247. unsigned len = (size32_t)strlen(label);
  4248. if (len < 6 || (0 != memcmp(label, "Graph ", 6)))
  4249. return false;
  4250. subGraphNum = 0;
  4251. subId = 0;
  4252. const char *finger = label+6;
  4253. const char *finger2 = strchr(finger, '-');
  4254. if (NULL == finger2) // just graphName
  4255. graphName.append(finger);
  4256. else
  4257. {
  4258. graphName.append((size32_t)((finger2-1)-finger), finger);
  4259. finger = finger2+2; // skip '-' and space
  4260. finger2 = strchr(finger, ' ');
  4261. if (finger2)
  4262. {
  4263. subGraphNum = atoi_l(finger, (size32_t)(finger2-finger));
  4264. finger = finger2+2; // skip space and '('
  4265. finger2 = strchr(finger, ')');
  4266. if (finger2)
  4267. subId = atoi64_l(finger, (size32_t)(finger2-finger));
  4268. }
  4269. else if (((len-(finger-label))>3) && 0 == memcmp(finger, "id(", 3)) // subgraph id only, new format.
  4270. {
  4271. finger += 3;
  4272. finger2 = strchr(finger, ')');
  4273. if (finger2)
  4274. subId = atoi64_l(finger, (size32_t)(finger2-finger));
  4275. }
  4276. }
  4277. return true;
  4278. }
  4279. void CLocalWorkUnit::setTimerInfo(const char *name, const char *subname, unsigned ms, unsigned count, unsigned max)
  4280. {
  4281. CriticalBlock block(crit);
  4282. IPropertyTree *timings = p->queryPropTree("Timings");
  4283. if (!timings)
  4284. timings = p->addPropTree("Timings", createPTree("Timings"));
  4285. StringBuffer fullname;
  4286. if (subname)
  4287. fullname.append('.').append(subname);
  4288. fullname.append(name);
  4289. StringBuffer xpath;
  4290. xpath.append("Timing[@name=\"").append(fullname).append("\"]");
  4291. IPropertyTree *timing = timings->queryPropTree(xpath.str());
  4292. if (!timing)
  4293. {
  4294. timing = timings->addPropTree("Timing", createPTree("Timing"));
  4295. timing->setProp("@name", fullname.str());
  4296. }
  4297. timing->setPropInt("@count", count);
  4298. timing->setPropInt("@duration", ms);
  4299. if (!max && 1==count) max = ms;
  4300. if (max)
  4301. timing->setPropInt("@max", max);
  4302. }
  4303. void CLocalWorkUnit::setTimeStamp(const char *application, const char *instance, const char *event, bool add)
  4304. {
  4305. CriticalBlock block(crit);
  4306. char timeStamp[64];
  4307. time_t tNow;
  4308. time(&tNow);
  4309. #ifdef _WIN32
  4310. struct tm *gmtNow;
  4311. gmtNow = gmtime(&tNow);
  4312. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%SZ", gmtNow);
  4313. #else
  4314. struct tm gmtNow;
  4315. gmtime_r(&tNow, &gmtNow);
  4316. strftime(timeStamp, 64, "%Y-%m-%dT%H:%M:%SZ", &gmtNow);
  4317. #endif //_WIN32
  4318. IPropertyTree *ts = p->queryPropTree("TimeStamps");
  4319. if (!ts) {
  4320. ts = p->addPropTree("TimeStamps", createPTree("TimeStamps"));
  4321. add = true;
  4322. }
  4323. IPropertyTree *t=NULL;
  4324. if (!add) {
  4325. StringBuffer path;
  4326. path.appendf("TimeStamp[@application=\"%s\"]",application);
  4327. t = ts->queryBranch(path.str());
  4328. }
  4329. if (!t) {
  4330. t = createPTree("TimeStamp");
  4331. t->setProp("@application", application);
  4332. add = true;
  4333. }
  4334. if (instance)
  4335. t->setProp("@instance", instance);
  4336. t->setProp(event, timeStamp);
  4337. IPropertyTree *et = t->queryPropTree(event);
  4338. if(et)
  4339. et->setPropInt("@ts",(int)tNow);
  4340. if (add)
  4341. ts->addPropTree("TimeStamp", t);
  4342. }
  4343. void CLocalWorkUnit::setTimeStamp(const char *application, const char *instance, const char *event)
  4344. {
  4345. setTimeStamp(application,instance,event,false);
  4346. }
  4347. void CLocalWorkUnit::addTimeStamp(const char *application, const char *instance, const char *event)
  4348. {
  4349. setTimeStamp(application,instance,event,true);
  4350. }
  4351. IStringVal &CLocalWorkUnit::getTimeStamp(const char *name, const char *application, IStringVal &str) const
  4352. {
  4353. CriticalBlock block(crit);
  4354. str.clear();
  4355. StringBuffer pname("TimeStamps/TimeStamp");
  4356. if (application)
  4357. pname.appendf("[@application=\"%s\"]", application);
  4358. pname.appendf("/%s", name);
  4359. Owned<IPropertyTreeIterator> stamps = p->getElements(pname.str());
  4360. if (stamps && stamps->first())
  4361. str.set(stamps->query().queryProp(NULL));
  4362. return str;
  4363. }
  4364. IConstWUTimeStampIterator& CLocalWorkUnit::getTimeStamps() const
  4365. {
  4366. CriticalBlock block(crit);
  4367. timestamps.load(p,"TimeStamps/*");
  4368. return *new CArrayIteratorOf<IConstWUTimeStamp,IConstWUTimeStampIterator> (timestamps, 0, (IConstWorkUnit *) this);
  4369. }
  4370. bool CLocalWorkUnit::getWuDate(unsigned & year, unsigned & month, unsigned& day)
  4371. {
  4372. CriticalBlock block(crit);
  4373. SCMStringBuffer wuidstr;
  4374. const char *wuid = getWuid(wuidstr).str();
  4375. if (sscanf(wuid, "W%4u%2u%2u", &year, &month, &day)==3)
  4376. {
  4377. }
  4378. return false;
  4379. }
  4380. IWUPlugin* CLocalWorkUnit::updatePluginByName(const char *qname)
  4381. {
  4382. CriticalBlock block(crit);
  4383. IConstWUPlugin *existing = getPluginByName(qname);
  4384. if (existing)
  4385. return (IWUPlugin *) existing;
  4386. if (!plugins.length())
  4387. p->addPropTree("Plugins", createPTree("Plugins"));
  4388. IPropertyTree *pl = p->queryPropTree("Plugins");
  4389. IPropertyTree *s = pl->addPropTree("Plugin", createPTree("Plugin"));
  4390. s->Link();
  4391. IWUPlugin* q = new CLocalWUPlugin(s);
  4392. q->Link();
  4393. plugins.append(*q);
  4394. q->setPluginName(qname);
  4395. return q;
  4396. }
  4397. IConstWUPlugin* CLocalWorkUnit::getPluginByName(const char *qname) const
  4398. {
  4399. CriticalBlock block(crit);
  4400. loadPlugins();
  4401. ForEachItemIn(idx, plugins)
  4402. {
  4403. SCMStringBuffer name;
  4404. IConstWUPlugin &cur = plugins.item(idx);
  4405. cur.getPluginName(name);
  4406. if (stricmp(name.str(), qname)==0)
  4407. {
  4408. cur.Link();
  4409. return &cur;
  4410. }
  4411. }
  4412. return NULL;
  4413. }
  4414. IWULibrary* CLocalWorkUnit::updateLibraryByName(const char *qname)
  4415. {
  4416. CriticalBlock block(crit);
  4417. IConstWULibrary *existing = getLibraryByName(qname);
  4418. if (existing)
  4419. return (IWULibrary *) existing;
  4420. if (!libraries.length())
  4421. p->addPropTree("Libraries", createPTree("Libraries"));
  4422. IPropertyTree *pl = p->queryPropTree("Libraries");
  4423. IPropertyTree *s = pl->addPropTree("Library", createPTree("Library"));
  4424. s->Link();
  4425. IWULibrary* q = new CLocalWULibrary(s);
  4426. q->Link();
  4427. libraries.append(*q);
  4428. q->setName(qname);
  4429. return q;
  4430. }
  4431. void CLocalWorkUnit::loadExceptions() const
  4432. {
  4433. CriticalBlock block(crit);
  4434. if (!exceptionsCached)
  4435. {
  4436. assertex(exceptions.length() == 0);
  4437. Owned<IPropertyTreeIterator> r = p->getElements("Exceptions/Exception");
  4438. for (r->first(); r->isValid(); r->next())
  4439. {
  4440. IPropertyTree *rp = &r->query();
  4441. rp->Link();
  4442. exceptions.append(*new CLocalWUException(rp));
  4443. }
  4444. exceptionsCached = true;
  4445. }
  4446. }
  4447. IConstWUExceptionIterator& CLocalWorkUnit::getExceptions() const
  4448. {
  4449. CriticalBlock block(crit);
  4450. loadExceptions();
  4451. return *new CArrayIteratorOf<IConstWUException,IConstWUExceptionIterator> (exceptions, 0, (IConstWorkUnit *) this);
  4452. }
  4453. unsigned CLocalWorkUnit::getExceptionCount() const
  4454. {
  4455. CriticalBlock block(crit);
  4456. loadExceptions();
  4457. return exceptions.length();
  4458. }
  4459. void CLocalWorkUnit::clearExceptions()
  4460. {
  4461. CriticalBlock block(crit);
  4462. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4463. exceptions.kill();
  4464. exceptionsCached = true;
  4465. p->removeProp("Exceptions");
  4466. }
  4467. IWUException* CLocalWorkUnit::createException()
  4468. {
  4469. CriticalBlock block(crit);
  4470. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4471. loadExceptions();
  4472. if (!exceptions.length())
  4473. p->addPropTree("Exceptions", createPTree("Exceptions"));
  4474. IPropertyTree *r = p->queryPropTree("Exceptions");
  4475. IPropertyTree *s = r->addPropTree("Exception", createPTree("Exception"));
  4476. IWUException* q = new CLocalWUException(LINK(s));
  4477. exceptions.append(*LINK(q));
  4478. Owned<IJlibDateTime> now = createDateTimeNow();
  4479. SCMStringBuffer temp;
  4480. now->getString(temp);
  4481. q->setTimeStamp(temp.str());
  4482. return q;
  4483. }
  4484. IConstWUWebServicesInfo* CLocalWorkUnit::getWebServicesInfo() const
  4485. {
  4486. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  4487. CriticalBlock block(crit);
  4488. if (!webServicesInfoCached)
  4489. {
  4490. assertex(!webServicesInfo);
  4491. IPropertyTree *s = p->getPropTree("WebServicesInfo");
  4492. if (s)
  4493. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  4494. webServicesInfoCached = true;
  4495. }
  4496. return webServicesInfo.getLink();
  4497. }
  4498. IWUWebServicesInfo* CLocalWorkUnit::updateWebServicesInfo(bool create)
  4499. {
  4500. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4501. CriticalBlock block(crit);
  4502. if (!webServicesInfoCached)
  4503. {
  4504. IPropertyTree *s = p->queryPropTree("WebServicesInfo");
  4505. if (!s)
  4506. {
  4507. if (create)
  4508. s = p->addPropTree("WebServicesInfo", createPTreeFromXMLString("<WebServicesInfo />"));
  4509. else
  4510. return NULL;
  4511. }
  4512. s->Link();
  4513. webServicesInfo.setown(new CLocalWUWebServicesInfo(s));
  4514. webServicesInfoCached = true;
  4515. }
  4516. return webServicesInfo.getLink();
  4517. }
  4518. IConstWURoxieQueryInfo* CLocalWorkUnit::getRoxieQueryInfo() const
  4519. {
  4520. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  4521. CriticalBlock block(crit);
  4522. if (!roxieQueryInfoCached)
  4523. {
  4524. assertex(!roxieQueryInfo);
  4525. IPropertyTree *s = p->getPropTree("RoxieQueryInfo");
  4526. if (s)
  4527. roxieQueryInfo.setown(new CLocalWURoxieQueryInfo(s));
  4528. roxieQueryInfoCached = true;
  4529. }
  4530. return roxieQueryInfo.getLink();
  4531. }
  4532. IWURoxieQueryInfo* CLocalWorkUnit::updateRoxieQueryInfo(const char *wuid, const char *roxieClusterName)
  4533. {
  4534. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4535. CriticalBlock block(crit);
  4536. if (!roxieQueryInfoCached)
  4537. {
  4538. IPropertyTree *s = p->queryPropTree("RoxieQueryInfo");
  4539. if (!s)
  4540. s = p->addPropTree("RoxieQueryInfo", createPTreeFromXMLString("<RoxieQueryInfo />"));
  4541. if (wuid && *wuid)
  4542. s->addProp("@wuid", wuid);
  4543. if (roxieClusterName && *roxieClusterName)
  4544. s->addProp("@roxieClusterName", roxieClusterName);
  4545. s->Link();
  4546. roxieQueryInfo.setown(new CLocalWURoxieQueryInfo(s));
  4547. roxieQueryInfoCached = true;
  4548. }
  4549. return roxieQueryInfo.getLink();
  4550. }
  4551. static int compareResults(IInterface **ll, IInterface **rr)
  4552. {
  4553. CLocalWUResult *l = (CLocalWUResult *) *ll;
  4554. CLocalWUResult *r = (CLocalWUResult *) *rr;
  4555. return l->getResultSequence() - r->getResultSequence();
  4556. }
  4557. void CLocalWorkUnit::loadResults() const
  4558. {
  4559. CriticalBlock block(crit);
  4560. if (!resultsCached)
  4561. {
  4562. assertex(results.length() == 0);
  4563. Owned<IPropertyTreeIterator> r = p->getElements("Results/Result");
  4564. for (r->first(); r->isValid(); r->next())
  4565. {
  4566. IPropertyTree *rp = &r->query();
  4567. rp->Link();
  4568. results.append(*new CLocalWUResult(rp));
  4569. }
  4570. results.sort(compareResults);
  4571. resultsCached = true;
  4572. }
  4573. }
  4574. void CLocalWorkUnit::loadVariables() const
  4575. {
  4576. CriticalBlock block(crit);
  4577. if (!variablesCached)
  4578. {
  4579. assertex(variables.length() == 0);
  4580. Owned<IPropertyTreeIterator> r = p->getElements("Variables/Variable");
  4581. for (r->first(); r->isValid(); r->next())
  4582. {
  4583. IPropertyTree *rp = &r->query();
  4584. rp->Link();
  4585. variables.append(*new CLocalWUResult(rp));
  4586. }
  4587. variablesCached = true;
  4588. }
  4589. }
  4590. void CLocalWorkUnit::loadTemporaries() const
  4591. {
  4592. CriticalBlock block(crit);
  4593. if (!temporariesCached)
  4594. {
  4595. assertex(temporaries.length() == 0);
  4596. Owned<IPropertyTreeIterator> r = p->getElements("Temporaries/Variable");
  4597. for (r->first(); r->isValid(); r->next())
  4598. {
  4599. IPropertyTree *rp = &r->query();
  4600. rp->Link();
  4601. temporaries.append(*new CLocalWUResult(rp));
  4602. }
  4603. temporariesCached = true;
  4604. }
  4605. }
  4606. IWUResult* CLocalWorkUnit::createResult()
  4607. {
  4608. CriticalBlock block(crit);
  4609. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  4610. loadResults();
  4611. if (!results.length())
  4612. p->addPropTree("Results", createPTree("Results"));
  4613. IPropertyTree *r = p->queryPropTree("Results");
  4614. IPropertyTree *s = r->addPropTree("Result", createPTreeFromXMLString("<Result fetchEntire='1'/>"));
  4615. s->Link();
  4616. IWUResult* q = new CLocalWUResult(s);
  4617. q->Link();
  4618. results.append(*q);
  4619. return q;
  4620. }
  4621. IWUResult* CLocalWorkUnit::updateResultByName(const char *qname)
  4622. {
  4623. CriticalBlock block(crit);
  4624. IConstWUResult *existing = getResultByName(qname);
  4625. if (existing)
  4626. return (IWUResult *) existing;
  4627. IWUResult* q = createResult();
  4628. q->setResultName(qname);
  4629. return q;
  4630. }
  4631. IWUResult* CLocalWorkUnit::updateResultBySequence(unsigned seq)
  4632. {
  4633. CriticalBlock block(crit);
  4634. IConstWUResult *existing = getResultBySequence(seq);
  4635. if (existing)
  4636. return (IWUResult *) existing;
  4637. IWUResult* q = createResult();
  4638. q->setResultSequence(seq);
  4639. return q;
  4640. }
  4641. IConstWUResultIterator& CLocalWorkUnit::getResults() const
  4642. {
  4643. CriticalBlock block(crit);
  4644. loadResults();
  4645. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (results, 0, (IConstWorkUnit *) this);
  4646. }
  4647. IConstWUResult* CLocalWorkUnit::getResultByName(const char *qname) const
  4648. {
  4649. CriticalBlock block(crit);
  4650. loadResults();
  4651. ForEachItemIn(idx, results)
  4652. {
  4653. SCMStringBuffer name;
  4654. IConstWUResult &cur = results.item(idx);
  4655. cur.getResultName(name);
  4656. if (stricmp(name.str(), qname)==0)
  4657. {
  4658. cur.Link();
  4659. return &cur;
  4660. }
  4661. }
  4662. return NULL;
  4663. }
  4664. IConstWUResult* CLocalWorkUnit::getResultBySequence(unsigned seq) const
  4665. {
  4666. CriticalBlock block(crit);
  4667. loadResults();
  4668. ForEachItemIn(idx, results)
  4669. {
  4670. IConstWUResult &cur = results.item(idx);
  4671. if (cur.getResultSequence() == seq)
  4672. {
  4673. cur.Link();
  4674. return &cur;
  4675. }
  4676. }
  4677. return NULL;
  4678. }
  4679. IConstWUResultIterator& CLocalWorkUnit::getVariables() const
  4680. {
  4681. CriticalBlock block(crit);
  4682. loadVariables();
  4683. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (variables, 0, (IConstWorkUnit *) this);
  4684. }
  4685. IConstWUResult* CLocalWorkUnit::getGlobalByName(const char *qname) const
  4686. {
  4687. CriticalBlock block(crit);
  4688. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  4689. return getVariableByName(qname);
  4690. Owned <IConstWorkUnit> global = factory->openWorkUnit(GLOBAL_WORKUNIT, false);
  4691. if (!global)
  4692. global.setown(factory->createWorkUnit(NULL, NULL, NULL));
  4693. return global->getVariableByName(qname);
  4694. }
  4695. IWUResult* CLocalWorkUnit::updateGlobalByName(const char *qname)
  4696. {
  4697. CriticalBlock block(crit);
  4698. if (strcmp(p->queryName(), GLOBAL_WORKUNIT)==0)
  4699. return updateVariableByName(qname);
  4700. Owned <IWorkUnit> global = factory->ensureNamedWorkUnit(GLOBAL_WORKUNIT);
  4701. return global->updateVariableByName(qname);
  4702. }
  4703. IConstWUResult* CLocalWorkUnit::getVariableByName(const char *qname) const
  4704. {
  4705. CriticalBlock block(crit);
  4706. loadVariables();
  4707. ForEachItemIn(idx, variables)
  4708. {
  4709. SCMStringBuffer name;
  4710. IConstWUResult &cur = variables.item(idx);
  4711. cur.getResultName(name);
  4712. if (stricmp(name.str(), qname)==0)
  4713. {
  4714. cur.Link();
  4715. return &cur;
  4716. }
  4717. }
  4718. return NULL;
  4719. }
  4720. IConstWUResult* CLocalWorkUnit::getTemporaryByName(const char *qname) const
  4721. {
  4722. CriticalBlock block(crit);
  4723. loadTemporaries();
  4724. ForEachItemIn(idx, temporaries)
  4725. {
  4726. SCMStringBuffer name;
  4727. IConstWUResult &cur = temporaries.item(idx);
  4728. cur.getResultName(name);
  4729. if (stricmp(name.str(), qname)==0)
  4730. {
  4731. cur.Link();
  4732. return &cur;
  4733. }
  4734. }
  4735. return NULL;
  4736. }
  4737. IConstWUResultIterator& CLocalWorkUnit::getTemporaries() const
  4738. {
  4739. CriticalBlock block(crit);
  4740. loadTemporaries();
  4741. return *new CArrayIteratorOf<IConstWUResult,IConstWUResultIterator> (temporaries, 0, (IConstWorkUnit *) this);
  4742. }
  4743. IWUResult* CLocalWorkUnit::updateTemporaryByName(const char *qname)
  4744. {
  4745. CriticalBlock block(crit);
  4746. IConstWUResult *existing = getTemporaryByName(qname);
  4747. if (existing)
  4748. return (IWUResult *) existing;
  4749. if (!temporaries.length())
  4750. p->addPropTree("Temporaries", createPTree("Temporaries"));
  4751. IPropertyTree *vars = p->queryPropTree("Temporaries");
  4752. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  4753. s->Link();
  4754. IWUResult* q = new CLocalWUResult(s);
  4755. q->Link();
  4756. temporaries.append(*q);
  4757. q->setResultName(qname);
  4758. return q;
  4759. }
  4760. IWUResult* CLocalWorkUnit::updateVariableByName(const char *qname)
  4761. {
  4762. CriticalBlock block(crit);
  4763. IConstWUResult *existing = getVariableByName(qname);
  4764. if (existing)
  4765. return (IWUResult *) existing;
  4766. if (!variables.length())
  4767. p->addPropTree("Variables", createPTree("Variables"));
  4768. IPropertyTree *vars = p->queryPropTree("Variables");
  4769. IPropertyTree *s = vars->addPropTree("Variable", createPTree("Variable"));
  4770. s->Link();
  4771. IWUResult* q = new CLocalWUResult(s);
  4772. q->Link();
  4773. variables.append(*q);
  4774. q->setResultName(qname);
  4775. return q;
  4776. }
  4777. void CLocalWorkUnit::deleteTempFiles(const char *graph, bool deleteOwned, bool deleteJobOwned)
  4778. {
  4779. CriticalBlock block(crit);
  4780. IPropertyTree *files = p->queryPropTree("Files");
  4781. if (!files) return;
  4782. Owned<IPropertyTreeIterator> iter = files->getElements("File");
  4783. ICopyArrayOf<IPropertyTree> toRemove;
  4784. ForEach (*iter)
  4785. {
  4786. IPropertyTree &file = iter->query();
  4787. WUFileKind fileKind = (WUFileKind) file.getPropInt("@kind", WUFileStandard);
  4788. if(file.getPropBool("@temporary")) fileKind = WUFileTemporary; // @temporary, legacy check
  4789. bool needDelete;
  4790. switch(fileKind)
  4791. {
  4792. case WUFileTemporary:
  4793. if(graph==NULL)
  4794. needDelete = true;
  4795. else
  4796. {
  4797. const char *graphOwner = file.queryProp("@graph");
  4798. needDelete = ((graphOwner==NULL) || (strcmp(graph, graphOwner)==0));
  4799. }
  4800. break;
  4801. case WUFileJobOwned:
  4802. needDelete = ((graph==NULL) && deleteJobOwned);
  4803. break;
  4804. case WUFileOwned:
  4805. needDelete = ((graph==NULL) && deleteOwned);
  4806. break;
  4807. default:
  4808. needDelete = false;
  4809. }
  4810. if(needDelete)
  4811. {
  4812. const char *name = file.queryProp("@name");
  4813. LOG(MCdebugProgress, unknownJob, "Removing workunit file %s from DFS", name);
  4814. Owned<IUserDescriptor> userDesc = getUserDescriptor();
  4815. queryDistributedFileDirectory().removePhysical(name, 0, NULL, NULL, userDesc);
  4816. toRemove.append(file);
  4817. }
  4818. }
  4819. ForEachItemIn(r, toRemove) files->removeTree(&toRemove.item(r));
  4820. }
  4821. static void _noteFileRead(IDistributedFile *file, IPropertyTree *filesRead)
  4822. {
  4823. IDistributedSuperFile *super = file->querySuperFile();
  4824. StringBuffer fname;
  4825. file->getLogicalName(fname);
  4826. StringBuffer path("File[@name=\"");
  4827. path.append(fname).append("\"]");
  4828. IPropertyTree *fileTree = filesRead->queryPropTree(path.str());
  4829. if (fileTree)
  4830. fileTree->setPropInt("@useCount", fileTree->getPropInt("@useCount")+1);
  4831. else
  4832. {
  4833. StringBuffer cluster;
  4834. file->getClusterName(0,cluster);
  4835. fileTree = createPTree();
  4836. fileTree->setProp("@name", fname.str());
  4837. fileTree->setProp("@cluster", cluster.str());
  4838. fileTree->setPropInt("@useCount", 1);
  4839. fileTree = filesRead->addPropTree("File", fileTree);
  4840. }
  4841. if (super)
  4842. {
  4843. Owned<IDistributedFileIterator> iter = super->getSubFileIterator(false);
  4844. ForEach (*iter)
  4845. {
  4846. IDistributedFile &file = iter->query();
  4847. StringBuffer fname;
  4848. file.getLogicalName(fname);
  4849. Owned<IPropertyTree> subfile = createPTree();
  4850. subfile->setProp("@name", fname.str());
  4851. fileTree->addPropTree("Subfile", subfile.getClear());
  4852. _noteFileRead(&file, filesRead);
  4853. }
  4854. }
  4855. }
  4856. void CLocalWorkUnit::noteFileRead(IDistributedFile *file)
  4857. {
  4858. CriticalBlock block(crit);
  4859. IPropertyTree *files = p->queryPropTree("FilesRead");
  4860. if (!files)
  4861. files = p->addPropTree("FilesRead", createPTree());
  4862. _noteFileRead(file, files);
  4863. }
  4864. static void addFile(IPropertyTree *files, const char *fileName, const char *cluster, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  4865. {
  4866. StringBuffer path("File[@name=\"");
  4867. path.append(fileName).append("\"]");
  4868. if (cluster)
  4869. path.append("[@cluster=\"").append(cluster).append("\"]");
  4870. IPropertyTree *file = files->queryPropTree(path.str());
  4871. if (file) files->removeTree(file);
  4872. file = createPTree();
  4873. file->setProp("@name", fileName);
  4874. if (cluster)
  4875. file->setProp("@cluster", cluster);
  4876. if (graphOwner)
  4877. file->setProp("@graph", graphOwner);
  4878. file->setPropInt("@kind", (unsigned)fileKind);
  4879. if (WUFileTemporary == fileKind)
  4880. file->setPropInt("@usageCount", usageCount);
  4881. files->addPropTree("File", file);
  4882. }
  4883. void CLocalWorkUnit::addFile(const char *fileName, StringArray *clusters, unsigned usageCount, WUFileKind fileKind, const char *graphOwner)
  4884. {
  4885. CriticalBlock block(crit);
  4886. IPropertyTree *files = p->queryPropTree("Files");
  4887. if (!files)
  4888. files = p->addPropTree("Files", createPTree());
  4889. if (!clusters)
  4890. addFile(fileName, NULL, usageCount, fileKind, graphOwner);
  4891. else
  4892. {
  4893. ForEachItemIn(c, *clusters)
  4894. ::addFile(files, fileName, clusters->item(c), usageCount, fileKind, graphOwner);
  4895. }
  4896. }
  4897. void CLocalWorkUnit::releaseFile(const char *fileName)
  4898. {
  4899. StringBuffer path("File[@name=\"");
  4900. path.append(fileName).append("\"]");
  4901. CriticalBlock block(crit);
  4902. IPropertyTree *files = p->queryPropTree("Files");
  4903. if (!files) return;
  4904. Owned<IPropertyTreeIterator> fiter = files->getElements(path.str());
  4905. ForEach (*fiter)
  4906. {
  4907. IPropertyTree *file = &fiter->query();
  4908. unsigned usageCount = file->getPropInt("@usageCount");
  4909. if (usageCount > 1)
  4910. file->setPropInt("@usageCount", usageCount-1);
  4911. else
  4912. {
  4913. StringAttr name(file->queryProp("@name"));
  4914. files->removeTree(file);
  4915. if (!name.isEmpty()&&(1 == usageCount))
  4916. {
  4917. Owned<IUserDescriptor> userDesc = getUserDescriptor();
  4918. if (queryDistributedFileDirectory().removePhysical(fileName, 0, NULL, NULL, userDesc))
  4919. LOG(MCdebugProgress, unknownJob, "Removed (released) file %s from DFS", name.get());
  4920. }
  4921. }
  4922. }
  4923. }
  4924. void CLocalWorkUnit::clearGraphProgress()
  4925. {
  4926. CConstGraphProgress::deleteWuidProgress(p->queryName());
  4927. }
  4928. void CLocalWorkUnit::resetBeforeGeneration()
  4929. {
  4930. CriticalBlock block(crit);
  4931. //Remove all associated files
  4932. Owned<IWUQuery> q = updateQuery();
  4933. q->removeAssociatedFiles();
  4934. //Remove any pre-existing workflow information
  4935. workflowIterator.clear();
  4936. p->removeProp("Workflow");
  4937. }
  4938. unsigned CLocalWorkUnit::queryFileUsage(const char *fileName) const
  4939. {
  4940. StringBuffer path("Files/File[@name=\"");
  4941. path.append(fileName).append("\"]/@usageCount");
  4942. CriticalBlock block(crit);
  4943. return p->getPropInt(path.str());
  4944. }
  4945. IPropertyTree *CLocalWorkUnit::getDiskUsageStats()
  4946. {
  4947. return p->getPropTree("DiskUsageStats");
  4948. }
  4949. void CLocalWorkUnit::addDiskUsageStats(__int64 _avgNodeUsage, unsigned _minNode, __int64 _minNodeUsage, unsigned _maxNode, __int64 _maxNodeUsage, __int64 _graphId)
  4950. {
  4951. IPropertyTree *stats = p->queryPropTree("DiskUsageStats");
  4952. offset_t maxNodeUsage;
  4953. if (stats)
  4954. maxNodeUsage = stats->getPropInt64("@maxNodeUsage");
  4955. else
  4956. {
  4957. stats = p->addPropTree("DiskUsageStats", createPTree());
  4958. maxNodeUsage = 0;
  4959. }
  4960. if ((offset_t)_maxNodeUsage > maxNodeUsage)
  4961. {
  4962. // record all details at time of max node usage.
  4963. stats->setPropInt("@minNode", _minNode);
  4964. stats->setPropInt("@maxNode", _maxNode);
  4965. stats->setPropInt64("@minNodeUsage", _minNodeUsage);
  4966. stats->setPropInt64("@maxNodeUsage", _maxNodeUsage);
  4967. stats->setPropInt64("@graphId", _graphId);
  4968. if (_avgNodeUsage)
  4969. {
  4970. unsigned _skewHi = (unsigned)((100 * (_maxNodeUsage-_avgNodeUsage))/_avgNodeUsage);
  4971. unsigned _skewLo = (unsigned)((100 * (_avgNodeUsage-_minNodeUsage))/_avgNodeUsage);
  4972. stats->setPropInt("@skewHi", _skewHi);
  4973. stats->setPropInt("@skewLo", _skewLo);
  4974. }
  4975. }
  4976. }
  4977. IPropertyTreeIterator & CLocalWorkUnit::getFileIterator() const
  4978. {
  4979. CriticalBlock block(crit);
  4980. return * p->getElements("Files/File");
  4981. }
  4982. IPropertyTreeIterator & CLocalWorkUnit::getFilesReadIterator() const
  4983. {
  4984. CriticalBlock block(crit);
  4985. return * p->getElements("FilesRead/File");
  4986. }
  4987. //=================================================================================================
  4988. IWUActivity * CLocalWorkUnit::updateActivity(__int64 id)
  4989. {
  4990. CriticalBlock block(crit);
  4991. IConstWUActivity *existing = getActivity(id);
  4992. if (existing)
  4993. return (IWUActivity *) existing;
  4994. if (!activities.length())
  4995. p->addPropTree("Activities", createPTree("Activities"));
  4996. IPropertyTree *pl = p->queryPropTree("Activities");
  4997. IPropertyTree *s = pl->addPropTree("Activity", createPTree("Activity"));
  4998. IWUActivity * q = new CLocalWUActivity(LINK(s), id);
  4999. activities.append(*LINK(q));
  5000. return q;
  5001. }
  5002. IConstWUActivity * CLocalWorkUnit::getActivity(__int64 id) const
  5003. {
  5004. CriticalBlock block(crit);
  5005. loadActivities();
  5006. ForEachItemIn(idx, activities)
  5007. {
  5008. IConstWUActivity &cur = activities.item(idx);
  5009. if (cur.getId() == id)
  5010. return &OLINK(cur);
  5011. }
  5012. return NULL;
  5013. }
  5014. void CLocalWorkUnit::loadActivities() const
  5015. {
  5016. CriticalBlock block(crit);
  5017. if (!activitiesCached)
  5018. {
  5019. assertex(activities.length() == 0);
  5020. Owned<IPropertyTreeIterator> r = p->getElements("Activities/Activity");
  5021. for (r->first(); r->isValid(); r->next())
  5022. {
  5023. IPropertyTree *rp = &r->query();
  5024. rp->Link();
  5025. activities.append(*new CLocalWUActivity(rp));
  5026. }
  5027. activitiesCached = true;
  5028. }
  5029. }
  5030. IConstWUActivityIterator& CLocalWorkUnit::getActivities() const
  5031. {
  5032. CriticalBlock block(crit);
  5033. loadActivities();
  5034. return *new CArrayIteratorOf<IConstWUActivity,IConstWUActivityIterator> (activities, 0, (IConstWorkUnit *) this);
  5035. }
  5036. //=================================================================================================
  5037. bool CLocalWorkUnit::switchThorQueue(const char *cluster, IQueueSwitcher *qs)
  5038. {
  5039. CriticalBlock block(crit);
  5040. if (qs->isAuto()&&!getAllowAutoQueueSwitch())
  5041. return false;
  5042. Owned<IConstWUClusterInfo> newci = getTargetClusterInfo(cluster);
  5043. if (!newci)
  5044. return false;
  5045. StringBuffer currentcluster;
  5046. if (!p->getProp("@clusterName",currentcluster))
  5047. return false;
  5048. Owned<IConstWUClusterInfo> curci = getTargetClusterInfo(currentcluster.str());
  5049. if (!curci)
  5050. return false;
  5051. SCMStringBuffer curqname;
  5052. curci->getThorQueue(curqname);
  5053. const char *wuid = p->queryName();
  5054. void *qi = qs->getQ(curqname.str(),wuid);
  5055. if (!qi)
  5056. return false;
  5057. setClusterName(cluster);
  5058. SCMStringBuffer newqname;
  5059. newci->getThorQueue(newqname);
  5060. qs->putQ(newqname.str(),wuid,qi);
  5061. return true;
  5062. }
  5063. //=================================================================================================
  5064. void CLocalWorkUnit::loadGraphs() const
  5065. {
  5066. CriticalBlock block(crit);
  5067. if (!cachedGraphs.get())
  5068. {
  5069. MemoryBuffer buf;
  5070. IPropertyTree *t = p->queryPropTree("PackedGraphs");
  5071. if (t&&t->getPropBin(NULL,buf)) {
  5072. cachedGraphs.setown(createPTree(buf));
  5073. }
  5074. else
  5075. cachedGraphs.set(p->queryPropTree("Graphs"));
  5076. if (cachedGraphs.get()) {
  5077. Owned<IPropertyTreeIterator> r = cachedGraphs->getElements("Graph");
  5078. for (r->first(); r->isValid(); r->next())
  5079. {
  5080. IPropertyTree *rp = &r->query();
  5081. rp->Link();
  5082. graphs.append(*new CLocalWUGraph(rp, p->queryName()));
  5083. }
  5084. }
  5085. }
  5086. }
  5087. mapEnums graphTypes[] = {
  5088. { GraphTypeAny, "unknown" },
  5089. { GraphTypeProgress, "progress" },
  5090. { GraphTypeEcl, "ECL" },
  5091. { GraphTypeActivities, "activities" },
  5092. { GraphTypeSubProgress, "subgraph" },
  5093. { GraphTypeSize, NULL },
  5094. };
  5095. CLocalWUGraph::CLocalWUGraph(IPropertyTree *props, const char *_wuid) : p(props), wuid(_wuid)
  5096. {
  5097. }
  5098. IStringVal& CLocalWUGraph::getName(IStringVal &str) const
  5099. {
  5100. str.set(p->queryProp("@name"));
  5101. return str;
  5102. }
  5103. IStringVal& CLocalWUGraph::getLabel(IStringVal &str) const
  5104. {
  5105. Owned<IPropertyTree> xgmml = getXGMMLTree(false);
  5106. str.set(xgmml->queryProp("@label"));
  5107. return str;
  5108. }
  5109. IStringVal& CLocalWUGraph::getXGMML(IStringVal &str, bool mergeProgress) const
  5110. {
  5111. Owned<IPropertyTree> xgmml = getXGMMLTree(mergeProgress);
  5112. if (xgmml)
  5113. {
  5114. StringBuffer x;
  5115. toXML(xgmml, x);
  5116. str.set(x.str());
  5117. }
  5118. return str;
  5119. }
  5120. unsigned CLocalWorkUnit::getGraphCount() const
  5121. {
  5122. CriticalBlock block(crit);
  5123. if (p->hasProp("Graphs"))
  5124. {
  5125. return p->queryPropTree("Graphs")->numChildren();
  5126. }
  5127. return 0;
  5128. }
  5129. unsigned CLocalWorkUnit::getSourceFileCount() const
  5130. {
  5131. CriticalBlock block(crit);
  5132. if (p->hasProp("FilesRead"))
  5133. {
  5134. return p->queryPropTree("FilesRead")->numChildren();
  5135. }
  5136. return 0;
  5137. }
  5138. unsigned CLocalWorkUnit::getResultCount() const
  5139. {
  5140. CriticalBlock block(crit);
  5141. if (p->hasProp("Results"))
  5142. {
  5143. return p->queryPropTree("Results")->numChildren();
  5144. }
  5145. return 0;
  5146. }
  5147. unsigned CLocalWorkUnit::getVariableCount() const
  5148. {
  5149. CriticalBlock block(crit);
  5150. if (p->hasProp("Variables"))
  5151. {
  5152. return p->queryPropTree("Variables")->numChildren();
  5153. }
  5154. return 0;
  5155. }
  5156. unsigned CLocalWorkUnit::getTimerCount() const
  5157. {
  5158. CriticalBlock block(crit);
  5159. if (p->hasProp("Timings"))
  5160. {
  5161. return p->queryPropTree("Timings")->numChildren();
  5162. }
  5163. return 0;
  5164. }
  5165. unsigned CLocalWorkUnit::getApplicationValueCount() const
  5166. {
  5167. CriticalBlock block(crit);
  5168. if (p->hasProp("Application"))
  5169. {
  5170. return p->queryPropTree("Application")->numChildren();
  5171. }
  5172. return 0;
  5173. }
  5174. IStringVal &CLocalWorkUnit::getXmlParams(IStringVal &str) const
  5175. {
  5176. CriticalBlock block(crit);
  5177. IPropertyTree *paramTree = p->queryPropTree("Parameters");
  5178. if (paramTree)
  5179. {
  5180. StringBuffer temp;
  5181. toXML(paramTree, temp);
  5182. str.set(temp.str());
  5183. }
  5184. return str;
  5185. }
  5186. const IPropertyTree *CLocalWorkUnit::getXmlParams() const
  5187. {
  5188. CriticalBlock block(crit);
  5189. return p->getPropTree("Parameters");
  5190. }
  5191. void CLocalWorkUnit::setXmlParams(const char *params)
  5192. {
  5193. CriticalBlock block(crit);
  5194. p->setPropTree("Parameters", createPTreeFromXMLString(params));
  5195. }
  5196. void CLocalWorkUnit::setXmlParams(IPropertyTree *tree)
  5197. {
  5198. CriticalBlock block(crit);
  5199. p->setPropTree("Parameters", tree);
  5200. }
  5201. unsigned __int64 CLocalWorkUnit::getHash() const
  5202. {
  5203. CriticalBlock block(crit);
  5204. return p->getPropInt64("@hash");
  5205. }
  5206. void CLocalWorkUnit::setHash(unsigned __int64 hash)
  5207. {
  5208. CriticalBlock block(crit);
  5209. p->setPropInt64("@hash", hash);
  5210. }
  5211. IConstWUGraphIterator& CLocalWorkUnit::getGraphs(WUGraphType type) const
  5212. {
  5213. CriticalBlock block(crit);
  5214. loadGraphs();
  5215. IConstWUGraphIterator *giter = new CArrayIteratorOf<IConstWUGraph,IConstWUGraphIterator> (graphs, 0, (IConstWorkUnit *) this);
  5216. if (type!=GraphTypeAny) {
  5217. class CConstWUGraphIterator: public CInterface, implements IConstWUGraphIterator
  5218. {
  5219. WUGraphType type;
  5220. Owned<IConstWUGraphIterator> base;
  5221. bool match()
  5222. {
  5223. return base->query().getType()==type;
  5224. }
  5225. public:
  5226. IMPLEMENT_IINTERFACE;
  5227. CConstWUGraphIterator(IConstWUGraphIterator *_base,WUGraphType _type)
  5228. : base(_base)
  5229. {
  5230. type = _type;
  5231. }
  5232. bool first()
  5233. {
  5234. if (!base->first())
  5235. return false;
  5236. if (match())
  5237. return true;
  5238. return next();
  5239. }
  5240. bool next()
  5241. {
  5242. while (base->next())
  5243. if (match())
  5244. return true;
  5245. return false;
  5246. }
  5247. virtual bool isValid()
  5248. {
  5249. return base->isValid();
  5250. }
  5251. IConstWUGraph & query()
  5252. {
  5253. return base->query();
  5254. }
  5255. };
  5256. giter = new CConstWUGraphIterator(giter,type);
  5257. }
  5258. return *giter;
  5259. }
  5260. IConstWUGraph* CLocalWorkUnit::getGraph(const char *qname) const
  5261. {
  5262. CriticalBlock block(crit);
  5263. loadGraphs();
  5264. ForEachItemIn(idx, graphs)
  5265. {
  5266. SCMStringBuffer name;
  5267. IConstWUGraph &cur = graphs.item(idx);
  5268. cur.getName(name);
  5269. if (stricmp(name.str(), qname)==0)
  5270. {
  5271. cur.Link();
  5272. return &cur;
  5273. }
  5274. }
  5275. return NULL;
  5276. }
  5277. IWUGraph* CLocalWorkUnit::createGraph()
  5278. {
  5279. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  5280. CriticalBlock block(crit);
  5281. ensureGraphsUnpacked();
  5282. loadGraphs();
  5283. if (!graphs.length())
  5284. p->addPropTree("Graphs", createPTree("Graphs"));
  5285. IPropertyTree *r = p->queryPropTree("Graphs");
  5286. IPropertyTree *s = r->addPropTree("Graph", createPTreeFromXMLString("<Graph fetchEntire='1'/>"));
  5287. s->Link();
  5288. IWUGraph* q = new CLocalWUGraph(s, p->queryName());
  5289. q->Link();
  5290. graphs.append(*q);
  5291. return q;
  5292. }
  5293. IWUGraph * CLocalWorkUnit::updateGraph(const char * name)
  5294. {
  5295. CriticalBlock block(crit);
  5296. ensureGraphsUnpacked();
  5297. IConstWUGraph *existing = getGraph(name);
  5298. if (existing)
  5299. return (IWUGraph *) existing;
  5300. IWUGraph * q = createGraph();
  5301. q->setName(name);
  5302. return q;
  5303. }
  5304. IConstWUGraphProgress *CLocalWorkUnit::getGraphProgress(const char *name) const
  5305. {
  5306. CriticalBlock block(crit);
  5307. return new CConstGraphProgress(p->queryName(), name);
  5308. }
  5309. IStringVal& CLocalWUGraph::getDOT(IStringVal &str) const
  5310. {
  5311. UNIMPLEMENTED;
  5312. }
  5313. void CLocalWUGraph::setName(const char *str)
  5314. {
  5315. p->setProp("@name", str);
  5316. progress.clear();
  5317. progress.setown(new CConstGraphProgress(wuid, str));
  5318. }
  5319. void CLocalWUGraph::setXGMML(const char *str)
  5320. {
  5321. setXGMMLTree(createPTreeFromXMLString(str));
  5322. }
  5323. void CLocalWUGraph::setXGMMLTree(IPropertyTree *graph)
  5324. {
  5325. assertex(strcmp(graph->queryName(), "graph")==0);
  5326. IPropertyTree *xgmml = createPTree("xgmml");
  5327. xgmml->setPropTree("graph", graph);
  5328. p->setPropTree("xgmml", xgmml);
  5329. }
  5330. void CLocalWUGraph::mergeProgress(IPropertyTree &rootNode, IPropertyTree &progressTree, const unsigned &progressV) const
  5331. {
  5332. IPropertyTree *graphNode = rootNode.queryPropTree("att/graph");
  5333. if (!graphNode) return;
  5334. unsigned nodeId = rootNode.getPropInt("@id");
  5335. StringBuffer progressNodePath("node[@id=\"");
  5336. progressNodePath.append(nodeId).append("\"]");
  5337. IPropertyTree *progressNode = progressTree.queryPropTree(progressNodePath.str());
  5338. if (progressNode)
  5339. {
  5340. Owned<IPropertyTreeIterator> edges = progressNode->getElements("edge");
  5341. ForEach (*edges)
  5342. {
  5343. IPropertyTree &edge = edges->query();
  5344. StringBuffer edgePath("edge[@id=\"");
  5345. edgePath.append(edge.queryProp("@id")).append("\"]");
  5346. IPropertyTree *graphEdge = graphNode->queryPropTree(edgePath.str());
  5347. if (graphEdge)
  5348. {
  5349. if (progressV < 1)
  5350. mergePTree(graphEdge, &edge);
  5351. else
  5352. { // must translate to XGMML format
  5353. Owned<IAttributeIterator> aIter = edge.getAttributes();
  5354. ForEach (*aIter)
  5355. {
  5356. const char *aName = aIter->queryName()+1;
  5357. if (0 != stricmp("id", aName)) // "id" reserved.
  5358. {
  5359. IPropertyTree *att = graphEdge->addPropTree("att", createPTree());
  5360. att->setProp("@name", aName);
  5361. att->setProp("@value", aIter->queryValue());
  5362. }
  5363. }
  5364. // 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)
  5365. Owned<IPropertyTreeIterator> iter = edge.getElements("*");
  5366. ForEach (*iter)
  5367. {
  5368. IPropertyTree &t = iter->query();
  5369. IPropertyTree *att = graphEdge->addPropTree("att", createPTree());
  5370. att->setProp("@name", t.queryName());
  5371. att->setProp("@value", t.queryProp(NULL));
  5372. }
  5373. }
  5374. }
  5375. }
  5376. Owned<IPropertyTreeIterator> nodes = progressNode->getElements("node");
  5377. ForEach (*nodes)
  5378. {
  5379. IPropertyTree &node = nodes->query();
  5380. StringBuffer nodePath("node[@id=\"");
  5381. nodePath.append(node.queryProp("@id")).append("\"]");
  5382. IPropertyTree *_node = graphNode->queryPropTree(nodePath.str());
  5383. if (_node)
  5384. {
  5385. if (progressV < 1)
  5386. mergePTree(_node, &node);
  5387. else
  5388. { // must translate to XGMML format
  5389. Owned<IAttributeIterator> aIter = node.getAttributes();
  5390. ForEach (*aIter)
  5391. {
  5392. const char *aName = aIter->queryName()+1;
  5393. if (0 != stricmp("id", aName)) // "id" reserved.
  5394. {
  5395. IPropertyTree *att = _node->addPropTree("att", createPTree());
  5396. att->setProp("@name", aName);
  5397. att->setProp("@value", aIter->queryValue());
  5398. }
  5399. }
  5400. }
  5401. }
  5402. }
  5403. }
  5404. Owned<IPropertyTreeIterator> iter = graphNode->getElements("node");
  5405. ForEach (*iter)
  5406. mergeProgress(iter->query(), progressTree, progressV);
  5407. }
  5408. IPropertyTree * CLocalWUGraph::getXGMMLTree(bool doMergeProgress) const
  5409. {
  5410. if (!doMergeProgress)
  5411. return p->getPropTree("xgmml/graph");
  5412. else
  5413. {
  5414. IPropertyTree *src = p->queryPropTree("xgmml/graph");
  5415. if (!src) return NULL;
  5416. Owned<IPropertyTree> copy = createPTreeFromIPT(src);
  5417. Owned<IConstWUGraphProgress> _progress;
  5418. if (progress) _progress.set(progress);
  5419. else
  5420. _progress.setown(new CConstGraphProgress(wuid, p->queryProp("@name")));
  5421. unsigned progressV = _progress->queryFormatVersion();
  5422. IPropertyTree *progressTree = _progress->queryProgressTree();
  5423. Owned<IPropertyTreeIterator> nodeIterator = copy->getElements("node");
  5424. ForEach (*nodeIterator)
  5425. mergeProgress(nodeIterator->query(), *progressTree, progressV);
  5426. return LINK(copy);
  5427. }
  5428. }
  5429. bool CLocalWUGraph::isValid() const
  5430. {
  5431. return p->hasProp("xgmml/graph/node");
  5432. }
  5433. WUGraphType CLocalWUGraph::getType() const
  5434. {
  5435. return (WUGraphType) getEnum(p, "@type", graphTypes);
  5436. }
  5437. IStringVal & CLocalWUGraph::getTypeName(IStringVal &str) const
  5438. {
  5439. str.set(p->queryProp("@type"));
  5440. if (!str.length())
  5441. str.set("unknown");
  5442. return str;
  5443. }
  5444. void CLocalWUGraph::setType(WUGraphType _type)
  5445. {
  5446. setEnum(p, "@type", _type, graphTypes);
  5447. }
  5448. //=================================================================================================
  5449. mapEnums queryFileTypes[] = {
  5450. { FileTypeCpp, "cpp" },
  5451. { FileTypeDll, "dll" },
  5452. { FileTypeResText, "res" },
  5453. { FileTypeHintXml, "hint" },
  5454. { FileTypeSize, NULL },
  5455. };
  5456. CLocalWUAssociated::CLocalWUAssociated(IPropertyTree *props) : p(props)
  5457. {
  5458. }
  5459. WUFileType CLocalWUAssociated::getType() const
  5460. {
  5461. return (WUFileType)getEnum(p, "@type", queryFileTypes);
  5462. }
  5463. IStringVal & CLocalWUAssociated::getDescription(IStringVal & str) const
  5464. {
  5465. str.set(p->queryProp("@desc"));
  5466. return str;
  5467. }
  5468. IStringVal & CLocalWUAssociated::getIp(IStringVal & str) const
  5469. {
  5470. str.set(p->queryProp("@ip"));
  5471. return str;
  5472. }
  5473. IStringVal & CLocalWUAssociated::getName(IStringVal & str) const
  5474. {
  5475. str.set(p->queryProp("@filename"));
  5476. return str;
  5477. }
  5478. IStringVal & CLocalWUAssociated::getNameTail(IStringVal & str) const
  5479. {
  5480. str.set(pathTail(p->queryProp("@filename")));
  5481. return str;
  5482. }
  5483. unsigned CLocalWUAssociated::getCrc() const
  5484. {
  5485. return p->getPropInt("@crc", 0);
  5486. }
  5487. //=================================================================================================
  5488. CLocalWUQuery::CLocalWUQuery(IPropertyTree *props) : p(props)
  5489. {
  5490. associatedCached = false;
  5491. }
  5492. mapEnums queryTypes[] = {
  5493. { QueryTypeUnknown, "unknown" },
  5494. { QueryTypeEcl, "ECL" },
  5495. { QueryTypeSql, "SQL" },
  5496. { QueryTypeXml, "XML" },
  5497. { QueryTypeAttribute, "Attribute" },
  5498. { QueryTypeSize, NULL },
  5499. };
  5500. WUQueryType CLocalWUQuery::getQueryType() const
  5501. {
  5502. return (WUQueryType) getEnum(p, "@type", queryTypes);
  5503. }
  5504. void CLocalWUQuery::setQueryType(WUQueryType qt)
  5505. {
  5506. setEnum(p, "@type", qt, queryTypes);
  5507. }
  5508. IStringVal& CLocalWUQuery::getQueryText(IStringVal &str) const
  5509. {
  5510. str.set(p->queryProp("Text"));
  5511. return str;
  5512. }
  5513. IStringVal& CLocalWUQuery::getQueryShortText(IStringVal &str) const
  5514. {
  5515. const char * text = p->queryProp("Text");
  5516. if (isArchiveQuery(text))
  5517. {
  5518. Owned<IPropertyTree> xml = createPTreeFromXMLString(text, ipt_caseInsensitive);
  5519. const char * path = xml->queryProp("Query/@attributePath");
  5520. if (path)
  5521. {
  5522. IPropertyTree * resolved = resolveDefinitionInArchive(xml, path);
  5523. if (resolved)
  5524. str.set(resolved->queryProp(NULL));
  5525. }
  5526. else
  5527. str.set(xml->queryProp("Query"));
  5528. }
  5529. else
  5530. str.set(text);
  5531. return str;
  5532. }
  5533. IStringVal& CLocalWUQuery::getQueryName(IStringVal &str) const
  5534. {
  5535. str.set(p->queryProp("@name"));
  5536. return str;
  5537. }
  5538. IStringVal& CLocalWUQuery::getQueryDllName(IStringVal &str) const
  5539. {
  5540. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  5541. if (entry)
  5542. entry->getNameTail(str);
  5543. return str;
  5544. }
  5545. IStringVal& CLocalWUQuery::getQueryCppName(IStringVal &str) const
  5546. {
  5547. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeCpp, 0);
  5548. if (entry)
  5549. entry->getName(str);
  5550. return str;
  5551. }
  5552. IStringVal& CLocalWUQuery::getQueryResTxtName(IStringVal &str) const
  5553. {
  5554. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeResText, 0);
  5555. if (entry)
  5556. entry->getName(str);
  5557. return str;
  5558. }
  5559. unsigned CLocalWUQuery::getQueryDllCrc() const
  5560. {
  5561. Owned<IConstWUAssociatedFile> entry = getAssociatedFile(FileTypeDll, 0);
  5562. if (entry)
  5563. return entry->getCrc();
  5564. return 0;
  5565. }
  5566. void CLocalWUQuery::setQueryText(const char *text)
  5567. {
  5568. p->setProp("Text", text);
  5569. }
  5570. void CLocalWUQuery::setQueryName(const char *qname)
  5571. {
  5572. p->setProp("@name", qname);
  5573. }
  5574. void CLocalWUQuery::addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc)
  5575. {
  5576. CriticalBlock block(crit);
  5577. loadAssociated();
  5578. if (!associated.length())
  5579. p->addPropTree("Associated", createPTree("Associated"));
  5580. IPropertyTree *pl = p->queryPropTree("Associated");
  5581. IPropertyTree *s = pl->addPropTree("File", createPTree("File"));
  5582. setEnum(s, "@type", type, queryFileTypes);
  5583. s->setProp("@filename", name);
  5584. s->setProp("@ip", ip);
  5585. s->setProp("@desc", desc);
  5586. if (crc)
  5587. s->setPropInt("@crc", crc);
  5588. IConstWUAssociatedFile * q = new CLocalWUAssociated(LINK(s));
  5589. associated.append(*q);
  5590. }
  5591. void CLocalWUQuery::removeAssociatedFiles()
  5592. {
  5593. associatedCached = false;
  5594. associated.kill();
  5595. p->removeProp("Associated");
  5596. }
  5597. IConstWUAssociatedFile * CLocalWUQuery::getAssociatedFile(WUFileType type, unsigned index) const
  5598. {
  5599. CriticalBlock block(crit);
  5600. loadAssociated();
  5601. ForEachItemIn(idx, associated)
  5602. {
  5603. CLocalWUAssociated &cur = static_cast<CLocalWUAssociated &>(associated.item(idx));
  5604. if (cur.getType() == type)
  5605. {
  5606. if (index-- == 0)
  5607. return &OLINK(cur);
  5608. }
  5609. }
  5610. return NULL;
  5611. }
  5612. void CLocalWUQuery::addSpecialCaseAssociated(WUFileType type, const char * propname, unsigned crc) const
  5613. {
  5614. const char * name = p->queryProp(propname);
  5615. if (name)
  5616. {
  5617. IPropertyTree *s = createPTree("File");
  5618. setEnum(s, "@type", type, queryFileTypes);
  5619. s->setProp("@filename", name);
  5620. if (crc)
  5621. s->setPropInt("@crc", crc);
  5622. associated.append(*new CLocalWUAssociated(s));
  5623. }
  5624. }
  5625. void CLocalWUQuery::loadAssociated() const
  5626. {
  5627. CriticalBlock block(crit);
  5628. if (!associatedCached)
  5629. {
  5630. assertex(associated.length() == 0);
  5631. addSpecialCaseAssociated(FileTypeDll, "DllName", p->getPropInt("DllCrc", 0));
  5632. addSpecialCaseAssociated(FileTypeCpp, "CppName", 0);
  5633. addSpecialCaseAssociated(FileTypeResText, "ResTxtName", 0);
  5634. Owned<IPropertyTreeIterator> r = p->getElements("Associated/File");
  5635. for (r->first(); r->isValid(); r->next())
  5636. {
  5637. IPropertyTree *rp = &r->query();
  5638. rp->Link();
  5639. associated.append(*new CLocalWUAssociated(rp));
  5640. }
  5641. associatedCached = true;
  5642. }
  5643. }
  5644. IConstWUAssociatedFileIterator& CLocalWUQuery::getAssociatedFiles() const
  5645. {
  5646. CriticalBlock block(crit);
  5647. loadAssociated();
  5648. return *new CArrayIteratorOf<IConstWUAssociatedFile,IConstWUAssociatedFileIterator> (associated, 0, (IConstWUQuery *) this);
  5649. }
  5650. //========================================================================================
  5651. CLocalWUWebServicesInfo::CLocalWUWebServicesInfo(IPropertyTree *props) : p(props)
  5652. {
  5653. }
  5654. IStringVal& CLocalWUWebServicesInfo::getModuleName(IStringVal &str) const
  5655. {
  5656. str.set(p->queryProp("@module"));
  5657. return str;
  5658. }
  5659. IStringVal& CLocalWUWebServicesInfo::getAttributeName(IStringVal &str) const
  5660. {
  5661. str.set(p->queryProp("@attribute"));
  5662. return str;
  5663. }
  5664. IStringVal& CLocalWUWebServicesInfo::getDefaultName(IStringVal &str) const
  5665. {
  5666. str.set(p->queryProp("@defaultName"));
  5667. return str;
  5668. }
  5669. unsigned CLocalWUWebServicesInfo::getWebServicesCRC() const
  5670. {
  5671. return (unsigned) p->getPropInt("@crc");
  5672. }
  5673. IStringVal& CLocalWUWebServicesInfo::getInfo(const char *name, IStringVal &str) const
  5674. {
  5675. if (!name)
  5676. {
  5677. StringBuffer ws_info;
  5678. ws_info.appendf("<%s ", p->queryName());
  5679. Owned<IAttributeIterator> attrs = p->getAttributes();
  5680. for(attrs->first(); attrs->isValid(); attrs->next())
  5681. {
  5682. const char *name = attrs->queryName()+1;
  5683. const char *value = attrs->queryValue();
  5684. ws_info.appendf("%s='%s' ", name, value);
  5685. }
  5686. ws_info.append("> \n");
  5687. Owned<IPropertyTreeIterator> info = p->getElements("*");
  5688. ForEach(*info)
  5689. {
  5690. IPropertyTree &item = info->query();
  5691. const char *name = item.queryName();
  5692. if (name)
  5693. {
  5694. MemoryBuffer mb;
  5695. bool isbin = p->isBinary(name);
  5696. if (isbin)
  5697. {
  5698. p->getPropBin(name,mb);
  5699. if (mb.length())
  5700. {
  5701. unsigned len = 0;
  5702. mb.read(len);
  5703. StringBuffer encodedString;
  5704. StringBuffer val(len, (const char *) mb.readDirect(len));
  5705. encodeXML(val, encodedString);
  5706. ws_info.appendf("<%s>%s</%s>", name, encodedString.str(), name);
  5707. }
  5708. }
  5709. else
  5710. {
  5711. StringBuffer tmp;
  5712. toXML(&item, tmp);
  5713. ws_info.append(tmp.str());
  5714. }
  5715. }
  5716. }
  5717. ws_info.appendf("</%s>", p->queryName());
  5718. str.setLen(ws_info.str(), ws_info.length());
  5719. }
  5720. else
  5721. {
  5722. MemoryBuffer mb;
  5723. p->getPropBin(name,mb);
  5724. if (mb.length())
  5725. {
  5726. unsigned len;
  5727. mb.read(len);
  5728. str.setLen((const char *) mb.readDirect(len), len);
  5729. }
  5730. }
  5731. return str;
  5732. }
  5733. void CLocalWUWebServicesInfo::setModuleName(const char *mname)
  5734. {
  5735. p->setProp("@module", mname);
  5736. }
  5737. void CLocalWUWebServicesInfo::setAttributeName(const char *aname)
  5738. {
  5739. p->setProp("@attribute", aname);
  5740. }
  5741. void CLocalWUWebServicesInfo::setDefaultName(const char *dname)
  5742. {
  5743. p->setProp("@defaultName", dname);
  5744. }
  5745. void CLocalWUWebServicesInfo::setWebServicesCRC(unsigned crc)
  5746. {
  5747. p->setPropInt("@crc", crc);
  5748. }
  5749. void CLocalWUWebServicesInfo::setInfo(const char *name, const char *info)
  5750. {
  5751. MemoryBuffer m;
  5752. unsigned len = (size32_t)strlen(info);
  5753. serializeLPString(len, info, m);
  5754. p->setPropBin(name, m.length(), m.toByteArray());
  5755. }
  5756. //========================================================================================
  5757. CLocalWURoxieQueryInfo::CLocalWURoxieQueryInfo(IPropertyTree *props) : p(props)
  5758. {
  5759. }
  5760. IStringVal& CLocalWURoxieQueryInfo::getQueryInfo(IStringVal &str) const
  5761. {
  5762. IPropertyTree *queryTree = p->queryPropTree("query");
  5763. if (queryTree)
  5764. {
  5765. StringBuffer temp;
  5766. toXML(queryTree, temp);
  5767. str.set(temp.str());
  5768. }
  5769. return str;
  5770. }
  5771. IStringVal& CLocalWURoxieQueryInfo::getDefaultPackageInfo(IStringVal &str) const
  5772. {
  5773. MemoryBuffer mb;
  5774. p->getPropBin("RoxiePackages",mb);
  5775. if (mb.length())
  5776. {
  5777. unsigned len;
  5778. mb.read(len);
  5779. str.setLen((const char *) mb.readDirect(len), len);
  5780. }
  5781. return str;
  5782. }
  5783. IStringVal& CLocalWURoxieQueryInfo::getRoxieClusterName(IStringVal &str) const
  5784. {
  5785. const char *val = p->queryProp("@roxieClusterName");
  5786. if (val)
  5787. str.set(val);
  5788. return str;
  5789. }
  5790. IStringVal& CLocalWURoxieQueryInfo::getWuid(IStringVal &str) const
  5791. {
  5792. const char *val = p->queryProp("@wuid");
  5793. if (val)
  5794. str.set(val);
  5795. return str;
  5796. }
  5797. void CLocalWURoxieQueryInfo::setQueryInfo(const char *info)
  5798. {
  5799. IPropertyTree *queryTree = p->queryPropTree("query");
  5800. if (queryTree)
  5801. p->removeTree(queryTree);
  5802. IPropertyTree * tempTree = p->addPropTree("query", createPTreeFromXMLString(info));
  5803. if (!p->hasProp("@roxieClusterName"))
  5804. {
  5805. const char *roxieClusterName = tempTree->queryProp("@roxieName");
  5806. if (roxieClusterName && *roxieClusterName)
  5807. p->addProp("@roxieClusterName", roxieClusterName);
  5808. }
  5809. if (!p->hasProp("@wuid"))
  5810. {
  5811. const char *wuid = tempTree->queryProp("Query/@wuid");
  5812. if (wuid && *wuid)
  5813. p->addProp("@wuid", wuid);
  5814. }
  5815. }
  5816. void CLocalWURoxieQueryInfo::setDefaultPackageInfo(const char *info, int len)
  5817. {
  5818. MemoryBuffer m;
  5819. serializeLPString(len, info, m);
  5820. p->setPropBin("RoxiePackages", m.length(), m.toByteArray());
  5821. }
  5822. void CLocalWURoxieQueryInfo::setRoxieClusterName(const char *info)
  5823. {
  5824. p->setProp("@roxieClusterName", info);
  5825. }
  5826. void CLocalWURoxieQueryInfo::setWuid(const char *info)
  5827. {
  5828. p->setProp("@wuid", info);
  5829. }
  5830. //========================================================================================
  5831. CLocalWUResult::CLocalWUResult(IPropertyTree *props) : p(props)
  5832. {
  5833. }
  5834. mapEnums resultStatuses[] = {
  5835. { ResultStatusUndefined, "undefined" },
  5836. { ResultStatusCalculated, "calculated" },
  5837. { ResultStatusSupplied, "supplied" },
  5838. { ResultStatusFailed, "failed" },
  5839. { ResultStatusPartial, "partial" },
  5840. { ResultStatusSize, NULL }
  5841. };
  5842. WUResultStatus CLocalWUResult::getResultStatus() const
  5843. {
  5844. return (WUResultStatus ) getEnum(p, "@status", resultStatuses);
  5845. }
  5846. IStringVal& CLocalWUResult::getResultName(IStringVal &str) const
  5847. {
  5848. str.set(p->queryProp("@name"));
  5849. return str;
  5850. }
  5851. int CLocalWUResult::getResultSequence() const
  5852. {
  5853. return p->getPropInt("@sequence", -1);
  5854. }
  5855. bool CLocalWUResult::isResultScalar() const
  5856. {
  5857. return p->getPropInt("@isScalar", 1) != 0;
  5858. }
  5859. bool findSize(int size, IntArray &sizes)
  5860. {
  5861. ForEachItemIn(idx, sizes)
  5862. {
  5863. if (sizes.item(idx)==size)
  5864. return true;
  5865. }
  5866. return false;
  5867. }
  5868. void CLocalWUResult::getSchema(TypeInfoArray &types, StringAttrArray &names, IStringVal * eclText) const
  5869. {
  5870. MemoryBuffer schema;
  5871. p->getPropBin("SchemaRaw", schema);
  5872. if (schema.length())
  5873. {
  5874. for (;;)
  5875. {
  5876. StringAttr name;
  5877. schema.read(name);
  5878. if (*schema.readDirect(0)==type_void)
  5879. break;
  5880. names.append(*new StringAttrItem(name));
  5881. types.append(*deserializeType(schema)); // MORE - nested records!
  5882. }
  5883. schema.skip(1);
  5884. if (schema.length() != schema.getPos())
  5885. {
  5886. unsigned eclLen;
  5887. schema.read(eclLen);
  5888. const char * schemaData = (const char *)schema.readDirect(eclLen);
  5889. if (eclText)
  5890. {
  5891. eclText->setLen(schemaData, eclLen);
  5892. if ((eclLen == 0) && names.ordinality())
  5893. {
  5894. const char * firstName = names.item(0).text;
  5895. StringBuffer temp;
  5896. temp.append("RECORD ");
  5897. types.item(0).getECLType(temp);
  5898. temp.append(" value{NAMED('").append(firstName).append("')}").append("; END;");
  5899. eclText->set(temp.str());
  5900. }
  5901. }
  5902. }
  5903. }
  5904. }
  5905. void readRow(StringBuffer &out, MemoryBuffer &in, TypeInfoArray &types, StringAttrArray &names)
  5906. {
  5907. ForEachItemIn(idx, types)
  5908. {
  5909. StringAttrItem &name = names.item(idx);
  5910. ITypeInfo &type = types.item(idx);
  5911. unsigned size = type.getSize();
  5912. switch(type.getTypeCode())
  5913. {
  5914. case type_data:
  5915. if (size==UNKNOWN_LENGTH)
  5916. {
  5917. if (in.remaining() < sizeof(int))
  5918. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  5919. in.read(size);
  5920. }
  5921. outputXmlData(size, in.readDirect(size), name.text, out);
  5922. break;
  5923. case type_string:
  5924. if (size==UNKNOWN_LENGTH)
  5925. {
  5926. if (in.remaining() < sizeof(int))
  5927. throw MakeStringException(WUERR_CorruptResult, "corrupt workunit information");
  5928. in.read(size);
  5929. }
  5930. outputXmlString(size, (const char *) in.readDirect(size), name.text, out);
  5931. break;
  5932. case type_varstring:
  5933. {
  5934. if (size == UNKNOWN_LENGTH)
  5935. size = (size32_t)strlen((const char *) in.readDirect(0))+1;
  5936. const char * text = (const char *) in.readDirect(size);
  5937. outputXmlString((size32_t)strlen(text), text, name.text, out);
  5938. break;
  5939. }
  5940. case type_unicode:
  5941. {
  5942. unsigned len = type.getStringLen();
  5943. if (size==UNKNOWN_LENGTH)
  5944. in.read(len);
  5945. outputXmlUnicode(len, (UChar const *) in.readDirect(len*2), name.text, out);
  5946. }
  5947. break;
  5948. case type_utf8:
  5949. {
  5950. unsigned len = type.getStringLen();
  5951. if (size==UNKNOWN_LENGTH)
  5952. {
  5953. in.read(len);
  5954. size = rtlUtf8Size(len, in.readDirect(0));
  5955. }
  5956. outputXmlUtf8(len, (const char *) in.readDirect(size), name.text, out);
  5957. }
  5958. break;
  5959. case type_qstring:
  5960. {
  5961. unsigned len = type.getStringLen();
  5962. if (size==UNKNOWN_LENGTH)
  5963. in.read(len);
  5964. unsigned outlen;
  5965. char *outstr;
  5966. rtlQStrToStrX(outlen, outstr, len, (const char *) in.readDirect(rtlQStrSize(len)));
  5967. outputXmlString(outlen, outstr, name.text, out);
  5968. free(outstr);
  5969. break;
  5970. }
  5971. case type_int:
  5972. case type_swapint:
  5973. if (type.isSigned())
  5974. {
  5975. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  5976. unsigned __int64 cval8 = 0;
  5977. //MORE: I think this is wrong - swapped doesn't mean little/big/
  5978. if (type.isSwappedEndian())
  5979. {
  5980. unsigned idx = 0;
  5981. if (raw[idx] & 0x80)
  5982. cval8 = (__int64)-1;
  5983. while (size--)
  5984. cval8 = (cval8 << 8) | raw[idx++];
  5985. }
  5986. else
  5987. {
  5988. if (raw[size-1] & 0x80)
  5989. cval8 = (__int64)-1;
  5990. while (size--)
  5991. cval8 = (cval8 << 8) | raw[size];
  5992. }
  5993. outputXmlInt((__int64) cval8, name.text, out);
  5994. }
  5995. else
  5996. {
  5997. const unsigned char *raw = (const unsigned char *) in.readDirect(size);
  5998. unsigned __int64 cval8 = 0;
  5999. if (type.isSwappedEndian())
  6000. {
  6001. unsigned idx = 0;
  6002. while (size--)
  6003. cval8 = (cval8 << 8) | raw[idx++];
  6004. }
  6005. else
  6006. {
  6007. while (size--)
  6008. cval8 = (cval8 << 8) | raw[size];
  6009. }
  6010. outputXmlUInt(cval8, name.text, out);
  6011. }
  6012. break;
  6013. case type_boolean:
  6014. bool cvalb;
  6015. in.read(cvalb);
  6016. outputXmlBool(cvalb, name.text, out);
  6017. break;
  6018. case type_decimal:
  6019. if (type.isSigned())
  6020. outputXmlDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  6021. else
  6022. outputXmlUDecimal(in.readDirect(size), size, type.getPrecision(), name.text, out);
  6023. break;
  6024. case type_real:
  6025. double cvald;
  6026. switch(size)
  6027. {
  6028. case 4:
  6029. float cvalf;
  6030. in.read(cvalf);
  6031. cvald = cvalf;
  6032. break;
  6033. case 8:
  6034. in.read(cvald);
  6035. break;
  6036. }
  6037. outputXmlReal(cvald, name.text, out);
  6038. break;
  6039. default:
  6040. assertex(!"unexpected type in raw record");
  6041. break;
  6042. }
  6043. }
  6044. }
  6045. IStringVal& CLocalWUResult::getResultXml(IStringVal &str) const
  6046. {
  6047. TypeInfoArray types;
  6048. StringAttrArray names;
  6049. getSchema(types, names);
  6050. StringBuffer xml;
  6051. MemoryBuffer raw;
  6052. p->getPropBin("Value", raw);
  6053. const char * name = p->queryProp("@name");
  6054. if (name)
  6055. xml.appendf("<Dataset name=\"%s\">", name);
  6056. else
  6057. xml.append("<Dataset>");
  6058. unsigned __int64 numrows = getResultRowCount();
  6059. while (numrows--)
  6060. {
  6061. xml.append("<Row>");
  6062. readRow(xml, raw, types, names);
  6063. xml.append("</Row>");
  6064. }
  6065. xml.append("</Dataset>");
  6066. str.set(xml.str());
  6067. return str;
  6068. }
  6069. unsigned CLocalWUResult::getResultFetchSize() const
  6070. {
  6071. return p->getPropInt("fetchSize", 100);
  6072. }
  6073. __int64 CLocalWUResult::getResultTotalRowCount() const
  6074. {
  6075. return p->getPropInt64("totalRowCount", -1);
  6076. }
  6077. __int64 CLocalWUResult::getResultRowCount() const
  6078. {
  6079. return p->getPropInt64("rowCount", 0);
  6080. }
  6081. void CLocalWUResult::getResultDataset(IStringVal & ecl, IStringVal & defs) const
  6082. {
  6083. ecl.set(p->queryProp("datasetEcl"));
  6084. defs.set(p->queryProp("datasetEclDefs"));
  6085. }
  6086. IStringVal& CLocalWUResult::getResultLogicalName(IStringVal & val) const
  6087. {
  6088. val.set(p->queryProp("logicalName"));
  6089. return val;
  6090. }
  6091. IStringVal& CLocalWUResult::getResultKeyField(IStringVal & ecl) const
  6092. {
  6093. ecl.set(p->queryProp("keyField"));
  6094. return ecl;
  6095. }
  6096. unsigned CLocalWUResult::getResultRequestedRows() const
  6097. {
  6098. return p->getPropInt("requestedRows", 1);
  6099. }
  6100. IStringVal& CLocalWUResult::getResultEclSchema(IStringVal & str) const
  6101. {
  6102. TypeInfoArray types;
  6103. StringAttrArray names;
  6104. getSchema(types, names, &str);
  6105. return str;
  6106. }
  6107. IStringVal& CLocalWUResult::getResultRecordSizeEntry(IStringVal & str) const
  6108. {
  6109. str.set(p->queryProp("@recordSizeEntry"));
  6110. return str;
  6111. }
  6112. IStringVal& CLocalWUResult::getResultTransformerEntry(IStringVal & str) const
  6113. {
  6114. str.set(p->queryProp("@transformerEntry"));
  6115. return str;
  6116. }
  6117. __int64 CLocalWUResult::getResultRowLimit() const
  6118. {
  6119. return p->getPropInt64("@rowLimit");
  6120. }
  6121. IStringVal& CLocalWUResult::getResultFilename(IStringVal & str) const
  6122. {
  6123. str.set(p->queryProp("@tempFilename"));
  6124. return str;
  6125. }
  6126. void CLocalWUResult::setResultStatus(WUResultStatus status)
  6127. {
  6128. setEnum(p, "@status", status, resultStatuses);
  6129. if (status==ResultStatusUndefined)
  6130. p->removeProp("Value");
  6131. }
  6132. void CLocalWUResult::setResultName(const char *s)
  6133. {
  6134. p->setProp("@name", s);
  6135. }
  6136. void CLocalWUResult::setResultSequence(unsigned seq)
  6137. {
  6138. p->setPropInt("@sequence", seq);
  6139. }
  6140. void CLocalWUResult::setResultSchemaRaw(unsigned size, const void *schema)
  6141. {
  6142. p->setPropBin("SchemaRaw", size, schema);
  6143. }
  6144. void CLocalWUResult::setResultScalar(bool isScalar)
  6145. {
  6146. p->setPropInt("@isScalar", (int) isScalar);
  6147. if (isScalar)
  6148. setResultTotalRowCount(1);
  6149. }
  6150. void CLocalWUResult::setResultRaw(unsigned len, const void *data, WUResultFormat format)
  6151. {
  6152. p->setPropBin("Value", len, data);
  6153. setResultStatus(ResultStatusSupplied);
  6154. setResultFormat(format);
  6155. }
  6156. void CLocalWUResult::setResultFormat(WUResultFormat format)
  6157. {
  6158. switch (format)
  6159. {
  6160. case ResultFormatXml:
  6161. p->setProp("@format","xml");
  6162. break;
  6163. case ResultFormatXmlSet:
  6164. p->setProp("@format","xmlSet");
  6165. break;
  6166. case ResultFormatCsv:
  6167. p->setProp("@format","csv");
  6168. break;
  6169. default:
  6170. p->removeProp("@format");
  6171. break;
  6172. }
  6173. }
  6174. void CLocalWUResult::setResultXML(const char *val)
  6175. {
  6176. p->setProp("xmlValue", val);
  6177. }
  6178. void CLocalWUResult::addResultRaw(unsigned len, const void *data, WUResultFormat format)
  6179. {
  6180. p->appendPropBin("Value", len, data);
  6181. setResultStatus(ResultStatusPartial);
  6182. const char *existingFormat = p->queryProp("@format");
  6183. const char *formatStr = NULL;
  6184. switch (format)
  6185. {
  6186. case ResultFormatXml:
  6187. formatStr = "xml";
  6188. break;
  6189. case ResultFormatXmlSet:
  6190. formatStr = "xmlSet";
  6191. break;
  6192. case ResultFormatCsv:
  6193. formatStr = "csv";
  6194. break;
  6195. default:
  6196. p->removeProp("@format");
  6197. break;
  6198. }
  6199. if (format)
  6200. {
  6201. if (existingFormat)
  6202. {
  6203. if (0 != stricmp(formatStr, existingFormat))
  6204. throw MakeStringException(WUERR_ResultFormatMismatch, "addResult format %s, does not match existing format %s", formatStr, existingFormat);
  6205. }
  6206. else
  6207. p->setProp("@format", formatStr);
  6208. }
  6209. }
  6210. void CLocalWUResult::setResultFetchSize(unsigned rows)
  6211. {
  6212. p->setPropInt("fetchSize", rows);
  6213. }
  6214. void CLocalWUResult::setResultTotalRowCount(__int64 rows)
  6215. {
  6216. p->setPropInt64("totalRowCount", rows);
  6217. }
  6218. void CLocalWUResult::setResultRowCount(__int64 rows)
  6219. {
  6220. p->setPropInt64("rowCount", rows);
  6221. }
  6222. void CLocalWUResult::setResultDataset(const char *ecl, const char *defs)
  6223. {
  6224. p->setProp("datasetEcl", ecl);
  6225. p->setProp("datasetEclDefs", defs);
  6226. }
  6227. void CLocalWUResult::setResultLogicalName(const char *logicalName)
  6228. {
  6229. p->setProp("logicalName", logicalName);
  6230. }
  6231. void CLocalWUResult::setResultKeyField(const char *ecl)
  6232. {
  6233. p->setProp("keyField", ecl);
  6234. }
  6235. void CLocalWUResult::setResultRequestedRows(unsigned rows)
  6236. {
  6237. p->setPropInt("requestedRows", rows);
  6238. }
  6239. void CLocalWUResult::setResultRecordSizeEntry(const char * entry)
  6240. {
  6241. p->setProp("@recordSizeEntry", entry);
  6242. }
  6243. void CLocalWUResult::setResultTransformerEntry(const char * entry)
  6244. {
  6245. p->setProp("@transformerEntry", entry);
  6246. }
  6247. void CLocalWUResult::setResultRowLimit(__int64 value)
  6248. {
  6249. p->setPropInt64("@rowLimit", value);
  6250. }
  6251. void CLocalWUResult::setResultFilename(const char * name)
  6252. {
  6253. p->setProp("@tempFilename", name);
  6254. }
  6255. // MORE - it's an undetected error if we call getResult... of a type that does not match schema
  6256. __int64 CLocalWUResult::getResultInt() const
  6257. {
  6258. __int64 result = 0;
  6259. MemoryBuffer s;
  6260. p->getPropBin("Value", s);
  6261. if (s.length())
  6262. s.read(result);
  6263. else
  6264. result = p->getPropInt64("xmlValue");
  6265. return result;
  6266. }
  6267. bool CLocalWUResult::getResultBool() const
  6268. {
  6269. bool result = false;
  6270. MemoryBuffer s;
  6271. p->getPropBin("Value", s);
  6272. if (s.length())
  6273. s.read(result);
  6274. else
  6275. result = p->getPropBool("xmlValue");
  6276. return result;
  6277. }
  6278. double CLocalWUResult::getResultReal() const
  6279. {
  6280. double result = 0;
  6281. MemoryBuffer s;
  6282. p->getPropBin("Value", s);
  6283. if (s.length())
  6284. s.read(result);
  6285. else
  6286. {
  6287. const char *xmlVal = p->queryProp("xmlValue");
  6288. if (xmlVal)
  6289. result = atof(xmlVal);
  6290. }
  6291. return result;
  6292. }
  6293. void CLocalWUResult::getResultDecimal(void * val, unsigned len, unsigned precision, bool isSigned) const
  6294. {
  6295. MemoryBuffer s;
  6296. p->getPropBin("Value", s);
  6297. if (s.length())
  6298. {
  6299. assertex(s.length() == len);
  6300. s.read(len, val);
  6301. }
  6302. else
  6303. {
  6304. const char *xmlVal = p->queryProp("xmlValue");
  6305. if (xmlVal)
  6306. {
  6307. TempDecimal d;
  6308. d.setString(strlen(xmlVal), xmlVal);
  6309. if (isSigned)
  6310. d.getDecimal(len, precision, val);
  6311. else
  6312. d.getUDecimal(len, precision, val);
  6313. }
  6314. else
  6315. memset(val, 0, len);
  6316. }
  6317. }
  6318. IStringVal& CLocalWUResult::getResultString(IStringVal & str) const
  6319. {
  6320. MemoryBuffer s;
  6321. p->getPropBin("Value", s);
  6322. if (s.length())
  6323. {
  6324. unsigned len;
  6325. s.read(len);
  6326. str.setLen((const char *) s.readDirect(len), len);
  6327. }
  6328. else
  6329. {
  6330. p->getPropBin("xmlValue", s);
  6331. if (p->isBinary("xmlValue"))
  6332. str.setLen(s.toByteArray(), s.length());
  6333. else
  6334. {
  6335. char *ascii = rtlUtf8ToVStr(rtlUtf8Length(s.length(), s.toByteArray()), s.toByteArray());
  6336. str.set(ascii);
  6337. rtlFree(ascii);
  6338. }
  6339. }
  6340. return str;
  6341. }
  6342. WUResultFormat CLocalWUResult::getResultFormat() const
  6343. {
  6344. const char * format = p->queryProp("@format");
  6345. if (!format)
  6346. return ResultFormatRaw;
  6347. else if (strcmp(format, "xml") == 0)
  6348. return ResultFormatXml;
  6349. else if (strcmp(format, "xmlSet") == 0)
  6350. return ResultFormatXmlSet;
  6351. else if (strcmp(format, "csv") == 0)
  6352. return ResultFormatCsv;
  6353. else
  6354. throw MakeStringException(WUERR_InvalidResultFormat, "Unrecognised result format %s", format);
  6355. }
  6356. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  6357. {
  6358. MemoryBuffer s;
  6359. p->getPropBin("Value", s);
  6360. unsigned len = s.length();
  6361. if (len)
  6362. {
  6363. WUResultFormat format = getResultFormat();
  6364. if (format == ResultFormatXml || format == ResultFormatXmlSet)
  6365. {
  6366. if (!xmlTransformer)
  6367. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate XML format result");
  6368. xmlTransformer->transform(data, len, s.readDirect(len), format == ResultFormatXml);
  6369. }
  6370. else if (format == ResultFormatCsv)
  6371. {
  6372. if (!csvTransformer)
  6373. throw MakeStringException(WUERR_MissingFormatTranslator, "No transformer supplied to translate Csv format result");
  6374. csvTransformer->transform(data, len, s.readDirect(len), true);
  6375. }
  6376. else
  6377. data.setLen(s.readDirect(len), len);
  6378. }
  6379. else
  6380. data.clear();
  6381. return data;
  6382. }
  6383. unsigned CLocalWUResult::getResultHash() const
  6384. {
  6385. MemoryBuffer s;
  6386. p->getPropBin("Value", s);
  6387. unsigned len = s.length();
  6388. const byte * data = (const byte *)s.toByteArray();
  6389. return ~hashc(data, len, ~0);
  6390. }
  6391. IDataVal& CLocalWUResult::getResultUnicode(IDataVal & data) const
  6392. {
  6393. MemoryBuffer s;
  6394. p->getPropBin("Value", s);
  6395. if (s.length())
  6396. {
  6397. unsigned len;
  6398. s.read(len);
  6399. data.setLen(s.readDirect(len*2), len*2);
  6400. }
  6401. else
  6402. {
  6403. StringBuffer utf8;
  6404. if (p->getProp("xmlValue", utf8))
  6405. {
  6406. unsigned outlen;
  6407. UChar *out;
  6408. rtlUtf8ToUnicodeX(outlen, out, utf8.length(), utf8.str());
  6409. data.setLen(out, outlen*2);
  6410. rtlFree(out);
  6411. }
  6412. else
  6413. data.clear();
  6414. }
  6415. return data;
  6416. }
  6417. __int64 CLocalWUResult::getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  6418. {
  6419. WUResultFormat format = getResultFormat();
  6420. if (format == ResultFormatRaw)
  6421. {
  6422. //MORE: This should not load the whole property...
  6423. MemoryBuffer s;
  6424. p->getPropBin("Value", s);
  6425. return s.length();
  6426. }
  6427. else
  6428. {
  6429. MemoryBuffer temp;
  6430. MemoryBuffer2IDataVal adaptor(temp);
  6431. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  6432. return temp.length();
  6433. }
  6434. }
  6435. IDataVal& CLocalWUResult::getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const
  6436. {
  6437. WUResultFormat format = getResultFormat();
  6438. if (format != ResultFormatRaw)
  6439. {
  6440. MemoryBuffer temp;
  6441. MemoryBuffer2IDataVal adaptor(temp);
  6442. getResultRaw(adaptor, xmlTransformer, csvTransformer);
  6443. unsigned len = temp.length();
  6444. if (from > len) from = len;
  6445. if (from + length > len) length = len - from;
  6446. data.setLen(temp.readDirect(len) + from, (size32_t)length);
  6447. return data;
  6448. }
  6449. else
  6450. {
  6451. //MORE: This should not load the whole property, and should be different from the code above...
  6452. MemoryBuffer s;
  6453. p->getPropBin("Value", s);
  6454. unsigned len = s.length();
  6455. if (from > len) from = len;
  6456. if (from + length > len) length = len - from;
  6457. data.setLen(s.readDirect(len) + from, (size32_t)length);
  6458. return data;
  6459. }
  6460. }
  6461. bool CLocalWUResult::getResultIsAll() const
  6462. {
  6463. return p->getPropBool("@isAll", false);
  6464. }
  6465. // MORE - it's an undetected error if we call setResult... of a type that does not match schema
  6466. void CLocalWUResult::setResultInt(__int64 val)
  6467. {
  6468. // Note: we always serialize scalar integer results as int8, and schema must reflect this
  6469. MemoryBuffer m;
  6470. serializeInt8(val, m);
  6471. p->setPropBin("Value", m.length(), m.toByteArray());
  6472. setResultRowCount(1);
  6473. setResultTotalRowCount(1);
  6474. }
  6475. void CLocalWUResult::setResultUInt(unsigned __int64 val)
  6476. {
  6477. setResultInt((__int64) val);
  6478. }
  6479. void CLocalWUResult::setResultReal(double val)
  6480. {
  6481. // Note: we always serialize scalar real results as real8, and schema must reflect this
  6482. MemoryBuffer m;
  6483. serializeReal8(val, m);
  6484. p->setPropBin("Value", m.length(), m.toByteArray());
  6485. setResultRowCount(1);
  6486. setResultTotalRowCount(1);
  6487. }
  6488. void CLocalWUResult::setResultBool(bool val)
  6489. {
  6490. MemoryBuffer m;
  6491. serializeBool(val, m);
  6492. p->setPropBin("Value", m.length(), m.toByteArray());
  6493. setResultRowCount(1);
  6494. setResultTotalRowCount(1);
  6495. }
  6496. void CLocalWUResult::setResultString(const char *val, unsigned len)
  6497. {
  6498. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  6499. MemoryBuffer m;
  6500. serializeLPString(len, val, m);
  6501. p->setPropBin("Value", m.length(), m.toByteArray());
  6502. setResultRowCount(1);
  6503. setResultTotalRowCount(1);
  6504. }
  6505. void CLocalWUResult::setResultUnicode(const void *val, unsigned len)
  6506. {
  6507. // Note: we always serialize scalar strings with length prefix, and schema must reflect this
  6508. MemoryBuffer m;
  6509. m.append(len).append(len*2, val);
  6510. p->setPropBin("Value", m.length(), m.toByteArray());
  6511. setResultRowCount(1);
  6512. setResultTotalRowCount(1);
  6513. }
  6514. void CLocalWUResult::setResultData(const void *val, unsigned len)
  6515. {
  6516. // Note: we always serialize scalar data with length prefix, and schema must reflect this
  6517. MemoryBuffer m;
  6518. serializeLPString(len, (const char *)val, m);
  6519. p->setPropBin("Value", m.length(), m.toByteArray());
  6520. setResultRowCount(1);
  6521. setResultTotalRowCount(1);
  6522. }
  6523. void CLocalWUResult::setResultDecimal(const void *val, unsigned len)
  6524. {
  6525. // Note: serialized as data but with length known from schema
  6526. MemoryBuffer m;
  6527. serializeFixedData(len, val, m);
  6528. p->setPropBin("Value", m.length(), m.toByteArray());
  6529. setResultRowCount(1);
  6530. setResultTotalRowCount(1);
  6531. }
  6532. void CLocalWUResult::setResultIsAll(bool value)
  6533. {
  6534. p->setPropBool("@isAll", value);
  6535. }
  6536. //==========================================================================================
  6537. CLocalWUPlugin::CLocalWUPlugin(IPropertyTree *props) : p(props)
  6538. {
  6539. }
  6540. IStringVal& CLocalWUPlugin::getPluginName(IStringVal &str) const
  6541. {
  6542. str.set(p->queryProp("@dllname"));
  6543. return str;
  6544. }
  6545. IStringVal& CLocalWUPlugin::getPluginVersion(IStringVal &str) const
  6546. {
  6547. str.set(p->queryProp("@version"));
  6548. return str;
  6549. }
  6550. bool CLocalWUPlugin::getPluginThor() const
  6551. {
  6552. return p->getPropInt("@thor") != 0;
  6553. }
  6554. bool CLocalWUPlugin::getPluginHole() const
  6555. {
  6556. return p->getPropInt("@hole") != 0;
  6557. }
  6558. void CLocalWUPlugin::setPluginName(const char *str)
  6559. {
  6560. p->setProp("@dllname", str);
  6561. }
  6562. void CLocalWUPlugin::setPluginVersion(const char *str)
  6563. {
  6564. p->setProp("@version", str);
  6565. }
  6566. void CLocalWUPlugin::setPluginThor(bool on)
  6567. {
  6568. p->setPropInt("@thor", (int) on);
  6569. }
  6570. void CLocalWUPlugin::setPluginHole(bool on)
  6571. {
  6572. p->setPropInt("@hole", (int) on);
  6573. }
  6574. //==========================================================================================
  6575. class WULibraryActivityIterator : public CInterface, implements IConstWULibraryActivityIterator
  6576. {
  6577. public:
  6578. WULibraryActivityIterator(IPropertyTree * tree) { iter.setown(tree->getElements("activity")); }
  6579. IMPLEMENT_IINTERFACE;
  6580. bool first() { return iter->first(); }
  6581. bool isValid() { return iter->isValid(); }
  6582. bool next() { return iter->next(); }
  6583. unsigned query() const { return iter->query().getPropInt("@id"); }
  6584. private:
  6585. Owned<IPropertyTreeIterator> iter;
  6586. };
  6587. CLocalWULibrary::CLocalWULibrary(IPropertyTree *props) : p(props)
  6588. {
  6589. }
  6590. IStringVal& CLocalWULibrary::getName(IStringVal &str) const
  6591. {
  6592. str.set(p->queryProp("@name"));
  6593. return str;
  6594. }
  6595. IConstWULibraryActivityIterator * CLocalWULibrary::getActivities() const
  6596. {
  6597. return new WULibraryActivityIterator(p);
  6598. }
  6599. void CLocalWULibrary::setName(const char *str)
  6600. {
  6601. p->setProp("@name", str);
  6602. }
  6603. void CLocalWULibrary::addActivity(unsigned id)
  6604. {
  6605. StringBuffer s;
  6606. s.append("activity[@id=\"").append(id).append("\"]");
  6607. if (!p->hasProp(s.str()))
  6608. p->addPropTree("activity", createPTree())->setPropInt("@id", id);
  6609. }
  6610. //==========================================================================================
  6611. CLocalWUActivity::CLocalWUActivity(IPropertyTree *props, __int64 id) : p(props)
  6612. {
  6613. if (id)
  6614. p->setPropInt64("@id", id);
  6615. }
  6616. __int64 CLocalWUActivity::getId() const
  6617. {
  6618. return p->getPropInt64("@id");
  6619. }
  6620. unsigned CLocalWUActivity::getKind() const
  6621. {
  6622. return (unsigned)p->getPropInt("@kind");
  6623. }
  6624. IStringVal & CLocalWUActivity::getHelper(IStringVal & str) const
  6625. {
  6626. str.set(p->queryProp("@helper"));
  6627. return str;
  6628. }
  6629. void CLocalWUActivity::setKind(unsigned kind)
  6630. {
  6631. p->setPropInt64("@kind", kind);
  6632. }
  6633. void CLocalWUActivity::setHelper(const char * str)
  6634. {
  6635. p->setProp("@helper", str);
  6636. }
  6637. //==========================================================================================
  6638. CLocalWUException::CLocalWUException(IPropertyTree *props) : p(props)
  6639. {
  6640. }
  6641. IStringVal& CLocalWUException::getExceptionSource(IStringVal &str) const
  6642. {
  6643. str.set(p->queryProp("@source"));
  6644. return str;
  6645. }
  6646. IStringVal& CLocalWUException::getExceptionMessage(IStringVal &str) const
  6647. {
  6648. str.set(p->queryProp(NULL));
  6649. return str;
  6650. }
  6651. unsigned CLocalWUException::getExceptionCode() const
  6652. {
  6653. return p->getPropInt("@code", 0);
  6654. }
  6655. WUExceptionSeverity CLocalWUException::getSeverity() const
  6656. {
  6657. return (WUExceptionSeverity)p->getPropInt("@severity", ExceptionSeverityError);
  6658. }
  6659. IStringVal & CLocalWUException::getTimeStamp(IStringVal & dt) const
  6660. {
  6661. dt.set(p->queryProp("@time"));
  6662. return dt;
  6663. }
  6664. IStringVal & CLocalWUException::getExceptionFileName(IStringVal & str) const
  6665. {
  6666. str.set(p->queryProp("@filename"));
  6667. return str;
  6668. }
  6669. unsigned CLocalWUException::getExceptionLineNo() const
  6670. {
  6671. return p->getPropInt("@row", 0);
  6672. }
  6673. unsigned CLocalWUException::getExceptionColumn() const
  6674. {
  6675. return p->getPropInt("@col", 0);
  6676. }
  6677. void CLocalWUException::setExceptionSource(const char *str)
  6678. {
  6679. p->setProp("@source", str);
  6680. }
  6681. void CLocalWUException::setExceptionMessage(const char *str)
  6682. {
  6683. p->setProp(NULL, str);
  6684. }
  6685. void CLocalWUException::setExceptionCode(unsigned code)
  6686. {
  6687. p->setPropInt("@code", code);
  6688. }
  6689. void CLocalWUException::setSeverity(WUExceptionSeverity level)
  6690. {
  6691. p->setPropInt("@severity", level);
  6692. }
  6693. void CLocalWUException::setTimeStamp(const char *str)
  6694. {
  6695. p->setProp("@time", str);
  6696. }
  6697. void CLocalWUException::setExceptionFileName(const char *str)
  6698. {
  6699. p->setProp("@filename", str);
  6700. }
  6701. void CLocalWUException::setExceptionLineNo(unsigned r)
  6702. {
  6703. p->setPropInt("@row", r);
  6704. }
  6705. void CLocalWUException::setExceptionColumn(unsigned c)
  6706. {
  6707. p->setPropInt("@col", c);
  6708. }
  6709. CLocalWUTimeStamp::CLocalWUTimeStamp(IPropertyTree *props) : p(props)
  6710. {
  6711. }
  6712. IStringVal & CLocalWUTimeStamp::getApplication(IStringVal & str) const
  6713. {
  6714. str.set(p->queryProp("@application"));
  6715. return str;
  6716. }
  6717. IStringVal & CLocalWUTimeStamp::getEvent(IStringVal & str) const
  6718. {
  6719. IPropertyTree* evt=p->queryPropTree("*[1]");
  6720. if(evt)
  6721. str.set(evt->queryName());
  6722. return str;
  6723. }
  6724. IStringVal & CLocalWUTimeStamp::getDate(IStringVal & str) const
  6725. {
  6726. str.set(p->queryProp("*[1]"));
  6727. return str;
  6728. }
  6729. CLocalWUAppValue::CLocalWUAppValue(IPropertyTree *props,unsigned child): p(props)
  6730. {
  6731. prop.append("*[").append(child).append("]");
  6732. }
  6733. IStringVal & CLocalWUAppValue::getApplication(IStringVal & str) const
  6734. {
  6735. str.set(p->queryName());
  6736. return str;
  6737. }
  6738. IStringVal & CLocalWUAppValue::getName(IStringVal & str) const
  6739. {
  6740. IPropertyTree* val=p->queryPropTree(prop.str());
  6741. if(val)
  6742. str.set(val->queryName());
  6743. return str;
  6744. }
  6745. IStringVal & CLocalWUAppValue::getValue(IStringVal & str) const
  6746. {
  6747. str.set(p->queryProp(prop.str()));
  6748. return str;
  6749. }
  6750. extern WORKUNIT_API ILocalWorkUnit * createLocalWorkUnit()
  6751. {
  6752. Owned<CLocalWorkUnit> cw = new CLocalWorkUnit("W_LOCAL", NULL, (ISecManager*)NULL, NULL);
  6753. ILocalWorkUnit* ret = QUERYINTERFACE(&cw->lockRemote(false), ILocalWorkUnit);
  6754. return ret;
  6755. }
  6756. StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str)
  6757. {
  6758. const CLocalWorkUnit *w = QUERYINTERFACE(wu, const CLocalWorkUnit);
  6759. if (!w)
  6760. {
  6761. const CLockedWorkUnit *wl = QUERYINTERFACE(wu, const CLockedWorkUnit);
  6762. if (wl)
  6763. w = wl->c;
  6764. }
  6765. if (w)
  6766. toXML(w->p, str, 0, XML_Format|XML_SortTags);
  6767. else
  6768. str.append("Unrecognized workunit format");
  6769. return str;
  6770. }
  6771. extern WORKUNIT_API IStringVal& exportWorkUnitToXML(const IConstWorkUnit *wu, IStringVal &str)
  6772. {
  6773. StringBuffer x;
  6774. str.set(exportWorkUnitToXML(wu,x).str());
  6775. return str;
  6776. }
  6777. extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags)
  6778. {
  6779. const CLocalWorkUnit *w = QUERYINTERFACE(wu, const CLocalWorkUnit);
  6780. if (!w)
  6781. {
  6782. const CLockedWorkUnit *wl = QUERYINTERFACE(wu, const CLockedWorkUnit);
  6783. if (wl)
  6784. w = wl->c;
  6785. }
  6786. if (w)
  6787. saveXML(filename, w->p, 0, XML_Format|XML_SortTags|extraXmlFlags);
  6788. }
  6789. extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password)
  6790. {
  6791. MemoryBuffer buffer;
  6792. Owned<INamedQueueConnection> conn = createNamedQueueConnection(0); // MORE - security token?
  6793. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  6794. Owned<IWorkUnit> workunit = factory->updateWorkUnit(wuid);
  6795. assertex(workunit);
  6796. SCMStringBuffer token;
  6797. createToken(wuid, username, password, token);
  6798. workunit->setSecurityToken(token.str());
  6799. SCMStringBuffer clusterName;
  6800. workunit->getClusterName(clusterName);
  6801. if (!clusterName.length())
  6802. throw MakeStringException(WUERR_InvalidCluster, "No target cluster specified");
  6803. workunit->commit();
  6804. workunit.clear();
  6805. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  6806. if (!clusterInfo)
  6807. throw MakeStringException(WUERR_InvalidCluster, "Unknown cluster %s", clusterName.str());
  6808. SCMStringBuffer serverQueue;
  6809. clusterInfo->getServerQueue(serverQueue);
  6810. assertex(serverQueue.length());
  6811. Owned<IJobQueue> queue = createJobQueue(serverQueue.str());
  6812. if (!queue.get())
  6813. throw MakeStringException(WUERR_InvalidQueue, "Could not create workunit queue");
  6814. IJobQueueItem *item = createJobQueueItem(wuid);
  6815. queue->enqueue(item);
  6816. }
  6817. extern WORKUNIT_API void abortWorkUnit(const char *wuid)
  6818. {
  6819. StringBuffer xpath("/WorkUnitAborts/");
  6820. xpath.append(wuid);
  6821. Owned<IRemoteConnection> acon = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE, SDS_LOCK_TIMEOUT);
  6822. acon->queryRoot()->setPropInt(NULL, 1);
  6823. }
  6824. extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  6825. {
  6826. if (checkWuSecAccess(wuid, secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  6827. submitWorkUnit(wuid, secuser.getName(), secuser.credentials().getPassword());
  6828. }
  6829. extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser)
  6830. {
  6831. if (checkWuSecAccess(wuid, secmgr, &secuser, SecAccess_Write, "Submit", true, true))
  6832. abortWorkUnit(wuid);
  6833. }
  6834. bool CLocalWorkUnit::hasWorkflow() const
  6835. {
  6836. return p->hasProp("Workflow");
  6837. }
  6838. unsigned CLocalWorkUnit::queryEventScheduledCount() const
  6839. {
  6840. CriticalBlock block(crit);
  6841. return p->getPropInt("Workflow/@eventScheduledCount", 0);
  6842. }
  6843. void CLocalWorkUnit::incEventScheduledCount()
  6844. {
  6845. CriticalBlock block(crit);
  6846. p->setPropInt("Workflow/@eventScheduledCount", p->getPropInt("Workflow/@eventScheduledCount", 0)+1);
  6847. }
  6848. IPropertyTree * CLocalWorkUnit::queryWorkflowTree() const
  6849. {
  6850. CriticalBlock block(crit);
  6851. return p->queryPropTree("Workflow");
  6852. }
  6853. IConstWorkflowItemIterator* CLocalWorkUnit::getWorkflowItems() const
  6854. {
  6855. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  6856. CriticalBlock block(crit);
  6857. if(!workflowIteratorCached)
  6858. {
  6859. assertex(!workflowIterator);
  6860. Owned<IPropertyTree> s = p->getPropTree("Workflow");
  6861. if(s)
  6862. workflowIterator.setown(createWorkflowItemIterator(s));
  6863. workflowIteratorCached = true;
  6864. }
  6865. return workflowIterator.getLink();
  6866. }
  6867. IWorkflowItemArray * CLocalWorkUnit::getWorkflowClone() const
  6868. {
  6869. unsigned count = 0;
  6870. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  6871. for(iter->first(); iter->isValid(); iter->next())
  6872. count++;
  6873. Owned<IWorkflowItemArray> array = createWorkflowItemArray(count);
  6874. for(iter->first(); iter->isValid(); iter->next())
  6875. array->addClone(iter->query());
  6876. return array.getLink();
  6877. }
  6878. IWorkflowItem * CLocalWorkUnit::addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor)
  6879. {
  6880. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  6881. CriticalBlock block(crit);
  6882. workflowIterator.clear();
  6883. workflowIteratorCached = false;
  6884. IPropertyTree * s = p->queryPropTree("Workflow");
  6885. if(!s)
  6886. s = p->addPropTree("Workflow", createPTree("Workflow"));
  6887. return createWorkflowItem(s, wfid, type, mode, success, failure, recovery, retriesAllowed, contingencyFor);
  6888. }
  6889. IWorkflowItemIterator * CLocalWorkUnit::updateWorkflowItems()
  6890. {
  6891. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  6892. CriticalBlock block(crit);
  6893. if(!workflowIterator)
  6894. {
  6895. IPropertyTree * s = p->queryPropTree("Workflow");
  6896. if(!s)
  6897. s = p->addPropTree("Workflow", createPTree("Workflow"));
  6898. workflowIterator.setown(createWorkflowItemIterator(s));
  6899. workflowIteratorCached = true;
  6900. }
  6901. return workflowIterator.getLink();
  6902. }
  6903. void CLocalWorkUnit::syncRuntimeWorkflow(IWorkflowItemArray * array)
  6904. {
  6905. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  6906. Owned<IWorkflowItem> item;
  6907. for(iter->first(); iter->isValid(); iter->next())
  6908. {
  6909. item.setown(iter->get());
  6910. item->syncRuntimeData(array->queryWfid(item->queryWfid()));
  6911. }
  6912. workflowIterator.clear();
  6913. workflowIteratorCached = false;
  6914. }
  6915. void CLocalWorkUnit::resetWorkflow()
  6916. {
  6917. if (hasWorkflow())
  6918. {
  6919. Owned<IWorkflowItemIterator> iter = updateWorkflowItems();
  6920. Owned<IWorkflowItem> wf;
  6921. for(iter->first(); iter->isValid(); iter->next())
  6922. {
  6923. wf.setown(iter->get());
  6924. wf->reset();
  6925. }
  6926. workflowIterator.clear();
  6927. workflowIteratorCached = false;
  6928. }
  6929. }
  6930. void CLocalWorkUnit::schedule()
  6931. {
  6932. CriticalBlock block(crit);
  6933. if(queryEventScheduledCount() == 0) return;
  6934. switch(getState())
  6935. {
  6936. case WUStateCompleted:
  6937. setState(WUStateWait);
  6938. break;
  6939. case WUStateFailed:
  6940. case WUStateArchived:
  6941. case WUStateAborting:
  6942. case WUStateAborted:
  6943. case WUStateScheduled:
  6944. throw MakeStringException(WUERR_CannotSchedule, "Cannot schedule workunit in this state");
  6945. }
  6946. StringBuffer rootPath;
  6947. SCMStringBuffer clusterName;
  6948. getClusterName(clusterName);
  6949. rootPath.append("/Schedule/").append(clusterName.str());
  6950. Owned<IRemoteConnection> conn = querySDS().connect(rootPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  6951. Owned<IPropertyTree> root = conn->getRoot();
  6952. if(!root->hasChildren())
  6953. {
  6954. StringBuffer addPath;
  6955. addPath.append("/Schedulers/").append(clusterName.str());
  6956. Owned<IRemoteConnection> addConn = querySDS().connect(addPath.str(), myProcessSession(), RTM_LOCK_WRITE | RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  6957. }
  6958. char const * wuid = p->queryName();
  6959. StringBuffer xpath("*/*/");
  6960. ncnameEscape(wuid, xpath);
  6961. bool more;
  6962. do more = root->removeProp(xpath.str()); while(more);
  6963. Owned<IConstWorkflowItemIterator> iter = getWorkflowItems();
  6964. Owned<IWorkflowEvent> event;
  6965. Owned<IPropertyTree> branch1, branch2;
  6966. for(iter->first(); iter->isValid(); iter->next())
  6967. {
  6968. event.setown(iter->query()->getScheduleEvent());
  6969. if(!event) continue;
  6970. ncnameEscape(event->queryName(), xpath.clear());
  6971. ensurePTree(root, xpath.str());
  6972. branch1.setown(root->getPropTree(xpath.str()));
  6973. ncnameEscape(event->queryText(), xpath.clear());
  6974. ensurePTree(branch1, xpath.str());
  6975. branch2.setown(branch1->getPropTree(xpath.str()));
  6976. ncnameEscape(wuid, xpath.clear());
  6977. ensurePTree(branch2, xpath.str());
  6978. }
  6979. }
  6980. void CLocalWorkUnit::deschedule()
  6981. {
  6982. if(queryEventScheduledCount() == 0) return;
  6983. if(getState() == WUStateWait)
  6984. setState(WUStateCompleted);
  6985. char const * wuid = p->queryName();
  6986. StringBuffer xpath;
  6987. xpath.append("*/*/*/");
  6988. ncnameEscape(wuid, xpath);
  6989. Owned<IRemoteConnection> conn = querySDS().connect("/Schedule", myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  6990. if(!conn) return;
  6991. Owned<IPropertyTree> root = conn->getRoot();
  6992. bool more;
  6993. do more = root->removeProp(xpath.str()); while(more);
  6994. }
  6995. mapEnums localFileUploadTypes[] = {
  6996. { UploadTypeFileSpray, "FileSpray" },
  6997. { UploadTypeWUResult, "WUResult" },
  6998. { UploadTypeWUResultCsv, "WUResultCsv" },
  6999. { UploadTypeWUResultXml, "WUResultXml" },
  7000. { UploadTypeSize, NULL }
  7001. };
  7002. class CLocalFileUpload : public CInterface, implements IConstLocalFileUpload
  7003. {
  7004. public:
  7005. CLocalFileUpload(IPropertyTree * _tree) : tree(_tree) {}
  7006. CLocalFileUpload(unsigned id, LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  7007. {
  7008. tree.setown(createPTree());
  7009. tree->setPropInt("@id", id);
  7010. setEnum(tree, "@type", type, localFileUploadTypes);
  7011. tree->setProp("@source", source);
  7012. tree->setProp("@destination", destination);
  7013. if (eventTag)
  7014. tree->setProp("@eventTag", eventTag);
  7015. }
  7016. IMPLEMENT_IINTERFACE;
  7017. IPropertyTree * getTree() { return tree.getLink(); }
  7018. virtual unsigned queryID() const { return tree->getPropInt("@id"); }
  7019. virtual LocalFileUploadType queryType() const { return (LocalFileUploadType)getEnum(tree, "@type", localFileUploadTypes); }
  7020. virtual IStringVal & getSource(IStringVal & ret) const { ret.set(tree->queryProp("@source")); return ret; }
  7021. virtual IStringVal & getDestination(IStringVal & ret) const { ret.set(tree->queryProp("@destination")); return ret; }
  7022. virtual IStringVal & getEventTag(IStringVal & ret) const { if(tree->hasProp("@eventTag")) ret.set(tree->queryProp("@eventTag")); else ret.clear(); return ret; }
  7023. private:
  7024. Owned<IPropertyTree> tree;
  7025. };
  7026. class CLocalFileUploadIterator : public CInterface, implements IConstLocalFileUploadIterator
  7027. {
  7028. public:
  7029. CLocalFileUploadIterator(IPropertyTree * _tree) : tree(_tree), iter(tree->getElements("LocalFileUpload")) {}
  7030. IMPLEMENT_IINTERFACE;
  7031. bool first() { return iter->first(); }
  7032. bool isValid() { return iter->isValid(); }
  7033. bool next() { return iter->next(); }
  7034. IConstLocalFileUpload * get() { return new CLocalFileUpload(&iter->get()); }
  7035. private:
  7036. Owned<IPropertyTree> tree;
  7037. Owned<IPropertyTreeIterator> iter;
  7038. };
  7039. IConstLocalFileUploadIterator * CLocalWorkUnit::getLocalFileUploads() const
  7040. {
  7041. // For this to be legally called, we must have the read-able interface. So we are already locked for (at least) read.
  7042. CriticalBlock block(crit);
  7043. Owned<IPropertyTree> s = p->getPropTree("LocalFileUploads");
  7044. if(s)
  7045. return new CLocalFileUploadIterator(s.getClear());
  7046. else
  7047. return NULL;
  7048. }
  7049. bool CLocalWorkUnit::requiresLocalFileUpload() const
  7050. {
  7051. SCMStringBuffer dest;
  7052. Owned<IConstWUResult> result;
  7053. Owned<IConstLocalFileUploadIterator> iter(getLocalFileUploads());
  7054. if(!iter)
  7055. return false;
  7056. for(iter->first(); iter->isValid(); iter->next())
  7057. {
  7058. Owned<IConstLocalFileUpload> upload(iter->get());
  7059. switch(upload->queryType())
  7060. {
  7061. case UploadTypeWUResult:
  7062. case UploadTypeWUResultCsv:
  7063. case UploadTypeWUResultXml:
  7064. upload->getDestination(dest);
  7065. result.setown(getResultByName(dest.str()));
  7066. if(!result)
  7067. return true;
  7068. break;
  7069. default:
  7070. throw MakeStringException(WUERR_InvalidUploadFormat, "Unsupported local file upload type %s", getEnumText(upload->queryType(), localFileUploadTypes));
  7071. }
  7072. }
  7073. return false;
  7074. }
  7075. unsigned CLocalWorkUnit::addLocalFileUpload(LocalFileUploadType type, char const * source, char const * destination, char const * eventTag)
  7076. {
  7077. // For this to be legally called, we must have the write-able interface. So we are already locked for write.
  7078. CriticalBlock block(crit);
  7079. IPropertyTree * s = p->queryPropTree("LocalFileUploads");
  7080. if(!s)
  7081. s = p->addPropTree("LocalFileUploads", createPTree());
  7082. unsigned id = s->numChildren();
  7083. Owned<CLocalFileUpload> upload = new CLocalFileUpload(id, type, source, destination, eventTag);
  7084. s->addPropTree("LocalFileUpload", upload->getTree());
  7085. return id;
  7086. }
  7087. #if 0
  7088. void testConstWorkflow(IConstWorkflowItem * cwf, bool * okay, bool * dep)
  7089. {
  7090. DBGLOG("Test workflow const iface %u", cwf->queryWfid());
  7091. unsigned deps = 0;
  7092. Owned<IWorkflowDependencyIterator> diter;
  7093. switch(cwf->queryWfid())
  7094. {
  7095. case 1:
  7096. assertex(!cwf->isScheduled());
  7097. assertex(cwf->queryType() == WFTypeNormal);
  7098. assertex(cwf->queryState() == WFStateNull);
  7099. diter.setown(cwf->getDependencies());
  7100. for(diter->first(); diter->isValid(); diter->next())
  7101. deps++;
  7102. assertex(deps==0);
  7103. okay[0] = true;
  7104. break;
  7105. case 2:
  7106. assertex(!cwf->isScheduled());
  7107. assertex(cwf->queryType() == WFTypeRecovery);
  7108. assertex(cwf->queryState() == WFStateSkip);
  7109. okay[1] = true;
  7110. break;
  7111. case 3:
  7112. assertex(cwf->queryContingencyFor() == 4);
  7113. okay[2] = true;
  7114. break;
  7115. case 4:
  7116. assertex(cwf->isScheduled());
  7117. assertex(cwf->queryType() == WFTypeNormal);
  7118. assertex(cwf->queryState() == WFStateReqd);
  7119. assertex(cwf->querySuccess() == 0);
  7120. assertex(cwf->queryFailure() == 3);
  7121. assertex(cwf->queryRecovery() == 2);
  7122. assertex(cwf->queryRetriesAllowed() == 10);
  7123. assertex(cwf->queryRetriesRemaining() == 10);
  7124. diter.setown(cwf->getDependencies());
  7125. for(diter->first(); diter->isValid(); diter->next())
  7126. {
  7127. dep[diter->query()-1] = true;
  7128. deps++;
  7129. }
  7130. assertex(deps==2);
  7131. assertex(dep[0]);
  7132. assertex(dep[1]);
  7133. okay[3] = true;
  7134. break;
  7135. case 5:
  7136. assertex(cwf->isScheduled());
  7137. assertex(!cwf->isScheduledNow());
  7138. assertex(cwf->querySchedulePriority() == 75);
  7139. assertex(cwf->queryScheduleCount() == 5);
  7140. assertex(cwf->queryScheduleCountRemaining() == 5);
  7141. okay[4] = true;
  7142. break;
  7143. case 6:
  7144. assertex(cwf->isScheduled());
  7145. assertex(!cwf->isScheduledNow());
  7146. assertex(cwf->querySchedulePriority() == 25);
  7147. assertex(!cwf->hasScheduleCount());
  7148. okay[5] = true;
  7149. break;
  7150. default:
  7151. assertex(!"unknown wfid in test");
  7152. }
  7153. }
  7154. void testRuntimeWorkflow(IRuntimeWorkflowItem * rwf, bool * okay)
  7155. {
  7156. DBGLOG("Test workflow runtime iface %u", rwf->queryWfid());
  7157. switch(rwf->queryWfid())
  7158. {
  7159. case 1:
  7160. case 2:
  7161. case 3:
  7162. okay[rwf->queryWfid()-1] = true;
  7163. break;
  7164. case 4:
  7165. {
  7166. unsigned tries = 0;
  7167. while(rwf->testAndDecRetries())
  7168. tries++;
  7169. assertex(tries == 10);
  7170. assertex(rwf->queryRetriesRemaining() == 0);
  7171. rwf->setState(WFStateFail);
  7172. assertex(rwf->queryState() == WFStateFail);
  7173. rwf->reset();
  7174. assertex(rwf->queryRetriesRemaining() == 10);
  7175. assertex(rwf->queryState() == WFStateReqd);
  7176. }
  7177. okay[3] = true;
  7178. break;
  7179. case 5:
  7180. {
  7181. assertex(rwf->queryScheduleCountRemaining() == 5);
  7182. unsigned count = 0;
  7183. do count++; while(rwf->decAndTestScheduleCountRemaining());
  7184. assertex(count == 5);
  7185. assertex(rwf->queryScheduleCountRemaining() == 0);
  7186. rwf->reset();
  7187. assertex(rwf->queryScheduleCountRemaining() == 5);
  7188. }
  7189. okay[4] = true;
  7190. break;
  7191. case 6:
  7192. {
  7193. assertex(!rwf->hasScheduleCount());
  7194. unsigned count;
  7195. for(count=0; count<20; count++)
  7196. assertex(rwf->decAndTestScheduleCountRemaining());
  7197. }
  7198. okay[5] = true;
  7199. break;
  7200. default:
  7201. assertex(!"unknown wfid in test");
  7202. }
  7203. }
  7204. void testWorkflow()
  7205. {
  7206. DBGLOG("workunit.cpp : testWorkflow");
  7207. CLocalWorkUnit wu("W-WF-TEST", 0, 0, 0);
  7208. Owned<IWorkflowItem> wf;
  7209. wf.setown(wu.addWorkflowItem(1, WFTypeNormal, 0, 0, 0, 0, 0));
  7210. wf.setown(wu.addWorkflowItem(2, WFTypeRecovery, 0, 0, 0, 0, 0));
  7211. wf.setown(wu.addWorkflowItem(3, WFTypeFailure, 0, 0, 0, 0, 4));
  7212. wf.setown(wu.addWorkflowItem(4, WFTypeNormal, 0, 3, 2, 10, 0));
  7213. wf->setScheduledNow();
  7214. wf->addDependency(1);
  7215. wf.setown(wu.addWorkflowItem(5, WFTypeNormal, 0, 0, 0, 0, 0));
  7216. wf->setScheduledOn("test", "foo*");
  7217. wf->setSchedulePriority(75);
  7218. wf->setScheduleCount(5);
  7219. wf.setown(wu.addWorkflowItem(6, WFTypeNormal, 0, 0, 0, 0, 0));
  7220. wf->setScheduledOn("test", "bar*");
  7221. wf->setSchedulePriority(25);
  7222. unsigned const n = 6;
  7223. bool okay[n];
  7224. bool dep[n];
  7225. unsigned i;
  7226. for(i=0; i<n; i++)
  7227. okay[i] = dep[i] = 0;
  7228. Owned<IConstWorkflowItemIterator> citer(wu.getWorkflowItems());
  7229. for(citer->first(); citer->isValid(); citer->next())
  7230. testConstWorkflow(citer->query(), okay, dep);
  7231. for(i=0; i<n; i++)
  7232. {
  7233. assertex(okay[i]);
  7234. okay[i] = false;
  7235. }
  7236. Owned<IWorkflowItemIterator> miter(wu.updateWorkflowItems());
  7237. for(miter->first(); miter->isValid(); miter->next())
  7238. {
  7239. Owned<IRuntimeWorkflowItem> rwf(miter->get());
  7240. testRuntimeWorkflow(rwf, okay);
  7241. }
  7242. for(i=0; i<n; i++)
  7243. {
  7244. assertex(okay[i]);
  7245. okay[i] = dep[i] = false;
  7246. }
  7247. Owned<IWorkflowItemArray> array(wu.getWorkflowClone());
  7248. unsigned wfid;
  7249. for(wfid = 1; array->isValid(wfid); wfid++)
  7250. testConstWorkflow(&array->queryWfid(wfid), okay, dep);
  7251. for(i=0; i<n; i++)
  7252. {
  7253. assertex(okay[i]);
  7254. okay[i] = false;
  7255. }
  7256. for(wfid = 1; array->isValid(wfid); wfid++)
  7257. testRuntimeWorkflow(&array->queryWfid(wfid), okay);
  7258. for(i=0; i<n; i++)
  7259. {
  7260. assertex(okay[i]);
  7261. okay[i] = false;
  7262. }
  7263. }
  7264. #endif
  7265. //------------------------------------------------------------------------------------------
  7266. class WorkUnitWaiter : public CInterface, implements ISDSSubscription, implements IAbortHandler
  7267. {
  7268. Semaphore changed;
  7269. SubscriptionId change;
  7270. public:
  7271. IMPLEMENT_IINTERFACE;
  7272. WorkUnitWaiter(const char *xpath)
  7273. {
  7274. change = querySDS().subscribe(xpath, *this, false);
  7275. aborted = false;
  7276. }
  7277. ~WorkUnitWaiter()
  7278. {
  7279. assertex(change==0);
  7280. }
  7281. void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData)
  7282. {
  7283. changed.signal();
  7284. }
  7285. bool wait(unsigned timeout)
  7286. {
  7287. return changed.wait(timeout) && !aborted;
  7288. }
  7289. bool onAbort()
  7290. {
  7291. aborted = true;
  7292. changed.signal();
  7293. return false;
  7294. }
  7295. void unsubscribe()
  7296. {
  7297. querySDS().unsubscribe(change);
  7298. change = 0;
  7299. }
  7300. bool aborted;
  7301. };
  7302. static WUState _waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, bool returnOnWaitState)
  7303. {
  7304. StringBuffer wuRoot;
  7305. getXPath(wuRoot, wuid);
  7306. WorkUnitWaiter waiter(wuRoot.str());
  7307. LocalIAbortHandler abortHandler(waiter);
  7308. WUState ret = WUStateUnknown;
  7309. Owned<IRemoteConnection> conn = querySDS().connect(wuRoot.str(), myProcessSession(), 0, SDS_LOCK_TIMEOUT);
  7310. if (conn)
  7311. {
  7312. unsigned start = msTick();
  7313. loop
  7314. {
  7315. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  7316. switch (ret)
  7317. {
  7318. case WUStateCompiled:
  7319. case WUStateUploadingFiles:
  7320. if (!compiled)
  7321. break;
  7322. // fall into
  7323. case WUStateCompleted:
  7324. case WUStateFailed:
  7325. case WUStateAborted:
  7326. waiter.unsubscribe();
  7327. return ret;
  7328. case WUStateWait:
  7329. if(returnOnWaitState)
  7330. {
  7331. waiter.unsubscribe();
  7332. return ret;
  7333. }
  7334. break;
  7335. case WUStateCompiling:
  7336. case WUStateRunning:
  7337. case WUStateDebugPaused:
  7338. case WUStateDebugRunning:
  7339. case WUStateBlocked:
  7340. case WUStateAborting:
  7341. if (queryDaliServerVersion().compare("2.1")>=0)
  7342. {
  7343. SessionId agent = conn->queryRoot()->getPropInt64("@agentSession", -1);
  7344. if((agent>0) && querySessionManager().sessionStopped(agent, 0))
  7345. {
  7346. waiter.unsubscribe();
  7347. conn->reload();
  7348. ret = (WUState) getEnum(conn->queryRoot(), "@state", states);
  7349. bool isEcl = false;
  7350. switch (ret)
  7351. {
  7352. case WUStateCompiling:
  7353. isEcl = true;
  7354. // drop into
  7355. case WUStateRunning:
  7356. case WUStateBlocked:
  7357. ret = WUStateFailed;
  7358. break;
  7359. case WUStateAborting:
  7360. ret = WUStateAborted;
  7361. break;
  7362. default:
  7363. return ret;
  7364. }
  7365. WARNLOG("_waitForWorkUnit terminated: %"I64F"d state = %d",(__int64)agent,(int)ret);
  7366. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  7367. Owned<IWorkUnit> wu = factory->updateWorkUnit(wuid);
  7368. wu->setState(ret);
  7369. Owned<IWUException> e = wu->createException();
  7370. e->setExceptionCode(isEcl ? 1001 : 1000);
  7371. e->setExceptionMessage(isEcl ? "EclServer terminated unexpectedly" : "Workunit terminated unexpectedly");
  7372. return ret;
  7373. }
  7374. }
  7375. break;
  7376. }
  7377. unsigned waited = msTick() - start;
  7378. if (timeout==-1)
  7379. {
  7380. waiter.wait(20000); // recheck state every 20 seconds even if no timeout, in case eclagent has crashed.
  7381. if (waiter.aborted)
  7382. {
  7383. ret = WUStateUnknown; // MORE - throw an exception?
  7384. break;
  7385. }
  7386. }
  7387. else if (waited > timeout || !waiter.wait(timeout-waited))
  7388. {
  7389. ret = WUStateUnknown; // MORE - throw an exception?
  7390. break;
  7391. }
  7392. conn->reload();
  7393. }
  7394. }
  7395. waiter.unsubscribe();
  7396. return ret;
  7397. }
  7398. extern WUState waitForWorkUnitToComplete(const char * wuid, int timeout, bool returnOnWaitState)
  7399. {
  7400. return _waitForWorkUnit(wuid, (unsigned)timeout, false, returnOnWaitState);
  7401. }
  7402. extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout, bool returnOnWaitState)
  7403. {
  7404. if (checkWuSecAccess(wuid, secmgr, &secuser, SecAccess_Read, "Wait for Complete", false, true))
  7405. return waitForWorkUnitToComplete(wuid, timeout, returnOnWaitState);
  7406. return WUStateUnknown;
  7407. }
  7408. extern bool waitForWorkUnitToCompile(const char * wuid, int timeout)
  7409. {
  7410. switch(_waitForWorkUnit(wuid, (unsigned)timeout, true, true))
  7411. {
  7412. case WUStateCompiled:
  7413. case WUStateCompleted:
  7414. case WUStateWait:
  7415. case WUStateUploadingFiles:
  7416. return true;
  7417. default:
  7418. return false;
  7419. }
  7420. }
  7421. extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout)
  7422. {
  7423. if (checkWuSecAccess(wuid, secmgr, &secuser, SecAccess_Read, "Wait for Compile", false, true))
  7424. return waitForWorkUnitToCompile(wuid, timeout);
  7425. return false;
  7426. }
  7427. extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response)
  7428. {
  7429. if (strnicmp(command, "<debug:", 7) == 0 && checkWuSecAccess(wuid, secmgr, &secuser, SecAccess_Read, "Debug", false, true))
  7430. {
  7431. Owned<IConstWorkUnit> wu = factory->secOpenWorkUnit(wuid, false, &secmgr, &secuser);
  7432. SCMStringBuffer ip;
  7433. unsigned port;
  7434. port = wu->getDebugAgentListenerPort();
  7435. wu->getDebugAgentListenerIP(ip);
  7436. SocketEndpoint debugEP(ip.str(), port);
  7437. Owned<ISocket> socket = ISocket::connect_timeout(debugEP, 1000);
  7438. unsigned len = (size32_t)strlen(command);
  7439. unsigned revlen = len;
  7440. _WINREV(revlen);
  7441. socket->write(&revlen, sizeof(revlen));
  7442. socket->write(command, len);
  7443. for (;;)
  7444. {
  7445. socket->read(&len, sizeof(len));
  7446. _WINREV(len);
  7447. if (len == 0)
  7448. break;
  7449. if (len & 0x80000000)
  7450. {
  7451. throwUnexpected();
  7452. }
  7453. char * mem = (char*) response.reserve(len);
  7454. socket->read(mem, len);
  7455. }
  7456. return true;
  7457. }
  7458. return false;
  7459. }
  7460. IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence)
  7461. {
  7462. switch ((int)sequence)
  7463. {
  7464. case ResultSequenceStored:
  7465. return w->updateVariableByName(name);
  7466. case ResultSequencePersist:
  7467. return w->updateGlobalByName(name);
  7468. case ResultSequenceInternal:
  7469. case ResultSequenceOnce:
  7470. return w->updateTemporaryByName(name);
  7471. default:
  7472. return w->updateResultBySequence(sequence);
  7473. }
  7474. }
  7475. IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence)
  7476. {
  7477. switch ((int)sequence)
  7478. {
  7479. case ResultSequenceStored:
  7480. return w->getVariableByName(name);
  7481. case ResultSequencePersist:
  7482. return w->getGlobalByName(name);
  7483. case ResultSequenceInternal:
  7484. case ResultSequenceOnce:
  7485. return w->getTemporaryByName(name);
  7486. default:
  7487. if (name && name[0])
  7488. return w->getResultByName(name);//name takes precedence over sequence
  7489. else
  7490. return w->getResultBySequence(sequence);
  7491. }
  7492. }
  7493. extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time)
  7494. {
  7495. if (wuid) {
  7496. char prefchar;
  7497. unsigned year,month,day,hour,min,sec;
  7498. if (sscanf(wuid, "%c%4u%2u%2u-%2u%2u%2u", &prefchar, &year, &month, &day, &hour, &min, &sec)==7) {
  7499. time.set(year, month, day, hour, min, sec, 0, true);
  7500. // time.setDate(year, month, day);
  7501. // time.setTime(hour, min, sec, 0, true); // for some reason time is local
  7502. return true;
  7503. }
  7504. }
  7505. return false;
  7506. }
  7507. extern WORKUNIT_API IStringVal& createToken(const char *wuid, const char *user, const char *password, IStringVal &str)
  7508. {
  7509. StringBuffer wu, token("X");
  7510. wu.append(wuid).append(';').append(user).append(';').append(password);
  7511. encrypt(token,wu.str());
  7512. str.set(token.str());
  7513. return str;
  7514. }
  7515. // This will be replaced by something more secure!
  7516. extern WORKUNIT_API void extractToken(const char *token, const char *wuid, IStringVal &user, IStringVal &password)
  7517. {
  7518. if (token && *token)
  7519. {
  7520. StringBuffer wu;
  7521. decrypt(wu, token+1);
  7522. const char *finger = strchr(wu.str(),';');
  7523. if (finger && strnicmp(wuid, wu.str(), finger-wu.str())==0)
  7524. {
  7525. const char *finger1 = strchr(++finger,';');
  7526. if(finger1)
  7527. {
  7528. user.setLen(finger, (size32_t)(finger1-finger));
  7529. password.setLen(++finger1, (size32_t)(wu.str() + wu.length() - finger1));
  7530. return;
  7531. }
  7532. }
  7533. throw MakeStringException(WUERR_InvalidSecurityToken, "Invalid call to extractToken");
  7534. }
  7535. }
  7536. extern WORKUNIT_API WUState getWorkUnitState(const char* state)
  7537. {
  7538. return (WUState) getEnum(state, states);
  7539. }
  7540. const LogMsgCategory MCschedconn = MCprogress(1000); // Category used to inform about schedule synchronization
  7541. class CWorkflowScheduleConnection : public CInterface, implements IWorkflowScheduleConnection
  7542. {
  7543. public:
  7544. CWorkflowScheduleConnection(char const * wuid)
  7545. {
  7546. basexpath.append("/WorkflowSchedule/").append(wuid);
  7547. flagxpath.append(basexpath.str()).append("/Active");
  7548. }
  7549. IMPLEMENT_IINTERFACE;
  7550. virtual void lock()
  7551. {
  7552. LOG(MCschedconn, "Locking base schedule connection");
  7553. baseconn.setown(querySDS().connect(basexpath.str(), myProcessSession(), RTM_CREATE_QUERY | RTM_LOCK_WRITE, INFINITE));
  7554. if(!baseconn)
  7555. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get base workflow schedule lock");
  7556. }
  7557. virtual void unlock()
  7558. {
  7559. LOG(MCschedconn, "Unlocking base schedule connection");
  7560. baseconn.clear();
  7561. }
  7562. virtual void setActive()
  7563. {
  7564. LOG(MCschedconn, "Setting active flag in schedule connection");
  7565. flagconn.setown(querySDS().connect(flagxpath.str(), myProcessSession(), RTM_CREATE | RTM_LOCK_WRITE | RTM_DELETE_ON_DISCONNECT, INFINITE));
  7566. if(!flagconn)
  7567. throw MakeStringException(WUERR_ScheduleLockFailed, "Could not get active workflow schedule lock");
  7568. }
  7569. virtual void resetActive()
  7570. {
  7571. LOG(MCschedconn, "Resetting active flag in schedule connection");
  7572. flagconn.clear();
  7573. }
  7574. virtual bool queryActive()
  7575. {
  7576. return baseconn->queryRoot()->hasProp("Active");
  7577. }
  7578. virtual bool pull(IWorkflowItemArray * workflow)
  7579. {
  7580. assertex(baseconn);
  7581. Owned<IPropertyTree> root = baseconn->getRoot();
  7582. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  7583. if(!eventQueue) return false;
  7584. if(!eventQueue->hasProp("Item")) return false;
  7585. {
  7586. Owned<IPropertyTreeIterator> eventItems = eventQueue->getElements("Item");
  7587. Owned<IPropertyTree> eventItem;
  7588. Owned<IRuntimeWorkflowItemIterator> wfItems = workflow->getSequenceIterator();
  7589. Owned<IRuntimeWorkflowItem> wfItem;
  7590. for(eventItems->first(); eventItems->isValid(); eventItems->next())
  7591. {
  7592. eventItem.setown(&eventItems->get());
  7593. const char * eventName = eventItem->queryProp("@name");
  7594. const char * eventText = eventItem->queryProp("@text");
  7595. for(wfItems->first(); wfItems->isValid(); wfItems->next())
  7596. {
  7597. wfItem.setown(wfItems->get());
  7598. if(wfItem->queryState() != WFStateWait)
  7599. continue;
  7600. Owned<IWorkflowEvent> targetEvent = wfItem->getScheduleEvent();
  7601. if(!targetEvent || !targetEvent->matches(eventName, eventText))
  7602. continue;
  7603. wfItem->setEvent(eventName, eventText);
  7604. wfItem->setState(WFStateReqd);
  7605. resetDepState(workflow, *wfItem);
  7606. }
  7607. }
  7608. }
  7609. bool more;
  7610. do
  7611. more = eventQueue->removeProp("Item");
  7612. while(more);
  7613. return true;
  7614. }
  7615. virtual void push(char const * name, char const * text)
  7616. {
  7617. assertex(baseconn);
  7618. Owned<IPropertyTree> root = baseconn->getRoot();
  7619. ensurePTree(root, "EventQueue");
  7620. Owned<IPropertyTree> eventQueue = root->getPropTree("EventQueue");
  7621. Owned<IPropertyTree> eventItem = createPTree();
  7622. eventItem->setProp("@name", name);
  7623. eventItem->setProp("@text", text);
  7624. eventQueue->addPropTree("Item", eventItem.getLink());
  7625. }
  7626. private:
  7627. void resetDepState(IWorkflowItemArray * workflow, IRuntimeWorkflowItem & item) const
  7628. {
  7629. Owned<IWorkflowDependencyIterator> iter(item.getDependencies());
  7630. for(iter->first(); iter->isValid(); iter->next())
  7631. {
  7632. IRuntimeWorkflowItem & dep = workflow->queryWfid(iter->query());
  7633. switch(dep.queryState())
  7634. {
  7635. case WFStateDone:
  7636. case WFStateFail:
  7637. dep.setState(WFStateNull);
  7638. resetDepState(workflow, dep);
  7639. break;
  7640. }
  7641. }
  7642. }
  7643. private:
  7644. StringBuffer basexpath;
  7645. StringBuffer flagxpath;
  7646. Owned<IRemoteConnection> baseconn;
  7647. Owned<IRemoteConnection> flagconn;
  7648. };
  7649. extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid)
  7650. {
  7651. return new CWorkflowScheduleConnection(wuid);
  7652. }
  7653. extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IWorkUnit * wu)
  7654. {
  7655. return QUERYINTERFACE(wu, IExtendedWUInterface);
  7656. }
  7657. extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, WUExceptionSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column)
  7658. {
  7659. Owned<IWUException> we = wu->createException();
  7660. we->setSeverity(severity);
  7661. we->setExceptionMessage(text);
  7662. if (source)
  7663. we->setExceptionSource(source);
  7664. if (code)
  7665. we->setExceptionCode(code);
  7666. if (filename)
  7667. we->setExceptionFileName(filename);
  7668. if (lineno)
  7669. {
  7670. we->setExceptionLineNo(lineno);
  7671. if (column)
  7672. we->setExceptionColumn(lineno);
  7673. }
  7674. }
  7675. #define UTF8_BOM "\357\273\277"
  7676. extern WORKUNIT_API bool isArchiveQuery(const char * text)
  7677. {
  7678. if (!text)
  7679. return false;
  7680. //skip utf8 BOM, probably excessive
  7681. if (memcmp(text, UTF8_BOM, 3) == 0)
  7682. text += 3;
  7683. loop
  7684. {
  7685. if (isspace(*text))
  7686. text++;
  7687. else if (text[0] == '<' && text[1] == '!' && text[2] == '-' && text[3] == '-')
  7688. {
  7689. text += 4;
  7690. loop
  7691. {
  7692. if (!*text) break;
  7693. if (text[0] == '-' && text[1] == '-' && text[2] == '>')
  7694. {
  7695. text += 3;
  7696. break;
  7697. }
  7698. text++;
  7699. }
  7700. }
  7701. else
  7702. break;
  7703. }
  7704. const char * archivePrefix = "<Archive";
  7705. return memicmp(text, archivePrefix, strlen(archivePrefix)) == 0;
  7706. }
  7707. //------------------------------------------------------------------------------
  7708. // Named Alias helper function
  7709. static IPropertyTree * resolveQueryByDll(IPropertyTree * queryRegistry, const char * dll)
  7710. {
  7711. StringBuffer xpath;
  7712. xpath.append("Query[@dll=\"").append(dll).append("\"]");
  7713. return queryRegistry->getPropTree(xpath);
  7714. }
  7715. static IPropertyTree * resolveQueryByWuid(IPropertyTree * queryRegistry, const char * wuid)
  7716. {
  7717. StringBuffer xpath;
  7718. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  7719. return queryRegistry->getPropTree(xpath);
  7720. }
  7721. static void clearAliases(IPropertyTree * queryRegistry, const char * id)
  7722. {
  7723. StringBuffer lcId(id);
  7724. lcId.toLowerCase();
  7725. StringBuffer xpath;
  7726. xpath.append("Alias[@id=\"").append(lcId).append("\"]");
  7727. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  7728. ForEach(*iter)
  7729. {
  7730. queryRegistry->removeProp(xpath.str());
  7731. }
  7732. }
  7733. IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll)
  7734. {
  7735. StringBuffer xpath;
  7736. xpath.append("Query[@wuid=\"").append(wuid).append("\"]");
  7737. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  7738. if (q)
  7739. return q;
  7740. StringBuffer lcName(name);
  7741. lcName.toLowerCase();
  7742. xpath.clear();
  7743. xpath.append("Query[@name=\"").append(lcName.str()).append("\"]");
  7744. Owned<IPropertyTreeIterator> iter = queryRegistry->getElements(xpath);
  7745. unsigned seq = 1;
  7746. ForEach(*iter)
  7747. {
  7748. unsigned thisSeq = iter->query().getPropInt("@seq");
  7749. if (thisSeq >= seq)
  7750. seq = thisSeq + 1;
  7751. }
  7752. StringBuffer id;
  7753. id.append(lcName).append(".").append(seq);
  7754. IPropertyTree * newEntry = createPTree("Query", ipt_caseInsensitive);
  7755. newEntry->setProp("@name", lcName);
  7756. newEntry->setProp("@wuid", wuid);
  7757. newEntry->setProp("@dll", dll);
  7758. newEntry->setProp("@id", id);
  7759. newEntry->setPropInt("@seq", seq);
  7760. return queryRegistry->addPropTree("Query", newEntry);
  7761. }
  7762. void removeNamedQuery(IPropertyTree * queryRegistry, const char * id)
  7763. {
  7764. StringBuffer lcId(id);
  7765. lcId.toLowerCase();
  7766. clearAliases(queryRegistry, lcId);
  7767. StringBuffer xpath;
  7768. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  7769. queryRegistry->removeProp(xpath);
  7770. }
  7771. void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll)
  7772. {
  7773. Owned<IPropertyTree> match = resolveQueryByDll(queryRegistry, dll);
  7774. if (!match)
  7775. return;
  7776. clearAliases(queryRegistry, match->queryProp("@id"));
  7777. queryRegistry->removeTree(match);
  7778. }
  7779. void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid)
  7780. {
  7781. Owned<IPropertyTree> match = resolveQueryByWuid(queryRegistry, wuid);
  7782. if (!match)
  7783. return;
  7784. clearAliases(queryRegistry, match->queryProp("@id"));
  7785. queryRegistry->removeTree(match);
  7786. }
  7787. void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id)
  7788. {
  7789. clearAliases(queryRegistry, id);
  7790. }
  7791. void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value)
  7792. {
  7793. StringBuffer lcName(name);
  7794. lcName.toLowerCase();
  7795. StringBuffer xpath;
  7796. xpath.append("Alias[@name=\"").append(lcName).append("\"]");
  7797. IPropertyTree * match = queryRegistry->queryPropTree(xpath);
  7798. if (!match)
  7799. {
  7800. IPropertyTree * newEntry = createPTree("Alias");
  7801. newEntry->setProp("@name", lcName);
  7802. match = queryRegistry->addPropTree("Alias", newEntry);
  7803. }
  7804. match->setProp("@id", value);
  7805. }
  7806. IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias)
  7807. {
  7808. StringBuffer xpath;
  7809. unsigned cnt = 0;
  7810. const char * search = alias;
  7811. loop
  7812. {
  7813. xpath.clear().append("Alias[@name=\"").append(search).append("\"]/@id");
  7814. const char * queryId = queryRegistry->queryProp(xpath);
  7815. if (!queryId)
  7816. break;
  7817. //Check for too many alias indirections.
  7818. if (cnt++ > 10)
  7819. return NULL;
  7820. search = queryId;
  7821. }
  7822. xpath.clear().append("Query[@id=\"").append(search).append("\"]");
  7823. return queryRegistry->getPropTree(xpath);
  7824. }
  7825. void setQuerySuspendedState(IPropertyTree * queryRegistry, const char *id, bool suspend)
  7826. {
  7827. StringBuffer lcId(id);
  7828. lcId.toLowerCase();
  7829. StringBuffer xpath;
  7830. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  7831. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  7832. if (tree)
  7833. {
  7834. if (suspend)
  7835. tree->addPropBool("@suspended", true);
  7836. else
  7837. tree->removeProp("@suspended");
  7838. }
  7839. else
  7840. throw MakeStringException((suspend)? QUERRREG_SUSPEND : QUERRREG_UNSUSPEND, "Modifying query suspended state failed. Could not find query %s", id);
  7841. }
  7842. void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment)
  7843. {
  7844. if (queryComment)
  7845. {
  7846. StringBuffer lcId(id);
  7847. lcId.toLowerCase();
  7848. StringBuffer xpath;
  7849. xpath.append("Query[@id=\"").append(lcId).append("\"]");
  7850. IPropertyTree *tree = queryRegistry->queryPropTree(xpath);
  7851. if (tree)
  7852. tree->setProp("@queryComment", queryComment);
  7853. else
  7854. throw MakeStringException(QUERRREG_COMMENT, "Could not find query %s", id);
  7855. }
  7856. }
  7857. extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot()
  7858. {
  7859. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  7860. if (!globalLock)
  7861. return NULL;
  7862. //Only lock the branch for the target we're interested in.
  7863. StringBuffer xpath;
  7864. xpath.append("/QuerySets");
  7865. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_READ, SDS_LOCK_TIMEOUT);
  7866. if (conn)
  7867. return conn->getRoot();
  7868. else
  7869. return NULL;
  7870. }
  7871. extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly)
  7872. {
  7873. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  7874. //Only lock the branch for the target we're interested in.
  7875. StringBuffer xpath;
  7876. xpath.append("/QuerySets/QuerySet[@id=\"").append(wsEclId).append("\"]");
  7877. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  7878. if (!conn)
  7879. {
  7880. if (readonly)
  7881. return NULL;
  7882. Owned<IPropertyTree> querySet = createPTree();
  7883. querySet->setProp("@id", wsEclId);
  7884. globalLock->queryRoot()->addPropTree("QuerySet", querySet.getClear());
  7885. globalLock->commit();
  7886. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  7887. if (!conn)
  7888. throwUnexpected();
  7889. }
  7890. return conn->getRoot();
  7891. }
  7892. IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite)
  7893. {
  7894. StringBuffer xpath;
  7895. StringBuffer lcName(name);
  7896. lcName.toLowerCase();
  7897. // see if "name" already exists
  7898. xpath.append("Package[@id='").append(name).append("']");
  7899. IPropertyTree *pkgTree = packageRegistry->queryPropTree(xpath.str());
  7900. if (pkgTree)
  7901. {
  7902. if (overWrite)
  7903. packageRegistry->removeTree(pkgTree);
  7904. else
  7905. throw MakeStringException(WUERR_PackageAlreadyExists, "Package name %s already exists, either delete it or specify overwrite",name);
  7906. }
  7907. IPropertyTree *tree = packageRegistry->addPropTree("Package", packageInfo);
  7908. tree->setProp("@id", lcName);
  7909. return tree;
  7910. }
  7911. void removeNamedPackage(IPropertyTree * packageRegistry, const char * id)
  7912. {
  7913. StringBuffer lcId(id);
  7914. lcId.toLowerCase();
  7915. StringBuffer xpath;
  7916. xpath.append("Package[@id=\"").append(lcId).append("\"]");
  7917. packageRegistry->removeProp(xpath);
  7918. }
  7919. extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly)
  7920. {
  7921. Owned<IRemoteConnection> globalLock = querySDS().connect("/PackageSets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  7922. //Only lock the branch for the target we're interested in.
  7923. StringBuffer xpath;
  7924. xpath.append("/PackageSets/PackageSet[@id=\"").append(wsEclId).append("\"]");
  7925. Owned<IRemoteConnection> conn = querySDS().connect(xpath.str(), myProcessSession(), readonly ? RTM_LOCK_READ : RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT);
  7926. if (!conn)
  7927. {
  7928. if (readonly)
  7929. return NULL;
  7930. Owned<IPropertyTree> querySet = createPTree();
  7931. querySet->setProp("@id", wsEclId);
  7932. globalLock->queryRoot()->addPropTree("PackageSet", querySet.getClear());
  7933. globalLock->commit();
  7934. conn.setown(querySDS().connect(xpath.str(), myProcessSession(), RTM_LOCK_WRITE, SDS_LOCK_TIMEOUT));
  7935. if (!conn)
  7936. throwUnexpected();
  7937. }
  7938. return conn->getRoot();
  7939. }
  7940. void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, IPropertyTree *packageInfo, WUQueryActivationOptions activateOption, StringBuffer &newQueryId)
  7941. {
  7942. StringBuffer cleanQueryName(queryName);
  7943. cleanQueryName.replace(' ', '_');
  7944. SCMStringBuffer dllName;
  7945. Owned<IConstWUQuery> q = workunit->getQuery();
  7946. q->getQueryDllName(dllName);
  7947. SCMStringBuffer wuid;
  7948. workunit->getWuid(wuid);
  7949. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  7950. StringBuffer currentTargetClusterType;
  7951. queryRegistry->getProp("@targetclustertype", currentTargetClusterType);
  7952. SCMStringBuffer targetClusterType;
  7953. workunit->getDebugValue("targetclustertype", targetClusterType);
  7954. if (currentTargetClusterType.length() < 1)
  7955. {
  7956. queryRegistry->setProp("@targetclustertype", targetClusterType.str());
  7957. }
  7958. else
  7959. {
  7960. if (strcmp(currentTargetClusterType.str(), "roxie") == 0 && strcmp(currentTargetClusterType.str(), targetClusterType.str())!=0)
  7961. {
  7962. throw MakeStringException(WUERR_MismatchClusterType, "TargetClusterTypes of workunit and queryset do not match.");
  7963. }
  7964. }
  7965. IPropertyTree *newEntry = addNamedQuery(queryRegistry, cleanQueryName, wuid.str(), dllName.str());
  7966. newQueryId.append(newEntry->queryProp("@id"));
  7967. workunit->setDebugValue("queryId", newQueryId.str(), true);
  7968. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS|| activateOption == ACTIVATE_DELETE_PREVIOUS)
  7969. {
  7970. Owned<IPropertyTree> aliasTree = resolveQueryAlias(queryRegistry, cleanQueryName);
  7971. setQueryAlias(queryRegistry, cleanQueryName, newQueryId);
  7972. if (aliasTree)
  7973. {
  7974. if (activateOption == ACTIVATE_SUSPEND_PREVIOUS)
  7975. setQuerySuspendedState(queryRegistry, cleanQueryName, true);
  7976. else
  7977. removeNamedQuery(queryRegistry, aliasTree->queryProp("@id"));
  7978. }
  7979. }
  7980. else if (activateOption == MAKE_ACTIVATE || activateOption == MAKE_ACTIVATE_LOAD_DATA_ONLY)
  7981. setQueryAlias(queryRegistry, cleanQueryName, newQueryId.str());
  7982. }
  7983. bool removeQuerySetAlias(const char *querySetName, const char *alias)
  7984. {
  7985. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  7986. StringBuffer xpath;
  7987. xpath.appendf("Alias[@name='%s']", alias);
  7988. IPropertyTree *t = queryRegistry->queryPropTree(xpath);
  7989. return queryRegistry->removeTree(t);
  7990. }
  7991. void addQuerySetAlias(const char *querySetName, const char *alias, const char *id)
  7992. {
  7993. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  7994. setQueryAlias(queryRegistry, alias, id);
  7995. }
  7996. void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend)
  7997. {
  7998. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  7999. setQuerySuspendedState(queryRegistry, id, suspend);
  8000. }
  8001. void deleteQuerySetQuery(const char *querySetName, const char *id)
  8002. {
  8003. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  8004. removeNamedQuery(queryRegistry, id);
  8005. }
  8006. void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id)
  8007. {
  8008. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  8009. clearAliases(queryRegistry, id);
  8010. }
  8011. void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *queryComment)
  8012. {
  8013. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, true);
  8014. setQueryCommentForNamedQuery(queryRegistry, id, queryComment);
  8015. }
  8016. const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, IStringVal &id)
  8017. {
  8018. Owned<IPropertyTree> queryRegistry = getQueryRegistry(querySetName, false);
  8019. StringBuffer xpath;
  8020. xpath.appendf("Query[@wuid='%s']", wuid);
  8021. IPropertyTree *q = queryRegistry->queryPropTree(xpath.str());
  8022. if (q)
  8023. {
  8024. id.set(q->queryProp("@id"));
  8025. }
  8026. return id.str();
  8027. }
  8028. bool looksLikeAWuid(const char * wuid)
  8029. {
  8030. if (!wuid)
  8031. return false;
  8032. if (wuid[0] != 'W')
  8033. return false;
  8034. if (!isdigit(wuid[1]) || !isdigit(wuid[2]) || !isdigit(wuid[3]) || !isdigit(wuid[4]))
  8035. return false;
  8036. if (!isdigit(wuid[5]) || !isdigit(wuid[6]) || !isdigit(wuid[7]) || !isdigit(wuid[8]))
  8037. return false;
  8038. return (wuid[9]=='-');
  8039. }
  8040. IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path)
  8041. {
  8042. IPropertyTree * module = archive;
  8043. const char * dot = strrchr(path, '.');
  8044. StringBuffer xpath;
  8045. if (dot)
  8046. {
  8047. xpath.clear().append("Module[@key='").appendLower(dot-path, path).append("']");
  8048. module = archive->queryPropTree(xpath);
  8049. path = dot+1;
  8050. }
  8051. else
  8052. module = archive->queryPropTree("Module[@key='']");
  8053. if (!module)
  8054. return NULL;
  8055. xpath.clear().append("Attribute[@key='").appendLower(strlen(path), path).append("']");
  8056. return module->queryPropTree(xpath);
  8057. }
  8058. extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc)
  8059. {
  8060. StringBuffer hostname;
  8061. queryHostIP().getIpText(hostname);
  8062. StringBuffer fullPathname;
  8063. makeAbsolutePath(name, fullPathname);
  8064. query->addAssociatedFile(type, fullPathname, hostname, description, crc);
  8065. }