workunit.cpp 324 KB

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