workunit.cpp 308 KB

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