ws_workunitsService.cpp 143 KB

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