ws_workunitsService.cpp 125 KB

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