workunit.cpp 336 KB

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