ws_workunitsService.cpp 119 KB

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