workunit.cpp 297 KB

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