ws_workunitsService.cpp 158 KB

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