ws_workunitsService.cpp 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388
  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 "ws_workunitsService.hpp"
  14. #include "ws_fs.hpp"
  15. #include "jlib.hpp"
  16. #include "jflz.hpp"
  17. #include "daclient.hpp"
  18. #include "dalienv.hpp"
  19. #include "dadfs.hpp"
  20. #include "daaudit.hpp"
  21. #include "dautils.hpp"
  22. #include "exception_util.hpp"
  23. #include "wujobq.hpp"
  24. #include "eventqueue.hpp"
  25. #include "fileview.hpp"
  26. #include "hqlerror.hpp"
  27. #include "sacmd.hpp"
  28. #include "wuwebview.hpp"
  29. #include "portlist.h"
  30. #include "dllserver.hpp"
  31. #include "schedulectrl.hpp"
  32. #include "scheduleread.hpp"
  33. #include "dadfs.hpp"
  34. #include "dfuwu.hpp"
  35. #include "thorplugin.hpp"
  36. #include "roxiecontrol.hpp"
  37. #include "deftype.hpp"
  38. #include "thorxmlwrite.hpp"
  39. #include "fvdatasource.hpp"
  40. #include "fvresultset.ipp"
  41. #include "ws_wudetails.hpp"
  42. #include "rtlformat.hpp"
  43. #include "package.h"
  44. #ifdef _USE_ZLIB
  45. #include "zcrypt.hpp"
  46. #endif
  47. #define ESP_WORKUNIT_DIR "workunits/"
  48. const char* zipFolder = "tempzipfiles" PATHSEPSTR;
  49. #define SDS_LOCK_TIMEOUT (5*60*1000) // 5 mins
  50. const unsigned CHECK_QUERY_STATUS_THREAD_POOL_SIZE = 25;
  51. class ExecuteExistingQueryInfo
  52. {
  53. public:
  54. ExecuteExistingQueryInfo(IConstWorkUnit *cw)
  55. {
  56. const char *name = cw->queryJobName();
  57. const char *div = strchr(name, '.');
  58. if (div)
  59. {
  60. queryset.set(name, div-name);
  61. query.set(div+1);
  62. }
  63. }
  64. public:
  65. StringAttr queryset;
  66. StringAttr query;
  67. };
  68. //The ECLWUActionNames[] has to match with the ESPenum ECLWUActions in the ecm file.
  69. static unsigned NumOfECLWUActionNames = 11;
  70. static const char *ECLWUActionNames[] = { "Abort", "Delete", "Deschedule", "Reschedule", "Pause",
  71. "PauseNow", "Protect", "Unprotect", "Restore", "Resume", "SetToFailed", NULL };
  72. class CECLWUActionsEx : public SoapEnumParamNew<CECLWUActions>
  73. {
  74. public:
  75. CECLWUActionsEx() : SoapEnumParamNew<CECLWUActions>() { init("ECLWUActions","string", ECLWUActionNames); }
  76. };
  77. static CECLWUActionsEx eclWUActionType;
  78. void setActionResult(const char* wuid, CECLWUActions action, const char* result, const char* strAction, IArrayOf<IConstWUActionResult>* results)
  79. {
  80. if (!results || !wuid || !*wuid || !result || !*result)
  81. return;
  82. Owned<IEspWUActionResult> res = createWUActionResult("", "");
  83. res->setWuid(wuid);
  84. res->setAction(strAction);
  85. res->setResult(result);
  86. results->append(*res.getClear());
  87. }
  88. bool doAction(IEspContext& context, StringArray& wuids, CECLWUActions action, IProperties* params, IArrayOf<IConstWUActionResult>* results)
  89. {
  90. if (!wuids.length())
  91. return true;
  92. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  93. bool bAllSuccess = true;
  94. const char* strAction = (action < NumOfECLWUActionNames) ? ECLWUActionNames[action] : "Unknown Action";
  95. for(aindex_t i=0; i<wuids.length();i++)
  96. {
  97. StringBuffer wuidStr = wuids.item(i);
  98. const char* wuid = wuidStr.trim().str();
  99. if (isEmpty(wuid))
  100. {
  101. WARNLOG("Empty Workunit ID");
  102. continue;
  103. }
  104. try
  105. {
  106. if (!looksLikeAWuid(wuid, 'W'))
  107. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  108. PROGLOG("%s %s", strAction, wuid);
  109. if ((action == CECLWUActions_Restore) || (action == CECLWUActions_EventDeschedule))
  110. {
  111. switch(action)
  112. {
  113. case CECLWUActions_Restore:
  114. {
  115. SocketEndpoint ep;
  116. if (params->hasProp("sashaServerIP"))
  117. ep.set(params->queryProp("sashaServerIP"), params->getPropInt("sashaServerPort"));
  118. else
  119. getSashaNode(ep);
  120. Owned<ISashaCommand> cmd = createSashaCommand();
  121. cmd->setAction(SCA_RESTORE);
  122. cmd->addId(wuid);
  123. Owned<INode> node = createINode(ep);
  124. if (!node)
  125. throw MakeStringException(ECLWATCH_INODE_NOT_FOUND,"INode not found.");
  126. StringBuffer s;
  127. if (!cmd->send(node, 1*60*1000))
  128. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to Archive server at %s.", ep.getUrlStr(s).str());
  129. if (cmd->numIds()==0)
  130. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Could not Archive/restore %s",wuid);
  131. StringBuffer reply;
  132. cmd->getId(0,reply);
  133. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  134. ensureWsWorkunitAccess(context, wuid, SecAccess_Write);
  135. break;
  136. }
  137. case CECLWUActions_EventDeschedule:
  138. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Full, false)
  139. || !context.validateFeatureAccess(OTHERS_WU_ACCESS, SecAccess_Full, false))
  140. ensureWsWorkunitAccess(context, wuid, SecAccess_Full);
  141. descheduleWorkunit(wuid);
  142. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  143. break;
  144. }
  145. }
  146. else
  147. {
  148. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  149. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  150. if(!cw)
  151. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  152. if ((action == CECLWUActions_Delete) && (cw->getState() == WUStateWait))
  153. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Cannot delete a workunit which is in a 'Wait' status.");
  154. switch(action)
  155. {
  156. case CECLWUActions_Pause:
  157. {
  158. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  159. WorkunitUpdate wu(&cw->lock());
  160. wu->setAction(WUActionPause);
  161. break;
  162. }
  163. case CECLWUActions_PauseNow:
  164. {
  165. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  166. WorkunitUpdate wu(&cw->lock());
  167. wu->setAction(WUActionPauseNow);
  168. break;
  169. }
  170. case CECLWUActions_Resume:
  171. {
  172. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  173. WorkunitUpdate wu(&cw->lock());
  174. wu->setAction(WUActionResume);
  175. break;
  176. }
  177. case CECLWUActions_Delete:
  178. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  179. {
  180. cw.clear();
  181. if (!factory->deleteWorkUnit(wuid))
  182. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid);
  183. AuditSystemAccess(context.queryUserId(), true, "Deleted %s", wuid);
  184. }
  185. break;
  186. case CECLWUActions_Abort:
  187. ensureWsWorkunitAccess(context, *cw, SecAccess_Full);
  188. {
  189. if (cw->getState() == WUStateWait)
  190. {
  191. WorkunitUpdate wu(&cw->lock());
  192. wu->deschedule();
  193. wu->setState(WUStateAborted);
  194. }
  195. else
  196. abortWorkUnit(wuid, context.querySecManager(), context.queryUser());
  197. AuditSystemAccess(context.queryUserId(), true, "Aborted %s", wuid);
  198. }
  199. break;
  200. case CECLWUActions_Protect:
  201. case CECLWUActions_Unprotect:
  202. cw->protect((action == CECLWUActions_Protect) ? true:false);
  203. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  204. break;
  205. case CECLWUActions_SetToFailed:
  206. {
  207. WorkunitUpdate wu(&cw->lock());
  208. wu->setState(WUStateFailed);
  209. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  210. }
  211. break;
  212. case CECLWUActions_EventReschedule:
  213. {
  214. WorkunitUpdate wu(&cw->lock());
  215. wu->schedule();
  216. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid);
  217. }
  218. break;
  219. }
  220. }
  221. PROGLOG("%s %s done", strAction, wuid);
  222. setActionResult(wuid, action, "Success", strAction, results);
  223. }
  224. catch (IException *e)
  225. {
  226. bAllSuccess = false;
  227. StringBuffer eMsg;
  228. StringBuffer failedMsg("Failed: ");
  229. setActionResult(wuid, action, failedMsg.append(e->errorMessage(eMsg)).str(), strAction, results);
  230. WARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, eMsg.str());
  231. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  232. e->Release();
  233. continue;
  234. }
  235. catch (...)
  236. {
  237. bAllSuccess = false;
  238. StringBuffer failedMsg;
  239. failedMsg.appendf("Unknown exception");
  240. setActionResult(wuid, action, failedMsg.str(), strAction, results);
  241. WARNLOG("Failed to %s for workunit: %s, %s", strAction, wuid, failedMsg.str());
  242. AuditSystemAccess(context.queryUserId(), false, "Failed to %s %s", strAction, wuid);
  243. continue;
  244. }
  245. }
  246. int timeToWait = 0;
  247. if (params)
  248. timeToWait = params->getPropInt("BlockTillFinishTimer");
  249. if (timeToWait != 0)
  250. {
  251. for(aindex_t i=0; i<wuids.length();i++)
  252. {
  253. const char* wuid=wuids.item(i);
  254. if (isEmpty(wuid))
  255. continue;
  256. waitForWorkUnitToComplete(wuid, timeToWait);
  257. }
  258. }
  259. return bAllSuccess;
  260. }
  261. bool doProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  262. {
  263. Owned<IProperties> params(createProperties(true));
  264. params->setProp("BlockTillFinishTimer", 0);
  265. return doAction(context, wuids, CECLWUActions_Protect, params, results);
  266. }
  267. bool doUnProtectWorkunits(IEspContext& context, StringArray& wuids, IArrayOf<IConstWUActionResult>* results)
  268. {
  269. Owned<IProperties> params(createProperties(true));
  270. params->setProp("BlockTillFinishTimer", 0);
  271. return doAction(context, wuids, CECLWUActions_Unprotect, params, results);
  272. }
  273. static void checkUpdateQuerysetLibraries()
  274. {
  275. Owned<IRemoteConnection> globalLock = querySDS().connect("/QuerySets/", myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SDS_LOCK_TIMEOUT);
  276. if (!globalLock)
  277. return;
  278. IPropertyTree *root = globalLock->queryRoot();
  279. if (!root)
  280. return;
  281. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  282. Owned<IPropertyTreeIterator> querySets = root->getElements("QuerySet");
  283. ForEach(*querySets)
  284. {
  285. IPropertyTree &querySet = querySets->query();
  286. if (querySet.hasProp("@updatedLibraries")) //only need to do this once, then publish and copy will keep up to date
  287. continue;
  288. Owned<IPropertyTreeIterator> queries = querySet.getElements("Query");
  289. ForEach(*queries)
  290. {
  291. IPropertyTree &query = queries->query();
  292. if (query.hasProp("@libCount"))
  293. continue;
  294. const char *wuid = query.queryProp("@wuid");
  295. if (!wuid || !*wuid)
  296. continue;
  297. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  298. if (!cw)
  299. continue;
  300. checkAddLibrariesToQueryEntry(&query, cw);
  301. }
  302. querySet.setPropBool("@updatedLibraries", true);
  303. }
  304. }
  305. void CWsWorkunitsEx::init(IPropertyTree *cfg, const char *process, const char *service)
  306. {
  307. if (!daliClientActive())
  308. {
  309. ERRLOG("No Dali Connection Active.");
  310. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  311. }
  312. setPasswordsFromSDS();
  313. DBGLOG("Initializing %s service [process = %s]", service, process);
  314. checkUpdateQuerysetLibraries();
  315. refreshValidClusters();
  316. daliServers.set(cfg->queryProp("Software/EspProcess/@daliServers"));
  317. const char *computer = cfg->queryProp("Software/EspProcess/@computer");
  318. if (daliServers.isEmpty() || !computer || streq(computer, "localhost")) //otherwise can't assume environment "." netAddresses are the same as my address
  319. queryHostIP().getIpText(envLocalAddress);
  320. else
  321. {
  322. //a bit weird, but other netAddresses in the environment are not the same localhost as this server
  323. //use the address of the DALI
  324. const char *finger = daliServers.get();
  325. while (*finger && !strchr(":;,", *finger))
  326. envLocalAddress.append(*finger++);
  327. }
  328. awusCacheMinutes = AWUS_CACHE_MIN_DEFAULT;
  329. VStringBuffer xpath("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/AWUsCacheMinutes", process, service);
  330. cfg->getPropInt(xpath.str(), awusCacheMinutes);
  331. xpath.setf("Software/EspProcess[@name=\"%s\"]/@PageCacheTimeoutSeconds", process);
  332. if (cfg->hasProp(xpath.str()))
  333. setPageCacheTimeoutMilliSeconds(cfg->getPropInt(xpath.str()));
  334. xpath.setf("Software/EspProcess[@name=\"%s\"]/@MaxPageCacheItems", process);
  335. if (cfg->hasProp(xpath.str()))
  336. setMaxPageCacheItems(cfg->getPropInt(xpath.str()));
  337. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@netAddress", process, service);
  338. if (cfg->hasProp(xpath.str()))
  339. {
  340. sashaServerIp.set(cfg->queryProp(xpath.str()));
  341. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/serverForArchivedECLWU/@port", process, service);
  342. sashaServerPort = cfg->getPropInt(xpath.str(), DEFAULT_SASHA_PORT);
  343. }
  344. maxRequestEntityLength = cfg->getPropInt("Software[1]/EspProcess[1]/EspProtocol[@type='http_protocol'][1]/@maxRequestEntityLength");
  345. directories.set(cfg->queryPropTree("Software/Directories"));
  346. const char *name = cfg->queryProp("Software/EspProcess/@name");
  347. getConfigurationDirectory(directories, "query", "esp", name ? name : "esp", queryDirectory);
  348. recursiveCreateDirectory(queryDirectory.str());
  349. dataCache.setown(new DataCache(DATA_SIZE));
  350. archivedWuCache.setown(new ArchivedWuCache(AWUS_CACHE_SIZE));
  351. wuArchiveCache.setown(new WUArchiveCache(WUARCHIVE_CACHE_SIZE));
  352. //Create a folder for temporarily holding gzip files by WUResultBin()
  353. Owned<IFile> tmpdir = createIFile(TEMPZIPDIR);
  354. if(!tmpdir->exists())
  355. tmpdir->createDirectory();
  356. recursiveCreateDirectory(ESP_WORKUNIT_DIR);
  357. m_sched.start();
  358. filesInUse.subscribe();
  359. //Start thread pool
  360. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ClusterQueryStateThreadPoolSize", process, service);
  361. Owned<CClusterQueryStateThreadFactory> threadFactory = new CClusterQueryStateThreadFactory();
  362. clusterQueryStatePool.setown(createThreadPool("CheckAndSetClusterQueryState Thread Pool", threadFactory, NULL,
  363. cfg->getPropInt(xpath.str(), CHECK_QUERY_STATUS_THREAD_POOL_SIZE)));
  364. }
  365. void CWsWorkunitsEx::refreshValidClusters()
  366. {
  367. validClusters.kill();
  368. Owned<IStringIterator> it = getTargetClusters(NULL, NULL);
  369. ForEach(*it)
  370. {
  371. SCMStringBuffer s;
  372. IStringVal &val = it->str(s);
  373. bool* found = validClusters.getValue(val.str());
  374. if (!found || !*found)
  375. validClusters.setValue(val.str(), true);
  376. }
  377. }
  378. bool CWsWorkunitsEx::isValidCluster(const char *cluster)
  379. {
  380. if (!cluster || !*cluster)
  381. return false;
  382. CriticalBlock block(crit);
  383. bool* found = validClusters.getValue(cluster);
  384. if (found && *found)
  385. return true;
  386. if (validateTargetClusterName(cluster))
  387. {
  388. refreshValidClusters();
  389. return true;
  390. }
  391. return false;
  392. }
  393. bool CWsWorkunitsEx::onWUCreate(IEspContext &context, IEspWUCreateRequest &req, IEspWUCreateResponse &resp)
  394. {
  395. try
  396. {
  397. NewWsWorkunit wu(context);
  398. resp.updateWorkunit().setWuid(wu->queryWuid());
  399. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wu->queryWuid());
  400. }
  401. catch(IException* e)
  402. {
  403. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  404. }
  405. return true;
  406. }
  407. bool origValueChanged(const char *newValue, const char *origValue, StringBuffer &s, bool nillable)
  408. {
  409. if (!nillable && isEmpty(newValue))
  410. return false;
  411. if(newValue && origValue)
  412. {
  413. if (!streq(origValue, newValue))
  414. {
  415. s.append(newValue).trim();
  416. return true;
  417. }
  418. return false;
  419. }
  420. if (newValue)
  421. {
  422. s.append(newValue).trim();
  423. return true;
  424. }
  425. return (origValue!=NULL);
  426. }
  427. bool CWsWorkunitsEx::onWUUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  428. {
  429. try
  430. {
  431. StringBuffer wuid = req.getWuid();
  432. WsWuHelpers::checkAndTrimWorkunit("WUUpdate", wuid);
  433. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  434. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  435. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  436. if(!cw)
  437. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  438. PROGLOG("WUUpdate: %s", wuid.str());
  439. if(req.getProtected() != req.getProtectedOrig())
  440. {
  441. cw->protect(req.getProtected());
  442. cw.clear();
  443. cw.setown(factory->openWorkUnit(wuid.str()));
  444. if(!cw)
  445. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  446. }
  447. if ((req.getState() == WUStateRunning)||(req.getState() == WUStateDebugPaused)||(req.getState() == WUStateDebugRunning))
  448. {
  449. WsWuInfo winfo(context, cw);
  450. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  451. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  452. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  453. return true;
  454. }
  455. WorkunitUpdate wu(&cw->lock());
  456. if(!req.getState_isNull() && (req.getStateOrig_isNull() || req.getState() != req.getStateOrig()))
  457. {
  458. if (!req.getStateOrig_isNull() && cw->getState() != (WUState) req.getStateOrig())
  459. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update workunit %s because its state has been changed internally. Please refresh the page and try again.", wuid.str());
  460. WUState state = (WUState) req.getState();
  461. if(state < WUStateSize)
  462. wu->setState(state);
  463. }
  464. StringBuffer s;
  465. if (origValueChanged(req.getJobname(), req.getJobnameOrig(), s))
  466. wu->setJobName(s.trim().str());
  467. if (origValueChanged(req.getDescription(), req.getDescriptionOrig(), s.clear()))
  468. wu->setDebugValue("description", (req.getDescription() && *req.getDescription()) ? s.trim().str() : NULL, true);
  469. double version = context.getClientVersion();
  470. if (version > 1.04)
  471. {
  472. if (origValueChanged(req.getClusterSelection(), req.getClusterOrig(), s.clear(), false))
  473. {
  474. if (!isValidCluster(s.str()))
  475. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", s.str());
  476. if (req.getState() == WUStateBlocked)
  477. switchWorkUnitQueue(wu.get(), s.str());
  478. else if ((req.getState() != WUStateSubmitted) && (req.getState() != WUStateRunning) && (req.getState() != WUStateDebugPaused) && (req.getState() != WUStateDebugRunning))
  479. wu->setClusterName(s.str());
  480. }
  481. }
  482. WsWuHelpers::setXmlParameters(wu, req.getXmlParams(), (req.getAction()==WUActionExecuteExisting));
  483. if (notEmpty(req.getQueryText()))
  484. {
  485. Owned<IWUQuery> query=wu->updateQuery();
  486. query->setQueryText(req.getQueryText());
  487. }
  488. if (version > 1.34 && notEmpty(req.getQueryMainDefinition()))
  489. {
  490. Owned<IWUQuery> query=wu->updateQuery();
  491. query->setQueryMainDefinition(req.getQueryMainDefinition());
  492. }
  493. if (!req.getResultLimit_isNull())
  494. wu->setResultLimit(req.getResultLimit());
  495. if (!req.getAction_isNull())
  496. {
  497. WUAction action = (WUAction) req.getAction();
  498. if(action < WUActionSize)
  499. wu->setAction(action);
  500. }
  501. if (!req.getPriorityClass_isNull())
  502. {
  503. WUPriorityClass priority = (WUPriorityClass) req.getPriorityClass();
  504. if(priority<PriorityClassSize)
  505. wu->setPriority(priority);
  506. }
  507. if (!req.getPriorityLevel_isNull())
  508. wu->setPriorityLevel(req.getPriorityLevel());
  509. if (origValueChanged(req.getScope(), req.getScopeOrig(), s.clear(), false))
  510. wu->setWuScope(s.str());
  511. ForEachItemIn(di, req.getDebugValues())
  512. {
  513. IConstDebugValue& item=req.getDebugValues().item(di);
  514. const char *debugName = item.getName();
  515. if (notEmpty(debugName))
  516. {
  517. StringBuffer expanded;
  518. if (*debugName=='-')
  519. debugName=expanded.append("eclcc").append(debugName).str();
  520. wu->setDebugValue(debugName, item.getValue(), true);
  521. }
  522. }
  523. ForEachItemIn(ai, req.getApplicationValues())
  524. {
  525. IConstApplicationValue& item=req.getApplicationValues().item(ai);
  526. if(notEmpty(item.getApplication()) && notEmpty(item.getName()))
  527. wu->setApplicationValue(item.getApplication(), item.getName(), item.getValue(), true);
  528. }
  529. wu->commit();
  530. wu.clear();
  531. WsWuInfo winfo(context, cw);
  532. winfo.getInfo(resp.updateWorkunit(), WUINFO_All);
  533. StringBuffer thorSlaveIP;
  534. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  535. thorSlaveIP = req.getThorSlaveIP();
  536. if (thorSlaveIP.length() > 0)
  537. {
  538. StringBuffer url;
  539. url.appendf("/WsWorkunits/WUInfo?Wuid=%s&ThorSlaveIP=%s", wuid.str(), thorSlaveIP.str());
  540. resp.setRedirectUrl(url.str());
  541. }
  542. else
  543. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  544. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  545. }
  546. catch(IException* e)
  547. {
  548. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  549. }
  550. return true;
  551. }
  552. bool CWsWorkunitsEx::onWUCreateAndUpdate(IEspContext &context, IEspWUUpdateRequest &req, IEspWUUpdateResponse &resp)
  553. {
  554. try
  555. {
  556. const char* wuid = req.getWuid();
  557. if (!wuid || !*wuid)
  558. {
  559. NewWsWorkunit wu(context);
  560. req.setWuid(wu->queryWuid());
  561. }
  562. }
  563. catch(IException* e)
  564. {
  565. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  566. }
  567. return onWUUpdate(context, req, resp);
  568. }
  569. static inline StringBuffer &appendUrlParameter(StringBuffer &url, const char *name, const char *value, bool &first)
  570. {
  571. if (notEmpty(value))
  572. {
  573. url.append(first ? '?' : '&').append(name).append('=').append(value);
  574. first=false;
  575. }
  576. return url;
  577. }
  578. bool CWsWorkunitsEx::onWUAction(IEspContext &context, IEspWUActionRequest &req, IEspWUActionResponse &resp)
  579. {
  580. try
  581. {
  582. CECLWUActions action;
  583. double version = context.getClientVersion();
  584. if (version >= 1.57)
  585. action = req.getWUActionType();
  586. else
  587. action = eclWUActionType.toEnum(req.getActionType());
  588. if (action == ECLWUActions_Undefined)
  589. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Action not defined.");
  590. Owned<IProperties> params = createProperties(true);
  591. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  592. if ((action == CECLWUActions_Restore) && !sashaServerIp.isEmpty())
  593. {
  594. params->setProp("sashaServerIP", sashaServerIp.get());
  595. params->setProp("sashaServerPort", sashaServerPort);
  596. }
  597. IArrayOf<IConstWUActionResult> results;
  598. if (doAction(context, req.getWuids(), action, params, &results) && (action != CECLWUActions_Delete) && checkRedirect(context))
  599. {
  600. StringBuffer redirect;
  601. if(req.getPageFrom() && strieq(req.getPageFrom(), "wuid"))
  602. redirect.append("/WsWorkunits/WUInfo?Wuid=").append(req.getWuids().item(0));
  603. else if (req.getPageFrom() && strieq(req.getPageFrom(), "scheduler"))
  604. {
  605. redirect.set("/WsWorkunits/WUShowScheduled");
  606. bool first=true;
  607. appendUrlParameter(redirect, "Cluster", req.getEventServer(), first);
  608. appendUrlParameter(redirect, "EventName", req.getEventName(), first);
  609. }
  610. else
  611. {
  612. redirect.append("/WsWorkunits/WUQuery");
  613. bool first=true;
  614. appendUrlParameter(redirect, "PageSize", req.getPageSize(), first);
  615. appendUrlParameter(redirect, "PageStartFrom", req.getCurrentPage(), first);
  616. appendUrlParameter(redirect, "Sortby", req.getSortby(), first);
  617. appendUrlParameter(redirect, "Descending", req.getDescending() ? "1" : "0", first);
  618. appendUrlParameter(redirect, "State", req.getState(), first);
  619. appendUrlParameter(redirect, "Cluster", req.getCluster(), first);
  620. appendUrlParameter(redirect, "Owner", req.getOwner(), first);
  621. appendUrlParameter(redirect, "StartDate", req.getStartDate(), first);
  622. appendUrlParameter(redirect, "EndDate", req.getEndDate(), first);
  623. appendUrlParameter(redirect, "ECL", req.getECL(), first);
  624. appendUrlParameter(redirect, "Jobname", req.getJobname(), first);
  625. }
  626. resp.setRedirectUrl(redirect.str());
  627. }
  628. else
  629. resp.setActionResults(results);
  630. }
  631. catch(IException* e)
  632. {
  633. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  634. }
  635. return true;
  636. }
  637. bool CWsWorkunitsEx::onWUDelete(IEspContext &context, IEspWUDeleteRequest &req, IEspWUDeleteResponse &resp)
  638. {
  639. try
  640. {
  641. IArrayOf<IConstWUActionResult> results;
  642. Owned<IProperties> params = createProperties(true);
  643. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  644. if (!doAction(context,req.getWuids(), CECLWUActions_Delete, params, &results))
  645. resp.setActionResults(results);
  646. }
  647. catch(IException* e)
  648. {
  649. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  650. }
  651. return true;
  652. }
  653. bool CWsWorkunitsEx::onWUAbort(IEspContext &context, IEspWUAbortRequest &req, IEspWUAbortResponse &resp)
  654. {
  655. try
  656. {
  657. IArrayOf<IConstWUActionResult> results;
  658. Owned<IProperties> params = createProperties(true);
  659. params->setProp("BlockTillFinishTimer", req.getBlockTillFinishTimer());
  660. if (!doAction(context,req.getWuids(), CECLWUActions_Abort, params, &results))
  661. resp.setActionResults(results);
  662. }
  663. catch(IException* e)
  664. {
  665. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  666. }
  667. return true;
  668. }
  669. bool CWsWorkunitsEx::onWUProtect(IEspContext &context, IEspWUProtectRequest &req, IEspWUProtectResponse &resp)\
  670. {
  671. try
  672. {
  673. IArrayOf<IConstWUActionResult> results;
  674. Owned<IProperties> params(createProperties(true));
  675. params->setProp("BlockTillFinishTimer", 0);
  676. CECLWUActions action = req.getProtect() ? CECLWUActions_Protect : CECLWUActions_Unprotect;
  677. if (!doAction(context,req.getWuids(), action, params, &results))
  678. resp.setActionResults(results);
  679. }
  680. catch(IException* e)
  681. {
  682. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  683. }
  684. return true;
  685. }
  686. bool CWsWorkunitsEx::onWUResubmit(IEspContext &context, IEspWUResubmitRequest &req, IEspWUResubmitResponse &resp)
  687. {
  688. try
  689. {
  690. Owned<IMultiException> me = MakeMultiException();
  691. StringAttr wuid;
  692. StringArray wuids;
  693. double version = context.getClientVersion();
  694. IArrayOf<IEspResubmittedWU> resubmittedWUs;
  695. for(aindex_t i=0; i<req.getWuids().length();i++)
  696. {
  697. StringBuffer requestWuid = req.getWuids().item(i);
  698. WsWuHelpers::checkAndTrimWorkunit("WUResubmit", requestWuid);
  699. ensureWsWorkunitAccess(context, requestWuid.str(), SecAccess_Write);
  700. PROGLOG("WUResubmit: %s", requestWuid.str());
  701. wuid.set(requestWuid.str());
  702. try
  703. {
  704. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  705. if(req.getCloneWorkunit() || req.getRecompile())
  706. {
  707. Owned<IConstWorkUnit> src(factory->openWorkUnit(wuid.str()));
  708. NewWsWorkunit wu(factory, context);
  709. wuid.set(wu->queryWuid());
  710. queryExtendedWU(wu)->copyWorkUnit(src, false, false);
  711. SCMStringBuffer token;
  712. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  713. }
  714. wuids.append(wuid.str());
  715. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  716. if(!cw)
  717. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  718. WsWuHelpers::submitWsWorkunit(context, cw, NULL, NULL, 0, req.getRecompile(), req.getResetWorkflow(), false);
  719. if (version < 1.40)
  720. continue;
  721. Owned<IEspResubmittedWU> resubmittedWU = createResubmittedWU();
  722. resubmittedWU->setWUID(wuid.str());
  723. if (!streq(requestWuid.str(), wuid.str()))
  724. resubmittedWU->setParentWUID(requestWuid.str());
  725. resubmittedWUs.append(*resubmittedWU.getClear());
  726. }
  727. catch (IException *E)
  728. {
  729. me->append(*E);
  730. }
  731. catch (...)
  732. {
  733. me->append(*MakeStringException(0,"Unknown exception submitting %s",wuid.str()));
  734. }
  735. }
  736. if(me->ordinality())
  737. throw me.getLink();
  738. int timeToWait = req.getBlockTillFinishTimer();
  739. if (timeToWait != 0)
  740. {
  741. for(aindex_t i=0; i<wuids.length(); i++)
  742. waitForWorkUnitToComplete(wuids.item(i), timeToWait);
  743. }
  744. if (version >= 1.40)
  745. resp.setWUs(resubmittedWUs);
  746. if(wuids.length()==1)
  747. {
  748. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuids.item(0)));
  749. }
  750. }
  751. catch(IException* e)
  752. {
  753. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  754. }
  755. return true;
  756. }
  757. bool CWsWorkunitsEx::onWUPushEvent(IEspContext &context, IEspWUPushEventRequest &req, IEspWUPushEventResponse &resp)
  758. {
  759. try
  760. {
  761. const char *name = req.getEventName();
  762. const char *text = req.getEventText();
  763. const char *target = NULL;
  764. if (notEmpty(name) && notEmpty(text))
  765. {
  766. PROGLOG("WUPushEvent: EventName %s, EventText %s", name, text);
  767. Owned<IScheduleEventPusher> pusher(getScheduleEventPusher());
  768. pusher->push(name, text, target);
  769. StringBuffer redirect("/WsWorkunits/WUShowScheduled");
  770. bool first=true;
  771. appendUrlParameter(redirect, "PushEventName", name, first);
  772. appendUrlParameter(redirect, "PushEventText", text, first);
  773. resp.setRedirectUrl(redirect.str());
  774. return true;
  775. }
  776. }
  777. catch(IException* e)
  778. {
  779. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  780. }
  781. return false;
  782. }
  783. bool CWsWorkunitsEx::onWUSchedule(IEspContext &context, IEspWUScheduleRequest &req, IEspWUScheduleResponse &resp)
  784. {
  785. try
  786. {
  787. StringBuffer wuid = req.getWuid();
  788. WsWuHelpers::checkAndTrimWorkunit("WUSchedule", wuid);
  789. const char* cluster = req.getCluster();
  790. if (isEmpty(cluster))
  791. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  792. if (!isValidCluster(cluster))
  793. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  794. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  795. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  796. ensureWsWorkunitAccess(context, *wu.get(), SecAccess_Write);
  797. switch(wu->getState())
  798. {
  799. case WUStateDebugPaused:
  800. case WUStateDebugRunning:
  801. case WUStateRunning:
  802. case WUStateAborting:
  803. case WUStateBlocked:
  804. throw MakeStringException(ECLWATCH_CANNOT_SCHEDULE_WORKUNIT, "Cannot schedule the workunit. Workunit state is '%s'.", wu->queryStateDesc());
  805. }
  806. PROGLOG("WUSchedule: %s", wuid.str());
  807. wu->clearExceptions();
  808. wu->setClusterName(cluster);
  809. if (notEmpty(req.getWhen()))
  810. {
  811. WsWuDateTime dt;
  812. dt.setString(req.getWhen());
  813. wu->setTimeScheduled(dt);
  814. }
  815. if(notEmpty(req.getSnapshot()))
  816. wu->setSnapshot(req.getSnapshot());
  817. wu->setState(WUStateScheduled);
  818. if (req.getMaxRunTime())
  819. wu->setDebugValueInt("maxRunTime", req.getMaxRunTime(), true);
  820. SCMStringBuffer token;
  821. wu->setSecurityToken(createToken(wuid.str(), context.queryUserId(), context.queryPassword(), token).str());
  822. AuditSystemAccess(context.queryUserId(), true, "Scheduled %s", wuid.str());
  823. }
  824. catch(IException* e)
  825. {
  826. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  827. }
  828. return true;
  829. }
  830. bool CWsWorkunitsEx::onWUSubmit(IEspContext &context, IEspWUSubmitRequest &req, IEspWUSubmitResponse &resp)
  831. {
  832. try
  833. {
  834. StringBuffer wuid = req.getWuid();
  835. WsWuHelpers::checkAndTrimWorkunit("WUSubmit", wuid);
  836. const char *cluster = req.getCluster();
  837. if (isEmpty(cluster))
  838. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No Cluster defined.");
  839. if (!isValidCluster(cluster))
  840. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  841. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  842. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  843. if(!cw)
  844. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  845. if (cw->getAction()==WUActionExecuteExisting)
  846. {
  847. ExecuteExistingQueryInfo info(cw);
  848. if (info.queryset.isEmpty() || info.query.isEmpty())
  849. {
  850. WorkunitUpdate wu(&cw->lock());
  851. throw WsWuHelpers::noteException(wu, MakeStringException(ECLWATCH_INVALID_INPUT,"Queryset and/or query not specified"));
  852. }
  853. WsWuHelpers::runWsWuQuery(context, cw, info.queryset.str(), info.query.str(), cluster, NULL);
  854. }
  855. else
  856. WsWuHelpers::submitWsWorkunit(context, cw, cluster, req.getSnapshot(), req.getMaxRunTime(), true, false, false);
  857. PROGLOG("WUSubmit: %s", wuid.str());
  858. if (req.getBlockTillFinishTimer() != 0)
  859. waitForWorkUnitToComplete(wuid.str(), req.getBlockTillFinishTimer());
  860. resp.setRedirectUrl(StringBuffer("/WsWorkunits/WUInfo?Wuid=").append(wuid).str());
  861. }
  862. catch(IException* e)
  863. {
  864. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  865. }
  866. return true;
  867. }
  868. ErrorSeverity checkGetExceptionSeverity(CWUExceptionSeverity severity)
  869. {
  870. switch (severity)
  871. {
  872. case CWUExceptionSeverity_INFO:
  873. return SeverityInformation;
  874. case CWUExceptionSeverity_WARNING:
  875. return SeverityWarning;
  876. case CWUExceptionSeverity_ERROR:
  877. return SeverityError;
  878. case CWUExceptionSeverity_ALERT:
  879. return SeverityAlert;
  880. }
  881. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT,"invalid exception severity");
  882. }
  883. bool CWsWorkunitsEx::onWURun(IEspContext &context, IEspWURunRequest &req, IEspWURunResponse &resp)
  884. {
  885. try
  886. {
  887. const char *cluster = req.getCluster();
  888. if (notEmpty(cluster) && !isValidCluster(cluster))
  889. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", cluster);
  890. StringBuffer wuidStr = req.getWuid();
  891. const char* runWuid = wuidStr.trim().str();
  892. StringBuffer wuid;
  893. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  894. if (runWuid && *runWuid)
  895. {
  896. if (!looksLikeAWuid(runWuid, 'W'))
  897. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", runWuid);
  898. PROGLOG("WURun: %s", runWuid);
  899. if (req.getCloneWorkunit())
  900. WsWuHelpers::runWsWorkunit(context, wuid, runWuid, cluster, req.getInput(), &req.getVariables(),
  901. &req.getDebugValues(), &req.getApplicationValues());
  902. else
  903. {
  904. WsWuHelpers::submitWsWorkunit(context, runWuid, cluster, NULL, 0, false, true, true, req.getInput(),
  905. &req.getVariables(), &req.getDebugValues(), &req.getApplicationValues());
  906. wuid.set(runWuid);
  907. }
  908. }
  909. else if (notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  910. {
  911. PROGLOG("WURun: QuerySet %s, Query %s", req.getQuerySet(), req.getQuery());
  912. WsWuHelpers::runWsWuQuery(context, wuid, req.getQuerySet(), req.getQuery(), cluster, req.getInput(),
  913. &req.getApplicationValues());
  914. }
  915. else
  916. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  917. int timeToWait = req.getWait();
  918. if (timeToWait != 0)
  919. waitForWorkUnitToComplete(wuid.str(), timeToWait);
  920. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  921. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  922. if (!cw)
  923. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  924. resp.setState(cw->queryStateDesc());
  925. resp.setWuid(wuid.str());
  926. switch (cw->getState())
  927. {
  928. case WUStateCompleted:
  929. case WUStateFailed:
  930. case WUStateUnknown:
  931. {
  932. SCMStringBuffer result;
  933. unsigned flags = WorkUnitXML_SeverityTags;
  934. if (req.getNoRootTag())
  935. flags |= WorkUnitXML_NoRoot;
  936. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  937. resp.setResults(result.str());
  938. break;
  939. }
  940. default:
  941. break;
  942. }
  943. }
  944. catch(IException* e)
  945. {
  946. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  947. }
  948. return true;
  949. }
  950. bool CWsWorkunitsEx::onWUFullResult(IEspContext &context, IEspWUFullResultRequest &req, IEspWUFullResultResponse &resp)
  951. {
  952. try
  953. {
  954. StringBuffer wuid = req.getWuid();
  955. WsWuHelpers::checkAndTrimWorkunit("WUFullResult", wuid);
  956. ErrorSeverity severity = checkGetExceptionSeverity(req.getExceptionSeverity());
  957. if (!wuid.length())
  958. throw MakeStringException(ECLWATCH_MISSING_PARAMS,"Workunit or Query required");
  959. if (!looksLikeAWuid(wuid, 'W'))
  960. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid.str());
  961. PROGLOG("WUFullResults: %s", wuid.str());
  962. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  963. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  964. if (!cw)
  965. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.", wuid.str());
  966. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  967. resp.setWuid(wuid.str());
  968. switch (cw->getState())
  969. {
  970. case WUStateCompleted:
  971. case WUStateFailed:
  972. case WUStateUnknown:
  973. {
  974. SCMStringBuffer result;
  975. unsigned flags = WorkUnitXML_SeverityTags;
  976. if (req.getNoRootTag())
  977. flags |= WorkUnitXML_NoRoot;
  978. if (context.getResponseFormat()==ESPSerializationJSON)
  979. getFullWorkUnitResultsJSON(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  980. else
  981. getFullWorkUnitResultsXML(context.queryUserId(), context.queryPassword(), cw.get(), result, flags, severity);
  982. resp.setResults(result.str());
  983. break;
  984. }
  985. default:
  986. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT, "Cannot get results Workunit %s %s.", wuid.str(), getWorkunitStateStr(cw->getState()));
  987. }
  988. }
  989. catch(IException* e)
  990. {
  991. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  992. }
  993. return true;
  994. }
  995. bool CWsWorkunitsEx::onWUWaitCompiled(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  996. {
  997. try
  998. {
  999. StringBuffer wuid = req.getWuid();
  1000. WsWuHelpers::checkAndTrimWorkunit("WUWaitCompiled", wuid);
  1001. PROGLOG("WUWaitCompiled: %s", wuid.str());
  1002. secWaitForWorkUnitToCompile(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait());
  1003. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1004. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1005. if(!cw)
  1006. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  1007. resp.setStateID(cw->getState());
  1008. }
  1009. catch(IException* e)
  1010. {
  1011. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1012. }
  1013. return true;
  1014. }
  1015. bool CWsWorkunitsEx::onWUWaitComplete(IEspContext &context, IEspWUWaitRequest &req, IEspWUWaitResponse &resp)
  1016. {
  1017. try
  1018. {
  1019. StringBuffer wuid = req.getWuid();
  1020. WsWuHelpers::checkAndTrimWorkunit("WUWaitComplete", wuid);
  1021. PROGLOG("WUWaitComplete: %s", wuid.str());
  1022. resp.setStateID(secWaitForWorkUnitToComplete(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getWait(), req.getReturnOnWait()));
  1023. }
  1024. catch(IException* e)
  1025. {
  1026. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1027. }
  1028. return true;
  1029. }
  1030. bool CWsWorkunitsEx::onWUCDebug(IEspContext &context, IEspWUDebugRequest &req, IEspWUDebugResponse &resp)
  1031. {
  1032. try
  1033. {
  1034. StringBuffer wuid = req.getWuid();
  1035. WsWuHelpers::checkAndTrimWorkunit("WUCDebug", wuid);
  1036. PROGLOG("WUCDebug: %s", wuid.str());
  1037. StringBuffer result;
  1038. secDebugWorkunit(wuid.str(), *context.querySecManager(), *context.queryUser(), req.getCommand(), result);
  1039. resp.setResult(result);
  1040. }
  1041. catch(IException* e)
  1042. {
  1043. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1044. }
  1045. return true;
  1046. }
  1047. bool CWsWorkunitsEx::onWUSyntaxCheckECL(IEspContext &context, IEspWUSyntaxCheckRequest &req, IEspWUSyntaxCheckResponse &resp)
  1048. {
  1049. try
  1050. {
  1051. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1052. NewWsWorkunit wu(factory, context);
  1053. wu->setAction(WUActionCheck);
  1054. if(notEmpty(req.getModuleName()) && notEmpty(req.getAttributeName()))
  1055. {
  1056. wu->setApplicationValue("SyntaxCheck", "ModuleName", req.getModuleName(), true);
  1057. wu->setApplicationValue("SyntaxCheck", "AttributeName", req.getAttributeName(), true);
  1058. }
  1059. ForEachItemIn(di, req.getDebugValues())
  1060. {
  1061. IConstDebugValue& item=req.getDebugValues().item(di);
  1062. const char *debugName = item.getName();
  1063. if (notEmpty(debugName))
  1064. {
  1065. StringBuffer expanded;
  1066. if (*debugName=='-')
  1067. debugName=expanded.append("eclcc").append(debugName).str();
  1068. wu->setDebugValue(debugName, item.getValue(), true);
  1069. }
  1070. }
  1071. wu.setQueryText(req.getECL());
  1072. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1073. wu->commit();
  1074. wu.clear();
  1075. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1076. waitForWorkUnitToComplete(wuid.str(), req.getTimeToWait());
  1077. Owned<IConstWorkUnit> cw(factory->openWorkUnit(wuid.str()));
  1078. WsWUExceptions errors(*cw);
  1079. resp.setErrors(errors);
  1080. StringBuffer msg;
  1081. WUState st = cw->getState();
  1082. cw.clear();
  1083. switch (st)
  1084. {
  1085. case WUStateAborted:
  1086. case WUStateCompleted:
  1087. case WUStateFailed:
  1088. if (!factory->deleteWorkUnit(wuid.str()))
  1089. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Workunit %s cannot be deleted.", wuid.str());
  1090. break;
  1091. default:
  1092. abortWorkUnit(wuid.str(), context.querySecManager(), context.queryUser());
  1093. if (!factory->deleteWorkUnit(wuid.str()))
  1094. {
  1095. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,
  1096. "WUSyntaxCheckECL has timed out. Workunit %s cannot be deleted now. You may delete it when its status changes.", wuid.str());
  1097. }
  1098. if (context.getClientVersion() < 1.57)
  1099. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "WUSyntaxCheckECL has timed out.");
  1100. resp.setMessage("WUSyntaxCheckECL has timed out.");
  1101. break;
  1102. }
  1103. }
  1104. catch(IException* e)
  1105. {
  1106. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1107. }
  1108. return true;
  1109. }
  1110. bool CWsWorkunitsEx::onWUCompileECL(IEspContext &context, IEspWUCompileECLRequest &req, IEspWUCompileECLResponse &resp)
  1111. {
  1112. try
  1113. {
  1114. ensureWsCreateWorkunitAccess(context);
  1115. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1116. NewWsWorkunit wu(factory, context);
  1117. if(req.getIncludeComplexity())
  1118. {
  1119. wu->setAction(WUActionCompile);
  1120. wu->setDebugValueInt("calculateComplexity",1,true);
  1121. }
  1122. else
  1123. wu->setAction(WUActionCheck);
  1124. if(req.getModuleName() && req.getAttributeName())
  1125. {
  1126. wu->setApplicationValue("SyntaxCheck","ModuleName",req.getModuleName(),true);
  1127. wu->setApplicationValue("SyntaxCheck","AttributeName",req.getAttributeName(),true);
  1128. }
  1129. if(req.getIncludeDependencies())
  1130. wu->setApplicationValueInt("SyntaxCheck","IncludeDependencies",1,true);
  1131. wu.setQueryText(req.getECL());
  1132. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear() StringAttr wuid(wu->queryWuid());
  1133. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1134. waitForWorkUnitToComplete(wuid.str(),req.getTimeToWait());
  1135. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1136. SCMStringBuffer s;
  1137. cw->getDebugValue("__Calculated__Complexity__",s);
  1138. if(s.length())
  1139. resp.setComplexity(s.str());
  1140. WsWUExceptions errors(*cw);
  1141. resp.setErrors(errors);
  1142. if(!errors.ErrCount())
  1143. {
  1144. IArrayOf<IEspWUECLAttribute> dependencies;
  1145. for(unsigned count=1;;count++)
  1146. {
  1147. SCMStringBuffer xml;
  1148. cw->getApplicationValue("SyntaxCheck",StringBuffer("Dependency").append(count).str(),xml);
  1149. if(!xml.length())
  1150. break;
  1151. Owned<IPropertyTree> dep=createPTreeFromXMLString(xml.str(), ipt_caseInsensitive);
  1152. if(!dep)
  1153. continue;
  1154. Owned<IEspWUECLAttribute> att = createWUECLAttribute("","");
  1155. att->setModuleName(dep->queryProp("@module"));
  1156. att->setAttributeName(dep->queryProp("@name"));
  1157. int flags = dep->getPropInt("@flags",0);
  1158. if(flags & ob_locked)
  1159. {
  1160. if(flags & ob_lockedself)
  1161. att->setIsCheckedOut(true);
  1162. else
  1163. att->setIsLocked(true);
  1164. }
  1165. if(flags & ob_sandbox)
  1166. att->setIsSandbox(true);
  1167. if(flags & ob_orphaned)
  1168. att->setIsOrphaned(true);
  1169. dependencies.append(*att.getLink());
  1170. }
  1171. resp.setDependencies(dependencies);
  1172. }
  1173. cw.clear();
  1174. if (!factory->deleteWorkUnit(wuid.str()))
  1175. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid.str());
  1176. }
  1177. catch(IException* e)
  1178. {
  1179. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1180. }
  1181. return true;
  1182. }
  1183. bool CWsWorkunitsEx::onWUGetDependancyTrees(IEspContext& context, IEspWUGetDependancyTreesRequest& req, IEspWUGetDependancyTreesResponse& resp)
  1184. {
  1185. try
  1186. {
  1187. unsigned int timeMilliSec = 500;
  1188. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1189. NewWsWorkunit wu(factory, context);
  1190. wu->setAction(WUActionCheck);
  1191. if (notEmpty(req.getCluster()))
  1192. wu->setClusterName(req.getCluster());
  1193. if (notEmpty(req.getSnapshot()))
  1194. wu->setSnapshot(req.getSnapshot());
  1195. wu->setDebugValue("gatherDependenciesSelection",notEmpty(req.getItems()) ? req.getItems() : NULL,true);
  1196. if (context.getClientVersion() > 1.12)
  1197. {
  1198. wu->setDebugValueInt("gatherDependencies", 1, true);
  1199. const char *timeout = req.getTimeoutMilliSec();
  1200. if (notEmpty(timeout))
  1201. {
  1202. const char *finger = timeout;
  1203. while (*finger)
  1204. {
  1205. if (!isdigit(*finger++))
  1206. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Incorrect timeout value");
  1207. }
  1208. timeMilliSec = atol(timeout);
  1209. }
  1210. }
  1211. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  1212. wu->commit();
  1213. wu.clear();
  1214. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1215. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), req.getSnapshot(), 0, true, false, false);
  1216. int state = waitForWorkUnitToComplete(wuid.str(), timeMilliSec);
  1217. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  1218. WsWUExceptions errors(*cw);
  1219. resp.setErrors(errors);
  1220. MemoryBuffer temp;
  1221. MemoryBuffer2IDataVal xmlresult(temp);
  1222. Owned<IConstWUResult> result = cw->getResultBySequence(0);
  1223. if (result)
  1224. {
  1225. result->getResultRaw(xmlresult, NULL, NULL);
  1226. resp.setDependancyTrees(temp);
  1227. }
  1228. wu.setown(&cw->lock());
  1229. wu->setState(WUStateAborted);
  1230. wu->commit();
  1231. wu.clear();
  1232. if (!factory->deleteWorkUnit(wuid.str()))
  1233. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "%s: Workunit cannot be deleted. Please check ESP log.", wuid.str());
  1234. }
  1235. catch(IException* e)
  1236. {
  1237. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1238. }
  1239. return true;
  1240. }
  1241. bool getWsWuInfoFromSasha(IEspContext &context, SocketEndpoint &ep, const char* wuid, IEspECLWorkunit *info)
  1242. {
  1243. Owned<INode> node = createINode(ep);
  1244. Owned<ISashaCommand> cmd = createSashaCommand();
  1245. cmd->addId(wuid);
  1246. cmd->setAction(SCA_GET);
  1247. if (!cmd->send(node, 1*60*1000))
  1248. {
  1249. StringBuffer url;
  1250. DBGLOG("Could not connect to Sasha server at %s", ep.getUrlStr(url).str());
  1251. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.", url.str());
  1252. }
  1253. if (cmd->numIds()==0)
  1254. {
  1255. DBGLOG("Could not read archived workunit %s",wuid);
  1256. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1257. }
  1258. unsigned num = cmd->numResults();
  1259. if (num < 1)
  1260. return false;
  1261. StringBuffer res;
  1262. cmd->getResult(0, res);
  1263. if(res.length() < 1)
  1264. return false;
  1265. Owned<IPropertyTree> wpt = createPTreeFromXMLString(res.str());
  1266. if (!wpt)
  1267. return false;
  1268. const char * owner = wpt->queryProp("@submitID");
  1269. ensureWsWorkunitAccessByOwnerId(context, owner, SecAccess_Read);
  1270. PROGLOG("GetArchivedWUInfo: %s", wuid);
  1271. info->setWuid(wuid);
  1272. info->setArchived(true);
  1273. if (notEmpty(owner))
  1274. info->setOwner(owner);
  1275. const char * state = wpt->queryProp("@state");
  1276. if (notEmpty(state))
  1277. info->setState(state);
  1278. const char * cluster = wpt->queryProp("@clusterName");
  1279. if (notEmpty(cluster))
  1280. info->setCluster(cluster);
  1281. if (context.querySecManager())
  1282. {
  1283. const char * scope = wpt->queryProp("@scope");
  1284. if (notEmpty(scope))
  1285. info->setScope(scope);
  1286. }
  1287. const char * jobName = wpt->queryProp("@jobName");
  1288. if (notEmpty(jobName))
  1289. info->setJobname(jobName);
  1290. const char * description = wpt->queryProp("Debug/description");
  1291. if (notEmpty(description))
  1292. info->setDescription(description);
  1293. const char * queryText = wpt->queryProp("Query/Text");
  1294. if (notEmpty(queryText))
  1295. info->updateQuery().setText(queryText);
  1296. const char * protectedWU = wpt->queryProp("@protected");
  1297. info->setProtected((protectedWU && *protectedWU!='0'));
  1298. return true;
  1299. }
  1300. #define WUDETAILS_REFRESH_MINS 1
  1301. void getArchivedWUInfo(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort, const char *wuid, IEspWUInfoResponse &resp)
  1302. {
  1303. SocketEndpoint ep;
  1304. if (sashaServerIP && *sashaServerIP)
  1305. ep.set(sashaServerIP, sashaServerPort);
  1306. else
  1307. getSashaNode(ep);
  1308. if (getWsWuInfoFromSasha(context, ep, wuid, &resp.updateWorkunit()))
  1309. {
  1310. resp.setCanCompile(false);
  1311. return;
  1312. }
  1313. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Cannot find workunit %s.", wuid);
  1314. return;
  1315. }
  1316. #define WUDETAILS_REFRESH_MINS 1
  1317. bool CWsWorkunitsEx::onWUInfo(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1318. {
  1319. try
  1320. {
  1321. StringBuffer wuid = req.getWuid();
  1322. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  1323. double version = context.getClientVersion();
  1324. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1325. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1326. else
  1327. {
  1328. try
  1329. {
  1330. //The access is checked here because getArchivedWUInfo() has its own access check.
  1331. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1332. PROGLOG("WUInfo: %s", wuid.str());
  1333. unsigned long flags=0;
  1334. if (req.getTruncateEclTo64k())
  1335. flags|=WUINFO_TruncateEclTo64k;
  1336. if (req.getIncludeExceptions())
  1337. flags|=WUINFO_IncludeExceptions;
  1338. if (req.getIncludeGraphs())
  1339. flags|=WUINFO_IncludeGraphs;
  1340. if (req.getIncludeSourceFiles())
  1341. flags|=WUINFO_IncludeSourceFiles;
  1342. if (req.getIncludeResults())
  1343. flags|=WUINFO_IncludeResults;
  1344. if (req.getIncludeVariables())
  1345. flags|=WUINFO_IncludeVariables;
  1346. if (req.getIncludeTimers())
  1347. flags|=WUINFO_IncludeTimers;
  1348. if (req.getIncludeDebugValues())
  1349. flags|=WUINFO_IncludeDebugValues;
  1350. if (req.getIncludeApplicationValues())
  1351. flags|=WUINFO_IncludeApplicationValues;
  1352. if (req.getIncludeWorkflows())
  1353. flags|=WUINFO_IncludeWorkflows;
  1354. if (!req.getSuppressResultSchemas())
  1355. flags|=WUINFO_IncludeEclSchemas;
  1356. if (req.getIncludeXmlSchemas())
  1357. flags|=WUINFO_IncludeXmlSchema;
  1358. if (req.getIncludeResultsViewNames())
  1359. flags|=WUINFO_IncludeResultsViewNames;
  1360. if (req.getIncludeResourceURLs())
  1361. flags|=WUINFO_IncludeResourceURLs;
  1362. if (req.getIncludeECL())
  1363. flags|=WUINFO_IncludeECL;
  1364. if (req.getIncludeHelpers())
  1365. flags|=WUINFO_IncludeHelpers;
  1366. if (req.getIncludeAllowedClusters())
  1367. flags|=WUINFO_IncludeAllowedClusters;
  1368. WsWuInfo winfo(context, wuid.str());
  1369. winfo.getInfo(resp.updateWorkunit(), flags);
  1370. if (req.getIncludeResultsViewNames()||req.getIncludeResourceURLs()||(version >= 1.50))
  1371. {
  1372. StringArray views, urls;
  1373. winfo.getResourceInfo(views, urls, WUINFO_IncludeResultsViewNames|WUINFO_IncludeResourceURLs);
  1374. IEspECLWorkunit& eclWU = resp.updateWorkunit();
  1375. if (req.getIncludeResultsViewNames())
  1376. resp.setResultViews(views);
  1377. if (req.getIncludeResourceURLs())
  1378. eclWU.setResourceURLs(urls);
  1379. if (version >= 1.50)
  1380. {
  1381. eclWU.setResultViewCount(views.length());
  1382. eclWU.setResourceURLCount(urls.length());
  1383. }
  1384. }
  1385. }
  1386. catch (IException *e)
  1387. {
  1388. if (e->errorCode() != ECLWATCH_CANNOT_OPEN_WORKUNIT)
  1389. throw e;
  1390. getArchivedWUInfo(context, sashaServerIp.get(), sashaServerPort, wuid.str(), resp);
  1391. e->Release();
  1392. }
  1393. switch (resp.getWorkunit().getStateID())
  1394. {
  1395. case WUStateCompiling:
  1396. case WUStateCompiled:
  1397. case WUStateScheduled:
  1398. case WUStateSubmitted:
  1399. case WUStateRunning:
  1400. case WUStateAborting:
  1401. case WUStateWait:
  1402. case WUStateUploadingFiles:
  1403. case WUStateDebugPaused:
  1404. case WUStateDebugRunning:
  1405. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1406. break;
  1407. case WUStateBlocked:
  1408. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS*5);
  1409. break;
  1410. }
  1411. resp.setCanCompile(notEmpty(context.queryUserId()));
  1412. if (version > 1.24 && notEmpty(req.getThorSlaveIP()))
  1413. resp.setThorSlaveIP(req.getThorSlaveIP());
  1414. ISecManager* secmgr = context.querySecManager();
  1415. if (!secmgr)
  1416. resp.setSecMethod(NULL);
  1417. else
  1418. resp.setSecMethod(secmgr->querySecMgrTypeName());
  1419. }
  1420. }
  1421. catch(IException* e)
  1422. {
  1423. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1424. }
  1425. return true;
  1426. }
  1427. bool CWsWorkunitsEx::onWUInfoDetails(IEspContext &context, IEspWUInfoRequest &req, IEspWUInfoResponse &resp)
  1428. {
  1429. return onWUInfo(context, req, resp);
  1430. }
  1431. bool CWsWorkunitsEx::onWUResultView(IEspContext &context, IEspWUResultViewRequest &req, IEspWUResultViewResponse &resp)
  1432. {
  1433. StringBuffer wuid = req.getWuid();
  1434. WsWuHelpers::checkAndTrimWorkunit("WUResultView", wuid);
  1435. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  1436. PROGLOG("WUResultView: %s", wuid.str());
  1437. Owned<IWuWebView> wv = createWuWebView(wuid.str(), NULL, NULL, getCFD(), true, nullptr);
  1438. StringBuffer html;
  1439. wv->renderSingleResult(req.getViewName(), req.getResultName(), html);
  1440. resp.setResult(html.str());
  1441. resp.setResult_mimetype("text/html");
  1442. return true;
  1443. }
  1444. void doWUQueryBySingleWuid(IEspContext &context, const char *wuid, IEspWUQueryResponse &resp)
  1445. {
  1446. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1447. WsWuInfo winfo(context, wuid);
  1448. winfo.getCommon(*info, 0);
  1449. IArrayOf<IEspECLWorkunit> results;
  1450. results.append(*info.getClear());
  1451. resp.setWorkunits(results);
  1452. resp.setPageSize(1);
  1453. resp.setCount(1);
  1454. PROGLOG("getWUInfo: %s", wuid);
  1455. }
  1456. void doWUQueryByFile(IEspContext &context, const char *logicalFile, IEspWUQueryResponse &resp)
  1457. {
  1458. StringBuffer wuid;
  1459. getWuidFromLogicalFileName(context, logicalFile, wuid);
  1460. if (!wuid.length())
  1461. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1462. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1463. Owned<IConstWorkUnit> cw= factory->openWorkUnit(wuid.str());
  1464. if (!cw)
  1465. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot find the workunit for file %s.", logicalFile);
  1466. if (getWsWorkunitAccess(context, *cw) < SecAccess_Read)
  1467. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED,"Cannot access the workunit for file %s.",logicalFile);
  1468. doWUQueryBySingleWuid(context, wuid.str(), resp);
  1469. resp.setFirst(false);
  1470. resp.setPageSize(1);
  1471. resp.setCount(1);
  1472. }
  1473. bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
  1474. {
  1475. if (isEmpty(name))
  1476. return false;
  1477. filters[count++] = value;
  1478. if ((value & WUSFwild) != 0 && !containsWildcard(name))
  1479. buff.append("*").append(name).append("*");
  1480. else
  1481. buff.append(name);
  1482. return true;
  1483. }
  1484. bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
  1485. {
  1486. if (isEmpty(stime))
  1487. return false;
  1488. CDateTime dt;
  1489. dt.setString(stime, NULL, true);
  1490. unsigned year, month, day, hour, minute, second, nano;
  1491. dt.getDate(year, month, day, true);
  1492. dt.getTime(hour, minute, second, nano, true);
  1493. VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  1494. filters[count++] = value;
  1495. buff.append(wuid.str());
  1496. return true;
  1497. }
  1498. bool addWUQueryFilterApplication(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *appname, const char *appkey, const char *appdata)
  1499. {
  1500. if (isEmpty(appname))
  1501. return false; // appname must be specified
  1502. if (isEmpty(appkey) && isEmpty(appdata)) //one or other is required ( MORE - see if cassandra can relax that)
  1503. return false;
  1504. VStringBuffer path("%s/%s", appname, appkey && *appkey ? appkey : "*");
  1505. buff.append(path.str());
  1506. buff.append(appdata);
  1507. filters[count++] = WUSFappvalue;
  1508. return true;
  1509. }
  1510. void readWUQuerySortOrder(const char* sortBy, const bool descending, WUSortField& sortOrder)
  1511. {
  1512. if (isEmpty(sortBy))
  1513. {
  1514. sortOrder = (WUSortField) (WUSFwuid | WUSFreverse);
  1515. return;
  1516. }
  1517. if (strieq(sortBy, "Owner"))
  1518. sortOrder = WUSFuser;
  1519. else if (strieq(sortBy, "JobName"))
  1520. sortOrder = WUSFjob;
  1521. else if (strieq(sortBy, "Cluster"))
  1522. sortOrder = WUSFcluster;
  1523. else if (strieq(sortBy, "Protected"))
  1524. sortOrder = WUSFprotected;
  1525. else if (strieq(sortBy, "State"))
  1526. sortOrder = WUSFstate;
  1527. else if (strieq(sortBy, "ClusterTime"))
  1528. sortOrder = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
  1529. else
  1530. sortOrder = WUSFwuid;
  1531. sortOrder = (WUSortField) (sortOrder | WUSFnocase);
  1532. if (descending)
  1533. sortOrder = (WUSortField) (sortOrder | WUSFreverse);
  1534. }
  1535. void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1536. {
  1537. SecAccessFlags accessOwn;
  1538. SecAccessFlags accessOthers;
  1539. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1540. double version = context.getClientVersion();
  1541. IArrayOf<IEspECLWorkunit> results;
  1542. int begin = 0;
  1543. unsigned int count = 100;
  1544. int pagesize = 100;
  1545. if (version > 1.01)
  1546. {
  1547. pagesize = (int)req.getPageSize();
  1548. if (!req.getCount_isNull())
  1549. pagesize = req.getCount();
  1550. if(pagesize < 1)
  1551. pagesize = 100;
  1552. begin = (int)req.getPageStartFrom();
  1553. }
  1554. else
  1555. {
  1556. count=(unsigned)req.getCount();
  1557. if(!count)
  1558. count=100;
  1559. if (notEmpty(req.getAfter()))
  1560. begin=atoi(req.getAfter());
  1561. else if (notEmpty(req.getBefore()))
  1562. begin=atoi(req.getBefore())-count;
  1563. if (begin < 0)
  1564. begin = 0;
  1565. pagesize = count;
  1566. }
  1567. WUSortField sortorder;
  1568. readWUQuerySortOrder(req.getSortby(), req.getDescending(), sortorder);
  1569. WUSortField filters[10];
  1570. unsigned short filterCount = 0;
  1571. MemoryBuffer filterbuf;
  1572. // Query filters should be added in order of expected power - add the most restrictive filters first
  1573. bool bDoubleCheckState = false;
  1574. if(req.getState() && *req.getState())
  1575. {
  1576. filters[filterCount++] = WUSFstate;
  1577. if (!strieq(req.getState(), "unknown"))
  1578. filterbuf.append(req.getState());
  1579. else
  1580. filterbuf.append("");
  1581. if (strieq(req.getState(), "submitted"))
  1582. bDoubleCheckState = true;
  1583. }
  1584. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1585. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1586. addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), (WUSortField) (WUSFfileread | WUSFnocase));
  1587. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1588. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
  1589. addWUQueryFilter(filters, filterCount, filterbuf, req.getECL(), (WUSortField) (WUSFecl | WUSFwild));
  1590. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1591. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1592. if (version < 1.55)
  1593. addWUQueryFilterApplication(filters, filterCount, filterbuf, req.getApplicationName(), req.getApplicationKey(), req.getApplicationData());
  1594. else
  1595. {
  1596. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1597. ForEachItemIn(i, applicationFilters)
  1598. {
  1599. IConstApplicationValue &item = applicationFilters.item(i);
  1600. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1601. }
  1602. }
  1603. filters[filterCount] = WUSFterm;
  1604. __int64 cacheHint = 0;
  1605. if (!req.getCacheHint_isNull())
  1606. cacheHint = req.getCacheHint();
  1607. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1608. unsigned numWUs;
  1609. PROGLOG("WUQuery: getWorkUnitsSorted");
  1610. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1611. if (version >= 1.41)
  1612. resp.setCacheHint(cacheHint);
  1613. PROGLOG("WUQuery: getWorkUnitsSorted done");
  1614. unsigned actualCount = 0;
  1615. ForEach(*it)
  1616. {
  1617. IConstWorkUnitInfo& cw = it->query();
  1618. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1619. {
  1620. numWUs--;
  1621. continue;
  1622. }
  1623. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1624. const char* wuid = cw.queryWuid();
  1625. if (!looksLikeAWuid(wuid, 'W'))
  1626. {
  1627. numWUs--;
  1628. continue;
  1629. }
  1630. actualCount++;
  1631. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1632. info->setWuid(cw.queryWuid());
  1633. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1634. {
  1635. info->setState("<Hidden>");
  1636. results.append(*info.getClear());
  1637. continue;
  1638. }
  1639. info->setProtected(cw.isProtected() ? 1 : 0);
  1640. info->setJobname(cw.queryJobName());
  1641. info->setOwner(cw.queryUser());
  1642. info->setCluster(cw.queryClusterName());
  1643. SCMStringBuffer s;
  1644. // info.setSnapshot(cw->getSnapshot(s).str());
  1645. info->setStateID(cw.getState());
  1646. info->setState(cw.queryStateDesc());
  1647. unsigned totalThorTimeMS = cw.getTotalThorTime();
  1648. StringBuffer totalThorTimeStr;
  1649. formatDuration(totalThorTimeStr, totalThorTimeMS);
  1650. if (version > 1.52)
  1651. info->setTotalClusterTime(totalThorTimeStr.str());
  1652. else
  1653. info->setTotalThorTime(totalThorTimeStr.str());
  1654. //if (cw->isPausing())
  1655. // info.setIsPausing(true);
  1656. // getEventScheduleFlag(info);
  1657. WsWuDateTime dt;
  1658. cw.getTimeScheduled(dt);
  1659. if(dt.isValid())
  1660. info->setDateTimeScheduled(dt.getString(s).str());
  1661. if (version >= 1.55)
  1662. {
  1663. IArrayOf<IEspApplicationValue> av;
  1664. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1665. ForEach(*app)
  1666. {
  1667. IConstWUAppValue& val=app->query();
  1668. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1669. t->setApplication(val.queryApplication());
  1670. t->setName(val.queryName());
  1671. t->setValue(val.queryValue());
  1672. av.append(*t.getLink());
  1673. }
  1674. info->setApplicationValues(av);
  1675. }
  1676. results.append(*info.getClear());
  1677. }
  1678. if (version > 1.02)
  1679. {
  1680. resp.setPageStartFrom(begin+1);
  1681. resp.setNumWUs(numWUs);
  1682. if (results.length() > (aindex_t)pagesize)
  1683. results.pop();
  1684. if(unsigned (begin + pagesize) < numWUs)
  1685. {
  1686. resp.setNextPage(begin + pagesize);
  1687. resp.setPageEndAt(begin + pagesize);
  1688. int last = begin + pagesize;
  1689. while (numWUs > (unsigned) last + pagesize)
  1690. last += pagesize;
  1691. resp.setLastPage(last);
  1692. }
  1693. else
  1694. {
  1695. resp.setNextPage(-1);
  1696. resp.setPageEndAt(numWUs);
  1697. }
  1698. if(begin > 0)
  1699. {
  1700. resp.setFirst(false);
  1701. if (begin - pagesize > 0)
  1702. resp.setPrevPage(begin - pagesize);
  1703. else
  1704. resp.setPrevPage(0);
  1705. }
  1706. resp.setPageSize(pagesize);
  1707. }
  1708. else
  1709. {
  1710. if(begin>0 && actualCount > 0)
  1711. {
  1712. char buf[10];
  1713. itoa(begin, buf, 10);
  1714. resp.setCurrent(buf);
  1715. }
  1716. if(count<actualCount)
  1717. {
  1718. char buf[10];
  1719. itoa(begin+count, buf, 10);
  1720. resp.setNext(buf);
  1721. resp.setNumWUs(numWUs);
  1722. if (results.length() > count)
  1723. results.pop();
  1724. }
  1725. if(begin == 0 && actualCount <= count)
  1726. resp.setFirst(false);
  1727. resp.setCount(count);
  1728. }
  1729. resp.setWorkunits(results);
  1730. return;
  1731. }
  1732. void doWULightWeightQueryWithSort(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  1733. {
  1734. SecAccessFlags accessOwn;
  1735. SecAccessFlags accessOthers;
  1736. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1737. double version = context.getClientVersion();
  1738. int pageStartFrom = 0;
  1739. int pageSize = 100;
  1740. if (!req.getPageStartFrom_isNull())
  1741. pageStartFrom = req.getPageStartFrom();
  1742. if (!req.getPageSize_isNull())
  1743. pageSize = req.getPageSize();
  1744. WUSortField sortOrder;
  1745. readWUQuerySortOrder(req.getSortBy(), req.getDescending(), sortOrder);
  1746. WUSortField filters[10];
  1747. unsigned short filterCount = 0;
  1748. MemoryBuffer filterbuf;
  1749. // Query filters should be added in order of expected power - add the most restrictive filters first
  1750. bool bDoubleCheckState = false;
  1751. if(req.getState() && *req.getState())
  1752. {
  1753. filters[filterCount++] = WUSFstate;
  1754. if (!strieq(req.getState(), "unknown"))
  1755. filterbuf.append(req.getState());
  1756. else
  1757. filterbuf.append("");
  1758. if (strieq(req.getState(), "submitted"))
  1759. bDoubleCheckState = true;
  1760. }
  1761. addWUQueryFilter(filters, filterCount, filterbuf, req.getWuid(), WUSFwildwuid);
  1762. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1763. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1764. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobName(), (WUSortField) (WUSFjob | WUSFnocase));
  1765. //StartDate example: 2015-08-26T14:26:00
  1766. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1767. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1768. IArrayOf<IConstApplicationValue>& applicationFilters = req.getApplicationValues();
  1769. ForEachItemIn(i, applicationFilters)
  1770. {
  1771. IConstApplicationValue &item = applicationFilters.item(i);
  1772. addWUQueryFilterApplication(filters, filterCount, filterbuf, item.getApplication(), item.getName(), item.getValue());
  1773. }
  1774. filters[filterCount] = WUSFterm;
  1775. __int64 cacheHint = 0;
  1776. if (!req.getCacheHint_isNull())
  1777. cacheHint = req.getCacheHint();
  1778. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1779. unsigned numWUs;
  1780. PROGLOG("getWorkUnitsSorted(LightWeight)");
  1781. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortOrder, filters, filterbuf.bufferBase(), pageStartFrom, pageSize+1, &cacheHint, &numWUs); // MORE - need security flags here!
  1782. resp.setCacheHint(cacheHint);
  1783. PROGLOG("getWorkUnitsSorted(LightWeight) done");
  1784. IArrayOf<IEspECLWorkunitLW> results;
  1785. ForEach(*it)
  1786. {
  1787. IConstWorkUnitInfo& cw = it->query();
  1788. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1789. {
  1790. numWUs--;
  1791. continue;
  1792. }
  1793. // This test is presumably trying to remove the global workunit, though it's not the right way to do so (since it will mess up page counts etc)
  1794. const char* wuid = cw.queryWuid();
  1795. if (!looksLikeAWuid(wuid, 'W'))
  1796. {
  1797. numWUs--;
  1798. continue;
  1799. }
  1800. Owned<IEspECLWorkunitLW> info = createECLWorkunitLW("","");
  1801. info->setWuid(cw.queryWuid());
  1802. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1803. {
  1804. info->setStateDesc("<Hidden>");
  1805. results.append(*info.getClear());
  1806. continue;
  1807. }
  1808. SCMStringBuffer s;
  1809. info->setIsProtected(cw.isProtected() ? 1 : 0);
  1810. info->setJobName(cw.queryJobName());
  1811. info->setWuScope(cw.queryWuScope());
  1812. info->setOwner(cw.queryUser());
  1813. info->setClusterName(cw.queryClusterName());
  1814. info->setState(cw.getState());
  1815. info->setStateDesc(cw.queryStateDesc());
  1816. info->setAction(cw.getAction());
  1817. info->setActionDesc(cw.queryActionDesc());
  1818. info->setPriority(cw.getPriority());
  1819. info->setPriorityLevel(cw.getPriorityLevel());
  1820. info->setPriorityDesc(cw.queryPriorityDesc());
  1821. info->setTotalClusterTime(cw.getTotalThorTime());
  1822. WsWuDateTime dt;
  1823. cw.getTimeScheduled(dt);
  1824. if(dt.isValid())
  1825. info->setDateTimeScheduled(dt.getString(s).str());
  1826. IArrayOf<IEspApplicationValue> av;
  1827. Owned<IConstWUAppValueIterator> app(&cw.getApplicationValues());
  1828. ForEach(*app)
  1829. {
  1830. IConstWUAppValue& val=app->query();
  1831. Owned<IEspApplicationValue> t= createApplicationValue("","");
  1832. t->setApplication(val.queryApplication());
  1833. t->setName(val.queryName());
  1834. t->setValue(val.queryValue());
  1835. av.append(*t.getClear());
  1836. }
  1837. info->setApplicationValues(av);
  1838. results.append(*info.getClear());
  1839. }
  1840. resp.setNumWUs(numWUs);
  1841. if (results.length() > (aindex_t)pageSize)
  1842. results.pop();
  1843. resp.setWorkunits(results);
  1844. return;
  1845. }
  1846. class CArchivedWUsReader : public CInterface, implements IArchivedWUsReader
  1847. {
  1848. IEspContext& context;
  1849. unsigned pageFrom, pageSize;
  1850. StringAttr sashaServerIP;
  1851. unsigned sashaServerPort;
  1852. unsigned cacheMinutes;
  1853. StringBuffer filterStr;
  1854. ArchivedWuCache& archivedWuCache;
  1855. unsigned numberOfWUsReturned;
  1856. bool hasMoreWU;
  1857. void readDateFilters(const char* startDateReq, const char* endDateReq, StringBuffer& from, StringBuffer& to)
  1858. {
  1859. CDateTime timeFrom, timeTo;
  1860. if(notEmpty(endDateReq))
  1861. {//endDateReq example: 2015-08-26T14:26:00
  1862. unsigned year, month, day, hour, minute, second, nano;
  1863. timeTo.setString(endDateReq, NULL, true);
  1864. timeTo.getDate(year, month, day, true);
  1865. timeTo.getTime(hour, minute, second, nano, true);
  1866. to.setf("%4d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second);
  1867. }
  1868. if(isEmpty(startDateReq))
  1869. return;
  1870. timeFrom.setString(startDateReq, NULL, true);
  1871. if (timeFrom >= timeTo)
  1872. return;
  1873. unsigned year0, month0, day0, hour0, minute0, second0, nano0;
  1874. timeFrom.getDate(year0, month0, day0, true);
  1875. timeFrom.getTime(hour0, minute0, second0, nano0, true);
  1876. from.setf("%4d%02d%02d%02d%02d%02d", year0, month0, day0, hour0, minute0, second0);
  1877. return;
  1878. }
  1879. bool addToFilterString(const char *name, const char *value)
  1880. {
  1881. if (isEmpty(name) || isEmpty(value))
  1882. return false;
  1883. filterStr.append(';').append(name).append("=").append(value);
  1884. return true;
  1885. }
  1886. bool addToFilterString(const char *name, unsigned value)
  1887. {
  1888. if (isEmpty(name))
  1889. return false;
  1890. filterStr.append(';').append(name).append("=").append(value);
  1891. return true;
  1892. }
  1893. void setFilterString(IEspWUQueryRequest& req)
  1894. {
  1895. filterStr.set("0");
  1896. addToFilterString("wuid", req.getWuid());
  1897. addToFilterString("cluster", req.getCluster());
  1898. addToFilterString("owner", req.getOwner());
  1899. addToFilterString("jobName", req.getJobname());
  1900. addToFilterString("state", req.getState());
  1901. addToFilterString("timeFrom", req.getStartDate());
  1902. addToFilterString("timeTo", req.getEndDate());
  1903. addToFilterString("pageStart", pageFrom);
  1904. addToFilterString("pageSize", pageSize);
  1905. if (sashaServerIP && *sashaServerIP)
  1906. {
  1907. addToFilterString("sashaServerIP", sashaServerIP.get());
  1908. addToFilterString("sashaServerPort", sashaServerPort);
  1909. }
  1910. }
  1911. void setFilterStringLW(IEspWULightWeightQueryRequest& req)
  1912. {
  1913. filterStr.set("1");
  1914. addToFilterString("wuid", req.getWuid());
  1915. addToFilterString("cluster", req.getCluster());
  1916. addToFilterString("owner", req.getOwner());
  1917. addToFilterString("jobName", req.getJobName());
  1918. addToFilterString("state", req.getState());
  1919. addToFilterString("timeFrom", req.getStartDate());
  1920. addToFilterString("timeTo", req.getEndDate());
  1921. addToFilterString("pageStart", pageFrom);
  1922. addToFilterString("pageSize", pageSize);
  1923. if (sashaServerIP && *sashaServerIP)
  1924. {
  1925. addToFilterString("sashaServerIP", sashaServerIP.get());
  1926. addToFilterString("sashaServerPort", sashaServerPort);
  1927. }
  1928. }
  1929. void initSashaCommand(ISashaCommand* cmd)
  1930. {
  1931. cmd->setAction(SCA_LIST);
  1932. cmd->setOutputFormat("owner,jobname,cluster,state");
  1933. cmd->setOnline(false);
  1934. cmd->setArchived(true);
  1935. cmd->setStart(pageFrom);
  1936. cmd->setLimit(pageSize+1); //read an extra WU to check hasMoreWU
  1937. }
  1938. void setSashaCommand(IEspWUQueryRequest& req, ISashaCommand* cmd)
  1939. {
  1940. if (notEmpty(req.getWuid()))
  1941. cmd->addId(req.getWuid());
  1942. if (notEmpty(req.getCluster()))
  1943. cmd->setCluster(req.getCluster());
  1944. if (notEmpty(req.getOwner()))
  1945. cmd->setOwner(req.getOwner());
  1946. if (notEmpty(req.getJobname()))
  1947. cmd->setJobName(req.getJobname());
  1948. if (notEmpty(req.getState()))
  1949. cmd->setState(req.getState());
  1950. StringBuffer timeFrom, timeTo;
  1951. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  1952. if (timeFrom.length())
  1953. cmd->setAfter(timeFrom.str());
  1954. if (timeTo.length())
  1955. cmd->setBefore(timeTo.str());
  1956. return;
  1957. }
  1958. void setSashaCommandLW(IEspWULightWeightQueryRequest& req, ISashaCommand* cmd)
  1959. {
  1960. if (notEmpty(req.getWuid()))
  1961. cmd->addId(req.getWuid());
  1962. if (notEmpty(req.getCluster()))
  1963. cmd->setCluster(req.getCluster());
  1964. if (notEmpty(req.getOwner()))
  1965. cmd->setOwner(req.getOwner());
  1966. if (notEmpty(req.getJobName()))
  1967. cmd->setJobName(req.getJobName());
  1968. if (notEmpty(req.getState()))
  1969. cmd->setState(req.getState());
  1970. StringBuffer timeFrom, timeTo;
  1971. readDateFilters(req.getStartDate(), req.getEndDate(), timeFrom, timeTo);
  1972. if (timeFrom.length())
  1973. cmd->setAfter(timeFrom.str());
  1974. if (timeTo.length())
  1975. cmd->setBefore(timeTo.str());
  1976. return;
  1977. }
  1978. IEspECLWorkunit *createArchivedWUEntry(StringArray& wuDataArray, bool canAccess)
  1979. {
  1980. Owned<IEspECLWorkunit> info= createECLWorkunit();
  1981. info->setWuid(wuDataArray.item(0));
  1982. if (!canAccess)
  1983. {
  1984. info->setState("<Hidden>");
  1985. return info.getClear();
  1986. }
  1987. const char* owner = wuDataArray.item(1);
  1988. const char* jobName = wuDataArray.item(2);
  1989. const char* cluster = wuDataArray.item(3);
  1990. const char* state = wuDataArray.item(4);
  1991. if (notEmpty(owner))
  1992. info->setOwner(owner);
  1993. if (notEmpty(jobName))
  1994. info->setJobname(jobName);
  1995. if (notEmpty(cluster))
  1996. info->setCluster(cluster);
  1997. if (notEmpty(state))
  1998. info->setState(state);
  1999. return info.getClear();
  2000. }
  2001. IEspECLWorkunitLW *createArchivedLWWUEntry(StringArray& wuDataArray, bool canAccess)
  2002. {
  2003. Owned<IEspECLWorkunitLW> info= createECLWorkunitLW();
  2004. info->setWuid(wuDataArray.item(0));
  2005. if (!canAccess)
  2006. {
  2007. info->setStateDesc("<Hidden>");
  2008. return info.getClear();
  2009. }
  2010. const char* owner = wuDataArray.item(1);
  2011. const char* jobName = wuDataArray.item(2);
  2012. const char* cluster = wuDataArray.item(3);
  2013. const char* state = wuDataArray.item(4);
  2014. if (notEmpty(owner))
  2015. info->setOwner(owner);
  2016. if (notEmpty(jobName))
  2017. info->setJobName(jobName);
  2018. if (notEmpty(cluster))
  2019. info->setClusterName(cluster);
  2020. if (notEmpty(state))
  2021. info->setStateDesc(state);
  2022. return info.getClear();
  2023. }
  2024. static int compareWuids(IInterface * const *_a, IInterface * const *_b)
  2025. {
  2026. IEspECLWorkunit *a = *(IEspECLWorkunit **)_a;
  2027. IEspECLWorkunit *b = *(IEspECLWorkunit **)_b;
  2028. return strcmp(b->getWuid(), a->getWuid());
  2029. }
  2030. static int compareLWWuids(IInterface * const *_a, IInterface * const *_b)
  2031. {
  2032. IEspECLWorkunitLW *a = *(IEspECLWorkunitLW **)_a;
  2033. IEspECLWorkunitLW *b = *(IEspECLWorkunitLW **)_b;
  2034. return strcmp(b->getWuid(), a->getWuid());
  2035. }
  2036. public:
  2037. IMPLEMENT_IINTERFACE_USING(CInterface);
  2038. CArchivedWUsReader(IEspContext& _context, const char* _sashaServerIP, unsigned _sashaServerPort, ArchivedWuCache& _archivedWuCache,
  2039. unsigned _cacheMinutes, unsigned _pageFrom, unsigned _pageSize)
  2040. : context(_context), sashaServerIP(_sashaServerIP), sashaServerPort(_sashaServerPort),
  2041. archivedWuCache(_archivedWuCache), cacheMinutes(_cacheMinutes), pageFrom(_pageFrom), pageSize(_pageSize)
  2042. {
  2043. hasMoreWU = false;
  2044. numberOfWUsReturned = 0;
  2045. }
  2046. void getArchivedWUs(bool lightWeight, IEspWUQueryRequest& req, IEspWULightWeightQueryRequest& reqLW, IArrayOf<IEspECLWorkunit>& archivedWUs, IArrayOf<IEspECLWorkunitLW>& archivedLWWUs)
  2047. {
  2048. if (!lightWeight)
  2049. setFilterString(req);
  2050. else
  2051. setFilterStringLW(reqLW);
  2052. Owned<ArchivedWuCacheElement> cachedResults = archivedWuCache.lookup(context, filterStr, "AddWhenAvailable", cacheMinutes);
  2053. if (cachedResults)
  2054. {
  2055. hasMoreWU = cachedResults->m_hasNextPage;
  2056. numberOfWUsReturned = cachedResults->numWUsReturned;
  2057. if (!lightWeight && cachedResults->m_results.length())
  2058. {
  2059. ForEachItemIn(i, cachedResults->m_results)
  2060. archivedWUs.append(*LINK(&cachedResults->m_results.item(i)));
  2061. }
  2062. if (lightWeight && cachedResults->resultsLW.length())
  2063. {
  2064. ForEachItemIn(i, cachedResults->resultsLW)
  2065. archivedLWWUs.append(*LINK(&cachedResults->resultsLW.item(i)));
  2066. }
  2067. return;
  2068. }
  2069. SocketEndpoint ep;
  2070. if (sashaServerIP && *sashaServerIP)
  2071. ep.set(sashaServerIP, sashaServerPort);
  2072. else
  2073. getSashaNode(ep);
  2074. Owned<INode> sashaserver = createINode(ep);
  2075. Owned<ISashaCommand> cmd = createSashaCommand();
  2076. initSashaCommand(cmd);
  2077. if (!lightWeight)
  2078. setSashaCommand(req, cmd);
  2079. else
  2080. setSashaCommandLW(reqLW, cmd);
  2081. if (!cmd->send(sashaserver))
  2082. {
  2083. StringBuffer msg("Cannot connect to archive server at ");
  2084. sashaserver->endpoint().getUrlStr(msg);
  2085. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  2086. }
  2087. numberOfWUsReturned = cmd->numIds();
  2088. hasMoreWU = (numberOfWUsReturned > pageSize);
  2089. if (hasMoreWU)
  2090. numberOfWUsReturned--;
  2091. if (numberOfWUsReturned == 0)
  2092. return;
  2093. SecAccessFlags accessOwn, accessOthers;
  2094. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  2095. for (unsigned i=0; i<numberOfWUsReturned; i++)
  2096. {
  2097. const char *csline = cmd->queryId(i);
  2098. if (!csline || !*csline)
  2099. continue;
  2100. StringArray wuDataArray;
  2101. wuDataArray.appendList(csline, ",");
  2102. const char* wuid = wuDataArray.item(0);
  2103. if (isEmpty(wuid))
  2104. {
  2105. WARNLOG("Empty WUID in SCA_LIST response"); // JCS->KW - have u ever seen this happen?
  2106. continue;
  2107. }
  2108. const char* owner = wuDataArray.item(1);
  2109. bool canAccess = chooseWuAccessFlagsByOwnership(context.queryUserId(), owner, accessOwn, accessOthers) >= SecAccess_Read;
  2110. if (!lightWeight)
  2111. {
  2112. Owned<IEspECLWorkunit> info = createArchivedWUEntry(wuDataArray, canAccess);
  2113. archivedWUs.append(*info.getClear());
  2114. }
  2115. else
  2116. {
  2117. Owned<IEspECLWorkunitLW> info = createArchivedLWWUEntry(wuDataArray, canAccess);
  2118. archivedLWWUs.append(*info.getClear());
  2119. }
  2120. }
  2121. if (!lightWeight)
  2122. archivedWUs.sort(compareWuids);
  2123. else
  2124. archivedLWWUs.sort(compareLWWuids);
  2125. archivedWuCache.add(filterStr, "AddWhenAvailable", hasMoreWU, numberOfWUsReturned, archivedWUs, archivedLWWUs);
  2126. return;
  2127. };
  2128. bool getHasMoreWU() { return hasMoreWU; };
  2129. unsigned getNumberOfWUsReturned() { return numberOfWUsReturned; };
  2130. };
  2131. void doWUQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2132. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2133. {
  2134. unsigned pageStart = (unsigned) req.getPageStartFrom();
  2135. unsigned pageSize = (unsigned) req.getPageSize();
  2136. if(pageSize < 1)
  2137. pageSize=500;
  2138. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2139. cacheMinutes, pageStart, pageSize);
  2140. IArrayOf<IEspECLWorkunit> archivedWUs;
  2141. IArrayOf<IEspECLWorkunitLW> dummyWUs;
  2142. Owned<CWULightWeightQueryRequest> dummyReq = new CWULightWeightQueryRequest("WsWorkunits");
  2143. PROGLOG("getWorkUnitsFromArchive");
  2144. archiveWUsReader->getArchivedWUs(false, req, *dummyReq, archivedWUs, dummyWUs);
  2145. PROGLOG("getWorkUnitsFromArchive done");
  2146. resp.setWorkunits(archivedWUs);
  2147. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2148. resp.setType("archived only");
  2149. resp.setPageSize(pageSize);
  2150. resp.setPageStartFrom(pageStart+1);
  2151. resp.setPageEndAt(pageStart + archiveWUsReader->getNumberOfWUsReturned());
  2152. if(pageStart > 0)
  2153. { //This is not the first page;
  2154. resp.setFirst(false);
  2155. resp.setPrevPage((pageStart > pageSize) ? pageStart - pageSize: 0);
  2156. }
  2157. if (archiveWUsReader->getHasMoreWU())
  2158. resp.setNextPage(pageStart + pageSize);
  2159. return;
  2160. }
  2161. void doWULightWeightQueryFromArchive(IEspContext &context, const char* sashaServerIP, unsigned sashaServerPort,
  2162. ArchivedWuCache &archivedWuCache, unsigned cacheMinutes, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2163. {
  2164. int pageStart = 0;
  2165. int pageSize=500;
  2166. if (!req.getPageStartFrom_isNull())
  2167. pageStart = req.getPageStartFrom();
  2168. if (!req.getPageSize_isNull())
  2169. pageSize = req.getPageSize();
  2170. Owned<IArchivedWUsReader> archiveWUsReader = new CArchivedWUsReader(context, sashaServerIP, sashaServerPort, archivedWuCache,
  2171. cacheMinutes, pageStart, pageSize);
  2172. Owned<CWUQueryRequest> dummyReq = new CWUQueryRequest("WsWorkunits");
  2173. IArrayOf<IEspECLWorkunit> dummyWUs;
  2174. IArrayOf<IEspECLWorkunitLW> archivedWUs;
  2175. PROGLOG("getWorkUnitsFromArchive(LightWeight)");
  2176. archiveWUsReader->getArchivedWUs(true, *dummyReq, req, dummyWUs, archivedWUs);
  2177. PROGLOG("getWorkUnitsFromArchive(LightWeight) done");
  2178. resp.setWorkunits(archivedWUs);
  2179. resp.setNumWUs(archiveWUsReader->getNumberOfWUsReturned());
  2180. return;
  2181. }
  2182. bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  2183. {
  2184. try
  2185. {
  2186. StringBuffer wuidStr = req.getWuid();
  2187. const char* wuid = wuidStr.trim().str();
  2188. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2189. doWUQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2190. else if(notEmpty(wuid) && looksLikeAWuid(wuid, 'W'))
  2191. doWUQueryBySingleWuid(context, wuid, resp);
  2192. else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
  2193. doWUQueryByFile(context, req.getLogicalFile(), resp);
  2194. else
  2195. doWUQueryWithSort(context, req, resp);
  2196. resp.setState(req.getState());
  2197. resp.setCluster(req.getCluster());
  2198. resp.setRoxieCluster(req.getRoxieCluster());
  2199. resp.setOwner(req.getOwner());
  2200. resp.setStartDate(req.getStartDate());
  2201. resp.setEndDate(req.getEndDate());
  2202. double version = context.getClientVersion();
  2203. StringBuffer basicQuery;
  2204. addToQueryString(basicQuery, "State", req.getState());
  2205. addToQueryString(basicQuery, "Cluster", req.getCluster());
  2206. addToQueryString(basicQuery, "Owner", req.getOwner());
  2207. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  2208. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  2209. if (version > 1.25 && req.getLastNDays() > -1)
  2210. addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
  2211. addToQueryString(basicQuery, "ECL", req.getECL());
  2212. addToQueryString(basicQuery, "Jobname", req.getJobname());
  2213. addToQueryString(basicQuery, "Type", req.getType());
  2214. if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
  2215. addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
  2216. resp.setFilters(basicQuery.str());
  2217. if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
  2218. {
  2219. resp.setSortby(req.getSortby());
  2220. addToQueryString(basicQuery, "Sortby", req.getSortby());
  2221. if (req.getDescending())
  2222. {
  2223. resp.setDescending(req.getDescending());
  2224. addToQueryString(basicQuery, "Descending", "1");
  2225. }
  2226. }
  2227. resp.setBasicQuery(basicQuery.str());
  2228. StringBuffer s;
  2229. if(notEmpty(req.getECL()))
  2230. resp.setECL(Utils::url_encode(req.getECL(), s).str());
  2231. if(notEmpty(req.getJobname()))
  2232. resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
  2233. }
  2234. catch(IException* e)
  2235. {
  2236. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2237. }
  2238. return true;
  2239. }
  2240. bool CWsWorkunitsEx::onWULightWeightQuery(IEspContext &context, IEspWULightWeightQueryRequest & req, IEspWULightWeightQueryResponse & resp)
  2241. {
  2242. try
  2243. {
  2244. if (req.getType() && strieq(req.getType(), "archived workunits"))
  2245. doWULightWeightQueryFromArchive(context, sashaServerIp.get(), sashaServerPort, *archivedWuCache, awusCacheMinutes, req, resp);
  2246. else
  2247. doWULightWeightQueryWithSort(context, req, resp);
  2248. }
  2249. catch(IException* e)
  2250. {
  2251. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2252. }
  2253. return true;
  2254. }
  2255. ITypeInfo * containsSingleSimpleFieldBlankXPath(IResultSetMetaData * meta)
  2256. {
  2257. if (meta->getColumnCount() != 1)
  2258. return NULL;
  2259. CResultSetMetaData * castMeta = static_cast<CResultSetMetaData *>(meta);
  2260. const char * xpath = castMeta->queryXPath(0);
  2261. if (xpath && (*xpath == 0))
  2262. {
  2263. return castMeta->queryType(0);
  2264. }
  2265. return NULL;
  2266. }
  2267. void csvSplitXPath(const char *xpath, StringBuffer &s, const char *&name, const char **childname=NULL)
  2268. {
  2269. if (!xpath)
  2270. return;
  2271. const char * slash = strchr(xpath, '/');
  2272. if (!slash)
  2273. {
  2274. name = xpath;
  2275. if (childname)
  2276. *childname = NULL;
  2277. }
  2278. else
  2279. {
  2280. if (!childname || strchr(slash+1, '/')) //output ignores xpaths that are too deep
  2281. return;
  2282. name = s.clear().append(slash-xpath, xpath).str();
  2283. *childname = slash+1;
  2284. }
  2285. }
  2286. void getCSVHeaders(const IResultSetMetaData& metaIn, CommonCSVWriter* writer, unsigned& layer)
  2287. {
  2288. StringBuffer xname;
  2289. const CResultSetMetaData& cMeta = static_cast<const CResultSetMetaData &>(metaIn);
  2290. IFvDataSourceMetaData* meta = cMeta.getMeta();
  2291. int columnCount = metaIn.getColumnCount();
  2292. for (unsigned idx = 0; idx < columnCount; idx++)
  2293. {
  2294. const CResultSetColumnInfo& column = cMeta.getColumn(idx);
  2295. unsigned flag = column.flag;
  2296. const char * name = meta->queryName(idx);
  2297. const char * childname = NULL;
  2298. switch (flag)
  2299. {
  2300. case FVFFbeginif:
  2301. case FVFFendif:
  2302. break;
  2303. case FVFFbeginrecord:
  2304. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2305. writer->outputBeginNested(name, false, true);
  2306. break;
  2307. case FVFFendrecord:
  2308. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2309. writer->outputEndNested(name, true);
  2310. break;
  2311. case FVFFdataset:
  2312. {
  2313. childname = "Row";
  2314. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2315. ITypeInfo* singleFieldType = (name && *name && childname && *childname)
  2316. ? containsSingleSimpleFieldBlankXPath(column.childMeta.get()) : NULL;
  2317. if (!singleFieldType)
  2318. {
  2319. bool nameValid = (name && *name);
  2320. if (nameValid || (childname && *childname))
  2321. {
  2322. if (nameValid)
  2323. writer->outputBeginNested(name, false, true);
  2324. if (childname && *childname)
  2325. writer->outputBeginNested(childname, false, !nameValid);
  2326. const CResultSetMetaData *childMeta = static_cast<const CResultSetMetaData *>(column.childMeta.get());
  2327. getCSVHeaders(*childMeta, writer, ++layer);
  2328. layer--;
  2329. if (childname && *childname)
  2330. writer->outputEndNested(childname, !nameValid);
  2331. if (nameValid)
  2332. writer->outputEndNested(name, true);
  2333. }
  2334. }
  2335. break;
  2336. }
  2337. case FVFFblob: //for now FileViewer will output the string "[blob]"
  2338. {
  2339. Owned<ITypeInfo> stringType = makeStringType(UNKNOWN_LENGTH, NULL, NULL);
  2340. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2341. StringBuffer eclTypeName;
  2342. stringType->getECLType(eclTypeName);
  2343. writer->outputCSVHeader(name, eclTypeName.str());
  2344. }
  2345. break;
  2346. default:
  2347. {
  2348. ITypeInfo & type = *column.type;
  2349. if (type.getTypeCode() == type_set)
  2350. {
  2351. childname = "Item";
  2352. csvSplitXPath(meta->queryXPath(idx), xname, name, &childname);
  2353. writer->outputBeginNested(name, true, true);
  2354. writer->outputEndNested(name, true);
  2355. }
  2356. else
  2357. {
  2358. csvSplitXPath(meta->queryXPath(idx), xname, name);
  2359. StringBuffer eclTypeName;
  2360. type.getECLType(eclTypeName);
  2361. writer->outputCSVHeader(name, eclTypeName.str());
  2362. }
  2363. break;
  2364. }
  2365. }
  2366. }
  2367. }
  2368. unsigned getResultCSV(IStringVal& ret, INewResultSet* result, const char* name, __int64 start, unsigned& count)
  2369. {
  2370. unsigned headerLayer = 0;
  2371. CSVOptions csvOptions;
  2372. csvOptions.delimiter.set(",");
  2373. csvOptions.terminator.set("\n");
  2374. csvOptions.includeHeader = true;
  2375. Owned<CommonCSVWriter> writer = new CommonCSVWriter(XWFtrim, csvOptions);
  2376. const IResultSetMetaData & meta = result->getMetaData();
  2377. getCSVHeaders(meta, writer, headerLayer);
  2378. writer->finishCSVHeaders();
  2379. Owned<IResultSetCursor> cursor = result->createCursor();
  2380. count = writeResultCursorXml(*writer, cursor, name, start, count, NULL);
  2381. ret.set(writer->str());
  2382. return count;
  2383. }
  2384. void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin, bool xsd, ESPSerializationFormat fmt, const IProperties *xmlns)
  2385. {
  2386. if (!result)
  2387. return;
  2388. total=result->getNumRows();
  2389. if(bin)
  2390. count = getResultBin(mb, result, (unsigned)start, count);
  2391. else
  2392. {
  2393. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  2394. {
  2395. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  2396. IMPLEMENT_IINTERFACE;
  2397. virtual const char * str() const { UNIMPLEMENTED; }
  2398. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  2399. virtual void clear() { } // support appending only
  2400. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  2401. virtual unsigned length() const { return buffer.length(); };
  2402. MemoryBuffer & buffer;
  2403. } adaptor(mb);
  2404. if (fmt==ESPSerializationCSV)
  2405. count = getResultCSV(adaptor, result, name, (unsigned) start, count);
  2406. else if (fmt==ESPSerializationJSON)
  2407. count = getResultJSON(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL);
  2408. else
  2409. count = getResultXml(adaptor, result, name, (unsigned) start, count, (xsd) ? "myschema" : NULL, xmlns);
  2410. }
  2411. }
  2412. INewResultSet* createFilteredResultSet(INewResultSet* result, IArrayOf<IConstNamedValue>* filterBy)
  2413. {
  2414. if (!result || !filterBy || !filterBy->length())
  2415. return NULL;
  2416. Owned<IFilteredResultSet> filter = result->createFiltered();
  2417. const IResultSetMetaData &meta = result->getMetaData();
  2418. unsigned columnCount = meta.getColumnCount();
  2419. ForEachItemIn(i, *filterBy)
  2420. {
  2421. IConstNamedValue &item = filterBy->item(i);
  2422. const char *name = item.getName();
  2423. const char *value = item.getValue();
  2424. if (!name || !*name || !value || !*value)
  2425. continue;
  2426. for(unsigned col = 0; col < columnCount; col++)
  2427. {
  2428. SCMStringBuffer scmbuf;
  2429. meta.getColumnLabel(scmbuf, col);
  2430. if (strieq(scmbuf.str(), name))
  2431. {
  2432. filter->addFilter(col, value);
  2433. break;
  2434. }
  2435. }
  2436. }
  2437. return filter->create();
  2438. }
  2439. void getWsWuResult(IEspContext &context, const char* wuid, const char *name, const char *logical, unsigned index, __int64 start,
  2440. unsigned& count, __int64& total, IStringVal& resname, bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& mb,
  2441. WUState& wuState, bool xsd=true)
  2442. {
  2443. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2444. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  2445. if(!cw)
  2446. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid);
  2447. Owned<IConstWUResult> result;
  2448. if (notEmpty(name))
  2449. result.setown(cw->getResultByName(name));
  2450. else if (notEmpty(logical))
  2451. {
  2452. Owned<IConstWUResultIterator> it = &cw->getResults();
  2453. ForEach(*it)
  2454. {
  2455. IConstWUResult &r = it->query();
  2456. SCMStringBuffer filename;
  2457. if(strieq(r.getResultLogicalName(filename).str(), logical))
  2458. {
  2459. result.setown(LINK(&r));
  2460. break;
  2461. }
  2462. }
  2463. }
  2464. else
  2465. result.setown(cw->getResultBySequence(index));
  2466. if (!result)
  2467. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2468. if (!resname.length())
  2469. result->getResultName(resname);
  2470. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  2471. SCMStringBuffer logicalName;
  2472. result->getResultLogicalName(logicalName);
  2473. Owned<INewResultSet> rs;
  2474. if (logicalName.length())
  2475. {
  2476. rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->queryClusterName())); //MORE is this wrong cluster?
  2477. }
  2478. else
  2479. rs.setown(resultSetFactory->createNewResultSet(result, wuid));
  2480. if (!filterBy || !filterBy->length())
  2481. appendResultSet(mb, rs, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2482. else
  2483. {
  2484. Owned<INewResultSet> filteredResult = createFilteredResultSet(rs, filterBy);
  2485. appendResultSet(mb, filteredResult, name, start, count, total, bin, xsd, context.getResponseFormat(), result->queryResultXmlns());
  2486. }
  2487. wuState = cw->getState();
  2488. }
  2489. void checkFileSizeLimit(unsigned long xmlSize, unsigned long sizeLimit)
  2490. {
  2491. if ((sizeLimit > 0) && (xmlSize > sizeLimit))
  2492. throw MakeStringException(ECLWATCH_CANNOT_OPEN_FILE,
  2493. "The file size (%ld bytes) exceeds the size limit (%ld bytes). You may set 'Option > 1' or use 'Download_XML' link to get compressed file.",
  2494. xmlSize, sizeLimit);
  2495. }
  2496. void openSaveFile(IEspContext &context, int opt, __int64 sizeLimit, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
  2497. {
  2498. if (opt < 1)
  2499. {
  2500. checkFileSizeLimit(buf.length(), sizeLimit);
  2501. resp.setThefile(buf);
  2502. resp.setThefile_mimetype(origMimeType);
  2503. }
  2504. else if (opt < 2)
  2505. {
  2506. checkFileSizeLimit(buf.length(), sizeLimit);
  2507. StringBuffer headerStr("attachment;");
  2508. if (filename && *filename)
  2509. {
  2510. const char* pFileName = strrchr(filename, PATHSEPCHAR);
  2511. if (pFileName)
  2512. headerStr.appendf("filename=%s", pFileName+1);
  2513. else
  2514. headerStr.appendf("filename=%s", filename);
  2515. }
  2516. MemoryBuffer buf0;
  2517. unsigned i = 0;
  2518. char* p = (char*) buf.toByteArray();
  2519. while (i < buf.length())
  2520. {
  2521. if (p[0] != 10)
  2522. buf0.append(p[0]);
  2523. else
  2524. buf0.append(0x0d);
  2525. p++;
  2526. i++;
  2527. }
  2528. resp.setThefile(buf);
  2529. resp.setThefile_mimetype(origMimeType);
  2530. context.addCustomerHeader("Content-disposition", headerStr.str());
  2531. }
  2532. else
  2533. {
  2534. #ifndef _USE_ZLIB
  2535. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2536. #else
  2537. StringBuffer fileNameStr, headerStr("attachment;");
  2538. if (notEmpty(filename))
  2539. {
  2540. fileNameStr.append(filename);
  2541. headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
  2542. }
  2543. else
  2544. fileNameStr.append("file");
  2545. StringBuffer ifname;
  2546. ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
  2547. IZZIPor* Zipor = createZZIPor();
  2548. int ret = 0;
  2549. if (opt > 2)
  2550. ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
  2551. else
  2552. ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
  2553. releaseIZ(Zipor);
  2554. if (ret < 0)
  2555. {
  2556. Owned<IFile> rFile = createIFile(ifname.str());
  2557. if (rFile->exists())
  2558. rFile->remove();
  2559. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2560. }
  2561. Owned <IFile> rf = createIFile(ifname.str());
  2562. if (!rf->exists())
  2563. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2564. MemoryBuffer out;
  2565. Owned <IFileIO> fio = rf->open(IFOread);
  2566. read(fio, 0, (size32_t) rf->size(), out);
  2567. resp.setThefile(out);
  2568. fio.clear();
  2569. rf->remove();
  2570. resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
  2571. context.addCustomerHeader("Content-disposition", headerStr.str());
  2572. #endif
  2573. }
  2574. }
  2575. bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
  2576. {
  2577. try
  2578. {
  2579. StringBuffer wuidStr = req.getWuid();
  2580. const char* wuidIn = wuidStr.trim().str();
  2581. if (wuidIn && *wuidIn)
  2582. {
  2583. if (!looksLikeAWuid(wuidIn, 'W'))
  2584. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2585. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2586. }
  2587. StringAttr wuid(wuidIn);
  2588. if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  2589. {
  2590. Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
  2591. if (!registry)
  2592. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
  2593. Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
  2594. if (!query)
  2595. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
  2596. resp.setQuerySet(req.getQuerySet());
  2597. resp.setQueryName(query->queryProp("@name"));
  2598. resp.setQueryId(query->queryProp("@id"));
  2599. wuid.set(query->queryProp("@wuid"));
  2600. }
  2601. int opt = req.getOption();
  2602. if (!wuid.isEmpty())
  2603. {
  2604. VStringBuffer logMsg("WUFile: %s", wuid.str());
  2605. if (notEmpty(req.getType()))
  2606. logMsg.append(", ").append(req.getType());
  2607. if (opt > 1)
  2608. logMsg.append(", download gzip");
  2609. else if (opt > 0)
  2610. logMsg.append(", download");
  2611. PROGLOG("%s", logMsg.str());
  2612. resp.setWuid(wuid.get());
  2613. MemoryBuffer mb;
  2614. WsWuInfo winfo(context, wuid);
  2615. if (strieq(File_ArchiveQuery, req.getType()))
  2616. {
  2617. winfo.getWorkunitArchiveQuery(mb);
  2618. openSaveFile(context, opt, req.getSizeLimit(), "ArchiveQuery.xml", HTTP_TYPE_APPLICATION_XML, mb, resp);
  2619. }
  2620. else if (strieq(File_Cpp,req.getType()) && notEmpty(req.getName()))
  2621. {
  2622. winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb, opt > 0);
  2623. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2624. }
  2625. else if (strieq(File_DLL,req.getType()))
  2626. {
  2627. StringBuffer name;
  2628. winfo.getWorkunitDll(name, mb);
  2629. resp.setFileName(name.str());
  2630. resp.setDaliServer(daliServers.get());
  2631. openSaveFile(context, opt, req.getSizeLimit(), req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
  2632. }
  2633. else if (strieq(File_Res,req.getType()))
  2634. {
  2635. winfo.getWorkunitResTxt(mb);
  2636. openSaveFile(context, opt, req.getSizeLimit(), "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2637. }
  2638. else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
  2639. {
  2640. winfo.getWorkunitThorLog(req.getName(), mb);
  2641. openSaveFile(context, opt, req.getSizeLimit(), "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2642. }
  2643. else if (strieq(File_ThorSlaveLog,req.getType()))
  2644. {
  2645. StringBuffer logDir;
  2646. getConfigurationDirectory(directories, "log", "thor", req.getProcess(), logDir);
  2647. winfo.getWorkunitThorSlaveLog(req.getClusterGroup(), req.getIPAddress(), req.getLogDate(), logDir.str(), req.getSlaveNumber(), mb, false);
  2648. openSaveFile(context, opt, req.getSizeLimit(), "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2649. }
  2650. else if (strieq(File_EclAgentLog,req.getType()))
  2651. {
  2652. winfo.getWorkunitEclAgentLog(req.getName(), req.getProcess(), mb);
  2653. openSaveFile(context, opt, req.getSizeLimit(), "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2654. }
  2655. else if (strieq(File_XML,req.getType()) && notEmpty(req.getName()))
  2656. {
  2657. const char* name = req.getName();
  2658. const char* ptr = strrchr(name, '/');
  2659. if (ptr)
  2660. ptr++;
  2661. else
  2662. ptr = name;
  2663. winfo.getWorkunitAssociatedXml(name, req.getIPAddress(), req.getPlainText(), req.getDescription(), opt > 0, true, mb);
  2664. openSaveFile(context, opt, req.getSizeLimit(), ptr, HTTP_TYPE_APPLICATION_XML, mb, resp);
  2665. }
  2666. else if (strieq(File_XML,req.getType()) || strieq(File_WUECL,req.getType()))
  2667. {
  2668. StringBuffer mimeType, fileName;
  2669. if (strieq(File_WUECL,req.getType()))
  2670. {
  2671. fileName.setf("%s.ecl", wuid.get());
  2672. winfo.getWorkunitQueryShortText(mb);
  2673. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2674. }
  2675. else
  2676. {
  2677. fileName.setf("%s.xml", wuid.get());
  2678. winfo.getWorkunitXml(req.getPlainText(), mb);
  2679. if (opt < 2)
  2680. {
  2681. const char* plainText = req.getPlainText();
  2682. if (plainText && (!stricmp(plainText, "yes")))
  2683. mimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2684. else
  2685. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2686. }
  2687. else
  2688. {
  2689. mimeType.set(HTTP_TYPE_APPLICATION_XML);
  2690. }
  2691. }
  2692. openSaveFile(context, opt, req.getSizeLimit(), fileName.str(), mimeType.str(), mb, resp);
  2693. }
  2694. PROGLOG("%s -- done", logMsg.str());
  2695. }
  2696. }
  2697. catch(IException* e)
  2698. {
  2699. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2700. }
  2701. return true;
  2702. }
  2703. void CWsWorkunitsEx::readWUFile(const char *wuid, WsWuInfo &winfo, IConstWUFileOption &item, bool forDownload, MemoryBuffer &mb, StringBuffer &fileName, StringBuffer &fileMimeType)
  2704. {
  2705. CWUFileType fileType = item.getFileType();
  2706. switch (fileType)
  2707. {
  2708. case CWUFileType_ArchiveQuery:
  2709. winfo.getWorkunitArchiveQuery(mb);
  2710. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  2711. fileName.set("ArchiveQuery.xml");
  2712. break;
  2713. case CWUFileType_CPP:
  2714. {
  2715. const char *tail=pathTail(item.getName());
  2716. fileName.set(tail ? tail : item.getName());
  2717. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2718. winfo.getWorkunitCpp(item.getName(), item.getDescription(), item.getIPAddress(),mb, forDownload);
  2719. break;
  2720. }
  2721. case CWUFileType_DLL:
  2722. {
  2723. const char *tail=pathTail(item.getName());
  2724. fileName.set(tail ? tail : item.getName());
  2725. fileMimeType.set(HTTP_TYPE_OCTET_STREAM);
  2726. break;
  2727. }
  2728. case CWUFileType_Res:
  2729. winfo.getWorkunitResTxt(mb);
  2730. fileName.set("res.txt");
  2731. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2732. break;
  2733. case CWUFileType_ThorLog:
  2734. winfo.getWorkunitThorLog(item.getName(), mb);
  2735. fileName.set("thormaster.log");
  2736. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2737. break;
  2738. case CWUFileType_ThorSlaveLog:
  2739. {
  2740. StringBuffer logDir;
  2741. getConfigurationDirectory(directories, "log", "thor", item.getProcess(), logDir);
  2742. winfo.getWorkunitThorSlaveLog(item.getClusterGroup(), item.getIPAddress(), item.getLogDate(), logDir.str(), item.getSlaveNumber(), mb, false);
  2743. fileName.set("ThorSlave.log");
  2744. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2745. break;
  2746. }
  2747. case CWUFileType_EclAgentLog:
  2748. winfo.getWorkunitEclAgentLog(item.getName(), item.getProcess(), mb);
  2749. fileName.set("eclagent.log");
  2750. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2751. break;
  2752. case CWUFileType_XML:
  2753. {
  2754. StringBuffer name = item.getName();
  2755. if (!name.isEmpty())
  2756. {
  2757. const char *tail=pathTail(name.str());
  2758. fileName.set(tail ? tail : name.str());
  2759. winfo.getWorkunitAssociatedXml(fileName.str(), item.getIPAddress(), item.getPlainText(), item.getDescription(), forDownload, true, mb);
  2760. }
  2761. else
  2762. {
  2763. fileName.setf("%s.xml", wuid);
  2764. winfo.getWorkunitXml(item.getPlainText(), mb);
  2765. }
  2766. const char* plainText = item.getPlainText();
  2767. if (plainText && strieq(plainText, "yes"))
  2768. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2769. else
  2770. fileMimeType.set(HTTP_TYPE_APPLICATION_XML);
  2771. break;
  2772. }
  2773. case CWUFileType_WUECL:
  2774. fileName.setf("%s.ecl", wuid);
  2775. winfo.getWorkunitQueryShortText(mb);
  2776. fileMimeType.set(HTTP_TYPE_TEXT_PLAIN);
  2777. break;
  2778. default:
  2779. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Unsupported file type %d.", fileType);
  2780. }
  2781. }
  2782. void CWsWorkunitsEx::zipAFolderToMB(const char *folderToZIP, const char *zipFileName, bool gzip, MemoryBuffer &mb)
  2783. {
  2784. StringBuffer folderToZIPEx, zipFileNameWithPath, zipCommand;
  2785. zipFileNameWithPath.set(zipFolder).append(zipFileName);
  2786. folderToZIPEx.set(folderToZIP).append("/*");
  2787. {
  2788. Owned<IFile> oldZIPFile = createIFile(zipFileNameWithPath.str());
  2789. if (oldZIPFile->exists())
  2790. oldZIPFile->remove();
  2791. }
  2792. if (!gzip)
  2793. zipCommand.appendf("zip -j %s %s", zipFileNameWithPath.str(), folderToZIPEx.str());
  2794. else
  2795. zipCommand.appendf("tar -czf %s %s", zipFileNameWithPath.str(), folderToZIPEx.str());
  2796. if (system(zipCommand.str()) != 0)
  2797. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Failed to execute system command %s. Please make sure that zip utility is installed.", zipCommand.str());
  2798. Owned<IFile> f = createIFile(zipFileNameWithPath.str());
  2799. Owned<IFileIO> io = f->open(IFOread);
  2800. void * data = mb.reserve((unsigned)io->size());
  2801. size32_t read = io->read(0, (unsigned)io->size(), data);
  2802. mb.setLength(read);
  2803. io->close();
  2804. f->remove();
  2805. }
  2806. void CWsWorkunitsEx::setAttachmentFileName(IEspContext &context, const char *fileName)
  2807. {
  2808. VStringBuffer headerStr("attachment;filename=%s", fileName);
  2809. context.addCustomerHeader("Content-disposition", headerStr.str());
  2810. }
  2811. bool CWsWorkunitsEx::onWUDownloadFiles(IEspContext &context, IEspWUDownloadFilesRequest &req, IEspWUDownloadFilesResponse &resp)
  2812. {
  2813. try
  2814. {
  2815. StringBuffer wuid = req.getWuid();
  2816. if (wuid.trim().isEmpty())
  2817. {
  2818. StringBuffer querySet = req.getQuerySet();
  2819. StringBuffer queryReq = req.getQuery();
  2820. if (queryReq.trim().isEmpty() || querySet.trim().isEmpty())
  2821. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WU ID or QuerySet/Query not specified");
  2822. Owned<IPropertyTree> registry = getQueryRegistry(querySet.str(), false);
  2823. if (!registry)
  2824. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", querySet.str());
  2825. Owned<IPropertyTree> query = resolveQueryAlias(registry, queryReq.str());
  2826. if (!query)
  2827. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", queryReq.str());
  2828. resp.setQuerySet(querySet.str());
  2829. resp.setQueryName(query->queryProp("@name"));
  2830. resp.setQueryId(query->queryProp("@id"));
  2831. wuid.set(query->queryProp("@wuid"));
  2832. }
  2833. if (!looksLikeAWuid(wuid, 'W'))
  2834. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID");
  2835. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  2836. IArrayOf<IConstWUFileOption> &wuFileOptions = req.getWUFileOptions();
  2837. if (!wuFileOptions.ordinality())
  2838. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No WU file specified");
  2839. CWUFileDownloadOption opt = req.getDownloadOption();
  2840. if ((wuFileOptions.length() > 1) && ((opt == CWUFileDownloadOption_OriginalText) || (opt == CWUFileDownloadOption_Attachment)))
  2841. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cannot download multiple files without zip");
  2842. Owned<IFile> zipDir;
  2843. StringBuffer folderToZIP, zipFileName;
  2844. if ((opt == CWUFileDownloadOption_ZIP) || (opt == CWUFileDownloadOption_GZIP))
  2845. {
  2846. StringBuffer userName;
  2847. if (context.queryUser())
  2848. userName.append(context.queryUser()->getName());
  2849. zipFileName.set("WUFiles_").append(wuid.str());
  2850. folderToZIP.set(zipFolder).append(zipFileName.str()).append('_').append(userName.str());
  2851. if (opt == CWUFileDownloadOption_ZIP)
  2852. zipFileName.append(".zip");
  2853. else
  2854. zipFileName.append(".gzip");
  2855. zipDir.setown(createIFile(folderToZIP));
  2856. if (!zipDir->exists())
  2857. zipDir->createDirectory();
  2858. else
  2859. cleanZAPFolder(zipDir, false);
  2860. }
  2861. resp.setWuid(wuid.str());
  2862. WsWuInfo winfo(context, wuid.str());
  2863. ForEachItemIn(i, wuFileOptions)
  2864. {
  2865. IConstWUFileOption &item = wuFileOptions.item(i);
  2866. MemoryBuffer mb;
  2867. StringBuffer downloadFileName, downloadFileMimeType;
  2868. readWUFile(wuid.str(), winfo, item, opt != CWUFileDownloadOption_OriginalText, mb, downloadFileName, downloadFileMimeType);
  2869. if (item.getFileType() == CWUFileType_DLL)
  2870. {
  2871. StringBuffer name;
  2872. winfo.getWorkunitDll(name, mb);
  2873. resp.setFileName(name.str());
  2874. resp.setDaliServer(daliServers.get());
  2875. }
  2876. if ((opt == CWUFileDownloadOption_OriginalText) || (opt == CWUFileDownloadOption_Attachment))
  2877. {
  2878. checkFileSizeLimit(mb.length(), item.getSizeLimit());
  2879. resp.setThefile(mb);
  2880. resp.setThefile_mimetype(downloadFileMimeType.str());
  2881. if (opt == CWUFileDownloadOption_Attachment)
  2882. setAttachmentFileName(context, downloadFileName.str());
  2883. break;
  2884. }
  2885. else
  2886. {
  2887. StringBuffer aZIPFile = folderToZIP;
  2888. aZIPFile.append(PATHSEPCHAR).append(downloadFileName.str());
  2889. Owned<IFile> wuIFile = createIFile(aZIPFile.str());
  2890. Owned<IFileIO> wuIFileIO = wuIFile->open(IFOcreate);
  2891. if (wuIFileIO)
  2892. wuIFileIO->write(0, mb.length(), mb.bufferBase());
  2893. }
  2894. }
  2895. if ((opt == CWUFileDownloadOption_ZIP) || (opt == CWUFileDownloadOption_GZIP))
  2896. {
  2897. MemoryBuffer mb;
  2898. zipAFolderToMB(folderToZIP.str(), zipFileName.str(), opt == CWUFileDownloadOption_GZIP, mb);
  2899. //Remove the temporary files and the folder
  2900. cleanZAPFolder(zipDir, true);
  2901. resp.setThefile(mb);
  2902. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  2903. setAttachmentFileName(context, zipFileName.str());
  2904. }
  2905. }
  2906. catch(IException* e)
  2907. {
  2908. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2909. }
  2910. return true;
  2911. }
  2912. bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
  2913. {
  2914. try
  2915. {
  2916. StringBuffer wuidStr = req.getWuid();
  2917. const char* wuidIn = wuidStr.trim().str();
  2918. if (wuidIn && *wuidIn)
  2919. {
  2920. if (!looksLikeAWuid(wuidIn, 'W'))
  2921. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuidIn);
  2922. ensureWsWorkunitAccess(context, wuidIn, SecAccess_Read);
  2923. }
  2924. MemoryBuffer mb;
  2925. __int64 total=0;
  2926. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2927. unsigned count = req.getCount(), requested=count;
  2928. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  2929. SCMStringBuffer name;
  2930. if(strieq(req.getFormat(),"csv"))
  2931. context.setResponseFormat(ESPSerializationCSV);
  2932. WUState wuState = WUStateUnknown;
  2933. bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
  2934. if (notEmpty(wuidIn) && notEmpty(req.getResultName()))
  2935. {
  2936. PROGLOG("WUResultBin: wuid %s, ResultName %s", wuidIn, req.getResultName());
  2937. getWsWuResult(context, wuidIn, req.getResultName(), NULL, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2938. }
  2939. else if (notEmpty(wuidIn) && (req.getSequence() >= 0))
  2940. {
  2941. PROGLOG("WUResultBin: wuid %s, Sequence %d", wuidIn, req.getSequence());
  2942. getWsWuResult(context, wuidIn, NULL, NULL, req.getSequence(), start, count, total, name, bin,filterBy, mb, wuState);
  2943. }
  2944. else if (notEmpty(req.getLogicalName()))
  2945. {
  2946. const char* logicalName = req.getLogicalName();
  2947. StringBuffer wuid;
  2948. getWuidFromLogicalFileName(context, logicalName, wuid);
  2949. if (!wuid.length())
  2950. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
  2951. PROGLOG("WUResultBin: %s", req.getLogicalName());
  2952. getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, filterBy, mb, wuState);
  2953. }
  2954. else
  2955. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2956. if(strieq(req.getFormat(),"csv"))
  2957. {
  2958. resp.setResult(mb);
  2959. resp.setResult_mimetype("text/csv");
  2960. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.csv");
  2961. }
  2962. else if(stricmp(req.getFormat(),"xls")==0)
  2963. {
  2964. Owned<IProperties> params(createProperties());
  2965. params->setProp("showCount",0);
  2966. StringBuffer xml;
  2967. xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
  2968. if (xml.length() > MAXXLSTRANSFER)
  2969. throw MakeStringException(ECLWATCH_TOO_BIG_DATA_SET, "The data set is too big to be converted to an Excel file. Please use the gzip link to download a compressed XML data file.");
  2970. StringBuffer xls;
  2971. xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
  2972. MemoryBuffer out;
  2973. out.setBuffer(xls.length(), (void*)xls.str());
  2974. resp.setResult(out);
  2975. resp.setResult_mimetype("application/vnd.ms-excel");
  2976. }
  2977. #ifdef _USE_ZLIB
  2978. else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
  2979. {
  2980. bool gzip = strieq(req.getFormat(),"gzip");
  2981. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2982. xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
  2983. VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
  2984. IZZIPor* Zipor = createZZIPor();
  2985. int ret = 0;
  2986. if (gzip)
  2987. ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
  2988. else
  2989. ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
  2990. releaseIZ(Zipor);
  2991. if (ret < 0)
  2992. {
  2993. Owned<IFile> rFile = createIFile(ifname.str());
  2994. if (rFile->exists())
  2995. rFile->remove();
  2996. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
  2997. }
  2998. MemoryBuffer out;
  2999. Owned <IFile> rf = createIFile(ifname.str());
  3000. if (rf->exists())
  3001. {
  3002. Owned <IFileIO> fio = rf->open(IFOread);
  3003. read(fio, 0, (size32_t) rf->size(), out);
  3004. resp.setResult(out);
  3005. }
  3006. if (gzip)
  3007. {
  3008. resp.setResult_mimetype("application/x-gzip");
  3009. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
  3010. }
  3011. else
  3012. {
  3013. resp.setResult_mimetype("application/zip");
  3014. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
  3015. }
  3016. Owned<IFile> rFile = createIFile(ifname.str());
  3017. if (rFile->exists())
  3018. rFile->remove();
  3019. }
  3020. #endif
  3021. else
  3022. {
  3023. resp.setResult(mb);
  3024. }
  3025. resp.setName(name.str());
  3026. resp.setWuid(wuidIn);
  3027. resp.setSequence(req.getSequence());
  3028. resp.setStart(start);
  3029. if (requested > total)
  3030. requested = (unsigned)total;
  3031. resp.setRequested(requested);
  3032. resp.setCount(count);
  3033. resp.setTotal(total);
  3034. resp.setFormat(req.getFormat());
  3035. }
  3036. catch(IException* e)
  3037. {
  3038. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3039. }
  3040. return true;
  3041. }
  3042. bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
  3043. {
  3044. try
  3045. {
  3046. StringBuffer wuid = req.getWuid();
  3047. WsWuHelpers::checkAndTrimWorkunit("WUResultSummary", wuid);
  3048. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3049. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3050. if(!cw)
  3051. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3052. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3053. PROGLOG("WUResultSummary: %s", wuid.str());
  3054. resp.setWuid(wuid.str());
  3055. resp.setSequence(req.getSequence());
  3056. IArrayOf<IEspECLResult> results;
  3057. Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
  3058. if (r)
  3059. {
  3060. WsWuInfo winfo(context, cw);
  3061. winfo.getResult(*r, results, 0);
  3062. resp.setFormat(r->getResultFormat());
  3063. resp.setResult(results.item(0));
  3064. }
  3065. }
  3066. catch(IException* e)
  3067. {
  3068. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3069. }
  3070. return true;
  3071. }
  3072. void getFileResults(IEspContext &context, const char* logicalName, const char* cluster,__int64 start, unsigned& count,__int64& total,
  3073. IStringVal& resname,bool bin, IArrayOf<IConstNamedValue>* filterBy, MemoryBuffer& buf, bool xsd)
  3074. {
  3075. Owned<IResultSetFactory> resultSetFactory = getSecResultSetFactory(context.querySecManager(), context.queryUser(), context.queryUserId(), context.queryPassword());
  3076. Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
  3077. if (!filterBy || !filterBy->length())
  3078. appendResultSet(buf, result, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  3079. else
  3080. {
  3081. Owned<INewResultSet> filteredResult = createFilteredResultSet(result, filterBy);
  3082. appendResultSet(buf, filteredResult, resname.str(), start, count, total, bin, xsd, context.getResponseFormat(), NULL);
  3083. }
  3084. }
  3085. void getWorkunitCluster(IEspContext &context, const char* wuid, SCMStringBuffer& cluster, bool checkArchiveWUs)
  3086. {
  3087. if (isEmpty(wuid))
  3088. return;
  3089. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3090. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  3091. if (cw)
  3092. cluster.set(cw->queryClusterName());
  3093. else if (checkArchiveWUs)
  3094. {
  3095. Owned<IPropertyTree> wuProps;// = getArchivedWorkUnitProperties(wuid);
  3096. if (wuProps)
  3097. cluster.set(wuProps->queryProp("@clusterName"));
  3098. }
  3099. }
  3100. bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
  3101. {
  3102. try
  3103. {
  3104. StringBuffer wuidStr = req.getWuid();
  3105. const char* wuid = wuidStr.trim().str();
  3106. if (wuid && *wuid)
  3107. {
  3108. if (!looksLikeAWuid(wuid, 'W'))
  3109. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Workunit ID: %s", wuid);
  3110. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  3111. }
  3112. MemoryBuffer mb;
  3113. SCMStringBuffer name;
  3114. __int64 total=0;
  3115. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  3116. unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
  3117. unsigned seq = req.getSequence();
  3118. bool inclXsd = !req.getSuppressXmlSchema();
  3119. VStringBuffer filter("start=%" I64F "d;count=%d", start, count);
  3120. addToQueryString(filter, "clusterName", req.getCluster(), ';');
  3121. addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
  3122. if (wuid && *wuid)
  3123. addToQueryString(filter, "wuid", wuid, ';');
  3124. addToQueryString(filter, "resultName", req.getResultName(), ';');
  3125. filter.appendf(";seq=%d;", seq);
  3126. if (inclXsd)
  3127. filter.append("xsd;");
  3128. if (context.getResponseFormat()==ESPSerializationJSON)
  3129. filter.append("json;");
  3130. IArrayOf<IConstNamedValue>* filterBy = &req.getFilterBy();
  3131. ForEachItemIn(i, *filterBy)
  3132. {
  3133. IConstNamedValue &item = filterBy->item(i);
  3134. const char *name = item.getName();
  3135. const char *value = item.getValue();
  3136. if (name && *name && value && *value)
  3137. addToQueryString(filter, name, value, ';');
  3138. }
  3139. const char* logicalName = req.getLogicalName();
  3140. const char* clusterName = req.getCluster();
  3141. const char* resultName = req.getResultName();
  3142. Owned<DataCacheElement> data;
  3143. if (!req.getBypassCachedResult())
  3144. data.setown(dataCache->lookup(context, filter, awusCacheMinutes));
  3145. if (data)
  3146. {
  3147. PROGLOG("Retrieving Cached WUResult: %s", filter.str());
  3148. mb.append(data->m_data.c_str());
  3149. name.set(data->m_name.c_str());
  3150. logicalName = data->m_logicalName.c_str();
  3151. wuid = data->m_wuid.c_str();
  3152. resultName = data->m_resultName.c_str();
  3153. seq = data->m_seq;
  3154. start = data->m_start;
  3155. count = data->m_rowcount;
  3156. requested = (unsigned)data->m_requested;
  3157. total = data->m_total;
  3158. if (notEmpty(logicalName))
  3159. resp.setLogicalName(logicalName);
  3160. else
  3161. {
  3162. if (notEmpty(wuid))
  3163. resp.setWuid(wuid);
  3164. resp.setSequence(seq);
  3165. }
  3166. }
  3167. else
  3168. {
  3169. PROGLOG("Retrieving WUResult: %s", filter.str());
  3170. WUState wuState = WUStateUnknown;
  3171. if(logicalName && *logicalName)
  3172. {
  3173. StringBuffer lwuid;
  3174. getWuidFromLogicalFileName(context, logicalName, lwuid);
  3175. SCMStringBuffer cluster;
  3176. if (lwuid.length())
  3177. getWorkunitCluster(context, lwuid.str(), cluster, true);
  3178. if (cluster.length())
  3179. {
  3180. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, filterBy, mb, inclXsd);
  3181. resp.setLogicalName(logicalName);
  3182. }
  3183. else if (notEmpty(clusterName))
  3184. {
  3185. getFileResults(context, logicalName, clusterName, start, count, total, name, false, filterBy, mb, inclXsd);
  3186. resp.setLogicalName(logicalName);
  3187. }
  3188. else
  3189. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
  3190. Owned<IWorkUnitFactory> wf = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3191. Owned<IConstWorkUnit> cw = wf->openWorkUnit(lwuid.str());
  3192. if (cw)
  3193. wuState = cw->getState();
  3194. }
  3195. else if (notEmpty(wuid) && notEmpty(resultName))
  3196. {
  3197. name.set(resultName);
  3198. getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3199. resp.setWuid(wuid);
  3200. resp.setSequence(seq);
  3201. }
  3202. else
  3203. {
  3204. getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, filterBy, mb, wuState, inclXsd);
  3205. resp.setWuid(wuid);
  3206. resp.setSequence(seq);
  3207. }
  3208. mb.append(0);
  3209. if (requested > total)
  3210. requested = (unsigned)total;
  3211. switch (wuState)
  3212. {
  3213. case WUStateCompleted:
  3214. case WUStateAborted:
  3215. case WUStateFailed:
  3216. case WUStateArchived:
  3217. dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
  3218. break;
  3219. }
  3220. }
  3221. resp.setName(name.str());
  3222. resp.setStart(start);
  3223. if (clusterName && *clusterName)
  3224. resp.setCluster(clusterName);
  3225. resp.setRequested(requested);
  3226. resp.setCount(count);
  3227. resp.setTotal(total);
  3228. resp.setResult(mb.toByteArray());
  3229. context.queryXslParameters()->setProp("escapeResults","1");
  3230. }
  3231. catch(IException* e)
  3232. {
  3233. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3234. }
  3235. return true;
  3236. }
  3237. void getScheduledWUs(IEspContext &context, const char *stateReq, const char *jobNameReq, const char *serverName, const char *eventName, IArrayOf<IEspScheduledWU> & results)
  3238. {
  3239. double version = context.getClientVersion();
  3240. if (notEmpty(serverName))
  3241. {
  3242. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3243. Owned<IScheduleReader> reader = getScheduleReader(serverName, eventName);
  3244. Owned<IScheduleReaderIterator> it(reader->getIterator());
  3245. while(it->isValidEventName())
  3246. {
  3247. StringBuffer ieventName;
  3248. it->getEventName(ieventName);
  3249. while(it->isValidEventText())
  3250. {
  3251. StringBuffer ieventText;
  3252. it->getEventText(ieventText);
  3253. while(it->isValidWuid())
  3254. {
  3255. StringBuffer wuid;
  3256. it->getWuid(wuid);
  3257. if (wuid.length())
  3258. {
  3259. bool match = true;
  3260. unsigned stateID = WUStateUnknown;
  3261. StringBuffer jobName, owner;
  3262. SCMStringBuffer state;
  3263. try
  3264. {
  3265. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3266. if (cw)
  3267. {
  3268. jobName.set(cw->queryJobName());
  3269. owner.set(cw->queryUser());
  3270. }
  3271. if (!isEmptyString(jobNameReq) && (jobName.isEmpty() || !WildMatch(jobName.str(), jobNameReq, true)))
  3272. match = false;
  3273. else if (!isEmptyString(stateReq))
  3274. {
  3275. if (!cw)
  3276. match = false;
  3277. else
  3278. {
  3279. if ((cw->getState() == WUStateScheduled) && cw->aborting())
  3280. {
  3281. stateID = WUStateAborting;
  3282. state.set("aborting");
  3283. }
  3284. else
  3285. {
  3286. stateID = cw->getState();
  3287. state.set(cw->queryStateDesc());
  3288. }
  3289. if (!strieq(stateReq, state.str()))
  3290. match = false;
  3291. }
  3292. }
  3293. }
  3294. catch (IException *e)
  3295. {
  3296. EXCLOG(e, "Get scheduled WUs");
  3297. e->Release();
  3298. match = false;
  3299. }
  3300. if (!match)
  3301. {
  3302. it->nextWuid();
  3303. continue;
  3304. }
  3305. Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
  3306. scheduledWU->setWuid(wuid.str());
  3307. scheduledWU->setCluster(serverName);
  3308. if (ieventName.length())
  3309. scheduledWU->setEventName(ieventName.str());
  3310. if (ieventText.str())
  3311. scheduledWU->setEventText(ieventText.str());
  3312. if (jobName.length())
  3313. scheduledWU->setJobName(jobName.str());
  3314. if (version >= 1.51)
  3315. {
  3316. if (owner.length())
  3317. scheduledWU->setOwner(owner.str());
  3318. if (state.length())
  3319. {
  3320. scheduledWU->setStateID(stateID);
  3321. scheduledWU->setState(state.str());
  3322. }
  3323. }
  3324. results.append(*scheduledWU.getLink());
  3325. }
  3326. it->nextWuid();
  3327. }
  3328. it->nextEventText();
  3329. }
  3330. it->nextEventName();
  3331. }
  3332. }
  3333. return;
  3334. }
  3335. bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
  3336. {
  3337. try
  3338. {
  3339. const char *clusterName = req.getCluster();
  3340. const char *eventName = req.getEventName();
  3341. const char *state = req.getState();
  3342. IArrayOf<IEspScheduledWU> results;
  3343. if(notEmpty(req.getPushEventName()))
  3344. resp.setPushEventName(req.getPushEventName());
  3345. if(notEmpty(req.getPushEventText()))
  3346. resp.setPushEventText(req.getPushEventText());
  3347. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  3348. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3349. Owned<IPropertyTree> root = &environment->getPTree();
  3350. unsigned i = 0;
  3351. Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
  3352. IArrayOf<IEspServerInfo> servers;
  3353. ForEach(*ic)
  3354. {
  3355. IPropertyTree &cluster = ic->query();
  3356. const char *iclusterName = cluster.queryProp("@name");
  3357. if (isEmpty(iclusterName))
  3358. continue;
  3359. if(isEmpty(clusterName))
  3360. getScheduledWUs(context, state, req.getJobName(), iclusterName, eventName, results);
  3361. else if (strieq(clusterName, iclusterName))
  3362. {
  3363. getScheduledWUs(context, state, req.getJobName(), clusterName, eventName, results);
  3364. resp.setClusterSelected(i+1);
  3365. }
  3366. Owned<IEspServerInfo> server = createServerInfo("");
  3367. server->setName(iclusterName);
  3368. servers.append(*server.getLink());
  3369. i++;
  3370. }
  3371. if (servers.length())
  3372. resp.setClusters(servers);
  3373. if (results.length())
  3374. resp.setWorkunits(results);
  3375. bool first=false;
  3376. StringBuffer Query("PageFrom=Scheduler");
  3377. appendUrlParameter(Query, "EventName", eventName, first);
  3378. appendUrlParameter(Query, "ECluster", clusterName, first);
  3379. resp.setQuery(Query.str());
  3380. }
  3381. catch(IException* e)
  3382. {
  3383. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3384. }
  3385. return true;
  3386. }
  3387. bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
  3388. {
  3389. try
  3390. {
  3391. if (req.getECL() && *req.getECL())
  3392. throw makeStringException(0, "WUExport no longer supports filtering by ECL text");
  3393. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3394. WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getJobname());
  3395. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
  3396. for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
  3397. {
  3398. Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str());
  3399. if (cw)
  3400. exportWorkUnitToXML(cw, xml, true, false, true);
  3401. }
  3402. xml.append("</Workunits>");
  3403. MemoryBuffer mb;
  3404. mb.setBuffer(xml.length(),(void*)xml.str());
  3405. resp.setExportData(mb);
  3406. resp.setExportData_mimetype(HTTP_TYPE_APPLICATION_XML);
  3407. }
  3408. catch(IException* e)
  3409. {
  3410. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3411. }
  3412. return true;
  3413. }
  3414. bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
  3415. {
  3416. try
  3417. {
  3418. StringBuffer wuid = req.getWuid();
  3419. WsWuHelpers::checkAndTrimWorkunit("WUListLocalFileRequired", wuid);
  3420. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3421. PROGLOG("WUListLocalFileRequired: %s", wuid.str());
  3422. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3423. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3424. if (!cw)
  3425. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid.str());
  3426. IArrayOf<IEspLogicalFileUpload> localFiles;
  3427. Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
  3428. ForEach(*it)
  3429. {
  3430. Owned<IConstLocalFileUpload> file = it->get();
  3431. if(!file)
  3432. continue;
  3433. Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
  3434. SCMStringBuffer s;
  3435. up->setType(file->queryType());
  3436. up->setSource(file->getSource(s).str());
  3437. up->setDestination(file->getDestination(s).str());
  3438. up->setEventTag(file->getEventTag(s).str());
  3439. localFiles.append(*up.getLink());
  3440. }
  3441. resp.setLocalFileUploads(localFiles);
  3442. }
  3443. catch(IException* e)
  3444. {
  3445. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3446. }
  3447. return true;
  3448. }
  3449. typedef enum wsEclTypes_
  3450. {
  3451. wsEclTypeUnknown,
  3452. xsdString,
  3453. xsdBoolean,
  3454. xsdDecimal,
  3455. xsdFloat,
  3456. xsdDouble,
  3457. xsdDuration,
  3458. xsdDateTime,
  3459. xsdTime,
  3460. xsdDate,
  3461. xsdYearMonth,
  3462. xsdYear,
  3463. xsdMonthDay,
  3464. xsdDay,
  3465. xsdMonth,
  3466. xsdHexBinary,
  3467. xsdBase64Binary,
  3468. xsdAnyURI,
  3469. xsdQName,
  3470. xsdNOTATION,
  3471. xsdNormalizedString,
  3472. xsdToken,
  3473. xsdLanguage,
  3474. xsdNMTOKEN,
  3475. xsdNMTOKENS,
  3476. xsdName,
  3477. xsdNCName,
  3478. xsdID,
  3479. xsdIDREF,
  3480. xsdIDREFS,
  3481. xsdENTITY,
  3482. xsdENTITIES,
  3483. xsdInteger,
  3484. xsdNonPositiveInteger,
  3485. xsdNegativeInteger,
  3486. xsdLong,
  3487. xsdInt,
  3488. xsdShort,
  3489. xsdByte,
  3490. xsdNonNegativeInteger,
  3491. xsdUnsignedLong,
  3492. xsdUnsignedInt,
  3493. xsdUnsignedShort,
  3494. xsdUnsignedByte,
  3495. xsdPositiveInteger,
  3496. tnsRawDataFile,
  3497. tnsCsvDataFile,
  3498. tnsEspStringArray,
  3499. tnsEspIntArray,
  3500. tnsXmlDataSet,
  3501. maxWsEclType
  3502. } wsEclType;
  3503. bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
  3504. {
  3505. try
  3506. {
  3507. StringBuffer wuid = req.getWuid();
  3508. WsWuHelpers::checkAndTrimWorkunit("WUAddLocalFileToWorkunit", wuid);
  3509. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Write);
  3510. resp.setWuid(wuid.str());
  3511. const char* varname = req.getName();
  3512. if (isEmpty(varname))
  3513. {
  3514. resp.setResult("Name is not defined!");
  3515. return true;
  3516. }
  3517. resp.setName(varname);
  3518. PROGLOG("WUAddLocalFileToWorkunit: %s, name %s", wuid.str(), varname);
  3519. wsEclType type = (wsEclType) req.getType();
  3520. const char *val = req.getVal();
  3521. unsigned len = req.getLength();
  3522. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3523. WorkunitUpdate wu(factory->updateWorkUnit(wuid.str()));
  3524. if (!wu)
  3525. {
  3526. resp.setResult("Workunit not found!");
  3527. return true;
  3528. }
  3529. Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
  3530. if (isEmpty(val))
  3531. val=req.getDefVal();
  3532. if (notEmpty(val))
  3533. {
  3534. switch (type)
  3535. {
  3536. case xsdBoolean:
  3537. wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
  3538. wuRslt->setResultStatus(ResultStatusSupplied);
  3539. break;
  3540. case xsdDecimal:
  3541. case xsdFloat:
  3542. case xsdDouble:
  3543. wuRslt->setResultReal(atof(val));
  3544. wuRslt->setResultStatus(ResultStatusSupplied);
  3545. break;
  3546. case xsdInteger:
  3547. case xsdNonPositiveInteger:
  3548. case xsdNegativeInteger:
  3549. case xsdLong:
  3550. case xsdInt:
  3551. case xsdShort:
  3552. case xsdByte:
  3553. case xsdNonNegativeInteger:
  3554. case xsdUnsignedLong:
  3555. case xsdUnsignedInt:
  3556. case xsdUnsignedShort:
  3557. case xsdUnsignedByte:
  3558. case xsdPositiveInteger:
  3559. wuRslt->setResultInt(_atoi64(val));
  3560. wuRslt->setResultStatus(ResultStatusSupplied);
  3561. break;
  3562. case tnsEspIntArray:
  3563. case tnsEspStringArray:
  3564. wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
  3565. break;
  3566. case tnsRawDataFile:
  3567. wuRslt->setResultRaw(len, val, ResultFormatRaw);
  3568. break;
  3569. case tnsXmlDataSet:
  3570. wuRslt->setResultRaw(len, val, ResultFormatXml);
  3571. break;
  3572. case tnsCsvDataFile:
  3573. case xsdBase64Binary: //tbd
  3574. case xsdHexBinary:
  3575. break;
  3576. default:
  3577. wuRslt->setResultString(val, len);
  3578. wuRslt->setResultStatus(ResultStatusSupplied);
  3579. break;
  3580. }
  3581. }
  3582. resp.setResult("Result has been set as required!");
  3583. }
  3584. catch(IException* e)
  3585. {
  3586. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3587. }
  3588. return true;
  3589. }
  3590. bool CWsWorkunitsEx::onWUGetGraphNameAndTypes(IEspContext &context,IEspWUGetGraphNameAndTypesRequest &req, IEspWUGetGraphNameAndTypesResponse &resp)
  3591. {
  3592. try
  3593. {
  3594. StringBuffer wuid = req.getWuid();
  3595. WsWuHelpers::checkAndTrimWorkunit("WUGraphQuery", wuid);
  3596. ensureWsWorkunitAccess(context, wuid.str(), SecAccess_Read);
  3597. PROGLOG("WUGetGraphNameAndTypes: %s", wuid.str());
  3598. StringBuffer type = req.getType();
  3599. WUGraphType graphType = GraphTypeAny;
  3600. if (type.trim().length())
  3601. graphType = getGraphTypeFromString(type.str());
  3602. IArrayOf<IEspNameAndType> graphNameAndTypes;
  3603. WsWuInfo winfo(context, wuid.str());
  3604. winfo.getWUGraphNameAndTypes(graphType, graphNameAndTypes);
  3605. resp.setGraphNameAndTypes(graphNameAndTypes);
  3606. }
  3607. catch(IException* e)
  3608. {
  3609. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3610. }
  3611. return true;
  3612. }
  3613. bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
  3614. {
  3615. try
  3616. {
  3617. StringBuffer wuid = req.getWuid();
  3618. WsWuHelpers::checkAndTrimWorkunit("WUProcessGraph", wuid);
  3619. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3620. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3621. if(!cw)
  3622. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3623. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3624. if (isEmpty(req.getName()))
  3625. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Please specify a graph name.");
  3626. Owned<IConstWUGraph> graph = cw->getGraph(req.getName());
  3627. if (!graph)
  3628. throw MakeStringException(ECLWATCH_GRAPH_NOT_FOUND, "Invalid graph name: %s for %s", req.getName(), wuid.str());
  3629. PROGLOG("WUProcessGraph: %s, Graph Name %s", wuid.str(), req.getName());
  3630. StringBuffer xml;
  3631. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
  3632. toXML(xgmml.get(), xml);
  3633. resp.setTheGraph(xml.str());
  3634. }
  3635. catch(IException* e)
  3636. {
  3637. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3638. }
  3639. return true;
  3640. }
  3641. bool isRunning(IConstWorkUnit &cw)
  3642. {
  3643. // MORE - move into workunit interface
  3644. switch (cw.getState())
  3645. {
  3646. case WUStateFailed:
  3647. case WUStateAborted:
  3648. case WUStateCompleted:
  3649. return false;
  3650. default:
  3651. return true;
  3652. }
  3653. }
  3654. void CWsWorkunitsEx::readGraph(IEspContext& context, const char* subGraphId, WUGraphIDType& id, bool running,
  3655. IConstWUGraph* graph, IArrayOf<IEspECLGraphEx>& graphs)
  3656. {
  3657. SCMStringBuffer name, label, type;
  3658. graph->getName(name);
  3659. graph->getLabel(label);
  3660. graph->getTypeName(type);
  3661. Owned<IEspECLGraphEx> g = createECLGraphEx("","");
  3662. g->setName(name.str());
  3663. g->setLabel(label.str());
  3664. g->setType(type.str());
  3665. WUGraphState graphState = graph->getState();
  3666. if (running && (WUGraphRunning == graphState))
  3667. {
  3668. g->setRunning(true);
  3669. g->setRunningId(id);
  3670. }
  3671. else if (context.getClientVersion() > 1.20)
  3672. {
  3673. if (WUGraphComplete == graphState)
  3674. g->setComplete(true);
  3675. else if (WUGraphFailed == graphState)
  3676. g->setFailed(true);
  3677. }
  3678. Owned<IPropertyTree> xgmml = graph->getXGMMLTree(true);
  3679. // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
  3680. // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
  3681. //JCSMORE this should be part of the API and therefore allow *only* the subtree to be pulled from the backend.
  3682. StringBuffer xml;
  3683. if (notEmpty(subGraphId))
  3684. {
  3685. VStringBuffer xpath("//node[@id='%s']", subGraphId);
  3686. toXML(xgmml->queryPropTree(xpath.str()), xml);
  3687. }
  3688. else
  3689. toXML(xgmml, xml);
  3690. g->setGraph(xml.str());
  3691. graphs.append(*g.getClear());
  3692. }
  3693. bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
  3694. {
  3695. try
  3696. {
  3697. StringBuffer wuid = req.getWuid();
  3698. WsWuHelpers::checkAndTrimWorkunit("WUGetGraph", wuid);
  3699. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3700. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3701. if(!cw)
  3702. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3703. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3704. WUGraphIDType id;
  3705. SCMStringBuffer runningGraph;
  3706. bool running = (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
  3707. IArrayOf<IEspECLGraphEx> graphs;
  3708. if (isEmpty(req.getGraphName())) // JCS->GS - is this really required??
  3709. {
  3710. PROGLOG("WUGetGraph: %s", wuid.str());
  3711. Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
  3712. ForEach(*it)
  3713. readGraph(context, req.getSubGraphId(), id, running, &it->query(), graphs);
  3714. }
  3715. else
  3716. {
  3717. PROGLOG("WUGetGraph: %s, Graph Name %s", wuid.str(), req.getGraphName());
  3718. Owned<IConstWUGraph> graph = cw->getGraph(req.getGraphName());
  3719. if (graph)
  3720. readGraph(context, req.getSubGraphId(), id, running, graph, graphs);
  3721. }
  3722. resp.setGraphs(graphs);
  3723. }
  3724. catch(IException* e)
  3725. {
  3726. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3727. }
  3728. return true;
  3729. }
  3730. bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
  3731. {
  3732. try
  3733. {
  3734. resp.setName(req.getName());
  3735. resp.setGraphName(req.getGraphName());
  3736. resp.setGraphType("eclwatch");
  3737. double version = context.getClientVersion();
  3738. if (version > 1.19)
  3739. resp.setSubGraphId(req.getSubGraphId());
  3740. if (version > 1.20)
  3741. resp.setSubGraphOnly(req.getSubGraphOnly());
  3742. }
  3743. catch(IException* e)
  3744. {
  3745. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3746. }
  3747. return true;
  3748. }
  3749. bool CWsWorkunitsEx::onWUDetails(IEspContext &context, IEspWUDetailsRequest &req, IEspWUDetailsResponse &resp)
  3750. {
  3751. try
  3752. {
  3753. StringBuffer wuid = req.getWUID();
  3754. WsWuHelpers::checkAndTrimWorkunit("WUDetails", wuid);
  3755. PROGLOG("WUDetails: %s", wuid.str());
  3756. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3757. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3758. if(!cw)
  3759. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3760. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3761. WUDetails wuDetails(cw, wuid);
  3762. wuDetails.processRequest(req, resp);
  3763. }
  3764. catch(IException* e)
  3765. {
  3766. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3767. }
  3768. return true;
  3769. }
  3770. bool CWsWorkunitsEx::onWUDetailsMeta(IEspContext &context, IEspWUDetailsMetaRequest &req, IEspWUDetailsMetaResponse &resp)
  3771. {
  3772. try
  3773. {
  3774. StringArray statistics;
  3775. for (unsigned i=StatisticKind::StKindAll+1; i<StatisticKind::StMax;++i)
  3776. {
  3777. const char * s = queryStatisticName((StatisticKind)i);
  3778. if (s && *s)
  3779. statistics.append(s);
  3780. }
  3781. resp.setStatistics(statistics);
  3782. StringArray attributes;
  3783. for (unsigned i=WuAttr::WAAll+1; i<WuAttr::WAMax; ++i)
  3784. {
  3785. const char * s = queryWuAttributeName((WuAttr)i);
  3786. if (s && *s)
  3787. attributes.append(s);
  3788. }
  3789. resp.setAttributes(attributes);
  3790. StringArray scopeTypes;
  3791. for (unsigned i=StatisticScopeType::SSTall+1; i<StatisticScopeType::SSTmax; ++i)
  3792. {
  3793. const char * s = queryScopeTypeName((StatisticScopeType)i);
  3794. if (s && *s)
  3795. scopeTypes.append(s);
  3796. }
  3797. resp.setScopeTypes(scopeTypes);
  3798. StringArray measures;
  3799. for (unsigned i=StatisticMeasure::SMeasureAll+1; i<StatisticMeasure::SMeasureMax; ++i)
  3800. {
  3801. const char *s = queryMeasureName((StatisticMeasure)i);
  3802. if (s && *s)
  3803. measures.append(s);
  3804. }
  3805. resp.setMeasures(measures);
  3806. }
  3807. catch(IException* e)
  3808. {
  3809. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3810. }
  3811. return true;
  3812. }
  3813. bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
  3814. {
  3815. try
  3816. {
  3817. StringBuffer wuid = req.getWuid();
  3818. WsWuHelpers::checkAndTrimWorkunit("WUGraphInfo", wuid);
  3819. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3820. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3821. if(!cw)
  3822. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3823. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  3824. resp.setWuid(wuid.str());
  3825. resp.setName(req.getName());
  3826. resp.setRunning(isRunning(*cw));
  3827. if (notEmpty(req.getGID()))
  3828. resp.setGID(req.getGID());
  3829. if(!req.getBatchWU_isNull())
  3830. resp.setBatchWU(req.getBatchWU());
  3831. }
  3832. catch(IException* e)
  3833. {
  3834. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3835. }
  3836. return true;
  3837. }
  3838. bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
  3839. {
  3840. try
  3841. {
  3842. StringBuffer wuid = req.getWuid();
  3843. WsWuHelpers::checkAndTrimWorkunit("WUGVCGraphInfo", wuid);
  3844. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3845. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3846. if(!cw)
  3847. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3848. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3849. resp.setWuid(wuid.str());
  3850. resp.setName(req.getName());
  3851. resp.setRunning(isRunning(*cw));
  3852. if (notEmpty(req.getGID()))
  3853. resp.setGID(req.getGID());
  3854. if(!req.getBatchWU_isNull())
  3855. resp.setBatchWU(req.getBatchWU());
  3856. StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
  3857. xml.appendf("<Graph id=\"%s\">", req.getName());
  3858. if (context.getClientVersion() > 1.17)
  3859. {
  3860. xml.append("<Subgraph>");
  3861. xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
  3862. xml.append("</Subgraph>");
  3863. }
  3864. xml.append("</Graph></Query></Endpoint></Control>");
  3865. resp.setTheGraph(xml.str());
  3866. }
  3867. catch(IException* e)
  3868. {
  3869. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3870. }
  3871. return true;
  3872. }
  3873. bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
  3874. {
  3875. try
  3876. {
  3877. StringBuffer wuid = req.getWuid();
  3878. WsWuHelpers::checkAndTrimWorkunit("WUGraphTiming", wuid);
  3879. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  3880. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str());
  3881. if(!cw)
  3882. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  3883. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  3884. PROGLOG("WUGraphTiming: %s", wuid.str());
  3885. resp.updateWorkunit().setWuid(wuid.str());
  3886. WsWuInfo winfo(context, cw);
  3887. IArrayOf<IConstECLTimingData> timingData;
  3888. winfo.getGraphTimingData(timingData);
  3889. resp.updateWorkunit().setTimingData(timingData);
  3890. }
  3891. catch(IException* e)
  3892. {
  3893. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3894. }
  3895. return true;
  3896. }
  3897. int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  3898. {
  3899. try
  3900. {
  3901. StringBuffer xml;
  3902. StringBuffer xslt;
  3903. if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
  3904. {
  3905. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  3906. Owned<IConstEnvironment> environment = factory->openEnvironment();
  3907. Owned<IPropertyTree> root = &environment->getPTree();
  3908. if(strieq(method,"WUQuery"))
  3909. {
  3910. SecAccessFlags accessOwn;
  3911. SecAccessFlags accessOthers;
  3912. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  3913. xml.append("<WUQuery>");
  3914. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  3915. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  3916. else
  3917. {
  3918. MapStringTo<bool> added;
  3919. Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
  3920. ForEach(*it)
  3921. {
  3922. const char *name = it->query().queryProp("@name");
  3923. if (notEmpty(name) && !added.getValue(name))
  3924. {
  3925. added.setValue(name, true);
  3926. appendXMLTag(xml, "Cluster", name);
  3927. }
  3928. }
  3929. }
  3930. xml.append("</WUQuery>");
  3931. xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
  3932. }
  3933. else if (strieq(method,"WUJobList"))
  3934. {
  3935. StringBuffer cluster, defaultProcess, range;
  3936. request->getParameter("Cluster", cluster);
  3937. request->getParameter("Process",defaultProcess);
  3938. request->getParameter("Range",range);
  3939. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
  3940. xml.append("<WUJobList>");
  3941. if (range.length())
  3942. appendXMLTag(xml, "Range", range.str());
  3943. if (clusterInfo)
  3944. {
  3945. const StringArray &thorInstances = clusterInfo->getThorProcesses();
  3946. ForEachItemIn(i, thorInstances)
  3947. {
  3948. const char* instance = thorInstances.item(i);
  3949. if (defaultProcess.length() && strieq(instance, defaultProcess.str()))
  3950. xml.append("<Cluster selected=\"1\">").append(instance).append("</Cluster>");
  3951. else
  3952. xml.append("<Cluster>").append(instance).append("</Cluster>");
  3953. }
  3954. }
  3955. xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
  3956. xml.append("</WUJobList>");
  3957. xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
  3958. response->addHeader("Expires", "0");
  3959. }
  3960. }
  3961. if (xslt.length() && xml.length())
  3962. {
  3963. StringBuffer html;
  3964. xsltTransform(xml.str(), xslt.str(), NULL, html);
  3965. response->setContent(html.str());
  3966. response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
  3967. response->send();
  3968. return 0;
  3969. }
  3970. }
  3971. catch(IException* e)
  3972. {
  3973. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3974. }
  3975. return onGetNotFound(context, request, response, service);
  3976. }
  3977. bool isDeploymentTypeCompressed(const char *type)
  3978. {
  3979. if (type && *type)
  3980. return (0==strncmp(type, "compressed_", strlen("compressed_")));
  3981. return false;
  3982. }
  3983. const char *skipCompressedTypeQualifier(const char *type)
  3984. {
  3985. if (isDeploymentTypeCompressed(type))
  3986. type += strlen("compressed_");
  3987. return type;
  3988. }
  3989. void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  3990. {
  3991. NewWsWorkunit wu(context);
  3992. StringAttr wuid(wu->queryWuid()); // NB queryWuid() not valid after workunit,clear()
  3993. wu->setAction(WUActionCompile);
  3994. StringBuffer name(req.getName());
  3995. if (!name.trim().length() && notEmpty(req.getFileName()))
  3996. splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
  3997. if (name.length())
  3998. wu->setJobName(name.str());
  3999. if (req.getObject().length())
  4000. {
  4001. MemoryBuffer mb;
  4002. const MemoryBuffer *uncompressed = &req.getObject();
  4003. if (isDeploymentTypeCompressed(req.getObjType()))
  4004. {
  4005. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4006. uncompressed = &mb;
  4007. }
  4008. StringBuffer text(uncompressed->length(), uncompressed->toByteArray());
  4009. wu.setQueryText(text.str());
  4010. }
  4011. if (req.getQueryMainDefinition())
  4012. wu.setQueryMain(req.getQueryMainDefinition());
  4013. if (req.getSnapshot())
  4014. wu->setSnapshot(req.getSnapshot());
  4015. if (!req.getResultLimit_isNull())
  4016. wu->setResultLimit(req.getResultLimit());
  4017. wu->commit();
  4018. wu.clear();
  4019. WsWuHelpers::submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false, false, NULL, NULL, &req.getDebugValues());
  4020. waitForWorkUnitToCompile(wuid.str(), req.getWait());
  4021. WsWuInfo winfo(context, wuid.str());
  4022. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4023. winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
  4024. name.clear();
  4025. if (notEmpty(resp.updateWorkunit().getJobname()))
  4026. origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
  4027. if (name.length()) //non generated user specified name, so override #Workunit('name')
  4028. {
  4029. WorkunitUpdate wx(&winfo.cw->lock());
  4030. wx->setJobName(name.str());
  4031. resp.updateWorkunit().setJobname(name.str());
  4032. }
  4033. PROGLOG("WUDeploy generates: %s", wuid.str());
  4034. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4035. }
  4036. StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
  4037. {
  4038. filename.append((name && *name) ? name : "workunit");
  4039. if (copy)
  4040. filename.append('_').append(copy);
  4041. if (notEmpty(ext))
  4042. filename.append(ext);
  4043. return filename;
  4044. }
  4045. inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
  4046. {
  4047. return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
  4048. }
  4049. void writeTempSharedObject(const MemoryBuffer &obj, const char *dir, StringBuffer &filename)
  4050. {
  4051. OwnedIFileIO io = createUniqueFile(dir, "query_copy_dll_", NULL, filename);
  4052. io->write(0, obj.length(), obj.toByteArray());
  4053. }
  4054. void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
  4055. {
  4056. StringBuffer name, ext;
  4057. if (srcpath && *srcpath)
  4058. splitFilename(srcpath, NULL, NULL, &name, &ext);
  4059. unsigned copy=0;
  4060. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
  4061. unsigned crc=0;
  4062. StringBuffer tempDllName;
  4063. const unsigned attempts = 3; // max attempts
  4064. for (unsigned i=0; i<attempts; i++)
  4065. {
  4066. while (checkFileExists(dllpath.str()))
  4067. {
  4068. if (crc==0)
  4069. crc = crc32(obj.toByteArray(), obj.length(), 0);
  4070. if (crc == crc_file(dllpath.str()))
  4071. {
  4072. DBGLOG("Workunit dll already exists: %s", dllpath.str());
  4073. if (tempDllName.length())
  4074. removeFileTraceIfFail(tempDllName);
  4075. return;
  4076. }
  4077. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
  4078. }
  4079. if (!tempDllName.length())
  4080. writeTempSharedObject(obj, dir, tempDllName);
  4081. try
  4082. {
  4083. renameFile(dllpath, tempDllName, false);
  4084. return;
  4085. }
  4086. catch (IException *e)
  4087. {
  4088. EXCLOG(e, "writeSharedObject"); //pretty small window for another copy of this dll to sneak by
  4089. e->Release();
  4090. }
  4091. }
  4092. throw MakeStringException(ECLWATCH_CANNOT_COPY_DLL, "Failed copying shared object %s", srcpath);
  4093. }
  4094. void deploySharedObject(IEspContext &context, StringBuffer &wuid, const char *filename, const char *cluster, const char *name, const MemoryBuffer &obj, const char *dir, const char *xml)
  4095. {
  4096. StringBuffer dllpath, dllname;
  4097. StringBuffer srcname(filename);
  4098. unsigned crc = 0;
  4099. Owned<IPropertyTree> srcxml;
  4100. if (xml && *xml)
  4101. {
  4102. srcxml.setown(createPTreeFromXMLString(xml));
  4103. if (srcxml && wuid.length())
  4104. {
  4105. crc = srcxml->getPropInt("Query[1]/Associated[1]/File[@type='dll'][1]/@crc", 0);
  4106. if (crc)
  4107. {
  4108. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4109. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4110. if (cw)
  4111. {
  4112. //is this a previous copy of same query, or a WUID collision?
  4113. if (cw->getHash() == (unsigned) srcxml->getPropInt64("@hash", 0))
  4114. {
  4115. Owned<IConstWUQuery> query = cw->getQuery();
  4116. if (query && crc == query->getQueryDllCrc())
  4117. return;
  4118. }
  4119. }
  4120. }
  4121. }
  4122. }
  4123. if (!srcname.length())
  4124. srcname.append(name).append(SharedObjectExtension);
  4125. writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
  4126. NewWsWorkunit wu(context, wuid); //duplicate wuid made unique
  4127. wuid.set(wu->queryWuid());
  4128. wu->setClusterName(cluster);
  4129. wu->commit();
  4130. StringBuffer dllXML;
  4131. if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
  4132. {
  4133. Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit(dllXML.str());
  4134. queryExtendedWU(wu)->copyWorkUnit(embeddedWU, true, true);
  4135. }
  4136. wu.associateDll(dllpath.str(), dllname.str());
  4137. if (name && *name)
  4138. wu->setJobName(name);
  4139. //clean slate, copy only select items from processed workunit xml
  4140. if (srcxml)
  4141. {
  4142. if (srcxml->hasProp("@jobName"))
  4143. wu->setJobName(srcxml->queryProp("@jobName"));
  4144. if (srcxml->hasProp("@token"))
  4145. wu->setSecurityToken(srcxml->queryProp("@token"));
  4146. if (srcxml->hasProp("Query/Text"))
  4147. wu.setQueryText(srcxml->queryProp("Query/Text"));
  4148. }
  4149. wu->setState(WUStateCompiled);
  4150. wu->commit();
  4151. wu.clear();
  4152. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4153. }
  4154. void CWsWorkunitsEx::deploySharedObjectReq(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml)
  4155. {
  4156. if (isEmpty(req.getFileName()))
  4157. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
  4158. const char *cluster = req.getCluster();
  4159. if (isEmpty(cluster))
  4160. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
  4161. const MemoryBuffer *uncompressed = &req.getObject();
  4162. MemoryBuffer mb;
  4163. if (isDeploymentTypeCompressed(req.getObjType()))
  4164. {
  4165. fastLZDecompressToBuffer(mb, req.getObject().bufferBase());
  4166. uncompressed = &mb;
  4167. }
  4168. StringBuffer wuid;
  4169. deploySharedObject(context, wuid, req.getFileName(), cluster, req.getName(), *uncompressed, dir, xml);
  4170. WsWuInfo winfo(context, wuid.str());
  4171. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  4172. PROGLOG("WUDeploy generates: %s", wuid.str());
  4173. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  4174. }
  4175. bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  4176. {
  4177. const char *type = skipCompressedTypeQualifier(req.getObjType());
  4178. try
  4179. {
  4180. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  4181. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  4182. if (notEmpty(req.getCluster()) && !isValidCluster(req.getCluster()))
  4183. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_NAME, "Invalid cluster name: %s", req.getCluster());
  4184. if (!type || !*type)
  4185. throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit unspecified object type.");
  4186. if (strieq(type, "archive")|| strieq(type, "ecl_text"))
  4187. deployEclOrArchive(context, req, resp);
  4188. else if (strieq(type, "shared_object"))
  4189. deploySharedObjectReq(context, req, resp, queryDirectory.str());
  4190. else
  4191. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unknown object type.", type);
  4192. }
  4193. catch(IException* e)
  4194. {
  4195. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4196. }
  4197. return true;
  4198. }
  4199. void CWsWorkunitsEx::createZAPFile(const char* fileName, size32_t len, const void* data)
  4200. {
  4201. if (!fileName || !*fileName)
  4202. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"File name not specified.");
  4203. Owned<IFile> wuInfoIFile = createIFile(fileName);
  4204. Owned<IFileIO> wuInfoIO = wuInfoIFile->open(IFOcreate);
  4205. if (wuInfoIO)
  4206. wuInfoIO->write(0, len, data);
  4207. }
  4208. void CWsWorkunitsEx::cleanZAPFolder(IFile* zipDir, bool removeFolder)
  4209. {
  4210. if (!zipDir)
  4211. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Invalid file interface for the zip folder.");
  4212. Owned<IDirectoryIterator> iter = zipDir->directoryFiles(NULL,false,false);
  4213. ForEach(*iter)
  4214. {
  4215. OwnedIFile thisFile = createIFile(iter->query().queryFilename());
  4216. if (thisFile->isFile() == foundYes)
  4217. thisFile->remove();
  4218. }
  4219. if (removeFolder)
  4220. zipDir->remove();
  4221. }
  4222. void CWsWorkunitsEx::addProcessLogfile(Owned<IConstWorkUnit>& cwu, WsWuInfo& winfo, const char* process, const char* path)
  4223. {
  4224. Owned<IPropertyTreeIterator> procs = cwu->getProcesses(process, NULL);
  4225. ForEach (*procs)
  4226. {
  4227. StringBuffer logSpec;
  4228. IPropertyTree& proc = procs->query();
  4229. proc.getProp("@log",logSpec);
  4230. if (!logSpec.length())
  4231. continue;
  4232. const char* processName = proc.queryName();
  4233. if (isEmpty(processName))
  4234. continue;
  4235. StringBuffer pid;
  4236. pid.appendf("%d",proc.getPropInt("@pid"));
  4237. MemoryBuffer mb;
  4238. try
  4239. {
  4240. if (strieq(process, "EclAgent"))
  4241. winfo.getWorkunitEclAgentLog(logSpec.str(), pid.str(), mb);
  4242. else if (strieq(process, "Thor"))
  4243. winfo.getWorkunitThorLog(logSpec.str(), mb);
  4244. }
  4245. catch(IException *e)
  4246. {
  4247. StringBuffer s;
  4248. e->errorMessage(s);
  4249. DBGLOG("Error accessing Process Log file %s: %s", logSpec.str(), s.str());
  4250. mb.append(s.str());
  4251. e->Release();
  4252. }
  4253. if (!mb.length())
  4254. continue;
  4255. const char * logName = logSpec.str();
  4256. for (const char * p=logSpec; *p; p++)
  4257. {
  4258. if (*p == '\\' || *p == '/')
  4259. logName = p+1;
  4260. }
  4261. VStringBuffer fileName("%s%c%s_%s", path, PATHSEPCHAR, processName, logName);
  4262. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4263. }
  4264. }
  4265. void CWsWorkunitsEx::addThorSlaveLogfile(Owned<IConstWorkUnit>& cwu, WsWuInfo& winfo, const char* path)
  4266. {
  4267. if (cwu->getWuidVersion() <= 0)
  4268. return;
  4269. StringAttr clusterName(cwu->queryClusterName());
  4270. if (clusterName.isEmpty()) //Cluster name may not be set yet
  4271. return;
  4272. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(clusterName.str());
  4273. if (!clusterInfo)
  4274. {
  4275. WARNLOG("Cannot find TargetClusterInfo for workunit %s", cwu->queryWuid());
  4276. return;
  4277. }
  4278. unsigned numberOfSlaveLogs = clusterInfo->getNumberOfSlaveLogs();
  4279. BoolHash uniqueProcesses;
  4280. Owned<IStringIterator> thorInstances = cwu->getProcesses("Thor");
  4281. ForEach (*thorInstances)
  4282. {
  4283. SCMStringBuffer processName;
  4284. thorInstances->str(processName);
  4285. if (processName.length() == 0)
  4286. continue;
  4287. bool* found = uniqueProcesses.getValue(processName.str());
  4288. if (found && *found)
  4289. continue;
  4290. uniqueProcesses.setValue(processName.str(), true);
  4291. StringBuffer groupName, logDir;
  4292. getClusterThorGroupName(groupName, processName.str());
  4293. if (groupName.isEmpty())
  4294. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Failed to get Thor Group Name for %s", processName.str());
  4295. getConfigurationDirectory(directories, "log", "thor", processName.str(), logDir);
  4296. Owned<IStringIterator> thorLogs = cwu->getLogs("Thor", processName.str());
  4297. ForEach (*thorLogs)
  4298. {
  4299. SCMStringBuffer logName;
  4300. thorLogs->str(logName);
  4301. if (logName.length() == 0)
  4302. continue;
  4303. const char* pStr = logName.str();
  4304. const char* ppStr = strstr(pStr, "/thormaster.");
  4305. if (!ppStr)
  4306. {
  4307. WARNLOG("Invalid thorlog entry in workunit xml: %s", logName.str());
  4308. continue;
  4309. }
  4310. ppStr += 12;
  4311. StringBuffer logDate = ppStr;
  4312. logDate.setLength(10);
  4313. for (unsigned i = 0; i < numberOfSlaveLogs; i++)
  4314. {
  4315. MemoryBuffer mb;
  4316. winfo.getWorkunitThorSlaveLog(groupName.str(), NULL, logDate.str(), logDir.str(), i+1, mb, false);
  4317. if (!mb.length())
  4318. continue;
  4319. VStringBuffer fileName("%s%c%s_thorslave.%d.%s.log", path, PATHSEPCHAR, processName.str(), i+1, logDate.str());
  4320. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4321. }
  4322. }
  4323. }
  4324. }
  4325. void CWsWorkunitsEx::createZAPWUInfoFile(IEspWUCreateZAPInfoRequest &req, Owned<IConstWorkUnit>& cwu, const char* pathNameStr)
  4326. {
  4327. StringBuffer sb;
  4328. sb.append("Workunit: ").append(cwu->queryWuid()).append("\r\n");
  4329. sb.append("User: ").append(cwu->queryUser()).append("\r\n");
  4330. sb.append("Build Version:").append(getBuildVersion()).append("\r\n");
  4331. sb.append("Cluster: ").append(cwu->queryClusterName()).append("\r\n");
  4332. if (req.getESPIPAddress())
  4333. sb.append("ESP: ").append(req.getESPIPAddress()).append("\r\n");
  4334. else
  4335. {
  4336. StringBuffer EspIP;
  4337. IpAddress ipaddr = queryHostIP();
  4338. ipaddr.getIpText(EspIP);
  4339. sb.append("ESP: ").append(EspIP.str()).append("\r\n");
  4340. }
  4341. if (req.getThorIPAddress())
  4342. sb.append("Thor: ").append(req.getThorIPAddress()).append("\r\n");
  4343. //Exceptions/Warnings/Info
  4344. Owned<IConstWUExceptionIterator> exceptions = &cwu->getExceptions();
  4345. StringBuffer info, warn, err, alert;
  4346. ForEach(*exceptions)
  4347. {
  4348. SCMStringBuffer temp;
  4349. switch (exceptions->query().getSeverity())
  4350. {
  4351. case SeverityInformation:
  4352. info.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4353. break;
  4354. case SeverityWarning:
  4355. warn.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4356. break;
  4357. case SeverityError:
  4358. err.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4359. break;
  4360. case SeverityAlert:
  4361. alert.append("\t").append(exceptions->query().getExceptionMessage(temp)).append("\r\n\r\n");
  4362. break;
  4363. }
  4364. }
  4365. if (err.length())
  4366. sb.append("Exceptions: ").append("\r\n").append(err);
  4367. if (warn.length())
  4368. sb.append("Warnings: ").append("\r\n").append(warn);
  4369. if (info.length())
  4370. sb.append("Information: ").append("\r\n").append(info);
  4371. if (alert.length())
  4372. sb.append("Alert: ").append("\r\n").append(alert);
  4373. //User provided Information
  4374. sb.append("Problem: ").append(req.getProblemDescription()).append("\r\n\r\n");
  4375. sb.append("What Changed: ").append(req.getWhatChanged()).append("\r\n\r\n");
  4376. sb.append("Timing: ").append(req.getWhereSlow()).append("\r\n\r\n");
  4377. VStringBuffer fileName("%s.txt", pathNameStr);
  4378. createZAPFile(fileName.str(), sb.length(), sb.str());
  4379. }
  4380. void CWsWorkunitsEx::createZAPWUXMLFile(WsWuInfo &winfo, const char* pathNameStr)
  4381. {
  4382. MemoryBuffer mb;
  4383. winfo.getWorkunitXml(NULL, mb);
  4384. VStringBuffer fileName("%s.xml", pathNameStr);
  4385. createZAPFile(fileName.str(), mb.length(), mb.bufferBase());
  4386. }
  4387. void CWsWorkunitsEx::createZAPECLQueryArchiveFiles(Owned<IConstWorkUnit>& cwu, const char* pathNameStr)
  4388. {
  4389. Owned<IConstWUQuery> query = cwu->getQuery();
  4390. if(!query)
  4391. return;
  4392. //Add archive if present
  4393. Owned<IConstWUAssociatedFileIterator> iter = &query->getAssociatedFiles();
  4394. ForEach(*iter)
  4395. {
  4396. IConstWUAssociatedFile & cur = iter->query();
  4397. SCMStringBuffer ssb, ip;
  4398. cur.getDescription(ssb);
  4399. if (!strieq(ssb.str(), "archive"))
  4400. continue;
  4401. cur.getName(ssb);
  4402. cur.getIp(ip);
  4403. if (!ssb.length() || !ip.length())
  4404. continue;
  4405. StringBuffer fileName, archiveContents;
  4406. try
  4407. {
  4408. SocketEndpoint ep(ip.str());
  4409. RemoteFilename rfn;
  4410. rfn.setRemotePath(ssb.str());
  4411. rfn.setIp(ep);
  4412. Owned<IFile> rFile = createIFile(rfn);
  4413. if (!rFile)
  4414. {
  4415. DBGLOG("Cannot open %s on %s", ssb.str(), ip.str());
  4416. continue;
  4417. }
  4418. archiveContents.loadFile(rFile);
  4419. }
  4420. catch (IException *e)
  4421. {
  4422. StringBuffer s;
  4423. e->errorMessage(s);
  4424. DBGLOG("Error accessing archive file %s: %s", ssb.str(), s.str());
  4425. archiveContents.insert(0, "Error accessing archive file ").appendf("%s: %s\r\n\r\n", ssb.str(), s.str());
  4426. e->Release();
  4427. }
  4428. fileName.setf("%s.archive", pathNameStr);
  4429. createZAPFile(fileName.str(), archiveContents.length(), archiveContents.str());
  4430. break;
  4431. }
  4432. //Add Query
  4433. SCMStringBuffer temp;
  4434. query->getQueryText(temp);
  4435. if (temp.length())
  4436. {
  4437. VStringBuffer fileName("%s.ecl", pathNameStr);
  4438. createZAPFile(fileName.str(), temp.length(), temp.str());
  4439. }
  4440. }
  4441. void CWsWorkunitsEx::createZAPWUGraphProgressFile(const char* wuid, const char* pathNameStr)
  4442. {
  4443. Owned<IPropertyTree> graphProgress = getWUGraphProgress(wuid, true);
  4444. if (graphProgress)
  4445. {
  4446. StringBuffer graphProgressXML;
  4447. toXML(graphProgress, graphProgressXML, 1, XML_Format);
  4448. VStringBuffer fileName("%s.graphprogress", pathNameStr);
  4449. createZAPFile(fileName.str(), graphProgressXML.length(), graphProgressXML.str());
  4450. }
  4451. }
  4452. bool CWsWorkunitsEx::onWUCreateZAPInfo(IEspContext &context, IEspWUCreateZAPInfoRequest &req, IEspWUCreateZAPInfoResponse &resp)
  4453. {
  4454. try
  4455. {
  4456. StringBuffer wuid = req.getWuid();
  4457. WsWuHelpers::checkAndTrimWorkunit("WUCreateZAPInfo", wuid);
  4458. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4459. Owned<IConstWorkUnit> cwu = factory->openWorkUnit(wuid.str());
  4460. if(!cwu.get())
  4461. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Cannot open workunit %s.", req.getWuid());
  4462. ensureWsWorkunitAccess(context, *cwu, SecAccess_Read);
  4463. PROGLOG("WUCreateZAPInfo: %s", wuid.str());
  4464. StringBuffer userName, nameStr, fileName;
  4465. StringBuffer zipFileName, zipFileNameWithPath, zipCommand, folderToZIP;
  4466. if (context.queryUser())
  4467. userName.append(context.queryUser()->getName());
  4468. nameStr.append("ZAPReport_").append(req.getWuid()).append('_').append(userName.str());
  4469. //create a folder for WU ZAP files
  4470. folderToZIP.append(zipFolder).append(nameStr.str());
  4471. Owned<IFile> zipDir = createIFile(folderToZIP.str());
  4472. if (!zipDir->exists())
  4473. zipDir->createDirectory();
  4474. else
  4475. cleanZAPFolder(zipDir, false);
  4476. //create WU ZAP files
  4477. VStringBuffer pathNameStr("%s/%s", folderToZIP.str(), nameStr.str());
  4478. createZAPWUInfoFile(req, cwu, pathNameStr.str());
  4479. createZAPECLQueryArchiveFiles(cwu, pathNameStr.str());
  4480. WsWuInfo winfo(context, cwu);
  4481. createZAPWUXMLFile(winfo, pathNameStr.str());
  4482. createZAPWUGraphProgressFile(req.getWuid(), pathNameStr.str());
  4483. addProcessLogfile(cwu, winfo, "EclAgent", folderToZIP.str());
  4484. addProcessLogfile(cwu, winfo, "Thor", folderToZIP.str());
  4485. if (req.getIncludeThorSlaveLog())
  4486. addThorSlaveLogfile(cwu, winfo, folderToZIP.str());
  4487. //Write out to ZIP file
  4488. const char* zipFName = req.getZAPFileName();
  4489. if (!zipFName || !*zipFName)
  4490. zipFileName.append(nameStr.str()).append(".zip");
  4491. else
  4492. {
  4493. zipFileName.set(zipFName);
  4494. const char* ext = pathExtension(zipFName);
  4495. if (!ext || !strieq(ext, ".zip"))
  4496. zipFileName.append(".zip");
  4497. }
  4498. zipFileNameWithPath.append(zipFolder).append(zipFileName.str());
  4499. pathNameStr.set(folderToZIP.str()).append("/*");
  4500. const char* password;
  4501. double version = context.getClientVersion();
  4502. if (version >= 1.70)
  4503. password = req.getZAPPassword();
  4504. else
  4505. password = req.getPassword();
  4506. if (password && *password)
  4507. zipCommand.appendf("zip -j --password %s %s %s", password, zipFileNameWithPath.str(), pathNameStr.str());
  4508. else
  4509. zipCommand.appendf("zip -j %s %s", zipFileNameWithPath.str(), pathNameStr.str());
  4510. int zipRet = system(zipCommand.str());
  4511. //Remove the temporary files and the folder
  4512. cleanZAPFolder(zipDir, true);
  4513. if (zipRet != 0)
  4514. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"Failed to execute system command 'zip'. Please make sure that zip utility is installed.");
  4515. //Download ZIP file to user
  4516. Owned<IFile> f = createIFile(zipFileNameWithPath.str());
  4517. Owned<IFileIO> io = f->open(IFOread);
  4518. MemoryBuffer mb;
  4519. void * data = mb.reserve((unsigned)io->size());
  4520. size32_t read = io->read(0, (unsigned)io->size(), data);
  4521. mb.setLength(read);
  4522. resp.setThefile(mb);
  4523. resp.setThefile_mimetype(HTTP_TYPE_OCTET_STREAM);
  4524. resp.setZAPFileName(zipFileName.str());
  4525. StringBuffer headerStr("attachment;filename=");
  4526. headerStr.append(zipFileName.str());
  4527. context.addCustomerHeader("Content-disposition", headerStr.str());
  4528. io->close();
  4529. f->remove();
  4530. }
  4531. catch(IException* e)
  4532. {
  4533. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4534. }
  4535. return true;
  4536. }
  4537. bool CWsWorkunitsEx::onWUGetZAPInfo(IEspContext &context, IEspWUGetZAPInfoRequest &req, IEspWUGetZAPInfoResponse &resp)
  4538. {
  4539. try
  4540. {
  4541. StringBuffer wuid = req.getWUID();
  4542. WsWuHelpers::checkAndTrimWorkunit("WUGetZAPInfo", wuid);
  4543. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4544. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  4545. if(!cw)
  4546. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT,"Cannot open workunit %s.",wuid.str());
  4547. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  4548. PROGLOG("WUGetZAPInfo: %s", wuid.str());
  4549. StringBuffer EspIP, ThorIP;
  4550. resp.setWUID(wuid.str());
  4551. resp.setBuildVersion(getBuildVersion());
  4552. IpAddress ipaddr = queryHostIP();
  4553. ipaddr.getIpText(EspIP);
  4554. resp.setESPIPAddress(EspIP.str());
  4555. //Get Archive
  4556. Owned<IConstWUQuery> query = cw->getQuery();
  4557. if(query)
  4558. {
  4559. SCMStringBuffer queryText;
  4560. query->getQueryText(queryText);
  4561. if (queryText.length() && isArchiveQuery(queryText.str()))
  4562. resp.setArchive(queryText.str());
  4563. }
  4564. //Get Thor IP
  4565. BoolHash uniqueProcesses;
  4566. Owned<IStringIterator> thorInstances = cw->getProcesses("Thor");
  4567. ForEach (*thorInstances)
  4568. {
  4569. SCMStringBuffer processName;
  4570. thorInstances->str(processName);
  4571. if (processName.length() < 1)
  4572. continue;
  4573. bool* found = uniqueProcesses.getValue(processName.str());
  4574. if (found && *found)
  4575. continue;
  4576. uniqueProcesses.setValue(processName.str(), true);
  4577. Owned<IStringIterator> thorLogs = cw->getLogs("Thor", processName.str());
  4578. ForEach (*thorLogs)
  4579. {
  4580. SCMStringBuffer logName;
  4581. thorLogs->str(logName);
  4582. if (!logName.length())
  4583. continue;
  4584. const char* thorIPPtr = NULL;
  4585. const char* ptr = logName.str();
  4586. while (ptr)
  4587. {
  4588. if (!thorIPPtr && (*ptr != '/'))
  4589. thorIPPtr = ptr;
  4590. else if (thorIPPtr && (*ptr == '/'))
  4591. break;
  4592. ptr++;
  4593. }
  4594. if (!thorIPPtr)
  4595. continue;
  4596. //Found a thor IP
  4597. if (ThorIP.length())
  4598. ThorIP.append(",");
  4599. if (!*ptr)
  4600. ThorIP.append(thorIPPtr);
  4601. else
  4602. ThorIP.append(ptr-thorIPPtr, thorIPPtr);
  4603. }
  4604. }
  4605. if (ThorIP.length())
  4606. resp.setThorIPAddress(ThorIP.str());
  4607. }
  4608. catch(IException* e)
  4609. {
  4610. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4611. }
  4612. return true;
  4613. }
  4614. bool CWsWorkunitsEx::onWUCheckFeatures(IEspContext &context, IEspWUCheckFeaturesRequest &req, IEspWUCheckFeaturesResponse &resp)
  4615. {
  4616. resp.setBuildVersionMajor(BUILD_VERSION_MAJOR);
  4617. resp.setBuildVersionMinor(BUILD_VERSION_MINOR);
  4618. resp.setBuildVersionPoint(BUILD_VERSION_POINT);
  4619. resp.setMaxRequestEntityLength(maxRequestEntityLength);
  4620. resp.updateDeployment().setUseCompression(true);
  4621. return true;
  4622. }
  4623. static const char * checkGetStatsNullInput(const char * s)
  4624. {
  4625. if (!s || !*s)
  4626. return nullptr;
  4627. return s;
  4628. }
  4629. static const char * checkGetStatsInput(const char * s)
  4630. {
  4631. if (!s || !*s)
  4632. return "*";
  4633. return s;
  4634. }
  4635. bool CWsWorkunitsEx::onWUGetStats(IEspContext &context, IEspWUGetStatsRequest &req, IEspWUGetStatsResponse &resp)
  4636. {
  4637. //This function is deprecated for 7.x and will be removed shortly afterwards.
  4638. //Anything that cannot be implemented with the scope iterator is implemented as a post filter
  4639. try
  4640. {
  4641. const char* creatorType = checkGetStatsNullInput(req.getCreatorType());
  4642. const char* creator = checkGetStatsNullInput(req.getCreator());
  4643. const char* scopeType = checkGetStatsNullInput(req.getScopeType());
  4644. const char* scope = checkGetStatsNullInput(req.getScope());
  4645. const char* kind = checkGetStatsNullInput(req.getKind());
  4646. const char* measure = req.getMeasure();
  4647. WuScopeFilter filter;
  4648. StatisticsFilter statsFilter(creatorType, creator, "*", "*", "*", "*");
  4649. filter.addOutputProperties(PTstatistics);
  4650. if (scopeType)
  4651. filter.addScopeType(scopeType);
  4652. if (scope)
  4653. filter.addScope(scope);
  4654. if (kind)
  4655. filter.addOutputStatistic(kind);
  4656. if (measure)
  4657. filter.setMeasure(measure);
  4658. if (!req.getMinScopeDepth_isNull() && !req.getMaxScopeDepth_isNull())
  4659. filter.setDepth(req.getMinScopeDepth(), req.getMaxScopeDepth());
  4660. else if (!req.getMinScopeDepth_isNull())
  4661. filter.setDepth(req.getMinScopeDepth(), req.getMinScopeDepth());
  4662. if (!req.getMinValue_isNull() || !req.getMaxValue_isNull())
  4663. {
  4664. unsigned __int64 lowValue = 0;
  4665. unsigned __int64 highValue = MaxStatisticValue;
  4666. if (!req.getMinValue_isNull())
  4667. lowValue = (unsigned __int64)req.getMinValue();
  4668. if (!req.getMaxValue_isNull())
  4669. highValue = (unsigned __int64)req.getMaxValue();
  4670. statsFilter.setValueRange(lowValue, highValue);
  4671. }
  4672. const char * textFilter = req.getFilter();
  4673. if (textFilter)
  4674. statsFilter.setFilter(textFilter);
  4675. filter.setIncludeNesting(0).finishedFilter();
  4676. bool createDescriptions = false;
  4677. if (!req.getCreateDescriptions_isNull())
  4678. createDescriptions = req.getCreateDescriptions();
  4679. StringBuffer wuid = req.getWUID();
  4680. PROGLOG("WUGetStats: %s", wuid.str());
  4681. IArrayOf<IEspWUStatisticItem> statistics;
  4682. if (strchr(wuid, '*'))
  4683. {
  4684. WUSortField filters[2];
  4685. MemoryBuffer filterbuf;
  4686. filters[0] = WUSFwildwuid;
  4687. filterbuf.append(wuid.str());
  4688. filters[1] = WUSFterm;
  4689. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  4690. Owned<IConstWorkUnitIterator> iter = factory->getWorkUnitsSorted((WUSortField) (WUSFwuid), filters, filterbuf.bufferBase(), 0, INT_MAX, NULL, NULL);
  4691. ForEach(*iter)
  4692. {
  4693. Owned<IConstWorkUnit> workunit = factory->openWorkUnit(iter->query().queryWuid());
  4694. if (workunit)
  4695. {
  4696. //No need to check for access since the list is already filtered
  4697. WsWuInfo winfo(context, workunit->queryWuid());
  4698. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4699. }
  4700. }
  4701. }
  4702. else
  4703. {
  4704. WsWuHelpers::checkAndTrimWorkunit("WUInfo", wuid);
  4705. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4706. WsWuInfo winfo(context, wuid);
  4707. winfo.getStats(filter, statsFilter, createDescriptions, statistics);
  4708. }
  4709. resp.setStatistics(statistics);
  4710. resp.setWUID(wuid.str());
  4711. }
  4712. catch(IException* e)
  4713. {
  4714. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4715. }
  4716. return true;
  4717. }
  4718. IPropertyTree* CWsWorkunitsEx::getWorkunitArchive(IEspContext &context, WsWuInfo& winfo, const char* wuid, unsigned cacheMinutes)
  4719. {
  4720. Owned<WUArchiveCacheElement> wuArchive = wuArchiveCache->lookup(context, wuid, cacheMinutes);
  4721. if (wuArchive)
  4722. return wuArchive->archive.getLink();
  4723. Owned<IPropertyTree> archive = winfo.getWorkunitArchive();
  4724. if (!archive)
  4725. return NULL;
  4726. wuArchiveCache->add(wuid, archive.getLink());
  4727. return archive.getClear();
  4728. }
  4729. bool CWsWorkunitsEx::onWUListArchiveFiles(IEspContext &context, IEspWUListArchiveFilesRequest &req, IEspWUListArchiveFilesResponse &resp)
  4730. {
  4731. try
  4732. {
  4733. const char* wuid = req.getWUID();
  4734. if (isEmpty(wuid))
  4735. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4736. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4737. PROGLOG("WUListArchiveFiles: %s", wuid);
  4738. WsWuInfo winfo(context, wuid);
  4739. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4740. if (!archive)
  4741. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4742. IArrayOf<IEspWUArchiveModule> modules;
  4743. IArrayOf<IEspWUArchiveFile> files;
  4744. winfo.listArchiveFiles(archive, "", modules, files);
  4745. if (modules.length())
  4746. resp.setArchiveModules(modules);
  4747. if (files.length())
  4748. resp.setFiles(files);
  4749. if (!modules.length() && !files.length())
  4750. resp.setMessage("Files not found");
  4751. }
  4752. catch(IException* e)
  4753. {
  4754. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4755. }
  4756. return true;
  4757. }
  4758. bool CWsWorkunitsEx::onWUGetArchiveFile(IEspContext &context, IEspWUGetArchiveFileRequest &req, IEspWUGetArchiveFileResponse &resp)
  4759. {
  4760. try
  4761. {
  4762. const char* wuid = req.getWUID();
  4763. const char* moduleName = req.getModuleName();
  4764. const char* attrName = req.getFileName();
  4765. if (isEmpty(wuid))
  4766. throw MakeStringException(ECLWATCH_NO_WUID_SPECIFIED, "No workunit defined.");
  4767. if (isEmpty(moduleName) && isEmpty(attrName))
  4768. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No file name defined.");
  4769. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  4770. PROGLOG("WUGetArchiveFile: %s", wuid);
  4771. WsWuInfo winfo(context, wuid);
  4772. Owned<IPropertyTree> archive = getWorkunitArchive(context, winfo, wuid, WUARCHIVE_CACHE_MINITES);
  4773. if (!archive)
  4774. throw MakeStringException(ECLWATCH_INVALID_INPUT,"No workunit archive found for %s.", wuid);
  4775. StringBuffer file;
  4776. winfo.getArchiveFile(archive, moduleName, attrName, req.getPath(), file);
  4777. if (file.length())
  4778. resp.setFile(file.str());
  4779. else
  4780. resp.setMessage("File not found");
  4781. }
  4782. catch(IException* e)
  4783. {
  4784. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  4785. }
  4786. return true;
  4787. }