workunit.cpp 330 KB

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