ws_workunitsService.cpp 135 KB

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