ws_workunitsService.cpp 152 KB

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