ws_workunitsService.cpp 185 KB

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