workunit.cpp 290 KB

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