ws_workunitsService.cpp 154 KB

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