ws_workunitsService.cpp 147 KB

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