workunit.cpp 300 KB

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