ws_workunitsService.cpp 175 KB

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