workunit.cpp 289 KB

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