ws_workunitsService.cpp 140 KB

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