workunit.cpp 335 KB

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