ws_workunitsService.cpp 153 KB

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