ws_workunitsService.cpp 152 KB

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