workunit.cpp 289 KB

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