ws_workunitsService.cpp 159 KB

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