ws_workunitsService.cpp 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547
  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. if (wlist.getSize() < 1)
  1410. {
  1411. resp.setNumWUs(0);
  1412. return;
  1413. }
  1414. if (wlist.getSize() < count)
  1415. count = (int) wlist.getSize() - 1;
  1416. WsWuSearch::iterator begin, end;
  1417. if(notEmpty(req.getAfter()))
  1418. {
  1419. begin=wlist.locate(req.getAfter());
  1420. end=min(begin+count,wlist.end());
  1421. }
  1422. else if (notEmpty(req.getBefore()))
  1423. {
  1424. end=wlist.locate(req.getBefore());
  1425. begin=max(end-count,wlist.begin());
  1426. }
  1427. else
  1428. {
  1429. begin=wlist.begin();
  1430. end=min(begin+count,wlist.end());
  1431. }
  1432. if(begin>wlist.begin() && begin<wlist.end())
  1433. resp.setCurrent(begin->c_str());
  1434. if (context.getClientVersion() > 1.02)
  1435. {
  1436. resp.setPageStartFrom(begin - wlist.begin() + 1);
  1437. resp.setNumWUs((int)wlist.getSize());
  1438. resp.setCount(end - begin);
  1439. }
  1440. if(end<wlist.end())
  1441. resp.setNext(end->c_str());
  1442. for(;begin!=end;begin++)
  1443. {
  1444. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1445. WsWuInfo winfo(context, begin->c_str());
  1446. winfo.getCommon(*info, 0);
  1447. results.append(*info.getClear());
  1448. }
  1449. resp.setPageSize(abs(count));
  1450. resp.setWorkunits(results);
  1451. return;
  1452. }
  1453. bool addWUQueryFilter(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *name, WUSortField value)
  1454. {
  1455. if (isEmpty(name))
  1456. return false;
  1457. filters[count++] = value;
  1458. buff.append(name);
  1459. return true;
  1460. }
  1461. bool addWUQueryFilterTime(WUSortField *filters, unsigned short &count, MemoryBuffer &buff, const char *stime, WUSortField value)
  1462. {
  1463. if (isEmpty(stime))
  1464. return false;
  1465. CDateTime dt;
  1466. dt.setString(stime, NULL, true);
  1467. unsigned year, month, day, hour, minute, second, nano;
  1468. dt.getDate(year, month, day, true);
  1469. dt.getTime(hour, minute, second, nano, true);
  1470. VStringBuffer wuid("W%4d%02d%02d-%02d%02d%02d",year,month,day,hour,minute,second);
  1471. filters[count++] = value;
  1472. buff.append(wuid.str());
  1473. return true;
  1474. }
  1475. void doWUQueryWithSort(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1476. {
  1477. SecAccessFlags accessOwn;
  1478. SecAccessFlags accessOthers;
  1479. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1480. double version = context.getClientVersion();
  1481. IArrayOf<IEspECLWorkunit> results;
  1482. int begin = 0;
  1483. unsigned int count = 100;
  1484. int pagesize = 100;
  1485. if (version > 1.01)
  1486. {
  1487. pagesize = (int)req.getPageSize();
  1488. if (!req.getCount_isNull())
  1489. pagesize = req.getCount();
  1490. if(pagesize < 1)
  1491. pagesize = 100;
  1492. begin = (int)req.getPageStartFrom();
  1493. }
  1494. else
  1495. {
  1496. count=(unsigned)req.getCount();
  1497. if(!count)
  1498. count=100;
  1499. if (notEmpty(req.getAfter()))
  1500. begin=atoi(req.getAfter());
  1501. else if (notEmpty(req.getBefore()))
  1502. begin=atoi(req.getBefore())-count;
  1503. if (begin < 0)
  1504. begin = 0;
  1505. pagesize = count;
  1506. }
  1507. WUSortField sortorder[2] = {(WUSortField) (WUSFwuid | WUSFreverse), WUSFterm};
  1508. if(notEmpty(req.getSortby()))
  1509. {
  1510. const char *sortby = req.getSortby();
  1511. if (strieq(sortby, "Owner"))
  1512. sortorder[0] = WUSFuser;
  1513. else if (strieq(sortby, "JobName"))
  1514. sortorder[0] = WUSFjob;
  1515. else if (strieq(sortby, "Cluster"))
  1516. sortorder[0] = WUSFcluster;
  1517. else if (strieq(sortby, "RoxieCluster"))
  1518. sortorder[0] = WUSFroxiecluster;
  1519. else if (strieq(sortby, "Protected"))
  1520. sortorder[0] = WUSFprotected;
  1521. else if (strieq(sortby, "State"))
  1522. sortorder[0] = WUSFstate;
  1523. else if (strieq(sortby, "ThorTime"))
  1524. sortorder[0] = (WUSortField) (WUSFtotalthortime+WUSFnumeric);
  1525. else
  1526. sortorder[0] = WUSFwuid;
  1527. bool descending = req.getDescending();
  1528. if (descending)
  1529. sortorder[0] = (WUSortField) (sortorder[0] | WUSFreverse);
  1530. }
  1531. WUSortField filters[10];
  1532. unsigned short filterCount = 0;
  1533. MemoryBuffer filterbuf;
  1534. bool bDoubleCheckState = false;
  1535. if(req.getState())
  1536. {
  1537. addWUQueryFilter(filters, filterCount, filterbuf, strieq(req.getState(), "unknown") ? "" : req.getState(), WUSFstate);
  1538. if (strieq(req.getState(), "submitted"))
  1539. bDoubleCheckState = true;
  1540. }
  1541. addWUQueryFilter(filters, filterCount, filterbuf, req.getCluster(), WUSFcluster);
  1542. if(version > 1.07)
  1543. addWUQueryFilter(filters, filterCount, filterbuf, req.getRoxieCluster(), WUSFroxiecluster);
  1544. addWUQueryFilter(filters, filterCount, filterbuf, req.getLogicalFile(), WUSFfileread);
  1545. addWUQueryFilter(filters, filterCount, filterbuf, req.getOwner(), (WUSortField) (WUSFuser | WUSFnocase));
  1546. addWUQueryFilter(filters, filterCount, filterbuf, req.getJobname(), (WUSortField) (WUSFjob | WUSFnocase));
  1547. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getStartDate(), WUSFwuid);
  1548. addWUQueryFilterTime(filters, filterCount, filterbuf, req.getEndDate(), WUSFwuidhigh);
  1549. filters[filterCount] = WUSFterm;
  1550. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1551. unsigned numWUs = factory->numWorkUnitsFiltered(filters, filterbuf.bufferBase());
  1552. Owned<IConstWorkUnitIterator> it = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), begin, pagesize+1, "", NULL);
  1553. unsigned actualCount = 0;
  1554. ForEach(*it)
  1555. {
  1556. actualCount++;
  1557. IConstWorkUnit& cw = it->query();
  1558. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cw, accessOwn, accessOthers) < SecAccess_Read)
  1559. continue;
  1560. if (bDoubleCheckState && (cw.getState() != WUStateSubmitted))
  1561. continue;
  1562. SCMStringBuffer parent;
  1563. if (!cw.getParentWuid(parent).length())
  1564. {
  1565. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1566. WsWuInfo winfo(context, cw.getWuid(parent).str());
  1567. winfo.getCommon(*info, 0);
  1568. results.append(*info.getClear());
  1569. }
  1570. }
  1571. if (version > 1.02)
  1572. {
  1573. resp.setPageStartFrom(begin+1);
  1574. resp.setNumWUs(numWUs);
  1575. if (results.length() > (aindex_t)pagesize)
  1576. results.pop();
  1577. if(begin + pagesize < numWUs)
  1578. {
  1579. resp.setNextPage(begin + pagesize);
  1580. resp.setPageEndAt(begin + pagesize);
  1581. int last = begin + pagesize;
  1582. while (numWUs > (unsigned) last + pagesize)
  1583. last += pagesize;
  1584. resp.setLastPage(last);
  1585. }
  1586. else
  1587. {
  1588. resp.setNextPage(-1);
  1589. resp.setPageEndAt(numWUs);
  1590. }
  1591. if(begin > 0)
  1592. {
  1593. resp.setFirst(false);
  1594. if (begin - pagesize > 0)
  1595. resp.setPrevPage(begin - pagesize);
  1596. else
  1597. resp.setPrevPage(0);
  1598. }
  1599. resp.setPageSize(pagesize);
  1600. }
  1601. else
  1602. {
  1603. if(begin>0 && actualCount > 0)
  1604. {
  1605. char buf[10];
  1606. itoa(begin, buf, 10);
  1607. resp.setCurrent(buf);
  1608. }
  1609. if(count<actualCount)
  1610. {
  1611. char buf[10];
  1612. itoa(begin+count, buf, 10);
  1613. resp.setNext(buf);
  1614. resp.setNumWUs(numWUs);
  1615. if (results.length() > count)
  1616. results.pop();
  1617. }
  1618. if(begin == 0 && actualCount <= count)
  1619. resp.setFirst(false);
  1620. resp.setCount(count);
  1621. }
  1622. resp.setWorkunits(results);
  1623. return;
  1624. }
  1625. void doWUQueryFromArchive(IEspContext &context, ArchivedWuCache &archivedWuCache, int cacheTime, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1626. {
  1627. SecAccessFlags accessOwn;
  1628. SecAccessFlags accessOthers;
  1629. getUserWuAccessFlags(context, accessOwn, accessOthers, true);
  1630. __int64 pageSize = req.getPageSize();
  1631. if(pageSize < 1)
  1632. pageSize=100;
  1633. __int64 displayStart = req.getPageStartFrom();
  1634. __int64 displayEnd = displayStart + pageSize;
  1635. unsigned dateLimit = 0;
  1636. bool hasNextPage = true;
  1637. SocketEndpoint ep;
  1638. getSashaNode(ep);
  1639. Owned<INode> sashaserver = createINode(ep);
  1640. CDateTime wuTimeFrom, wuTimeTo;
  1641. if(notEmpty(req.getEndDate()))
  1642. wuTimeTo.setString(req.getEndDate(), NULL, true);
  1643. else
  1644. wuTimeTo.setNow();
  1645. if(notEmpty(req.getStartDate()))
  1646. {
  1647. wuTimeFrom.setString(req.getStartDate(), NULL, true);
  1648. dateLimit = 1;
  1649. }
  1650. IArrayOf<IEspECLWorkunit> results;
  1651. StringBuffer filter;
  1652. addToQueryString(filter, "cluster", req.getCluster(), ';');
  1653. addToQueryString(filter, "owner", req.getOwner(), ';');
  1654. addToQueryString(filter, "jobName", req.getJobname(), ';');
  1655. addToQueryString(filter, "state", req.getState(), ';');
  1656. StringBuffer s;
  1657. if (!req.getLastNDays_isNull() && req.getLastNDays()>0)
  1658. addToQueryString(filter, "LastNDays", s.clear().append(req.getLastNDays()).str(), ';');
  1659. else
  1660. {
  1661. addToQueryString(filter, "wuTimeFrom", req.getStartDate(), ';');
  1662. addToQueryString(filter, "wuTimeTo", req.getEndDate(), ';');
  1663. }
  1664. addToQueryString(filter, "displayStart", s.append(displayStart).str(), ';');
  1665. addToQueryString(filter, "pageSize", s.clear().append(pageSize).str(), ';');
  1666. Owned<ArchivedWuCacheElement> found = archivedWuCache.lookup(context, filter, "AddWhenAvailable", cacheTime);
  1667. if (found)
  1668. {
  1669. hasNextPage = found->m_hasNextPage;
  1670. if (found->m_results.length())
  1671. {
  1672. ForEachItemIn(ai, found->m_results)
  1673. {
  1674. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1675. info->copy(found->m_results.item(ai));
  1676. results.append(*info.getClear());
  1677. }
  1678. }
  1679. }
  1680. else
  1681. {
  1682. IArrayOf<IEspECLWorkunit> resultList;
  1683. CDateTime timeTo = wuTimeTo;
  1684. __int64 totalWus = 0;
  1685. bool complete = false;
  1686. while (!complete)
  1687. {
  1688. CDateTime timeFrom = timeTo;
  1689. timeFrom.adjustTime(-1439); //one day earlier
  1690. if (dateLimit > 0 && wuTimeFrom > timeFrom)
  1691. timeFrom = wuTimeFrom;
  1692. unsigned year0, month0, day0, hour0, minute0, second0, nano0;
  1693. timeFrom.getDate(year0, month0, day0, true);
  1694. timeFrom.getTime(hour0, minute0, second0, nano0, true);
  1695. VStringBuffer wuFrom("%4d%02d%02d%02d%02d", year0, month0, day0, hour0, minute0);
  1696. unsigned year, month, day, hour, minute, second, nano;
  1697. timeTo.getDate(year, month, day, true);
  1698. timeTo.getTime(hour, minute, second, nano, true);
  1699. VStringBuffer wuTo("%4d%02d%02d%02d%02d", year, month, day, hour, minute);
  1700. __int64 begin = 0;
  1701. unsigned limit = 1000;
  1702. bool continueSashaLoop = true;
  1703. while (continueSashaLoop)
  1704. {
  1705. Owned<ISashaCommand> cmd = createSashaCommand();
  1706. cmd->setAction(SCA_LIST);
  1707. cmd->setOnline(false);
  1708. cmd->setArchived(true);
  1709. cmd->setAfter(wuFrom.str());
  1710. cmd->setBefore(wuTo.str());
  1711. cmd->setStart((unsigned)begin);
  1712. cmd->setLimit(limit);
  1713. if (notEmpty(req.getCluster()))
  1714. cmd->setCluster(req.getCluster());
  1715. if (notEmpty(req.getOwner()))
  1716. cmd->setOwner(req.getOwner());
  1717. if (notEmpty(req.getJobname()))
  1718. cmd->setJobName(req.getJobname());
  1719. if (notEmpty(req.getState()))
  1720. cmd->setState(req.getState());
  1721. cmd->setOutputFormat("owner,jobname,cluster,state");
  1722. if (!cmd->send(sashaserver))
  1723. {
  1724. StringBuffer msg("Cannot connect to archive server at ");
  1725. sashaserver->endpoint().getUrlStr(msg);
  1726. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  1727. }
  1728. unsigned actualCount = cmd->numIds();
  1729. if (actualCount < 1)
  1730. break;
  1731. totalWus += actualCount;
  1732. if (actualCount < limit)
  1733. continueSashaLoop = false;
  1734. for (unsigned ii=0; ii<actualCount; ii++)
  1735. {
  1736. const char *csline = cmd->queryId(ii);
  1737. if (!csline)
  1738. continue;
  1739. StringArray wuidArray;
  1740. CslToStringArray(csline, wuidArray, false);
  1741. if (chooseWuAccessFlagsByOwnership(context.queryUserId(), cmd->queryOwner(), accessOwn, accessOthers) < SecAccess_Read)
  1742. continue;
  1743. const char* wuid = wuidArray.item(0);
  1744. if (isEmpty(wuid))
  1745. continue;
  1746. __int64 addToPos = -1;
  1747. ForEachItemIn(ridx, resultList)
  1748. {
  1749. IEspECLWorkunit& w = resultList.item(ridx);
  1750. if (isEmpty(w.getWuid()))
  1751. continue;
  1752. if (strcmp(wuid, w.getWuid())>0)
  1753. {
  1754. addToPos = ridx;
  1755. break;
  1756. }
  1757. }
  1758. if (addToPos < 0 && (ridx > displayEnd))
  1759. continue;
  1760. Owned<IEspECLWorkunit> info= createECLWorkunit("","");
  1761. info->setWuid(wuid);
  1762. if (notEmpty(wuidArray.item(1)))
  1763. info->setOwner(wuidArray.item(1));
  1764. if (notEmpty(wuidArray.item(2)))
  1765. info->setJobname(wuidArray.item(2));
  1766. if (notEmpty(wuidArray.item(3)))
  1767. info->setCluster(wuidArray.item(3));
  1768. if (notEmpty(wuidArray.item(4)))
  1769. info->setState(wuidArray.item(4));
  1770. if (addToPos < 0)
  1771. resultList.append(*info.getClear());
  1772. else
  1773. resultList.add(*info.getClear(), (aindex_t) addToPos);
  1774. if (resultList.length() > displayEnd)
  1775. resultList.pop();
  1776. }
  1777. begin += limit;
  1778. }
  1779. timeTo.adjustTime(-1440);//one day earlier
  1780. if (dateLimit > 0 && wuTimeFrom > timeTo) //we reach the date limit
  1781. {
  1782. if (totalWus <= displayEnd)
  1783. hasNextPage = false;
  1784. complete = true;
  1785. }
  1786. else if ( resultList.length() >= displayEnd) //we have all we need
  1787. complete = true;
  1788. }
  1789. if (displayEnd > resultList.length())
  1790. displayEnd = resultList.length();
  1791. for (aindex_t i = (aindex_t)displayStart; i < (aindex_t)displayEnd; i++)
  1792. {
  1793. Owned<IEspECLWorkunit> info = createECLWorkunit("","");
  1794. info->copy(resultList.item(i));
  1795. results.append(*info.getClear());
  1796. }
  1797. archivedWuCache.add(filter, "AddWhenAvailable", hasNextPage, results);
  1798. }
  1799. resp.setPageStartFrom(displayStart+1);
  1800. resp.setPageEndAt(displayEnd);
  1801. if(dateLimit < 1 || hasNextPage)
  1802. resp.setNextPage(displayStart + pageSize);
  1803. else
  1804. resp.setNextPage(-1);
  1805. if(displayStart > 0)
  1806. {
  1807. resp.setFirst(false);
  1808. if (displayStart - pageSize > 0)
  1809. resp.setPrevPage(displayStart - pageSize);
  1810. else
  1811. resp.setPrevPage(0);
  1812. }
  1813. resp.setPageSize(pageSize);
  1814. resp.setWorkunits(results);
  1815. resp.setType("archived only");
  1816. return;
  1817. }
  1818. bool CWsWorkunitsEx::onWUQuery(IEspContext &context, IEspWUQueryRequest & req, IEspWUQueryResponse & resp)
  1819. {
  1820. try
  1821. {
  1822. DBGLOG("Started CWsWorkunitsEx::onWUQuery\n");
  1823. if (req.getType() && strieq(req.getType(), "archived workunits"))
  1824. doWUQueryFromArchive(context, *archivedWuCache, awusCacheMinutes, req, resp);
  1825. else if(notEmpty(req.getWuid()))
  1826. doWUQueryBySingleWuid(context, req.getWuid(), resp);
  1827. else if (notEmpty(req.getECL()) || notEmpty(req.getApplicationName()) || notEmpty(req.getApplicationKey()) || notEmpty(req.getApplicationData()))
  1828. doWUQueryByXPath(context, req, resp);
  1829. else if (notEmpty(req.getLogicalFile()) && req.getLogicalFileSearchType() && strieq(req.getLogicalFileSearchType(), "Created"))
  1830. doWUQueryByFile(context, req.getLogicalFile(), resp);
  1831. else
  1832. doWUQueryWithSort(context, req, resp);
  1833. resp.setState(req.getState());
  1834. resp.setCluster(req.getCluster());
  1835. resp.setRoxieCluster(req.getRoxieCluster());
  1836. resp.setOwner(req.getOwner());
  1837. resp.setStartDate(req.getStartDate());
  1838. resp.setEndDate(req.getEndDate());
  1839. double version = context.getClientVersion();
  1840. StringBuffer basicQuery;
  1841. addToQueryString(basicQuery, "State", req.getState());
  1842. addToQueryString(basicQuery, "Cluster", req.getCluster());
  1843. if (version > 1.07)
  1844. addToQueryString(basicQuery, "RoxieCluster", req.getRoxieCluster());
  1845. addToQueryString(basicQuery, "Owner", req.getOwner());
  1846. addToQueryString(basicQuery, "StartDate", req.getStartDate());
  1847. addToQueryString(basicQuery, "EndDate", req.getEndDate());
  1848. if (version > 1.25 && req.getLastNDays() > -1)
  1849. addToQueryString(basicQuery, "LastNDays", StringBuffer().append(req.getLastNDays()).str());
  1850. addToQueryString(basicQuery, "ECL", req.getECL());
  1851. addToQueryString(basicQuery, "Jobname", req.getJobname());
  1852. addToQueryString(basicQuery, "Type", req.getType());
  1853. if (addToQueryString(basicQuery, "LogicalFile", req.getLogicalFile()))
  1854. addToQueryString(basicQuery, "LogicalFileSearchType", req.getLogicalFileSearchType());
  1855. resp.setFilters(basicQuery.str());
  1856. if (notEmpty(req.getSortby()) && !strstr(basicQuery.str(), StringBuffer(req.getSortby()).append('=').str()))
  1857. {
  1858. resp.setSortby(req.getSortby());
  1859. addToQueryString(basicQuery, "Sortby", req.getSortby());
  1860. if (req.getDescending())
  1861. {
  1862. resp.setDescending(req.getDescending());
  1863. addToQueryString(basicQuery, "Descending", "1");
  1864. }
  1865. }
  1866. resp.setBasicQuery(basicQuery.str());
  1867. StringBuffer s;
  1868. if(notEmpty(req.getECL()))
  1869. resp.setECL(Utils::url_encode(req.getECL(), s).str());
  1870. if(notEmpty(req.getJobname()))
  1871. resp.setJobname(Utils::url_encode(req.getJobname(), s.clear()).str());
  1872. }
  1873. catch(IException* e)
  1874. {
  1875. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1876. }
  1877. return true;
  1878. }
  1879. void appendResultSet(MemoryBuffer& mb, INewResultSet* result, const char *name, __int64 start, unsigned& count, __int64& total, bool bin)
  1880. {
  1881. if (!result)
  1882. return;
  1883. const IResultSetMetaData &meta = result->getMetaData();
  1884. Owned<IResultSetCursor> cursor(result->createCursor());
  1885. total=result->getNumRows();
  1886. if(bin)
  1887. count = getResultBin(mb, result, (unsigned)start, count);
  1888. else
  1889. {
  1890. struct MemoryBuffer2IStringVal : public CInterface, implements IStringVal
  1891. {
  1892. MemoryBuffer2IStringVal(MemoryBuffer & _buffer) : buffer(_buffer) {}
  1893. IMPLEMENT_IINTERFACE;
  1894. virtual const char * str() const { UNIMPLEMENTED; }
  1895. virtual void set(const char *val) { buffer.append(strlen(val),val); }
  1896. virtual void clear() { } // support appending only
  1897. virtual void setLen(const char *val, unsigned length) { buffer.append(length, val); }
  1898. virtual unsigned length() const { return buffer.length(); };
  1899. MemoryBuffer & buffer;
  1900. } adaptor(mb);
  1901. count = getResultXml(adaptor, result, name, (unsigned) start, count, "myschema");
  1902. }
  1903. }
  1904. 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)
  1905. {
  1906. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  1907. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  1908. Owned<IConstWUResult> result;
  1909. if (notEmpty(name))
  1910. result.setown(cw->getResultByName(name));
  1911. else if (notEmpty(logical))
  1912. {
  1913. Owned<IConstWUResultIterator> it = &cw->getResults();
  1914. ForEach(*it)
  1915. {
  1916. IConstWUResult &r = it->query();
  1917. SCMStringBuffer filename;
  1918. if(strieq(r.getResultLogicalName(filename).str(), logical))
  1919. {
  1920. result.setown(LINK(&r));
  1921. break;
  1922. }
  1923. }
  1924. }
  1925. else
  1926. result.setown(cw->getResultBySequence(index));
  1927. if (!result)
  1928. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  1929. if (!resname.length())
  1930. result->getResultName(resname);
  1931. Owned<IResultSetFactory> resultSetFactory;
  1932. if (context.querySecManager())
  1933. resultSetFactory.setown(getSecResultSetFactory(*context.querySecManager(), *context.queryUser()));
  1934. else
  1935. resultSetFactory.setown(getResultSetFactory(context.queryUserId(), context.queryPassword()));
  1936. SCMStringBuffer logicalName;
  1937. result->getResultLogicalName(logicalName);
  1938. Owned<INewResultSet> rs;
  1939. if (logicalName.length())
  1940. {
  1941. SCMStringBuffer cluster; //MORE is this wrong cluster?
  1942. rs.setown(resultSetFactory->createNewFileResultSet(logicalName.str(), cw->getClusterName(cluster).str()));
  1943. }
  1944. else
  1945. rs.setown(resultSetFactory->createNewResultSet(result, wuid));
  1946. appendResultSet(mb, rs, name, start, count, total, bin);
  1947. }
  1948. void openSaveFile(IEspContext &context, int opt, const char* filename, const char* origMimeType, MemoryBuffer& buf, IEspWULogFileResponse &resp)
  1949. {
  1950. if (opt < 1)
  1951. {
  1952. resp.setThefile(buf);
  1953. resp.setThefile_mimetype(origMimeType);
  1954. }
  1955. else if (opt < 2)
  1956. {
  1957. StringBuffer headerStr("attachment;");
  1958. if (filename && *filename)
  1959. headerStr.appendf("filename=%s", filename);
  1960. MemoryBuffer buf0;
  1961. unsigned i = 0;
  1962. char* p = (char*) buf.toByteArray();
  1963. while (i < buf.length())
  1964. {
  1965. if (p[0] != 10)
  1966. buf0.append(p[0]);
  1967. else
  1968. buf0.append(0x0d);
  1969. p++;
  1970. i++;
  1971. }
  1972. resp.setThefile(buf);
  1973. resp.setThefile_mimetype(origMimeType);
  1974. context.addCustomerHeader("Content-disposition", headerStr.str());
  1975. }
  1976. else
  1977. {
  1978. #ifndef _USE_ZLIB
  1979. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  1980. #else
  1981. StringBuffer fileNameStr, headerStr("attachment;");
  1982. if (notEmpty(filename))
  1983. {
  1984. fileNameStr.append(filename);
  1985. headerStr.append("filename=").append(filename).append((opt>2) ? ".gz" : ".zip");
  1986. }
  1987. else
  1988. fileNameStr.append("file");
  1989. StringBuffer ifname;
  1990. ifname.appendf("%s%sT%xAT%x", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick()).append((opt>2)? "" : ".zip");
  1991. IZZIPor* Zipor = createZZIPor();
  1992. int ret = 0;
  1993. if (opt > 2)
  1994. ret = Zipor->gzipToFile(buf.length(), (void*)buf.toByteArray(), ifname.str());
  1995. else
  1996. ret = Zipor->zipToFile(buf.length(), (void*)buf.toByteArray(), fileNameStr.str(), ifname.str());
  1997. releaseIZ(Zipor);
  1998. if (ret < 0)
  1999. {
  2000. Owned<IFile> rFile = createIFile(ifname.str());
  2001. if (rFile->exists())
  2002. rFile->remove();
  2003. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2004. }
  2005. Owned <IFile> rf = createIFile(ifname.str());
  2006. if (!rf->exists())
  2007. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA,"The data cannot be compressed.");
  2008. MemoryBuffer out;
  2009. Owned <IFileIO> fio = rf->open(IFOread);
  2010. read(fio, 0, (size32_t) rf->size(), out);
  2011. resp.setThefile(out);
  2012. fio.clear();
  2013. rf->remove();
  2014. resp.setThefile_mimetype((opt > 2) ? "application/x-gzip" : "application/zip");
  2015. context.addCustomerHeader("Content-disposition", headerStr.str());
  2016. #endif
  2017. }
  2018. }
  2019. bool CWsWorkunitsEx::onWUFile(IEspContext &context,IEspWULogFileRequest &req, IEspWULogFileResponse &resp)
  2020. {
  2021. try
  2022. {
  2023. DBGLOG("CWsWorkunitsEx::onWUFile WUID=%s",req.getWuid());
  2024. ensureWsWorkunitAccess(context, req.getWuid(), SecAccess_Read);
  2025. StringAttr wuid(req.getWuid());
  2026. if (wuid.isEmpty() && notEmpty(req.getQuerySet()) && notEmpty(req.getQuery()))
  2027. {
  2028. Owned<IPropertyTree> registry = getQueryRegistry(req.getQuerySet(), false);
  2029. if (!registry)
  2030. throw MakeStringException(ECLWATCH_QUERYSET_NOT_FOUND, "Queryset %s not found", req.getQuerySet());
  2031. Owned<IPropertyTree> query = resolveQueryAlias(registry, req.getQuery());
  2032. if (!query)
  2033. throw MakeStringException(ECLWATCH_QUERYID_NOT_FOUND, "Query %s not found", req.getQuery());
  2034. resp.setQuerySet(req.getQuerySet());
  2035. resp.setQueryName(query->queryProp("@name"));
  2036. resp.setQueryId(query->queryProp("@id"));
  2037. wuid.set(query->queryProp("@wuid"));
  2038. }
  2039. int opt = req.getOption();
  2040. if (!wuid.isEmpty())
  2041. {
  2042. resp.setWuid(wuid.get());
  2043. MemoryBuffer mb;
  2044. WsWuInfo winfo(context, wuid);
  2045. if (strieq(File_ArchiveQuery, req.getType()))
  2046. {
  2047. winfo.getWorkunitArchiveQuery(mb);
  2048. openSaveFile(context, opt, "ArchiveQuery.xml", HTTP_TYPE_TEXT_XML, mb, resp);
  2049. }
  2050. else if (strieq(File_Cpp,req.getType()) && notEmpty(req.getName()))
  2051. {
  2052. winfo.getWorkunitCpp(req.getName(), req.getDescription(), req.getIPAddress(),mb);
  2053. openSaveFile(context, opt, req.getName(), HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2054. }
  2055. else if (strieq(File_DLL,req.getType()))
  2056. {
  2057. StringBuffer name;
  2058. winfo.getWorkunitDll(name, mb);
  2059. resp.setFileName(name.str());
  2060. openSaveFile(context, opt, req.getName(), HTTP_TYPE_OCTET_STREAM, mb, resp);
  2061. }
  2062. else if (strieq(File_Res,req.getType()))
  2063. {
  2064. winfo.getWorkunitResTxt(mb);
  2065. openSaveFile(context, opt, "res.txt", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2066. }
  2067. else if (strncmp(req.getType(), File_ThorLog, 7) == 0)
  2068. {
  2069. winfo.getWorkunitThorLog(mb);
  2070. openSaveFile(context, opt, "thormaster.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2071. }
  2072. else if (strieq(File_ThorSlaveLog,req.getType()))
  2073. {
  2074. winfo.getWorkunitThorSlaveLog(req.getSlaveIP(), mb);
  2075. openSaveFile(context, opt, "ThorSlave.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2076. }
  2077. else if (strieq(File_EclAgentLog,req.getType()))
  2078. {
  2079. winfo.getWorkunitEclAgentLog(mb);
  2080. openSaveFile(context, opt, "eclagent.log", HTTP_TYPE_TEXT_PLAIN, mb, resp);
  2081. }
  2082. else if (strieq(File_XML,req.getType()))
  2083. {
  2084. winfo.getWorkunitXml(req.getPlainText(), mb);
  2085. resp.setThefile(mb);
  2086. const char* plainText = req.getPlainText();
  2087. if (plainText && (!stricmp(plainText, "yes")))
  2088. resp.setThefile_mimetype(HTTP_TYPE_TEXT_PLAIN);
  2089. else
  2090. resp.setThefile_mimetype(HTTP_TYPE_TEXT_XML);
  2091. }
  2092. }
  2093. }
  2094. catch(IException* e)
  2095. {
  2096. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2097. }
  2098. return true;
  2099. }
  2100. bool CWsWorkunitsEx::onWUResultBin(IEspContext &context,IEspWUResultBinRequest &req, IEspWUResultBinResponse &resp)
  2101. {
  2102. try
  2103. {
  2104. ensureWsWorkunitAccess(context, req.getWuid(), SecAccess_Read);
  2105. MemoryBuffer mb;
  2106. __int64 total=0;
  2107. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2108. unsigned count = req.getCount(), requested=count;
  2109. SCMStringBuffer name;
  2110. bool bin = (req.getFormat() && strieq(req.getFormat(),"raw"));
  2111. if (notEmpty(req.getWuid()) && notEmpty(req.getResultName()))
  2112. getWsWuResult(context, req.getWuid(), req.getResultName(), NULL, 0, start, count, total, name, bin, mb);
  2113. else if (notEmpty(req.getWuid()) && (req.getSequence() >= 0))
  2114. getWsWuResult(context, req.getWuid(), NULL, NULL, req.getSequence(), start, count, total, name, bin,mb);
  2115. else if (notEmpty(req.getLogicalName()))
  2116. {
  2117. const char* logicalName = req.getLogicalName();
  2118. StringBuffer wuid;
  2119. getWuidFromLogicalFileName(context, logicalName, wuid);
  2120. if (!wuid.length())
  2121. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot find the workunit for file %s.",logicalName);
  2122. getWsWuResult(context, wuid.str(), NULL, logicalName, 0, start, count, total, name, bin, mb);
  2123. }
  2124. else
  2125. throw MakeStringException(ECLWATCH_CANNOT_GET_WU_RESULT,"Cannot open the workunit result.");
  2126. if(stricmp(req.getFormat(),"xls")==0)
  2127. {
  2128. Owned<IProperties> params(createProperties());
  2129. params->setProp("showCount",0);
  2130. StringBuffer xml;
  2131. xml.append("<WUResultExcel><Result>").append(mb.length(), mb.toByteArray()).append("</Result></WUResultExcel>");
  2132. if (xml.length() > MAXXLSTRANSFER)
  2133. 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.");
  2134. StringBuffer xls;
  2135. xsltTransform(xml.str(), StringBuffer(getCFD()).append("./smc_xslt/result.xslt").str(), params, xls);
  2136. MemoryBuffer out;
  2137. out.setBuffer(xls.length(), (void*)xls.str());
  2138. resp.setResult(out);
  2139. resp.setResult_mimetype("application/vnd.ms-excel");
  2140. }
  2141. #ifdef _USE_ZLIB
  2142. else if(strieq(req.getFormat(),"zip") || strieq(req.getFormat(),"gzip"))
  2143. {
  2144. bool gzip = strieq(req.getFormat(),"gzip");
  2145. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2146. xml.append("<Result>").append(mb.length(),mb.toByteArray()).append("</Result>");
  2147. VStringBuffer ifname("%s%sT%xAT%x%s", TEMPZIPDIR, PATHSEPSTR, (unsigned)(memsize_t)GetCurrentThreadId(), msTick(), gzip ? "" : ".zip");
  2148. IZZIPor* Zipor = createZZIPor();
  2149. int ret = 0;
  2150. if (gzip)
  2151. ret = Zipor->gzipToFile(xml.length(), (void*)xml.str(), ifname.str());
  2152. else
  2153. ret = Zipor->zipToFile(xml.length(), (void*)xml.str(), "WUResult.xml", ifname.str());
  2154. releaseIZ(Zipor);
  2155. if (ret < 0)
  2156. {
  2157. Owned<IFile> rFile = createIFile(ifname.str());
  2158. if (rFile->exists())
  2159. rFile->remove();
  2160. throw MakeStringException(ECLWATCH_CANNOT_COMPRESS_DATA, "The data cannot be compressed.");
  2161. }
  2162. MemoryBuffer out;
  2163. Owned <IFile> rf = createIFile(ifname.str());
  2164. if (rf->exists())
  2165. {
  2166. Owned <IFileIO> fio = rf->open(IFOread);
  2167. read(fio, 0, (size32_t) rf->size(), out);
  2168. resp.setResult(out);
  2169. }
  2170. if (gzip)
  2171. {
  2172. resp.setResult_mimetype("application/x-gzip");
  2173. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.gz");
  2174. }
  2175. else
  2176. {
  2177. resp.setResult_mimetype("application/zip");
  2178. context.addCustomerHeader("Content-disposition", "attachment;filename=WUResult.xml.zip");
  2179. }
  2180. Owned<IFile> rFile = createIFile(ifname.str());
  2181. if (rFile->exists())
  2182. rFile->remove();
  2183. }
  2184. #endif
  2185. else
  2186. {
  2187. resp.setResult(mb);
  2188. }
  2189. resp.setName(name.str());
  2190. resp.setWuid(req.getWuid());
  2191. resp.setSequence(req.getSequence());
  2192. resp.setStart(start);
  2193. if (requested > total)
  2194. requested = (unsigned)total;
  2195. resp.setRequested(requested);
  2196. resp.setCount(count);
  2197. resp.setTotal(total);
  2198. resp.setFormat(req.getFormat());
  2199. }
  2200. catch(IException* e)
  2201. {
  2202. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2203. }
  2204. return true;
  2205. }
  2206. bool CWsWorkunitsEx::onWUResultSummary(IEspContext &context, IEspWUResultSummaryRequest &req, IEspWUResultSummaryResponse &resp)
  2207. {
  2208. try
  2209. {
  2210. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2211. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2212. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2213. resp.setWuid(req.getWuid());
  2214. resp.setSequence(req.getSequence());
  2215. IArrayOf<IEspECLResult> results;
  2216. Owned<IConstWUResult> r = cw->getResultBySequence(req.getSequence());
  2217. if (r)
  2218. {
  2219. WsWuInfo winfo(context, cw);
  2220. winfo.getResult(*r, results, 0);
  2221. resp.setFormat(r->getResultFormat());
  2222. resp.setResult(results.item(0));
  2223. }
  2224. }
  2225. catch(IException* e)
  2226. {
  2227. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2228. }
  2229. return true;
  2230. }
  2231. void getFileResults(IEspContext &context, const char* logicalName, const char* cluster,__int64 start, unsigned& count,__int64& total,IStringVal& resname,bool bin, MemoryBuffer& buf)
  2232. {
  2233. Owned<IResultSetFactory> resultSetFactory;
  2234. if (context.querySecManager())
  2235. resultSetFactory.setown(getSecResultSetFactory(*context.querySecManager(), *context.queryUser()));
  2236. else
  2237. resultSetFactory.setown(getResultSetFactory(context.queryUserId(), context.queryPassword()));
  2238. Owned<INewResultSet> result(resultSetFactory->createNewFileResultSet(logicalName, cluster));
  2239. appendResultSet(buf, result, resname.str(), start, count, total, bin);
  2240. }
  2241. void getWorkunitCluster(IEspContext &context, const char* wuid, SCMStringBuffer& cluster, bool checkArchiveWUs)
  2242. {
  2243. if (isEmpty(wuid))
  2244. return;
  2245. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2246. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2247. if (cw)
  2248. cw->getClusterName(cluster);
  2249. else if (checkArchiveWUs)
  2250. {
  2251. Owned<IPropertyTree> wuProps;// = getArchivedWorkUnitProperties(wuid);
  2252. if (wuProps)
  2253. cluster.set(wuProps->queryProp("@clusterName"));
  2254. }
  2255. }
  2256. bool CWsWorkunitsEx::onWUResult(IEspContext &context, IEspWUResultRequest &req, IEspWUResultResponse &resp)
  2257. {
  2258. try
  2259. {
  2260. ensureWsWorkunitAccess(context, req.getWuid(), SecAccess_Read);
  2261. MemoryBuffer mb;
  2262. SCMStringBuffer name;
  2263. __int64 total=0;
  2264. __int64 start = req.getStart() > 0 ? req.getStart() : 0;
  2265. unsigned count=req.getCount() ? req.getCount() : 100, requested=count;
  2266. unsigned seq = req.getSequence();
  2267. VStringBuffer filter("start=%"I64F"d;count=%d", start, count);
  2268. addToQueryString(filter, "clusterName", req.getCluster(), ';');
  2269. addToQueryString(filter, "logicalName", req.getLogicalName(), ';');
  2270. addToQueryString(filter, "wuid", req.getWuid(), ';');
  2271. addToQueryString(filter, "resultName", req.getResultName(), ';');
  2272. filter.appendf(";seq=%d;", seq);
  2273. const char* wuid = req.getWuid();
  2274. const char* logicalName = req.getLogicalName();
  2275. const char* clusterName = req.getCluster();
  2276. const char* resultName = req.getResultName();
  2277. Owned<DataCacheElement> data = dataCache->lookup(context, filter, awusCacheMinutes);
  2278. if (data)
  2279. {
  2280. mb.append(data->m_data.c_str());
  2281. name.set(data->m_name.c_str());
  2282. logicalName = data->m_logicalName.c_str();
  2283. wuid = data->m_wuid.c_str();
  2284. resultName = data->m_resultName.c_str();
  2285. seq = data->m_seq;
  2286. start = data->m_start;
  2287. count = data->m_rowcount;
  2288. requested = (unsigned)data->m_requested;
  2289. total = data->m_total;
  2290. if (notEmpty(logicalName))
  2291. resp.setLogicalName(logicalName);
  2292. else
  2293. {
  2294. if (notEmpty(wuid))
  2295. resp.setWuid(wuid);
  2296. resp.setSequence(seq);
  2297. }
  2298. }
  2299. else
  2300. {
  2301. if(logicalName && *logicalName)
  2302. {
  2303. StringBuffer lwuid;
  2304. getWuidFromLogicalFileName(context, logicalName, lwuid);
  2305. SCMStringBuffer cluster;
  2306. if (lwuid.length())
  2307. getWorkunitCluster(context, lwuid.str(), cluster, true);
  2308. if (cluster.length())
  2309. {
  2310. getFileResults(context, logicalName, cluster.str(), start, count, total, name, false, mb);
  2311. resp.setLogicalName(logicalName);
  2312. }
  2313. else if (notEmpty(clusterName))
  2314. {
  2315. getFileResults(context, logicalName, clusterName, start, count, total, name, false, mb);
  2316. resp.setLogicalName(logicalName);
  2317. }
  2318. else
  2319. throw MakeStringException(ECLWATCH_INVALID_INPUT,"Need valid target cluster to browse file %s.",logicalName);
  2320. }
  2321. else if (notEmpty(wuid) && notEmpty(resultName))
  2322. {
  2323. name.set(resultName);
  2324. getWsWuResult(context, wuid, resultName, NULL, 0, start, count, total, name, false, mb);
  2325. resp.setWuid(wuid);
  2326. resp.setSequence(seq);
  2327. }
  2328. else
  2329. {
  2330. getWsWuResult(context, wuid, NULL, NULL, seq, start, count, total, name, false, mb);
  2331. resp.setWuid(wuid);
  2332. resp.setSequence(seq);
  2333. }
  2334. mb.append(0);
  2335. if (requested > total)
  2336. requested = (unsigned)total;
  2337. dataCache->add(filter, mb.toByteArray(), name.str(), logicalName, wuid, resultName, seq, start, count, requested, total);
  2338. }
  2339. resp.setName(name.str());
  2340. resp.setStart(start);
  2341. if (clusterName && *clusterName)
  2342. resp.setCluster(clusterName);
  2343. resp.setRequested(requested);
  2344. resp.setCount(count);
  2345. resp.setTotal(total);
  2346. resp.setResult(mb.toByteArray());
  2347. context.queryXslParameters()->setProp("escapeResults","1");
  2348. }
  2349. catch(IException* e)
  2350. {
  2351. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2352. }
  2353. return true;
  2354. }
  2355. void getScheduledWUs(IEspContext &context, const char *serverName, const char *eventName, IArrayOf<IEspScheduledWU> & results)
  2356. {
  2357. if (notEmpty(serverName))
  2358. {
  2359. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2360. Owned<IScheduleReader> reader = getScheduleReader(serverName, eventName);
  2361. Owned<IScheduleReaderIterator> it(reader->getIterator());
  2362. while(it->isValidEventName())
  2363. {
  2364. StringBuffer ieventName;
  2365. it->getEventName(ieventName);
  2366. while(it->isValidEventText())
  2367. {
  2368. StringBuffer ieventText;
  2369. it->getEventText(ieventText);
  2370. while(it->isValidWuid())
  2371. {
  2372. StringBuffer wuid;
  2373. it->getWuid(wuid);
  2374. if (wuid.length())
  2375. {
  2376. Owned<IEspScheduledWU> scheduledWU = createScheduledWU("");
  2377. scheduledWU->setWuid(wuid.str());
  2378. scheduledWU->setCluster(serverName);
  2379. if (ieventName.length())
  2380. scheduledWU->setEventName(ieventName.str());
  2381. if (ieventText.str())
  2382. scheduledWU->setEventText(ieventText.str());
  2383. try
  2384. {
  2385. SCMStringBuffer s;
  2386. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid.str(), false);
  2387. if (cw)
  2388. scheduledWU->setJobName(cw->getJobName(s).str());
  2389. }
  2390. catch (IException *e)
  2391. {
  2392. e->Release();
  2393. }
  2394. results.append(*scheduledWU.getLink());
  2395. }
  2396. it->nextWuid();
  2397. }
  2398. it->nextEventText();
  2399. }
  2400. it->nextEventName();
  2401. }
  2402. }
  2403. return;
  2404. }
  2405. bool CWsWorkunitsEx::onWUShowScheduled(IEspContext &context, IEspWUShowScheduledRequest & req, IEspWUShowScheduledResponse & resp)
  2406. {
  2407. try
  2408. {
  2409. DBGLOG("WUShowScheduled");
  2410. const char *clusterName = req.getCluster();
  2411. const char *eventName = req.getEventName();
  2412. IArrayOf<IEspScheduledWU> results;
  2413. if(notEmpty(req.getPushEventName()))
  2414. resp.setPushEventName(req.getPushEventName());
  2415. if(notEmpty(req.getPushEventText()))
  2416. resp.setPushEventText(req.getPushEventText());
  2417. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2418. Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
  2419. Owned<IPropertyTree> root = &environment->getPTree();
  2420. if (!root)
  2421. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  2422. unsigned i = 0;
  2423. Owned<IPropertyTreeIterator> ic = root->getElements("Software/Topology/Cluster");
  2424. IArrayOf<IEspServerInfo> servers;
  2425. ForEach(*ic)
  2426. {
  2427. IPropertyTree &cluster = ic->query();
  2428. const char *iclusterName = cluster.queryProp("@name");
  2429. if (isEmpty(iclusterName))
  2430. continue;
  2431. if(isEmpty(clusterName))
  2432. getScheduledWUs(context, iclusterName, eventName, results);
  2433. else if (strieq(clusterName, iclusterName))
  2434. {
  2435. getScheduledWUs(context, clusterName, eventName, results);
  2436. resp.setClusterSelected(i+1);
  2437. }
  2438. Owned<IEspServerInfo> server = createServerInfo("");
  2439. server->setName(iclusterName);
  2440. servers.append(*server.getLink());
  2441. i++;
  2442. }
  2443. if (servers.length())
  2444. resp.setClusters(servers);
  2445. if (results.length())
  2446. resp.setWorkunits(results);
  2447. bool first=false;
  2448. StringBuffer Query("PageFrom=Scheduler");
  2449. appendUrlParameter(Query, "EventName", eventName, first);
  2450. appendUrlParameter(Query, "ECluster", clusterName, first);
  2451. resp.setQuery(Query.str());
  2452. }
  2453. catch(IException* e)
  2454. {
  2455. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2456. }
  2457. return true;
  2458. }
  2459. bool CWsWorkunitsEx::onWUExport(IEspContext &context, IEspWUExportRequest &req, IEspWUExportResponse &resp)
  2460. {
  2461. try
  2462. {
  2463. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2464. WsWuSearch ws(context, req.getOwner(), req.getState(), req.getCluster(), req.getStartDate(), req.getEndDate(), req.getECL(), req.getJobname());
  2465. StringBuffer xml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Workunits>");
  2466. for(WsWuSearch::iterator it=ws.begin(); it!=ws.end(); it++)
  2467. {
  2468. Owned<IConstWorkUnit> cw = factory->openWorkUnit(it->c_str(), false);
  2469. if (cw)
  2470. exportWorkUnitToXML(cw, xml);
  2471. }
  2472. xml.append("</Workunits>");
  2473. MemoryBuffer mb;
  2474. mb.setBuffer(xml.length(),(void*)xml.str());
  2475. resp.setExportData(mb);
  2476. resp.setExportData_mimetype(HTTP_TYPE_TEXT_XML);
  2477. }
  2478. catch(IException* e)
  2479. {
  2480. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2481. }
  2482. return true;
  2483. }
  2484. bool CWsWorkunitsEx::onWUListLocalFileRequired(IEspContext& context, IEspWUListLocalFileRequiredRequest& req, IEspWUListLocalFileRequiredResponse& resp)
  2485. {
  2486. try
  2487. {
  2488. const char* wuid = req.getWuid();
  2489. if (isEmpty(wuid))
  2490. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit ID not defined.");
  2491. ensureWsWorkunitAccess(context, wuid, SecAccess_Read);
  2492. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2493. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid, false);
  2494. if (!cw)
  2495. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Workunit %s not found.", wuid);
  2496. IArrayOf<IEspLogicalFileUpload> localFiles;
  2497. Owned<IConstLocalFileUploadIterator> it = cw->getLocalFileUploads();
  2498. ForEach(*it)
  2499. {
  2500. Owned<IConstLocalFileUpload> file = it->get();
  2501. if(!file)
  2502. continue;
  2503. Owned<IEspLogicalFileUpload> up = createLogicalFileUpload();
  2504. SCMStringBuffer s;
  2505. up->setType(file->queryType());
  2506. up->setSource(file->getSource(s).str());
  2507. up->setDestination(file->getDestination(s).str());
  2508. up->setEventTag(file->getEventTag(s).str());
  2509. localFiles.append(*up.getLink());
  2510. }
  2511. resp.setLocalFileUploads(localFiles);
  2512. }
  2513. catch(IException* e)
  2514. {
  2515. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2516. }
  2517. return true;
  2518. }
  2519. typedef enum wsEclTypes_
  2520. {
  2521. wsEclTypeUnknown,
  2522. xsdString,
  2523. xsdBoolean,
  2524. xsdDecimal,
  2525. xsdFloat,
  2526. xsdDouble,
  2527. xsdDuration,
  2528. xsdDateTime,
  2529. xsdTime,
  2530. xsdDate,
  2531. xsdYearMonth,
  2532. xsdYear,
  2533. xsdMonthDay,
  2534. xsdDay,
  2535. xsdMonth,
  2536. xsdHexBinary,
  2537. xsdBase64Binary,
  2538. xsdAnyURI,
  2539. xsdQName,
  2540. xsdNOTATION,
  2541. xsdNormalizedString,
  2542. xsdToken,
  2543. xsdLanguage,
  2544. xsdNMTOKEN,
  2545. xsdNMTOKENS,
  2546. xsdName,
  2547. xsdNCName,
  2548. xsdID,
  2549. xsdIDREF,
  2550. xsdIDREFS,
  2551. xsdENTITY,
  2552. xsdENTITIES,
  2553. xsdInteger,
  2554. xsdNonPositiveInteger,
  2555. xsdNegativeInteger,
  2556. xsdLong,
  2557. xsdInt,
  2558. xsdShort,
  2559. xsdByte,
  2560. xsdNonNegativeInteger,
  2561. xsdUnsignedLong,
  2562. xsdUnsignedInt,
  2563. xsdUnsignedShort,
  2564. xsdUnsignedByte,
  2565. xsdPositiveInteger,
  2566. tnsRawDataFile,
  2567. tnsCsvDataFile,
  2568. tnsEspStringArray,
  2569. tnsEspIntArray,
  2570. tnsXmlDataSet,
  2571. maxWsEclType
  2572. } wsEclType;
  2573. bool CWsWorkunitsEx::onWUAddLocalFileToWorkunit(IEspContext& context, IEspWUAddLocalFileToWorkunitRequest& req, IEspWUAddLocalFileToWorkunitResponse& resp)
  2574. {
  2575. try
  2576. {
  2577. const char* wuid = req.getWuid();
  2578. if (isEmpty(wuid))
  2579. {
  2580. resp.setResult("WUID is not defined!");
  2581. return true;
  2582. }
  2583. ensureWsWorkunitAccess(context, wuid, SecAccess_Write);
  2584. resp.setWuid(wuid);
  2585. const char* varname = req.getName();
  2586. if (isEmpty(varname))
  2587. {
  2588. resp.setResult("Name is not defined!");
  2589. return true;
  2590. }
  2591. resp.setName(varname);
  2592. wsEclType type = (wsEclType) req.getType();
  2593. const char *val = req.getVal();
  2594. unsigned len = req.getLength();
  2595. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2596. WorkunitUpdate wu(factory->updateWorkUnit(wuid));
  2597. if (!wu)
  2598. {
  2599. resp.setResult("Workunit not found!");
  2600. return true;
  2601. }
  2602. Owned<IWUResult> wuRslt = wu->updateResultByName(varname);
  2603. if (isEmpty(val))
  2604. val=req.getDefVal();
  2605. if (notEmpty(val))
  2606. {
  2607. switch (type)
  2608. {
  2609. case xsdBoolean:
  2610. wuRslt->setResultBool((strieq(val, "1") || strieq(val, "true") || strieq(val, "on")));
  2611. wuRslt->setResultStatus(ResultStatusSupplied);
  2612. break;
  2613. case xsdDecimal:
  2614. case xsdFloat:
  2615. case xsdDouble:
  2616. wuRslt->setResultReal(atof(val));
  2617. wuRslt->setResultStatus(ResultStatusSupplied);
  2618. break;
  2619. case xsdInteger:
  2620. case xsdNonPositiveInteger:
  2621. case xsdNegativeInteger:
  2622. case xsdLong:
  2623. case xsdInt:
  2624. case xsdShort:
  2625. case xsdByte:
  2626. case xsdNonNegativeInteger:
  2627. case xsdUnsignedLong:
  2628. case xsdUnsignedInt:
  2629. case xsdUnsignedShort:
  2630. case xsdUnsignedByte:
  2631. case xsdPositiveInteger:
  2632. wuRslt->setResultInt(_atoi64(val));
  2633. wuRslt->setResultStatus(ResultStatusSupplied);
  2634. break;
  2635. case tnsEspIntArray:
  2636. case tnsEspStringArray:
  2637. wuRslt->setResultRaw(len, val, ResultFormatXmlSet);
  2638. break;
  2639. case tnsRawDataFile:
  2640. wuRslt->setResultRaw(len, val, ResultFormatRaw);
  2641. break;
  2642. case tnsXmlDataSet:
  2643. wuRslt->setResultRaw(len, val, ResultFormatXml);
  2644. break;
  2645. case tnsCsvDataFile:
  2646. case xsdBase64Binary: //tbd
  2647. case xsdHexBinary:
  2648. break;
  2649. default:
  2650. wuRslt->setResultString(val, len);
  2651. wuRslt->setResultStatus(ResultStatusSupplied);
  2652. break;
  2653. }
  2654. }
  2655. resp.setResult("Result has been set as required!");
  2656. }
  2657. catch(IException* e)
  2658. {
  2659. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2660. }
  2661. return true;
  2662. }
  2663. void getClusterConfig(char const * clusterType, char const * clusterName, char const * processName, StringBuffer& netAddress)
  2664. {
  2665. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2666. Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
  2667. Owned<IPropertyTree> pRoot = &environment->getPTree();
  2668. VStringBuffer xpath("Software/%s[@name='%s']", clusterType, clusterName);
  2669. IPropertyTree* pCluster = pRoot->queryPropTree(xpath.str());
  2670. if (!pCluster)
  2671. throw MakeStringException(ECLWATCH_CLUSTER_NOT_IN_ENV_INFO, "'%s %s' is not defined.", clusterType, clusterName);
  2672. const char* port = pCluster->queryProp(xpath.set(processName).append("@port").str());
  2673. const char* computer = pCluster->queryProp(xpath.set(processName).append("@computer").str());
  2674. if (isEmpty(computer))
  2675. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "'%s %s: %s' is not defined.", clusterType, clusterName, processName);
  2676. Owned<IConstMachineInfo> pMachine = environment->getMachine(computer);
  2677. if (pMachine)
  2678. {
  2679. StringBufferAdaptor s(netAddress);
  2680. pMachine->getNetAddress(s);
  2681. #ifdef MACHINE_IP
  2682. if (streq(netAddress.str(), "."))
  2683. netAddress = MACHINE_IP;
  2684. #endif
  2685. netAddress.append(':').append(port);
  2686. }
  2687. return;
  2688. }
  2689. bool CWsWorkunitsEx::onWUProcessGraph(IEspContext &context,IEspWUProcessGraphRequest &req, IEspWUProcessGraphResponse &resp)
  2690. {
  2691. try
  2692. {
  2693. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2694. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2695. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2696. Owned <IConstWUGraph> graph = cw->getGraph(req.getName());
  2697. Owned <IPropertyTree> xgmml = graph->getXGMMLTree(true); // merge in graph progress information
  2698. StringBuffer xml;
  2699. resp.setTheGraph(toXML(xgmml.get(), xml).str());
  2700. }
  2701. catch(IException* e)
  2702. {
  2703. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2704. }
  2705. return true;
  2706. }
  2707. bool isRunning(IConstWorkUnit &cw)
  2708. {
  2709. // MORE - move into workunit interface
  2710. switch (cw.getState())
  2711. {
  2712. case WUStateFailed:
  2713. case WUStateAborted:
  2714. case WUStateCompleted:
  2715. return false;
  2716. default:
  2717. return true;
  2718. }
  2719. }
  2720. bool CWsWorkunitsEx::onWUGetGraph(IEspContext& context, IEspWUGetGraphRequest& req, IEspWUGetGraphResponse& resp)
  2721. {
  2722. try
  2723. {
  2724. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2725. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2726. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2727. WUGraphIDType id;
  2728. SCMStringBuffer runningGraph;
  2729. bool running= (isRunning(*cw) && cw->getRunningGraph(runningGraph,id));
  2730. IArrayOf<IEspECLGraphEx> graphs;
  2731. Owned<IConstWUGraphIterator> it = &cw->getGraphs(GraphTypeAny);
  2732. ForEach(*it)
  2733. {
  2734. IConstWUGraph &graph = it->query();
  2735. if(!graph.isValid())
  2736. continue;
  2737. SCMStringBuffer name, label, type;
  2738. graph.getName(name);
  2739. graph.getLabel(label);
  2740. graph.getTypeName(type);
  2741. if(isEmpty(req.getGraphName()) || strieq(name.str(), req.getGraphName()))
  2742. {
  2743. Owned<IEspECLGraphEx> g = createECLGraphEx("","");
  2744. g->setName(name.str());
  2745. g->setLabel(label.str());
  2746. g->setType(type.str());
  2747. if(running && streq(name.str(), runningGraph.str()))
  2748. {
  2749. g->setRunning(true);
  2750. g->setRunningId(id);
  2751. }
  2752. Owned<IPropertyTree> xgmml = graph.getXGMMLTree(true);
  2753. // New functionality, if a subgraph id is specified and we only want to load the xgmml for that subgraph
  2754. // then we need to conditionally pull a propertytree from the xgmml graph one and use that for the xgmml.
  2755. StringBuffer xml;
  2756. if (notEmpty(req.getSubGraphId()))
  2757. {
  2758. VStringBuffer xpath("//node[@id='%s']", req.getSubGraphId());
  2759. toXML(xgmml->queryPropTree(xpath.str()), xml);
  2760. }
  2761. else
  2762. toXML(xgmml, xml);
  2763. g->setGraph(xml.str());
  2764. if (context.getClientVersion() > 1.20)
  2765. {
  2766. Owned<IConstWUGraphProgress> progress = cw->getGraphProgress(name.str());
  2767. if (progress)
  2768. {
  2769. WUGraphState graphstate= progress->queryGraphState();
  2770. if (graphstate == WUGraphComplete)
  2771. g->setComplete(true);
  2772. else if (graphstate == WUGraphFailed)
  2773. g->setFailed(true);
  2774. }
  2775. }
  2776. graphs.append(*g.getClear());
  2777. }
  2778. }
  2779. resp.setGraphs(graphs);
  2780. }
  2781. catch(IException* e)
  2782. {
  2783. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2784. }
  2785. return true;
  2786. }
  2787. bool CWsWorkunitsEx::onGVCAjaxGraph(IEspContext &context, IEspGVCAjaxGraphRequest &req, IEspGVCAjaxGraphResponse &resp)
  2788. {
  2789. try
  2790. {
  2791. resp.setName(req.getName());
  2792. resp.setGraphName(req.getGraphName());
  2793. resp.setGraphType("eclwatch");
  2794. double version = context.getClientVersion();
  2795. if (version > 1.19)
  2796. resp.setSubGraphId(req.getSubGraphId());
  2797. if (version > 1.20)
  2798. resp.setSubGraphOnly(req.getSubGraphOnly());
  2799. }
  2800. catch(IException* e)
  2801. {
  2802. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2803. }
  2804. return true;
  2805. }
  2806. bool CWsWorkunitsEx::onWUGraphInfo(IEspContext &context,IEspWUGraphInfoRequest &req, IEspWUGraphInfoResponse &resp)
  2807. {
  2808. try
  2809. {
  2810. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2811. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2812. if(!cw)
  2813. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",req.getWuid());
  2814. ensureWsWorkunitAccess(context, *cw, SecAccess_Write);
  2815. resp.setWuid(req.getWuid());
  2816. resp.setName(req.getName());
  2817. resp.setRunning(isRunning(*cw));
  2818. if (notEmpty(req.getGID()))
  2819. resp.setGID(req.getGID());
  2820. if(!req.getBatchWU_isNull())
  2821. resp.setBatchWU(req.getBatchWU());
  2822. }
  2823. catch(IException* e)
  2824. {
  2825. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2826. }
  2827. return true;
  2828. }
  2829. bool CWsWorkunitsEx::onWUGVCGraphInfo(IEspContext &context,IEspWUGVCGraphInfoRequest &req, IEspWUGVCGraphInfoResponse &resp)
  2830. {
  2831. try
  2832. {
  2833. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2834. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2835. if(!cw)
  2836. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",req.getWuid());
  2837. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2838. resp.setWuid(req.getWuid());
  2839. resp.setName(req.getName());
  2840. resp.setRunning(isRunning(*cw));
  2841. if (notEmpty(req.getGID()))
  2842. resp.setGID(req.getGID());
  2843. if(!req.getBatchWU_isNull())
  2844. resp.setBatchWU(req.getBatchWU());
  2845. StringBuffer xml("<Control><Endpoint><Query id=\"Gordon.Extractor.0\">");
  2846. xml.appendf("<Graph id=\"%s\">", req.getName());
  2847. if (context.getClientVersion() > 1.17)
  2848. {
  2849. xml.append("<Subgraph>");
  2850. xml.append(req.getSubgraphId_isNull() ? 0 : req.getSubgraphId());
  2851. xml.append("</Subgraph>");
  2852. }
  2853. xml.append("</Graph></Query></Endpoint></Control>");
  2854. resp.setTheGraph(xml.str());
  2855. }
  2856. catch(IException* e)
  2857. {
  2858. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2859. }
  2860. return true;
  2861. }
  2862. bool CWsWorkunitsEx::onWUGraphTiming(IEspContext &context, IEspWUGraphTimingRequest &req, IEspWUGraphTimingResponse &resp)
  2863. {
  2864. try
  2865. {
  2866. DBGLOG("WUGraphTiming WUID=%s", req.getWuid());
  2867. Owned<IWorkUnitFactory> factory = getWorkUnitFactory(context.querySecManager(), context.queryUser());
  2868. Owned<IConstWorkUnit> cw = factory->openWorkUnit(req.getWuid(), false);
  2869. if(!cw)
  2870. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot open workunit %s.",req.getWuid());
  2871. ensureWsWorkunitAccess(context, *cw, SecAccess_Read);
  2872. resp.updateWorkunit().setWuid(req.getWuid());
  2873. WsWuInfo winfo(context, cw);
  2874. IArrayOf<IConstECLTimingData> timingData;
  2875. winfo.getGraphTimingData(timingData, 0);
  2876. resp.updateWorkunit().setTimingData(timingData);
  2877. }
  2878. catch(IException* e)
  2879. {
  2880. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2881. }
  2882. return true;
  2883. }
  2884. int CWsWorkunitsSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  2885. {
  2886. try
  2887. {
  2888. StringBuffer xml;
  2889. StringBuffer xslt;
  2890. if(strieq(method,"WUQuery") || strieq(method,"WUJobList"))
  2891. {
  2892. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2893. Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
  2894. Owned<IPropertyTree> root = &environment->getPTree();
  2895. if (!root)
  2896. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  2897. if(strieq(method,"WUQuery"))
  2898. {
  2899. SecAccessFlags accessOwn;
  2900. SecAccessFlags accessOthers;
  2901. getUserWuAccessFlags(context, accessOwn, accessOthers, false);
  2902. xml.append("<WUQuery>");
  2903. if ((accessOwn == SecAccess_None) && (accessOthers == SecAccess_None))
  2904. xml.appendf("<ErrorMessage>Access to workunit is denied.</ErrorMessage>");
  2905. else
  2906. {
  2907. MapStringTo<bool> added;
  2908. Owned<IPropertyTreeIterator> it = root->getElements("Software/Topology/Cluster");
  2909. ForEach(*it)
  2910. {
  2911. const char *name = it->query().queryProp("@name");
  2912. if (notEmpty(name) && !added.getValue(name))
  2913. {
  2914. added.setValue(name, true);
  2915. appendXMLTag(xml, "Cluster", name);
  2916. }
  2917. }
  2918. }
  2919. xml.append("</WUQuery>");
  2920. xslt.append(getCFD()).append("./smc_xslt/wuid_search.xslt");
  2921. }
  2922. else if (strieq(method,"WUJobList"))
  2923. {
  2924. StringBuffer cluster;
  2925. request->getParameter("Cluster", cluster);
  2926. StringBuffer range;
  2927. request->getParameter("Range",range);
  2928. Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(cluster);
  2929. xml.append("<WUJobList>");
  2930. if (range.length())
  2931. appendXMLTag(xml, "Range", range.str());
  2932. if (clusterInfo)
  2933. {
  2934. const StringArray &thorInstances = clusterInfo->getThorProcesses();
  2935. ForEachItemIn(i, thorInstances)
  2936. {
  2937. xml.append("<Cluster").append('>').append(thorInstances.item(i)).append("</Cluster>");
  2938. }
  2939. }
  2940. xml.append("<TargetCluster>").append(cluster).append("</TargetCluster>");
  2941. xml.append("</WUJobList>");
  2942. xslt.append(getCFD()).append("./smc_xslt/jobs_search.xslt");
  2943. response->addHeader("Expires", "0");
  2944. }
  2945. }
  2946. if (xslt.length() && xml.length())
  2947. {
  2948. StringBuffer html;
  2949. xsltTransform(xml.str(), xslt.str(), NULL, html);
  2950. response->setContent(html.str());
  2951. response->setContentType(HTTP_TYPE_TEXT_HTML_UTF8);
  2952. response->send();
  2953. return 0;
  2954. }
  2955. }
  2956. catch(IException* e)
  2957. {
  2958. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2959. }
  2960. return onGetNotFound(context, request, response, service);
  2961. }
  2962. void deployEclOrArchive(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  2963. {
  2964. NewWsWorkunit wu(context);
  2965. SCMStringBuffer wuid;
  2966. wu->getWuid(wuid);
  2967. wu->setAction(WUActionCompile);
  2968. StringBuffer name(req.getName());
  2969. if (!name.trim().length() && notEmpty(req.getFileName()))
  2970. splitFilename(req.getFileName(), NULL, NULL, &name, NULL);
  2971. if (name.length())
  2972. wu->setJobName(name.str());
  2973. if (req.getObject().length())
  2974. {
  2975. StringBuffer text(req.getObject().length(), req.getObject().toByteArray());
  2976. wu.setQueryText(text.str());
  2977. }
  2978. if (!req.getResultLimit_isNull())
  2979. wu->setResultLimit(req.getResultLimit());
  2980. wu->commit();
  2981. wu.clear();
  2982. submitWsWorkunit(context, wuid.str(), req.getCluster(), NULL, 0, true, false);
  2983. waitForWorkUnitToCompile(wuid.str(), req.getWait());
  2984. WsWuInfo winfo(context, wuid.str());
  2985. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  2986. winfo.getExceptions(resp.updateWorkunit(), WUINFO_All);
  2987. name.clear();
  2988. if (notEmpty(resp.updateWorkunit().getJobname()))
  2989. origValueChanged(req.getName(), resp.updateWorkunit().getJobname(), name, false);
  2990. if (name.length()) //non generated user specified name, so override #Workunit('name')
  2991. {
  2992. WorkunitUpdate wx(&winfo.cw->lock());
  2993. wx->setJobName(name.str());
  2994. resp.updateWorkunit().setJobname(name.str());
  2995. }
  2996. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  2997. }
  2998. StringBuffer &sharedObjectFileName(StringBuffer &filename, const char *name, const char *ext, unsigned copy)
  2999. {
  3000. filename.append((name && *name) ? name : "workunit");
  3001. if (copy)
  3002. filename.append('-').append(copy);
  3003. if (notEmpty(ext))
  3004. filename.append(ext);
  3005. return filename;
  3006. }
  3007. inline StringBuffer &buildFullDllPath(StringBuffer &dllpath, StringBuffer &dllname, const char *dir, const char *name, const char *ext, unsigned copy)
  3008. {
  3009. return addPathSepChar(dllpath.set(dir)).append(sharedObjectFileName(dllname, name, ext, copy));
  3010. }
  3011. void writeSharedObject(const char *srcpath, const MemoryBuffer &obj, const char *dir, StringBuffer &dllpath, StringBuffer &dllname)
  3012. {
  3013. StringBuffer name, ext;
  3014. if (srcpath && *srcpath)
  3015. splitFilename(srcpath, NULL, NULL, &name, &ext);
  3016. unsigned copy=0;
  3017. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), copy);
  3018. while (checkFileExists(dllpath.str()))
  3019. buildFullDllPath(dllpath.clear(), dllname.clear(), dir, name.str(), ext.str(), ++copy);
  3020. DBGLOG("Writing workunit dll: %s", dllpath.str());
  3021. Owned<IFile> f = createIFile(dllpath.str());
  3022. Owned<IFileIO> io = f->open(IFOcreate);
  3023. io->write(0, obj.length(), obj.toByteArray());
  3024. }
  3025. void deploySharedObject(IEspContext &context, StringBuffer &wuid, const char *filename, const char *cluster, const char *name, const MemoryBuffer &obj, const char *dir, const char *xml)
  3026. {
  3027. StringBuffer dllpath, dllname;
  3028. StringBuffer srcname(filename);
  3029. if (!srcname.length())
  3030. srcname.append(name).append(SharedObjectExtension);
  3031. writeSharedObject(srcname.str(), obj, dir, dllpath, dllname);
  3032. NewWsWorkunit wu(context);
  3033. StringBufferAdaptor isvWuid(wuid);
  3034. wu->getWuid(isvWuid);
  3035. wu->setClusterName(cluster);
  3036. wu->commit();
  3037. StringBuffer dllXML;
  3038. if (getWorkunitXMLFromFile(dllpath.str(), dllXML))
  3039. {
  3040. Owned<ILocalWorkUnit> embeddedWU = createLocalWorkUnit();
  3041. embeddedWU->loadXML(dllXML.str());
  3042. queryExtendedWU(wu)->copyWorkUnit(embeddedWU);
  3043. }
  3044. wu.associateDll(dllpath.str(), dllname.str());
  3045. if (name && *name)
  3046. wu->setJobName(name);
  3047. //clean slate, copy only select items from processed workunit xml
  3048. if (xml && *xml)
  3049. {
  3050. Owned<IPropertyTree> srcxml = createPTreeFromXMLString(xml);
  3051. if (srcxml->hasProp("@jobName"))
  3052. wu->setJobName(srcxml->queryProp("@jobName"));
  3053. if (srcxml->hasProp("@token"))
  3054. wu->setSecurityToken(srcxml->queryProp("@token"));
  3055. if (srcxml->hasProp("Query/Text"))
  3056. wu.setQueryText(srcxml->queryProp("Query/Text"));
  3057. }
  3058. wu->setState(WUStateCompiled);
  3059. wu->commit();
  3060. wu.clear();
  3061. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  3062. }
  3063. void deploySharedObject(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp, const char *dir, const char *xml=NULL)
  3064. {
  3065. if (isEmpty(req.getFileName()))
  3066. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File name required when deploying a shared object.");
  3067. if (isEmpty(req.getCluster()))
  3068. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name required when deploying a shared object.");
  3069. StringBuffer wuid;
  3070. deploySharedObject(context, wuid, req.getFileName(), req.getCluster(), req.getName(), req.getObject(), dir, xml);
  3071. WsWuInfo winfo(context, wuid.str());
  3072. winfo.getCommon(resp.updateWorkunit(), WUINFO_All);
  3073. AuditSystemAccess(context.queryUserId(), true, "Updated %s", wuid.str());
  3074. }
  3075. bool CWsWorkunitsEx::onWUDeployWorkunit(IEspContext &context, IEspWUDeployWorkunitRequest & req, IEspWUDeployWorkunitResponse & resp)
  3076. {
  3077. const char *type = req.getObjType();
  3078. try
  3079. {
  3080. if (!context.validateFeatureAccess(OWN_WU_ACCESS, SecAccess_Write, false))
  3081. throw MakeStringException(ECLWATCH_ECL_WU_ACCESS_DENIED, "Failed to create workunit. Permission denied.");
  3082. if (strieq(type, "archive")|| strieq(type, "ecl_text"))
  3083. deployEclOrArchive(context, req, resp);
  3084. else if (strieq(type, "shared_object"))
  3085. deploySharedObject(context, req, resp, queryDirectory.str());
  3086. else
  3087. throw MakeStringException(ECLWATCH_INVALID_INPUT, "WUDeployWorkunit '%s' unkown object type.", type);
  3088. }
  3089. catch(IException* e)
  3090. {
  3091. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3092. }
  3093. return true;
  3094. }