ws_fsService.cpp 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434
  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. #pragma warning (disable : 4786)
  14. #pragma warning (disable : 4129)
  15. #include <math.h>
  16. #include "jsocket.hpp"
  17. #include "dasds.hpp"
  18. #include "dadfs.hpp"
  19. #include "dautils.hpp"
  20. #include "daclient.hpp"
  21. #include "wshelpers.hpp"
  22. #include "dfuwu.hpp"
  23. #include "workunit.hpp"
  24. #include "ws_fsService.hpp"
  25. #ifdef _WIN32
  26. #include "windows.h"
  27. #endif
  28. #include "dalienv.hpp"
  29. #include "dfuutil.hpp"
  30. #include "portlist.h"
  31. #include "sacmd.hpp"
  32. #include "exception_util.hpp"
  33. #define DFU_WU_URL "DfuWorkunitsAccess"
  34. #define DFU_EX_URL "DfuExceptionsAccess"
  35. #define FILE_SPRAY_URL "FileSprayAccess"
  36. #define FILE_DESPRAY_URL "FileDesprayAccess"
  37. #define WUDETAILS_REFRESH_MINS 1
  38. const unsigned dropZoneFileSearchMaxFiles = 1000;
  39. void SetResp(StringBuffer &resp, IConstDFUWorkUnit * wu, bool array);
  40. int Schedule::run()
  41. {
  42. PROGLOG("DfuWorkunit WUSchedule Thread started.");
  43. while(!stopping)
  44. {
  45. unsigned int waitTimeMillies = 1000*60;
  46. if (!detached)
  47. {
  48. try
  49. {
  50. if (waitTimeMillies == (unsigned)-1)
  51. {
  52. PROGLOG("WS_FS WUSchedule Thread Re-started.");
  53. waitTimeMillies = 1000*60;
  54. }
  55. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  56. Owned<IConstDFUWorkUnitIterator> itr = factory->getWorkUnitsByState(DFUstate_scheduled);
  57. itr->first();
  58. while(itr->isValid())
  59. {
  60. Owned<IConstDFUWorkUnit> wu = itr->get();
  61. CDateTime dt, now;
  62. now.setNow();
  63. try
  64. {
  65. wu->getTimeScheduled(dt);
  66. if (now.compare(dt) > 0)
  67. {
  68. StringAttr wuid(wu->queryId());
  69. wu.clear();
  70. submitDFUWorkUnit(wuid.get());
  71. }
  72. }
  73. catch(IException *e)
  74. {
  75. StringBuffer msg;
  76. IERRLOG("Exception %d:%s in WsWorkunits Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  77. e->Release();
  78. }
  79. itr->next();
  80. }
  81. }
  82. catch(IException *e)
  83. {
  84. StringBuffer msg;
  85. IERRLOG("Exception %d:%s in WS_FS Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  86. e->Release();
  87. }
  88. catch(...)
  89. {
  90. IERRLOG("Unknown exception in WS_FS Schedule::run");
  91. }
  92. }
  93. else
  94. {
  95. OWARNLOG("Detached from DALI, WS_FS schedule interrupted");
  96. waitTimeMillies = (unsigned)-1;
  97. }
  98. semSchedule.wait(waitTimeMillies);
  99. }
  100. return 0;
  101. }
  102. void CFileSprayEx::init(IPropertyTree *cfg, const char *process, const char *service)
  103. {
  104. StringBuffer xpath;
  105. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/QueueLabel", process, service);
  106. cfg->getProp(xpath.str(), m_QueueLabel);
  107. StringArray qlist;
  108. getDFUServerQueueNames(qlist, nullptr);
  109. if (qlist.ordinality())
  110. {
  111. if (!m_QueueLabel.length())
  112. m_QueueLabel.append(qlist.item(0));
  113. else
  114. {
  115. bool found = false;
  116. ForEachItemIn(i, qlist)
  117. {
  118. const char* qname = qlist.item(i);
  119. if (qname && strieq(qname, m_QueueLabel.str()))
  120. {
  121. found = true;
  122. break;
  123. }
  124. }
  125. if (!found)
  126. throw MakeStringException(-1, "Invalid DFU Queue Label %s in configuration file", m_QueueLabel.str());
  127. }
  128. }
  129. xpath.setf("Software/EspProcess[@name=\"%s\"]/@PageCacheTimeoutSeconds", process);
  130. if (cfg->hasProp(xpath.str()))
  131. setPageCacheTimeoutMilliSeconds(cfg->getPropInt(xpath.str()));
  132. xpath.setf("Software/EspProcess[@name=\"%s\"]/@MaxPageCacheItems", process);
  133. if (cfg->hasProp(xpath.str()))
  134. setMaxPageCacheItems(cfg->getPropInt(xpath.str()));
  135. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/MonitorQueueLabel", process, service);
  136. cfg->getProp(xpath.str(), m_MonitorQueueLabel);
  137. directories.set(cfg->queryPropTree("Software/Directories"));
  138. StringBuffer prop;
  139. prop.appendf("queueLabel=%s", m_QueueLabel.str());
  140. DBGLOG("%s", prop.str());
  141. prop.clear();
  142. prop.appendf("monitorQueueLabel=%s", m_MonitorQueueLabel.str());
  143. DBGLOG("%s", prop.str());
  144. if (!daliClientActive())
  145. {
  146. OERRLOG("No Dali Connection Active.");
  147. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in your configuration file");
  148. }
  149. m_sched.start();
  150. }
  151. StringBuffer& CFileSprayEx::getAcceptLanguage(IEspContext& context, StringBuffer& acceptLanguage)
  152. {
  153. context.getAcceptLanguage(acceptLanguage);
  154. if (!acceptLanguage.length())
  155. {
  156. acceptLanguage.set("en");
  157. return acceptLanguage;
  158. }
  159. acceptLanguage.setLength(2);
  160. VStringBuffer languageFile("%ssmc_xslt/nls/%s/hpcc.xml", getCFD(), acceptLanguage.str());
  161. if (!checkFileExists(languageFile.str()))
  162. acceptLanguage.set("en");
  163. return acceptLanguage;
  164. }
  165. void ParsePath(const char * fullPath, StringBuffer &ip, StringBuffer &filePath, StringBuffer &title)
  166. {
  167. ip.clear();
  168. filePath.clear();
  169. title.clear();
  170. if(fullPath == NULL || *fullPath == '\0')
  171. return;
  172. const char* ptr = fullPath;
  173. if(*ptr == '\\' && *(ptr+1) == '\\')
  174. {
  175. ptr += 2;
  176. while(*ptr != '\0' && *ptr != '\\')
  177. ptr++;
  178. ip.append(ptr - fullPath - 2, fullPath + 2);
  179. }
  180. filePath.append(ptr);
  181. ptr = fullPath + strlen(fullPath) - 1;
  182. while(ptr > fullPath && *ptr != '\\')
  183. ptr--;
  184. title.append(ptr + 1);
  185. }
  186. const char * const NODATETIME="1970-01-01T00:00:00Z";
  187. // Assign from a dfuwu workunit structure to an esp request workunit structure.
  188. static void DeepAssign(IEspContext &context, IConstDFUWorkUnit *src, IEspDFUWorkunit &dest)
  189. {
  190. if(src == NULL)
  191. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "'Source DFU workunit' doesn't exist.");
  192. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  193. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  194. Owned<IPropertyTree> root = &constEnv->getPTree();
  195. double version = context.getClientVersion();
  196. StringBuffer tmp, encoded;
  197. dest.setID(src->queryId());
  198. if (src->getClusterName(tmp.clear()).length()!=0)
  199. {
  200. char *clusterName = (char *)tmp.str();
  201. if (clusterName && *clusterName)
  202. {
  203. StringBuffer clusterNameForDisplay(clusterName);
  204. Owned<IPropertyTreeIterator> clusters= root->getElements("Software/Topology/Cluster");
  205. if (clusters->first())
  206. {
  207. do {
  208. IPropertyTree &cluster = clusters->query();
  209. const char* name = cluster.queryProp("@name");
  210. if (!name || !*name)
  211. continue;
  212. Owned<IPropertyTreeIterator> thorClusters= cluster.getElements(eqThorCluster);
  213. Owned<IPropertyTreeIterator> roxieClusters= cluster.getElements(eqRoxieCluster);
  214. if (thorClusters->first() || roxieClusters->first())
  215. {
  216. if (thorClusters->first())
  217. {
  218. IPropertyTree &thorCluster = thorClusters->query();
  219. const char* process = thorCluster.queryProp("@process");
  220. if (process && *process)
  221. {
  222. if (clusterName && !stricmp(clusterName, process))
  223. {
  224. clusterNameForDisplay.clear().append(name);
  225. break;
  226. }
  227. }
  228. }
  229. if (roxieClusters->first())
  230. {
  231. IPropertyTree &roxieCluster = roxieClusters->query();
  232. const char* process = roxieCluster.queryProp("@process");
  233. if (process && *process)
  234. {
  235. if (clusterName && !stricmp(clusterName, name))
  236. {
  237. clusterNameForDisplay.clear().append(name);
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. } while (clusters->next());
  244. }
  245. dest.setClusterName(clusterNameForDisplay.str());
  246. }
  247. }
  248. if ((version > 1.05) && src->getDFUServerName(tmp.clear()).length())
  249. dest.setDFUServerName(tmp.str());
  250. if (src->getJobName(tmp.clear()).length()!=0)
  251. dest.setJobName(tmp.str());
  252. else
  253. dest.setJobName("");
  254. if (src->getQueue(tmp.clear()).length()!=0)
  255. dest.setQueue(tmp.str());
  256. if (src->getUser(tmp.clear()).length()!=0)
  257. dest.setUser(tmp.str());
  258. dest.setIsProtected(src->isProtected());
  259. dest.setCommand(src->getCommand());
  260. IConstDFUprogress *prog = src->queryProgress();
  261. if (prog != NULL)
  262. {
  263. DFUstate state = prog->getState();
  264. dest.setState(state);
  265. StringBuffer statemsg;
  266. encodeDFUstate(state,statemsg);
  267. dest.setStateMessage(statemsg.str());
  268. CDateTime startAt;
  269. CDateTime stoppAt;
  270. prog->getTimeStarted(startAt);
  271. prog->getTimeStopped(stoppAt);
  272. StringBuffer tmpstr;
  273. startAt.getDateString(tmpstr);
  274. tmpstr.append(" ");
  275. startAt.getTimeString(tmpstr);
  276. dest.setTimeStarted(tmpstr.str());
  277. tmpstr.clear();
  278. stoppAt.getDateString(tmpstr);
  279. tmpstr.append(" ");
  280. stoppAt.getTimeString(tmpstr);
  281. dest.setTimeStopped(tmpstr.str());
  282. StringBuffer prgmsg;
  283. prog->formatProgressMessage(prgmsg);
  284. dest.setProgressMessage(prgmsg.str());
  285. prog->formatSummaryMessage(prgmsg.clear());
  286. dest.setSummaryMessage(prgmsg.str());
  287. unsigned secs = prog->getSecsLeft();
  288. if(secs > 0)
  289. dest.setSecsLeft(secs);
  290. dest.setPercentDone(prog->getPercentDone());
  291. }
  292. IConstDFUoptions *options = src->queryOptions();
  293. if(options)
  294. {
  295. dest.setReplicate(options->getReplicate());
  296. dest.setOverwrite(options->getOverwrite());
  297. }
  298. IConstDFUfileSpec * file = src->querySource();
  299. if (file != NULL)
  300. {
  301. //if (file->getTitle(tmp.clear()).length()!=0)
  302. // dest.setSourceTitle(tmp.str());
  303. StringBuffer lfn;
  304. file->getLogicalName(lfn);
  305. if (lfn.length() != 0)
  306. dest.setSourceLogicalName(lfn.str());
  307. else
  308. dest.setSourceFormat(file->getFormat());
  309. if (file->getRawDirectory(tmp.clear()).length()!=0)
  310. dest.setSourceDirectory(tmp.str());
  311. SocketEndpoint srcdali;
  312. StringBuffer srcdaliip;
  313. file->getForeignDali(srcdali);
  314. srcdali.getIpText(srcdaliip);
  315. if(srcdaliip.length() > 0 && strcmp(srcdaliip.str(), "0.0.0.0") != 0)
  316. dest.setSourceDali(srcdaliip.str());
  317. StringBuffer diffkeyname;
  318. file->getDiffKey(diffkeyname);
  319. if(diffkeyname.length() > 0)
  320. dest.setSourceDiffKeyName(diffkeyname.str());
  321. StringBuffer socket, dir, title;
  322. unsigned np = file->getNumParts(0); // should handle multiple clusters?
  323. if (lfn.length() == 0) { // no logical name
  324. if (np == 1)
  325. {
  326. Owned<IFileDescriptor> info;
  327. try
  328. {
  329. info.setown(file->getFileDescriptor());
  330. if(info)
  331. {
  332. Owned<INode> node = info->getNode(0);
  333. if (node)
  334. {
  335. node->endpoint().getIpText(socket);
  336. dest.setSourceIP(socket.str());
  337. }
  338. const char *defaultdir = info->queryDefaultDir();
  339. if (defaultdir&&*defaultdir)
  340. addPathSepChar(dir.append(defaultdir));
  341. file->getRawFileMask(dir);
  342. dest.setSourceFilePath(dir.str());
  343. }
  344. }
  345. catch(IException *e)
  346. {
  347. EXCLOG(e,"DeepAssign getFileDescriptor");
  348. e->Release();
  349. }
  350. }
  351. }
  352. if (np)
  353. dest.setSourceNumParts(np);
  354. unsigned rs = file->getRecordSize();
  355. if (rs)
  356. dest.setSourceRecordSize(rs);
  357. StringBuffer rowtag;
  358. file->getRowTag(rowtag);
  359. if(rowtag.length() > 0)
  360. dest.setRowTag(rowtag.str());
  361. if (version >= 1.04 && (file->getFormat() == DFUff_csv))
  362. {
  363. StringBuffer separate, terminate, quote, escape;
  364. bool quotedTerminator;
  365. file->getCsvOptions(separate,terminate,quote, escape, quotedTerminator);
  366. if(separate.length() > 0)
  367. dest.setSourceCsvSeparate(separate.str());
  368. if(terminate.length() > 0)
  369. dest.setSourceCsvTerminate(terminate.str());
  370. if(quote.length() > 0)
  371. dest.setSourceCsvQuote(quote.str());
  372. if((version >= 1.05) && (escape.length() > 0))
  373. dest.setSourceCsvEscape(escape.str());
  374. if(version >=1.10)
  375. dest.setQuotedTerminator(quotedTerminator);
  376. }
  377. }
  378. file = src->queryDestination();
  379. if (file != NULL)
  380. {
  381. StringBuffer lfn;
  382. file->getLogicalName(lfn);
  383. if (lfn.length() != 0)
  384. dest.setDestLogicalName(lfn.str());
  385. else
  386. dest.setDestFormat(file->getFormat());
  387. if (file->getRawDirectory(tmp.clear()).length()!=0)
  388. dest.setDestDirectory(tmp.str());
  389. if (file->getGroupName(0,tmp.clear()).length()!=0) // should handle multiple clusters?
  390. {
  391. char *clusterName = (char *)tmp.str();
  392. if (clusterName)
  393. dest.setDestGroupName(clusterName);
  394. }
  395. StringBuffer socket, dir, title;
  396. unsigned np = file->getNumParts(0); // should handle multiple clusters?
  397. if (lfn.length() == 0) { // no logical name
  398. if (np == 1)
  399. {
  400. Owned<IFileDescriptor> info;
  401. try
  402. {
  403. info.setown(file->getFileDescriptor());
  404. if(info)
  405. {
  406. Owned<INode> node = info->getNode(0);
  407. if (node)
  408. {
  409. node->endpoint().getIpText(socket);
  410. dest.setDestIP(socket.str());
  411. }
  412. const char *defaultdir = info->queryDefaultDir();
  413. if (defaultdir&&*defaultdir)
  414. addPathSepChar(dir.append(defaultdir));
  415. file->getRawFileMask(dir);
  416. dest.setDestFilePath(dir.str());
  417. }
  418. }
  419. catch(IException *e)
  420. {
  421. EXCLOG(e,"DeepAssign getFileDescriptor dest");
  422. e->Release();
  423. }
  424. }
  425. }
  426. if (np)
  427. dest.setDestNumParts(np);
  428. unsigned rs = file->getRecordSize();
  429. if (rs)
  430. dest.setDestRecordSize(rs);
  431. dest.setCompress(file->isCompressed());
  432. }
  433. // monitor stuff
  434. IConstDFUmonitor *monitor = src->queryMonitor();
  435. if (monitor) {
  436. monitor->getEventName(tmp.clear());
  437. if (tmp.length())
  438. dest.setMonitorEventName(tmp.str());
  439. bool sub = monitor->getSub();
  440. dest.setMonitorSub(sub);
  441. unsigned sl = monitor->getShotLimit();
  442. if (sl)
  443. dest.setMonitorShotLimit(sl);
  444. }
  445. }
  446. bool CFileSprayEx::ParseLogicalPath(const char * pLogicalPath, const char* groupName, const char* cluster,
  447. StringBuffer &folder, StringBuffer &title, StringBuffer &defaultFolder, StringBuffer &defaultReplicateFolder)
  448. {
  449. if(!pLogicalPath || !*pLogicalPath)
  450. return false;
  451. folder.clear();
  452. title.clear();
  453. defaultFolder.clear();
  454. defaultReplicateFolder.clear();
  455. DFD_OS os = DFD_OSdefault;
  456. if(groupName != NULL && *groupName != '\0')
  457. {
  458. StringBuffer basedir;
  459. GroupType groupType;
  460. Owned<IGroup> group = queryNamedGroupStore().lookup(groupName, basedir, groupType);
  461. if (group) {
  462. switch (queryOS(group->queryNode(0).endpoint())) {
  463. case MachineOsW2K:
  464. os = DFD_OSwindows; break;
  465. case MachineOsSolaris:
  466. case MachineOsLinux:
  467. os = DFD_OSunix; break;
  468. }
  469. if (directories.get())
  470. {
  471. switch (groupType)
  472. {
  473. case grp_roxie:
  474. getConfigurationDirectory(directories, "data", "roxie", cluster, defaultFolder);
  475. getConfigurationDirectory(directories, "data2", "roxie", cluster, defaultReplicateFolder);
  476. // MORE - should extend to systems with higher redundancy
  477. break;
  478. case grp_hthor:
  479. getConfigurationDirectory(directories, "data", "hthor", cluster, defaultFolder);
  480. break;
  481. case grp_thor:
  482. default:
  483. getConfigurationDirectory(directories, "data", "thor", cluster, defaultFolder);
  484. getConfigurationDirectory(directories, "mirror", "thor", cluster, defaultReplicateFolder);
  485. }
  486. }
  487. }
  488. else
  489. {
  490. // Error here?
  491. }
  492. }
  493. makePhysicalPartName(pLogicalPath,0,0,folder,false,os,defaultFolder.str());
  494. const char *n = pLogicalPath;
  495. const char* p;
  496. do {
  497. p = strstr(n,"::");
  498. if(p)
  499. n = p+2;
  500. } while(p);
  501. title.append(n);
  502. return true;
  503. }
  504. bool CFileSprayEx::ParseLogicalPath(const char * pLogicalPath, StringBuffer &title)
  505. {
  506. if(!pLogicalPath || !*pLogicalPath)
  507. return false;
  508. title.clear();
  509. const char *n = pLogicalPath;
  510. const char* p;
  511. do {
  512. p = strstr(n,"::");
  513. if(p)
  514. n = p+2;
  515. } while(p);
  516. title.append(n);
  517. return true;
  518. }
  519. void setRoxieClusterPartDiskMapping(const char *clusterName, const char *defaultFolder, const char *defaultReplicateFolder,
  520. bool supercopy, IDFUfileSpec *wuFSpecDest, IDFUoptions *wuOptions)
  521. {
  522. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  523. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  524. VStringBuffer dirxpath("Software/RoxieCluster[@name=\"%s\"]",clusterName);
  525. Owned<IPropertyTree> pEnvRoot = &constEnv->getPTree();
  526. Owned<IPropertyTreeIterator> processes = pEnvRoot->getElements(dirxpath);
  527. if (!processes->first())
  528. {
  529. DBGLOG("Failed to get RoxieCluster settings");
  530. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "Failed to get RoxieCluster settings. The workunit will not be created.");
  531. }
  532. IPropertyTree &process = processes->query();
  533. const char *slaveConfig = process.queryProp("@slaveConfig");
  534. if (!slaveConfig || !*slaveConfig)
  535. {
  536. DBGLOG("Failed to get RoxieCluster settings");
  537. throw MakeStringException(ECLWATCH_INVALID_CLUSTER_INFO, "Failed to get RoxieCluster settings. The workunit will not be created.");
  538. }
  539. bool replicate = false;
  540. unsigned redundancy = 0; // Number of "spare" copies of the data
  541. unsigned channelsPerNode = 1; // Overloaded and cyclic modes
  542. int replicateOffset = 1; // Used In cyclic mode only
  543. unsigned numDataCopies = process.getPropInt("@numDataCopies", 1);
  544. ClusterPartDiskMapSpec spec;
  545. spec.setDefaultBaseDir(defaultFolder);
  546. if (strieq(slaveConfig, "overloaded"))
  547. {
  548. channelsPerNode = process.getPropInt("@channelsPernode", 1);
  549. spec.setDefaultReplicateDir(defaultReplicateFolder);
  550. }
  551. else if (strieq(slaveConfig, "full redundancy"))
  552. {
  553. redundancy = numDataCopies-1;
  554. replicateOffset = 0;
  555. replicate = true;
  556. }
  557. else if (strieq(slaveConfig, "cyclic redundancy"))
  558. {
  559. redundancy = numDataCopies-1;
  560. channelsPerNode = numDataCopies;
  561. replicateOffset = process.getPropInt("@cyclicOffset", 1);
  562. spec.setDefaultReplicateDir(defaultReplicateFolder);
  563. replicate = true;
  564. }
  565. spec.setRoxie (redundancy, channelsPerNode, replicateOffset);
  566. if (!supercopy)
  567. spec.setRepeatedCopies(CPDMSRP_lastRepeated,false);
  568. wuFSpecDest->setClusterPartDiskMapSpec(clusterName,spec);
  569. wuOptions->setReplicate(replicate);
  570. }
  571. StringBuffer& getNodeGroupFromLFN(StringBuffer& nodeGroup, const char* lfn, const char* username, const char* passwd)
  572. {
  573. Owned<IUserDescriptor> udesc;
  574. if(username != NULL && *username != '\0')
  575. {
  576. udesc.setown(createUserDescriptor());
  577. udesc->set(username, passwd);
  578. }
  579. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(lfn, udesc);
  580. if (!df)
  581. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Failed to find file: %s", lfn);
  582. return df->getClusterGroupName(0, nodeGroup);
  583. }
  584. StringBuffer& constructFileMask(const char* filename, StringBuffer& filemask)
  585. {
  586. filemask.clear().append(filename).toLowerCase().append("._$P$_of_$N$");
  587. return filemask;
  588. }
  589. bool CFileSprayEx::onDFUWUSearch(IEspContext &context, IEspDFUWUSearchRequest & req, IEspDFUWUSearchResponse & resp)
  590. {
  591. try
  592. {
  593. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Read, ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  594. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  595. Owned<IConstEnvironment> environment = factory->openEnvironment();
  596. Owned<IPropertyTree> root = &environment->getPTree();
  597. StringArray dfuclusters;
  598. Owned<IPropertyTreeIterator> clusterIterator = root->getElements("Software/Topology/Cluster");
  599. if (clusterIterator->first())
  600. {
  601. do {
  602. IPropertyTree &cluster = clusterIterator->query();
  603. const char *clusterName = cluster.queryProp("@name");
  604. if (!clusterName || !*clusterName)
  605. continue;
  606. dfuclusters.append(clusterName);
  607. } while (clusterIterator->next());
  608. }
  609. resp.setClusterNames(dfuclusters);
  610. }
  611. catch(IException* e)
  612. {
  613. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  614. }
  615. return true;
  616. }
  617. int readFromCommaSeparatedString(const char *commaSeparatedString, StringBuffer* output)
  618. {
  619. int numOfItems = 0;
  620. if (commaSeparatedString && *commaSeparatedString)
  621. {
  622. char *pStr = (char *) commaSeparatedString;
  623. while (pStr)
  624. {
  625. char item[1024];
  626. bool bFoundComma = false;
  627. int len = strlen(pStr);
  628. for (int i = 0; i < len; i++)
  629. {
  630. char *pStr1 = pStr + i;
  631. if (pStr1[0] != ',')
  632. continue;
  633. strncpy(item, pStr, pStr1 - pStr);
  634. item[pStr1 - pStr] = 0;
  635. bFoundComma = true;
  636. if (i < len - 1)
  637. pStr = pStr1 + 1;
  638. else
  639. pStr = NULL;
  640. break;
  641. }
  642. if (!bFoundComma && len > 0)
  643. {
  644. strcpy(item, pStr);
  645. pStr = NULL;
  646. }
  647. output[numOfItems] = item;
  648. numOfItems++;
  649. }
  650. }
  651. return numOfItems;
  652. }
  653. bool CFileSprayEx::GetArchivedDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  654. {
  655. StringBuffer user;
  656. context.getUserID(user);
  657. StringBuffer sashaAddress;
  658. IArrayOf<IConstTpSashaServer> sashaservers;
  659. CTpWrapper dummy;
  660. dummy.getTpSashaServers(sashaservers);
  661. ForEachItemIn(i, sashaservers)
  662. {
  663. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  664. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  665. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  666. }
  667. SocketEndpoint ep;
  668. ep.set(sashaAddress,DEFAULT_SASHA_PORT);
  669. Owned<INode> sashaserver = createINode(ep);
  670. __int64 count=req.getPageSize();
  671. if(count < 1)
  672. count=100;
  673. __int64 begin=req.getPageStartFrom();
  674. if (begin < 0)
  675. begin = 0;
  676. Owned<ISashaCommand> cmd = createSashaCommand();
  677. cmd->setAction(SCA_LIST);
  678. cmd->setOnline(false);
  679. cmd->setArchived(true);
  680. cmd->setDFU(true);
  681. cmd->setLimit((int) count+1);
  682. cmd->setStart((int)begin);
  683. if(req.getCluster() && *req.getCluster())
  684. cmd->setCluster(req.getCluster());
  685. if(req.getOwner() && *req.getOwner())
  686. cmd->setOwner(req.getOwner());
  687. if(req.getJobname() && *req.getJobname())
  688. cmd->setJobName(req.getJobname());
  689. if(req.getStateReq() && *req.getStateReq())
  690. cmd->setState(req.getStateReq());
  691. cmd->setOutputFormat("owner,jobname,cluster,state,command");//date range/owner/jobname/state*/
  692. if (!cmd->send(sashaserver))
  693. {
  694. StringBuffer url;
  695. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  696. "Sasha (%s) took too long to respond from: Get archived workUnits.",
  697. ep.getUrlStr(url).str());
  698. }
  699. IArrayOf<IEspDFUWorkunit> results;
  700. __int64 actualCount = cmd->numIds();
  701. StringBuffer s;
  702. for (unsigned j=0;j<actualCount;j++)
  703. {
  704. const char *wuidStr = cmd->queryId(j);
  705. if (!wuidStr)
  706. continue;
  707. StringBuffer strArray[6];
  708. readFromCommaSeparatedString(wuidStr, strArray);
  709. //skip any workunits without access
  710. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  711. resultWU->setArchived(true);
  712. if (strArray[0].length() > 0)
  713. resultWU->setID(strArray[0].str());
  714. if (strArray[1].length() > 0)
  715. resultWU->setUser(strArray[1].str());
  716. if (strArray[2].length() > 0)
  717. resultWU->setJobName(strArray[2].str());
  718. if (strArray[3].length() > 0)
  719. resultWU->setClusterName(strArray[3].str());
  720. if (strArray[4].length() > 0)
  721. resultWU->setStateMessage(strArray[4].str());
  722. if (strArray[5].length() > 0)
  723. resultWU->setCommand(atoi(strArray[5].str()));
  724. results.append(*resultWU.getLink());
  725. }
  726. resp.setPageStartFrom(begin+1);
  727. resp.setNextPage(-1);
  728. if(count < actualCount)
  729. {
  730. if (results.length() > count)
  731. {
  732. results.pop();
  733. }
  734. resp.setNextPage(begin + count);
  735. resp.setPageEndAt(begin + count);
  736. }
  737. else
  738. {
  739. resp.setPageEndAt(begin + actualCount);
  740. }
  741. if(begin > 0)
  742. {
  743. resp.setFirst(false);
  744. if (begin - count > 0)
  745. resp.setPrevPage(begin - count);
  746. else
  747. resp.setPrevPage(0);
  748. }
  749. resp.setPageSize(count);
  750. resp.setResults(results);
  751. StringBuffer basicQuery;
  752. if (req.getStateReq() && *req.getStateReq())
  753. {
  754. resp.setStateReq(req.getStateReq());
  755. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  756. }
  757. if (req.getCluster() && *req.getCluster())
  758. {
  759. resp.setCluster(req.getCluster());
  760. addToQueryString(basicQuery, "Cluster", req.getCluster());
  761. }
  762. if (req.getOwner() && *req.getOwner())
  763. {
  764. resp.setOwner(req.getOwner());
  765. addToQueryString(basicQuery, "Owner", req.getOwner());
  766. }
  767. if (req.getType() && *req.getType())
  768. {
  769. resp.setType(req.getType());
  770. addToQueryString(basicQuery, "Type", req.getType());
  771. }
  772. resp.setFilters(basicQuery.str());
  773. resp.setBasicQuery(basicQuery.str());
  774. return true;
  775. }
  776. bool CFileSprayEx::getOneDFUWorkunit(IEspContext& context, const char* wuid, IEspGetDFUWorkunitsResponse& resp)
  777. {
  778. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  779. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(wuid, false);
  780. if (!wu)
  781. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", wuid);
  782. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit();
  783. resultWU->setID(wuid);
  784. resultWU->setCommand(wu->getCommand());
  785. resultWU->setIsProtected(wu->isProtected());
  786. StringBuffer jobname, user, cluster;
  787. resultWU->setJobName(wu->getJobName(jobname).str());
  788. resultWU->setUser(wu->getUser(user).str());
  789. const char* clusterName = wu->getClusterName(cluster).str();
  790. if (clusterName && *clusterName)
  791. {
  792. Owned<IStringIterator> targets = getTargetClusters(NULL, clusterName);
  793. if (!targets->first())
  794. resultWU->setClusterName(clusterName);
  795. else
  796. {
  797. SCMStringBuffer targetCluster;
  798. targets->str(targetCluster);
  799. resultWU->setClusterName(targetCluster.str());
  800. }
  801. }
  802. IConstDFUprogress* prog = wu->queryProgress();
  803. if (prog)
  804. {
  805. StringBuffer statemsg;
  806. DFUstate state = prog->getState();
  807. encodeDFUstate(state, statemsg);
  808. resultWU->setState(state);
  809. resultWU->setStateMessage(statemsg.str());
  810. resultWU->setPercentDone(prog->getPercentDone());
  811. }
  812. IArrayOf<IEspDFUWorkunit> result;
  813. result.append(*resultWU.getClear());
  814. resp.setResults(result);
  815. return true;
  816. }
  817. bool CFileSprayEx::onGetDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  818. {
  819. try
  820. {
  821. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Read, ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  822. StringBuffer wuidStr = req.getWuid();
  823. const char* wuid = wuidStr.trim().str();
  824. if (wuid && *wuid && looksLikeAWuid(wuid, 'D'))
  825. return getOneDFUWorkunit(context, wuid, resp);
  826. double version = context.getClientVersion();
  827. if (version > 1.02)
  828. {
  829. const char *type = req.getType();
  830. if (type && *type && !stricmp(type, "archived workunits"))
  831. {
  832. return GetArchivedDFUWorkunits(context, req, resp);
  833. }
  834. }
  835. StringBuffer clusterReq;
  836. const char *clusterName = req.getCluster();
  837. if(clusterName && *clusterName)
  838. {
  839. clusterReq.append(clusterName);
  840. }
  841. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  842. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  843. Owned<IPropertyTree> root = &constEnv->getPTree();
  844. StringArray targetClusters, clusterProcesses;
  845. Owned<IPropertyTreeIterator> clusters= root->getElements("Software/Topology/Cluster");
  846. if (clusters->first())
  847. {
  848. do {
  849. IPropertyTree &cluster = clusters->query();
  850. const char* name = cluster.queryProp("@name");
  851. if (!name || !*name)
  852. continue;
  853. Owned<IPropertyTreeIterator> thorClusters= cluster.getElements(eqThorCluster);
  854. Owned<IPropertyTreeIterator> roxieClusters= cluster.getElements(eqRoxieCluster);
  855. if (thorClusters->first() || roxieClusters->first())
  856. {
  857. bool bFound = false;
  858. if (thorClusters->first())
  859. {
  860. IPropertyTree &thorCluster = thorClusters->query();
  861. const char* process = thorCluster.queryProp("@process");
  862. if (process && *process)
  863. {
  864. targetClusters.append(name);
  865. clusterProcesses.append(process);
  866. if (clusterName && !stricmp(clusterName, name))
  867. {
  868. clusterReq.clear().append(process);
  869. }
  870. }
  871. }
  872. if (!bFound && roxieClusters->first())
  873. {
  874. IPropertyTree &roxieCluster = roxieClusters->query();
  875. const char* process = roxieCluster.queryProp("@process");
  876. if (process && *process)
  877. {
  878. targetClusters.append(name);
  879. clusterProcesses.append(process);
  880. if (clusterName && !stricmp(clusterName, name))
  881. {
  882. clusterReq.clear().append(process);
  883. }
  884. }
  885. }
  886. }
  887. } while (clusters->next());
  888. }
  889. __int64 pagesize = req.getPageSize();
  890. __int64 pagefrom = req.getPageStartFrom();
  891. __int64 displayFrom = 0;
  892. if (pagesize < 1)
  893. {
  894. pagesize = 100;
  895. }
  896. if (pagefrom > 0)
  897. {
  898. displayFrom = pagefrom;
  899. }
  900. DFUsortfield sortorder[2] = {DFUsf_wuid, DFUsf_term};
  901. sortorder[0] = (DFUsortfield) (DFUsf_wuid + DFUsf_reverse);
  902. if(req.getSortby() && *req.getSortby())
  903. {
  904. const char *sortby = req.getSortby();
  905. if (!stricmp(sortby, "Owner"))
  906. sortorder[0] = DFUsf_user;
  907. else if (!stricmp(sortby, "JobName"))
  908. sortorder[0] = DFUsf_job;
  909. else if (!stricmp(sortby, "Cluster"))
  910. sortorder[0] = DFUsf_cluster;
  911. else if (!stricmp(sortby, "State"))
  912. sortorder[0] = DFUsf_state;
  913. else if (!stricmp(sortby, "Type"))
  914. sortorder[0] = DFUsf_command;
  915. else if (!stricmp(sortby, "Protected"))
  916. sortorder[0] = DFUsf_protected;
  917. else if (!stricmp(sortby, "PCTDone"))
  918. sortorder[0] = (DFUsortfield) (DFUsf_pcdone | DFUsf_numeric);
  919. else
  920. sortorder[0] = DFUsf_wuid;
  921. bool descending = req.getDescending();
  922. if (descending)
  923. sortorder[0] = (DFUsortfield) (sortorder[0] | DFUsf_reverse);
  924. }
  925. DFUsortfield filters[10];
  926. unsigned short filterCount = 0;
  927. MemoryBuffer filterbuf;
  928. if(req.getStateReq() && *req.getStateReq())
  929. {
  930. filters[filterCount] = DFUsf_state;
  931. filterCount++;
  932. if (stricmp(req.getStateReq(), "unknown") != 0)
  933. filterbuf.append(req.getStateReq());
  934. else
  935. filterbuf.append("");
  936. }
  937. if(wuid && *wuid)
  938. {
  939. filters[filterCount] = DFUsf_wildwuid;
  940. filterCount++;
  941. filterbuf.append(wuid);
  942. }
  943. if(clusterName && *clusterName)
  944. {
  945. filters[filterCount] = DFUsf_cluster;
  946. filterCount++;
  947. filterbuf.append(clusterReq.str());
  948. }
  949. if(req.getOwner() && *req.getOwner())
  950. {
  951. filters[filterCount] = DFUsortfield (DFUsf_user | DFUsf_nocase);
  952. filterCount++;
  953. filterbuf.append(req.getOwner());
  954. }
  955. if(req.getJobname() && *req.getJobname())
  956. {
  957. filters[filterCount] = DFUsortfield (DFUsf_job | DFUsf_nocase);
  958. filterCount++;
  959. filterbuf.append(req.getJobname());
  960. }
  961. filters[filterCount] = DFUsf_term;
  962. __int64 cacheHint = req.getCacheHint();
  963. if (cacheHint < 0) //Not set yet
  964. cacheHint = 0;
  965. IArrayOf<IEspDFUWorkunit> result;
  966. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  967. unsigned numWUs;
  968. PROGLOG("GetDFUWorkunits: getWorkUnitsSorted");
  969. Owned<IConstDFUWorkUnitIterator> itr = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), (int) displayFrom, (int) pagesize+1, req.getOwner(), &cacheHint, &numWUs);
  970. if (version >= 1.07)
  971. resp.setCacheHint(cacheHint);
  972. PROGLOG("GetDFUWorkunits: getWorkUnitsSorted done");
  973. //unsigned actualCount = 0;
  974. itr->first();
  975. while(itr->isValid())
  976. {
  977. Owned<IConstDFUWorkUnit> wu = itr->get();
  978. //actualCount++;
  979. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  980. resultWU->setID(wu->queryId());
  981. StringBuffer jobname, user, cluster;
  982. resultWU->setJobName(wu->getJobName(jobname).str());
  983. resultWU->setCommand(wu->getCommand());
  984. resultWU->setUser(wu->getUser(user).str());
  985. const char* clusterName = wu->getClusterName(cluster).str();
  986. if (clusterName)
  987. {
  988. StringBuffer clusterForDisplay(clusterName);
  989. if (clusterProcesses.ordinality())
  990. {
  991. for (unsigned i = 0; i < clusterProcesses.length(); i++)
  992. {
  993. const char* clusterProcessName = clusterProcesses.item(i);
  994. if (!stricmp(clusterProcessName, clusterName))
  995. {
  996. clusterForDisplay.clear().append(targetClusters.item(i));
  997. break;
  998. }
  999. }
  1000. }
  1001. resultWU->setClusterName(clusterForDisplay.str());
  1002. }
  1003. resultWU->setIsProtected(wu->isProtected());
  1004. IConstDFUprogress *prog = wu->queryProgress();
  1005. if (prog != NULL)
  1006. {
  1007. DFUstate state = prog->getState();
  1008. resultWU->setState(state);
  1009. StringBuffer statemsg;
  1010. encodeDFUstate(state,statemsg);
  1011. resultWU->setStateMessage(statemsg.str());
  1012. resultWU->setPercentDone(prog->getPercentDone());
  1013. }
  1014. result.append(*resultWU.getLink());
  1015. itr->next();
  1016. }
  1017. if (result.length() > pagesize)
  1018. result.pop();
  1019. resp.setPageSize(pagesize);
  1020. resp.setNumWUs(numWUs);
  1021. resp.setPageStartFrom(displayFrom + 1);
  1022. if(displayFrom + pagesize < numWUs)
  1023. {
  1024. resp.setNextPage(displayFrom + pagesize);
  1025. resp.setPageEndAt(pagefrom + pagesize);
  1026. __int64 last = displayFrom + pagesize;
  1027. while (last + pagesize < numWUs)
  1028. {
  1029. last += pagesize;
  1030. }
  1031. resp.setLastPage(last);
  1032. }
  1033. else
  1034. {
  1035. resp.setNextPage(-1);
  1036. resp.setPageEndAt(numWUs);
  1037. }
  1038. if(displayFrom > 0)
  1039. {
  1040. resp.setFirst(false);
  1041. if (displayFrom - pagesize > 0)
  1042. resp.setPrevPage(displayFrom - pagesize);
  1043. else
  1044. resp.setPrevPage(0);
  1045. }
  1046. StringBuffer basicQuery;
  1047. if (req.getStateReq() && *req.getStateReq())
  1048. {
  1049. resp.setStateReq(req.getStateReq());
  1050. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  1051. }
  1052. if (req.getCluster() && *req.getCluster())
  1053. {
  1054. resp.setCluster(req.getCluster());
  1055. addToQueryString(basicQuery, "Cluster", req.getCluster());
  1056. }
  1057. if (req.getOwner() && *req.getOwner())
  1058. {
  1059. resp.setOwner(req.getOwner());
  1060. addToQueryString(basicQuery, "Owner", req.getOwner());
  1061. }
  1062. resp.setFilters(basicQuery.str());
  1063. if (req.getSortby() && *req.getSortby())
  1064. {
  1065. resp.setSortby(req.getSortby());
  1066. if (req.getDescending())
  1067. resp.setDescending(req.getDescending());
  1068. StringBuffer strbuf = req.getSortby();
  1069. strbuf.append("=");
  1070. String str1(strbuf.str());
  1071. String str(basicQuery.str());
  1072. if (str.indexOf(str1) < 0)
  1073. {
  1074. addToQueryString(basicQuery, "Sortby", req.getSortby());
  1075. if (req.getDescending())
  1076. addToQueryString(basicQuery, "Descending", "1");
  1077. }
  1078. }
  1079. resp.setBasicQuery(basicQuery.str());
  1080. resp.setResults(result);
  1081. }
  1082. catch(IException* e)
  1083. {
  1084. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1085. }
  1086. return true;
  1087. }
  1088. void CFileSprayEx::addToQueryString(StringBuffer &queryString, const char *name, const char *value)
  1089. {
  1090. if (queryString.length() > 0)
  1091. {
  1092. queryString.append("&amp;");
  1093. }
  1094. queryString.append(name);
  1095. queryString.append("=");
  1096. queryString.append(value);
  1097. }
  1098. void CFileSprayEx::getInfoFromSasha(IEspContext &context, const char *sashaServer, const char* wuid, IEspDFUWorkunit *info)
  1099. {
  1100. Owned<ISashaCommand> cmd = createSashaCommand();
  1101. cmd->addId(wuid);
  1102. cmd->setAction(SCA_GET);
  1103. cmd->setArchived(true);
  1104. cmd->setDFU(true);
  1105. SocketEndpoint ep(sashaServer, DEFAULT_SASHA_PORT);
  1106. Owned<INode> node = createINode(ep);
  1107. if (!cmd->send(node,1*60*1000))
  1108. {
  1109. StringBuffer url;
  1110. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  1111. "Sasha (%s) took too long to respond from: Get information for %s.",
  1112. ep.getUrlStr(url).str(), wuid);
  1113. }
  1114. if (cmd->numIds()==0)
  1115. {
  1116. DBGLOG("Could not read archived %s",wuid);
  1117. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1118. }
  1119. unsigned num = cmd->numResults();
  1120. if (num < 1)
  1121. return;
  1122. StringBuffer res;
  1123. cmd->getResult(0,res);
  1124. if(res.length() < 1)
  1125. return;
  1126. Owned<IPropertyTree> wu = createPTreeFromXMLString(res.str());
  1127. if (!wu)
  1128. return;
  1129. const char * command = wu->queryProp("@command");
  1130. const char * submitID = wu->queryProp("@submitID");
  1131. const char * cluster = wu->queryProp("@clusterName");
  1132. const char * queue = wu->queryProp("@queue");
  1133. const char * jobName = wu->queryProp("@jobName");
  1134. const char * protectedWU = wu->queryProp("@protected");
  1135. info->setID(wuid);
  1136. info->setArchived(true);
  1137. if (command && *command)
  1138. info->setCommandMessage(command);
  1139. if (cluster && *cluster)
  1140. info->setClusterName(cluster);
  1141. if (submitID && *submitID)
  1142. info->setUser(submitID);
  1143. if (queue && *queue)
  1144. info->setQueue(queue);
  1145. if (jobName && *jobName)
  1146. info->setJobName(jobName);
  1147. if (protectedWU && stricmp(protectedWU, "0"))
  1148. info->setIsProtected(true);
  1149. else
  1150. info->setIsProtected(false);
  1151. IPropertyTree *source = wu->queryPropTree("Source");
  1152. if(source)
  1153. {
  1154. const char * directory = source->queryProp("@directory");
  1155. const char * name = source->queryProp("@name");
  1156. if (directory && *directory)
  1157. info->setSourceDirectory(directory);
  1158. if (name && *name)
  1159. info->setSourceLogicalName(name);
  1160. }
  1161. IPropertyTree *dest = wu->queryPropTree("Destination");
  1162. if(dest)
  1163. {
  1164. const char * directory = dest->queryProp("@directory");
  1165. int numParts = dest->getPropInt("@numparts", -1);
  1166. if (directory && *directory)
  1167. info->setDestDirectory(directory);
  1168. if (numParts > 0)
  1169. info->setDestNumParts(numParts);
  1170. }
  1171. IPropertyTree *progress = wu->queryPropTree("Progress");
  1172. if(progress)
  1173. {
  1174. const char * state = progress->queryProp("@state");
  1175. const char * timeStarted = progress->queryProp("@timestarted");
  1176. const char * timeStopped = progress->queryProp("@timestopped");
  1177. if (state && *state)
  1178. info->setStateMessage(state);
  1179. if (timeStarted && *timeStarted)
  1180. {
  1181. StringBuffer startStr = timeStarted;
  1182. startStr.replace('T', ' ');
  1183. info->setTimeStarted(startStr.str());
  1184. }
  1185. if (timeStopped && *timeStopped)
  1186. {
  1187. StringBuffer stopStr = timeStopped;
  1188. stopStr.replace('T', ' ');
  1189. info->setTimeStopped(stopStr.str());
  1190. }
  1191. }
  1192. return;
  1193. }
  1194. bool CFileSprayEx::getArchivedWUInfo(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1195. {
  1196. const char *wuid = req.getWuid();
  1197. if (wuid && *wuid)
  1198. {
  1199. StringBuffer sashaAddress;
  1200. IArrayOf<IConstTpSashaServer> sashaservers;
  1201. CTpWrapper dummy;
  1202. dummy.getTpSashaServers(sashaservers);
  1203. ForEachItemIn(i, sashaservers)
  1204. {
  1205. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1206. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1207. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1208. }
  1209. if (sashaAddress.length() < 1)
  1210. {
  1211. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1212. }
  1213. getInfoFromSasha(context, sashaAddress.str(), wuid, &resp.updateResult());
  1214. return true;
  1215. }
  1216. return false;
  1217. }
  1218. bool CFileSprayEx::onGetDFUWorkunit(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1219. {
  1220. try
  1221. {
  1222. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Read, ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1223. const char* wuid = req.getWuid();
  1224. if (!wuid || !*wuid)
  1225. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dfu workunit ID not specified.");
  1226. bool found = false;
  1227. double version = context.getClientVersion();
  1228. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1229. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(wuid, false);
  1230. if(wu)
  1231. {
  1232. IEspDFUWorkunit &result = resp.updateResult();
  1233. PROGLOG("GetDFUWorkunit: %s", wuid);
  1234. DeepAssign(context, wu, result);
  1235. int n = resp.getResult().getState();
  1236. if (n == DFUstate_scheduled || n == DFUstate_queued || n == DFUstate_started)
  1237. {
  1238. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1239. }
  1240. found = true;
  1241. }
  1242. else if ((version > 1.02) && getArchivedWUInfo(context, req, resp))
  1243. {
  1244. found = true;
  1245. }
  1246. if (!found)
  1247. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1248. }
  1249. catch(IException* e)
  1250. {
  1251. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1252. }
  1253. return true;
  1254. }
  1255. bool CFileSprayEx::onGetDFUProgress(IEspContext &context, IEspProgressRequest &req, IEspProgressResponse &resp)
  1256. {
  1257. try
  1258. {
  1259. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Read, ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1260. const char* wuid = req.getWuid();
  1261. if(!wuid || !*wuid)
  1262. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit ID not specified.");
  1263. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1264. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  1265. if(!wu)
  1266. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1267. resp.setWuid(req.getWuid());
  1268. PROGLOG("GetDFUProgress: %s", wuid);
  1269. IConstDFUprogress *prog = wu->queryProgress();
  1270. if (prog)
  1271. {
  1272. resp.setPercentDone(prog->getPercentDone());
  1273. resp.setKbPerSec(prog->getKbPerSec());
  1274. resp.setKbPerSecAve(prog->getKbPerSecAve());
  1275. resp.setSecsLeft(prog->getSecsLeft());
  1276. StringBuffer statestr;
  1277. encodeDFUstate(prog->getState(), statestr);
  1278. resp.setState(statestr.str());
  1279. resp.setSlavesDone(prog->getSlavesDone());
  1280. StringBuffer msg;
  1281. prog->formatProgressMessage(msg);
  1282. resp.setProgressMessage(msg.str());
  1283. prog->formatSummaryMessage(msg.clear());
  1284. resp.setSummaryMessage(msg.str());
  1285. prog->getTimeTaken(msg.clear());
  1286. resp.setTimeTaken(msg.str());
  1287. }
  1288. }
  1289. catch(IException* e)
  1290. {
  1291. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1292. }
  1293. return true;
  1294. }
  1295. bool CFileSprayEx::onCreateDFUWorkunit(IEspContext &context, IEspCreateDFUWorkunit &req, IEspCreateDFUWorkunitResponse &resp)
  1296. {
  1297. try
  1298. {
  1299. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to create DFU workunit. Permission denied.");
  1300. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1301. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1302. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  1303. setUserAuth(context, wu);
  1304. wu->commit();
  1305. const char * d = wu->queryId();
  1306. IEspDFUWorkunit &result = resp.updateResult();
  1307. DeepAssign(context, wu, result);
  1308. result.setOverwrite(false);
  1309. result.setReplicate(true);
  1310. }
  1311. catch(IException* e)
  1312. {
  1313. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1314. }
  1315. return true;
  1316. }
  1317. bool CFileSprayEx::onUpdateDFUWorkunit(IEspContext &context, IEspUpdateDFUWorkunit &req, IEspUpdateDFUWorkunitResponse &resp)
  1318. {
  1319. try
  1320. {
  1321. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1322. IConstDFUWorkunit & reqWU = req.getWu();
  1323. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1324. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(reqWU.getID());
  1325. if(!wu)
  1326. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", reqWU.getID());
  1327. PROGLOG("UpdateDFUWorkunit: %s", reqWU.getID());
  1328. IDFUprogress *prog = wu->queryUpdateProgress();
  1329. if (prog && req.getStateOrig() != reqWU.getState())
  1330. {
  1331. if (prog->getState() != req.getStateOrig())
  1332. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT,"Cannot update DFU workunit %s because its state has been changed internally. Please refresh the page and try again.",reqWU.getID());
  1333. prog->setState((enum DFUstate)reqWU.getState());
  1334. }
  1335. const char* clusterOrig = req.getClusterOrig();
  1336. const char* cluster = reqWU.getClusterName();
  1337. if(cluster && (!clusterOrig || stricmp(clusterOrig, cluster)))
  1338. {
  1339. wu->setClusterName(reqWU.getClusterName());
  1340. }
  1341. const char* jobNameOrig = req.getJobNameOrig();
  1342. const char* jobName = reqWU.getJobName();
  1343. if(jobName && (!jobNameOrig || stricmp(jobNameOrig, jobName)))
  1344. {
  1345. wu->setJobName(jobName);
  1346. }
  1347. if (reqWU.getIsProtected() != req.getIsProtectedOrig())
  1348. wu->protect(reqWU.getIsProtected());
  1349. wu->commit();
  1350. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(reqWU.getID()).str());
  1351. }
  1352. catch(IException* e)
  1353. {
  1354. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1355. }
  1356. return true;
  1357. }
  1358. bool markWUFailed(IDFUWorkUnitFactory *f, const char *wuid)
  1359. {
  1360. Owned<IDFUWorkUnit> wu = f->updateWorkUnit(wuid);
  1361. if(!wu)
  1362. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", wuid);
  1363. IDFUprogress *prog = wu->queryUpdateProgress();
  1364. if(!prog)
  1365. throw MakeStringException(ECLWATCH_PROGRESS_INFO_NOT_FOUND, "progress information not found for workunit %s.", wuid);
  1366. else if(prog->getState() == DFUstate_started)
  1367. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Cannot delete workunit %s because its state is Started.", wuid);
  1368. else
  1369. {
  1370. prog->setState(DFUstate_failed);
  1371. return true;
  1372. }
  1373. return false;
  1374. }
  1375. static unsigned NumOfDFUWUActionNames = 5;
  1376. static const char *DFUWUActionNames[] = { "Delete", "Protect" , "Unprotect" , "Restore" , "SetToFailed" };
  1377. bool CFileSprayEx::onDFUWorkunitsAction(IEspContext &context, IEspDFUWorkunitsActionRequest &req, IEspDFUWorkunitsActionResponse &resp)
  1378. {
  1379. try
  1380. {
  1381. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1382. CDFUWUActions action = req.getType();
  1383. if (action == DFUWUActions_Undefined)
  1384. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Action not defined.");
  1385. StringArray& wuids = req.getWuids();
  1386. if (!wuids.ordinality())
  1387. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit not defined.");
  1388. Owned<INode> node;
  1389. Owned<ISashaCommand> cmd;
  1390. StringBuffer sashaAddress;
  1391. if (action == CDFUWUActions_Restore)
  1392. {
  1393. IArrayOf<IConstTpSashaServer> sashaservers;
  1394. CTpWrapper dummy;
  1395. dummy.getTpSashaServers(sashaservers);
  1396. ForEachItemIn(i, sashaservers)
  1397. {
  1398. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1399. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1400. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1401. }
  1402. if (sashaAddress.length() < 1)
  1403. {
  1404. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1405. }
  1406. SocketEndpoint ep(sashaAddress.str(), DEFAULT_SASHA_PORT);
  1407. node.setown(createINode(ep));
  1408. cmd.setown(createSashaCommand());
  1409. cmd->setAction(SCA_RESTORE);
  1410. cmd->setDFU(true);
  1411. }
  1412. IArrayOf<IEspDFUActionResult> results;
  1413. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1414. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1415. {
  1416. const char* wuid = wuids.item(i);
  1417. const char* actionStr = (action < NumOfDFUWUActionNames) ? DFUWUActionNames[action] : "Unknown";
  1418. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1419. res->setID(wuid);
  1420. res->setAction(actionStr);
  1421. try
  1422. {
  1423. PROGLOG("%s %s", actionStr, wuid);
  1424. switch (action)
  1425. {
  1426. case CDFUWUActions_Delete:
  1427. if (!markWUFailed(factory, wuid))
  1428. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Failed to mark workunit failed.");
  1429. if (!factory->deleteWorkUnit(wuid))
  1430. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Failed in deleting workunit.");
  1431. res->setResult("Success");
  1432. break;
  1433. case CDFUWUActions_Restore:
  1434. cmd->addId(wuid);
  1435. if (!cmd->send(node,1*60*1000))
  1436. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,
  1437. "Sasha (%s) took too long to respond from: Restore workunit %s.",
  1438. sashaAddress.str(), wuid);
  1439. {
  1440. StringBuffer reply = "Restore ID: ";
  1441. if (!cmd->getId(0, reply))
  1442. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed to get ID.");
  1443. res->setResult(reply.str());
  1444. }
  1445. break;
  1446. case CDFUWUActions_Protect:
  1447. case CDFUWUActions_Unprotect:
  1448. case CDFUWUActions_SetToFailed:
  1449. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuid);
  1450. if(!wu.get())
  1451. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed in calling updateWorkUnit().");
  1452. switch (action)
  1453. {
  1454. case CDFUWUActions_Protect:
  1455. wu->protect(true);
  1456. break;
  1457. case CDFUWUActions_Unprotect:
  1458. wu->protect(false);
  1459. break;
  1460. case CDFUWUActions_SetToFailed:
  1461. IDFUprogress *prog = wu->queryUpdateProgress();
  1462. if (!prog)
  1463. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed in calling queryUpdateProgress().");
  1464. prog->setState(DFUstate_failed);
  1465. break;
  1466. }
  1467. wu->commit();
  1468. res->setResult("Success");
  1469. break;
  1470. }
  1471. PROGLOG("%s %s done", actionStr, wuid);
  1472. }
  1473. catch (IException *e)
  1474. {
  1475. StringBuffer eMsg, failedMsg("Failed: ");
  1476. res->setResult(failedMsg.append(e->errorMessage(eMsg)).str());
  1477. e->Release();
  1478. }
  1479. results.append(*res.getLink());
  1480. }
  1481. resp.setDFUActionResults(results);
  1482. }
  1483. catch(IException* e)
  1484. {
  1485. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1486. }
  1487. return true;
  1488. }
  1489. bool CFileSprayEx::onDeleteDFUWorkunits(IEspContext &context, IEspDeleteDFUWorkunits &req, IEspDeleteDFUWorkunitsResponse &resp)
  1490. {
  1491. try
  1492. {
  1493. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1494. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1495. StringArray & wuids = req.getWuids();
  1496. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1497. {
  1498. const char* wuid = wuids.item(i);
  1499. if (markWUFailed(factory, wuid))
  1500. {
  1501. factory->deleteWorkUnit(wuid);
  1502. PROGLOG("DeleteDFUWorkunits: %s deleted", wuid);
  1503. }
  1504. }
  1505. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1506. }
  1507. catch(IException* e)
  1508. {
  1509. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1510. }
  1511. return true;
  1512. }
  1513. bool CFileSprayEx::onDeleteDFUWorkunit(IEspContext &context, IEspDeleteDFUWorkunit &req, IEspDeleteDFUWorkunitResponse &resp)
  1514. {
  1515. try
  1516. {
  1517. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1518. const char* wuid = req.getWuid();
  1519. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1520. if (markWUFailed(factory, wuid))
  1521. {
  1522. resp.setResult(factory->deleteWorkUnit(wuid));
  1523. PROGLOG("DeleteDFUWorkunit: %s deleted", wuid);
  1524. }
  1525. else
  1526. resp.setResult(false);
  1527. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1528. }
  1529. catch(IException* e)
  1530. {
  1531. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1532. }
  1533. return true;
  1534. }
  1535. bool CFileSprayEx::onSubmitDFUWorkunit(IEspContext &context, IEspSubmitDFUWorkunit &req, IEspSubmitDFUWorkunitResponse &resp)
  1536. {
  1537. try
  1538. {
  1539. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to submit DFU workunit. Permission denied.");
  1540. if (!req.getWuid() || !*req.getWuid())
  1541. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Workunit ID required");
  1542. PROGLOG("SubmitDFUWorkunit: %s", req.getWuid());
  1543. submitDFUWorkUnit(req.getWuid());
  1544. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1545. }
  1546. catch(IException* e)
  1547. {
  1548. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1549. }
  1550. return true;
  1551. }
  1552. bool CFileSprayEx::onAbortDFUWorkunit(IEspContext &context, IEspAbortDFUWorkunit &req, IEspAbortDFUWorkunitResponse &resp)
  1553. {
  1554. try
  1555. {
  1556. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Write, ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to abort DFU workunit. Permission denied.");
  1557. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1558. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1559. if(!wu)
  1560. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1561. PROGLOG("AbortDFUWorkunit: %s", req.getWuid());
  1562. wu->requestAbort();
  1563. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1564. }
  1565. catch(IException* e)
  1566. {
  1567. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1568. }
  1569. return true;
  1570. }
  1571. bool CFileSprayEx::onGetDFUExceptions(IEspContext &context, IEspGetDFUExceptions &req, IEspGetDFUExceptionsResponse &resp)
  1572. {
  1573. try
  1574. {
  1575. context.ensureFeatureAccess(DFU_EX_URL, SecAccess_Read, ECLWATCH_DFU_EX_ACCESS_DENIED, "Failed to get DFU Exceptions. Permission denied.");
  1576. IArrayOf<IEspDFUException> result;
  1577. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1578. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1579. if(!wu)
  1580. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1581. PROGLOG("GetDFUExceptions: %s", req.getWuid());
  1582. Owned<IExceptionIterator> itr = wu->getExceptionIterator();
  1583. itr->first();
  1584. while(itr->isValid())
  1585. {
  1586. Owned<IEspDFUException> resultE = createDFUException("", "");
  1587. IException &e = itr->query();
  1588. resultE->setCode(e.errorCode());
  1589. StringBuffer msg;
  1590. resultE->setMessage(e.errorMessage(msg).str());
  1591. result.append(*resultE.getLink());
  1592. itr->next();
  1593. }
  1594. resp.setResult(result);
  1595. }
  1596. catch(IException* e)
  1597. {
  1598. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1599. }
  1600. return true;
  1601. }
  1602. void CFileSprayEx::readAndCheckSpraySourceReq(MemoryBuffer& srcxml, const char* srcIP, const char* srcPath,
  1603. StringBuffer& sourceIPReq, StringBuffer& sourcePathReq)
  1604. {
  1605. StringBuffer sourcePath(srcPath);
  1606. sourceIPReq.set(srcIP);
  1607. sourceIPReq.trim();
  1608. sourcePath.trim();
  1609. if(srcxml.length() == 0)
  1610. {
  1611. if (sourceIPReq.isEmpty())
  1612. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source network IP not specified.");
  1613. if (sourcePath.isEmpty())
  1614. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source path not specified.");
  1615. }
  1616. getStandardPosixPath(sourcePathReq, sourcePath.str());
  1617. }
  1618. bool CFileSprayEx::onSprayFixed(IEspContext &context, IEspSprayFixed &req, IEspSprayFixedResponse &resp)
  1619. {
  1620. try
  1621. {
  1622. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Spray. Permission denied.");
  1623. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  1624. const char* destNodeGroup = req.getDestGroup();
  1625. if(destNodeGroup == NULL || *destNodeGroup == '\0')
  1626. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination node group not specified.");
  1627. MemoryBuffer& srcxml = (MemoryBuffer&)req.getSrcxml();
  1628. StringBuffer sourceIPReq, sourcePathReq;
  1629. readAndCheckSpraySourceReq(srcxml, req.getSourceIP(), req.getSourcePath(), sourceIPReq, sourcePathReq);
  1630. const char* srcip = sourceIPReq.str();
  1631. const char* srcfile = sourcePathReq.str();
  1632. const char* destname = req.getDestLogicalName();
  1633. if(!destname || !*destname)
  1634. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1635. CDfsLogicalFileName lfn;
  1636. if (!lfn.setValidate(destname))
  1637. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename:'%s'", destname);
  1638. destname = lfn.get();
  1639. PROGLOG("SprayFixed: DestLogicalName %s, DestGroup %s", destname, destNodeGroup);
  1640. StringBuffer gName, ipAddr;
  1641. const char *pTr = strchr(destNodeGroup, ' ');
  1642. if (pTr)
  1643. {
  1644. gName.append(pTr - destNodeGroup, destNodeGroup);
  1645. ipAddr.append(pTr+1);
  1646. }
  1647. else
  1648. gName.append(destNodeGroup);
  1649. if (ipAddr.length() > 0)
  1650. ParseLogicalPath(destname, ipAddr.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1651. else
  1652. ParseLogicalPath(destname, destNodeGroup, NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1653. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1654. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1655. wu->setClusterName(gName.str());
  1656. wu->setJobName(destTitle.str());
  1657. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  1658. setUserAuth(context, wu);
  1659. wu->setCommand(DFUcmd_import);
  1660. IDFUfileSpec *source = wu->queryUpdateSource();
  1661. if(srcxml.length() == 0)
  1662. {
  1663. RemoteMultiFilename rmfn;
  1664. SocketEndpoint ep(srcip);
  1665. rmfn.setEp(ep);
  1666. StringBuffer fnamebuf(srcfile);
  1667. fnamebuf.trim();
  1668. rmfn.append(fnamebuf.str()); // handles comma separated files
  1669. source->setMultiFilename(rmfn);
  1670. }
  1671. else
  1672. {
  1673. srcxml.append('\0');
  1674. source->setFromXML((const char*)srcxml.toByteArray());
  1675. }
  1676. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1677. bool nosplit = req.getNosplit();
  1678. int recordsize = req.getSourceRecordSize();
  1679. const char* format = req.getSourceFormat();
  1680. if ((recordsize == RECFMVB_RECSIZE_ESCAPE) || (format && strieq(format, "recfmvb")))
  1681. {//recordsize may be set by dfuplus; format may be set by EclWatch
  1682. source->setFormat(DFUff_recfmvb);
  1683. destination->setFormat(DFUff_variable);
  1684. }
  1685. else if ((recordsize == RECFMV_RECSIZE_ESCAPE) || (format && strieq(format, "recfmv")))
  1686. {
  1687. source->setFormat(DFUff_recfmv);
  1688. destination->setFormat(DFUff_variable);
  1689. }
  1690. else if ((recordsize == PREFIX_VARIABLE_RECSIZE_ESCAPE) || (format && strieq(format, "variable")))
  1691. {
  1692. source->setFormat(DFUff_variable);
  1693. destination->setFormat(DFUff_variable);
  1694. }
  1695. else if((recordsize == PREFIX_VARIABLE_BIGENDIAN_RECSIZE_ESCAPE) || (format && strieq(format, "variablebigendian")))
  1696. {
  1697. source->setFormat(DFUff_variablebigendian);
  1698. destination->setFormat(DFUff_variable);
  1699. }
  1700. else if(recordsize == 0 && !nosplit) // -ve record sizes for blocked
  1701. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid record size");
  1702. else
  1703. source->setRecordSize(recordsize);
  1704. destination->setLogicalName(destname);
  1705. destination->setDirectory(destFolder.str());
  1706. StringBuffer fileMask;
  1707. constructFileMask(destTitle.str(), fileMask);
  1708. destination->setFileMask(fileMask.str());
  1709. destination->setGroupName(gName.str());
  1710. const char * encryptkey = req.getEncrypt();
  1711. if(req.getCompress()||(encryptkey&&*encryptkey))
  1712. destination->setCompressed(true);
  1713. ClusterPartDiskMapSpec mspec;
  1714. destination->getClusterPartDiskMapSpec(gName.str(), mspec);
  1715. mspec.setDefaultBaseDir(defaultFolder.str());
  1716. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  1717. destination->setClusterPartDiskMapSpec(gName.str(), mspec);
  1718. int repo = req.getReplicateOffset();
  1719. bool isNull = req.getReplicateOffset_isNull();
  1720. if (!isNull && (repo!=1))
  1721. destination->setReplicateOffset(repo);
  1722. if (req.getWrap())
  1723. destination->setWrap(true);
  1724. IDFUoptions *options = wu->queryUpdateOptions();
  1725. const char * decryptkey = req.getDecrypt();
  1726. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  1727. options->setEncDec(encryptkey,decryptkey);
  1728. options->setReplicate(req.getReplicate());
  1729. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1730. const char* prefix = req.getPrefix();
  1731. if(prefix && *prefix)
  1732. options->setLengthPrefix(prefix);
  1733. if(req.getNosplit())
  1734. options->setNoSplit(true);
  1735. if(req.getNorecover())
  1736. options->setNoRecover(true);
  1737. if(req.getMaxConnections() > 0)
  1738. options->setmaxConnections(req.getMaxConnections());
  1739. if(req.getThrottle() > 0)
  1740. options->setThrottle(req.getThrottle());
  1741. if(req.getTransferBufferSize() > 0)
  1742. options->setTransferBufferSize(req.getTransferBufferSize());
  1743. if (req.getPull())
  1744. options->setPull(true);
  1745. if (req.getPush())
  1746. options->setPush(true);
  1747. if (req.getFailIfNoSourceFile())
  1748. options->setFailIfNoSourceFile(true);
  1749. if (req.getRecordStructurePresent())
  1750. options->setRecordStructurePresent(true);
  1751. options->setExpireDays(req.getExpireDays());
  1752. resp.setWuid(wu->queryId());
  1753. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1754. submitDFUWorkUnit(wu.getClear());
  1755. }
  1756. catch(IException* e)
  1757. {
  1758. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1759. }
  1760. return true;
  1761. }
  1762. bool CFileSprayEx::onSprayVariable(IEspContext &context, IEspSprayVariable &req, IEspSprayResponse &resp)
  1763. {
  1764. try
  1765. {
  1766. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Spray. Permission denied.");
  1767. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  1768. const char* destNodeGroup = req.getDestGroup();
  1769. if(destNodeGroup == NULL || *destNodeGroup == '\0')
  1770. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination node group not specified.");
  1771. StringBuffer gName, ipAddr;
  1772. const char *pTr = strchr(destNodeGroup, ' ');
  1773. if (pTr)
  1774. {
  1775. gName.append(pTr - destNodeGroup, destNodeGroup);
  1776. ipAddr.append(pTr+1);
  1777. }
  1778. else
  1779. gName.append(destNodeGroup);
  1780. MemoryBuffer& srcxml = (MemoryBuffer&)req.getSrcxml();
  1781. StringBuffer sourceIPReq, sourcePathReq;
  1782. readAndCheckSpraySourceReq(srcxml, req.getSourceIP(), req.getSourcePath(), sourceIPReq, sourcePathReq);
  1783. const char* srcip = sourceIPReq.str();
  1784. const char* srcfile = sourcePathReq.str();
  1785. const char* destname = req.getDestLogicalName();
  1786. if(!destname || !*destname)
  1787. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1788. CDfsLogicalFileName lfn;
  1789. if (!lfn.setValidate(destname))
  1790. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename:'%s'", destname);
  1791. destname = lfn.get();
  1792. PROGLOG("SprayVariable: DestLogicalName %s, DestGroup %s", destname, destNodeGroup);
  1793. if (ipAddr.length() > 0)
  1794. ParseLogicalPath(destname, ipAddr.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1795. else
  1796. ParseLogicalPath(destname, destNodeGroup, NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1797. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1798. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1799. wu->setClusterName(gName.str());
  1800. wu->setJobName(destTitle.str());
  1801. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  1802. setUserAuth(context, wu);
  1803. wu->setCommand(DFUcmd_import);
  1804. IDFUfileSpec *source = wu->queryUpdateSource();
  1805. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1806. IDFUoptions *options = wu->queryUpdateOptions();
  1807. if(srcxml.length() == 0)
  1808. {
  1809. RemoteMultiFilename rmfn;
  1810. SocketEndpoint ep(srcip);
  1811. rmfn.setEp(ep);
  1812. StringBuffer fnamebuf(srcfile);
  1813. fnamebuf.trim();
  1814. rmfn.append(fnamebuf.str()); // handles comma separated files
  1815. source->setMultiFilename(rmfn);
  1816. }
  1817. else
  1818. {
  1819. srcxml.append('\0');
  1820. source->setFromXML((const char*)srcxml.toByteArray());
  1821. }
  1822. source->setMaxRecordSize(req.getSourceMaxRecordSize());
  1823. source->setFormat((DFUfileformat)req.getSourceFormat());
  1824. StringBuffer rowtag;
  1825. if (req.getIsJSON())
  1826. {
  1827. const char *srcRowPath = req.getSourceRowPath();
  1828. if (!srcRowPath || *srcRowPath != '/')
  1829. rowtag.append("/");
  1830. rowtag.append(srcRowPath);
  1831. }
  1832. else
  1833. rowtag.append(req.getSourceRowTag());
  1834. // if rowTag specified, it means it's xml or json format, otherwise it's csv
  1835. if(rowtag.length())
  1836. {
  1837. source->setRowTag(rowtag);
  1838. options->setKeepHeader(true);
  1839. }
  1840. else
  1841. {
  1842. const char* cs = req.getSourceCsvSeparate();
  1843. if (req.getNoSourceCsvSeparator())
  1844. {
  1845. cs = "";
  1846. }
  1847. else if(cs == NULL || *cs == '\0')
  1848. cs = "\\,";
  1849. const char* ct = req.getSourceCsvTerminate();
  1850. if(ct == NULL || *ct == '\0')
  1851. ct = "\\n,\\r\\n";
  1852. const char* cq = req.getSourceCsvQuote();
  1853. if(cq== NULL)
  1854. cq = "\"";
  1855. source->setCsvOptions(cs, ct, cq, req.getSourceCsvEscape(), req.getQuotedTerminator());
  1856. options->setQuotedTerminator(req.getQuotedTerminator());
  1857. }
  1858. destination->setLogicalName(destname);
  1859. destination->setDirectory(destFolder.str());
  1860. StringBuffer fileMask;
  1861. constructFileMask(destTitle.str(), fileMask);
  1862. destination->setFileMask(fileMask.str());
  1863. destination->setGroupName(gName.str());
  1864. ClusterPartDiskMapSpec mspec;
  1865. destination->getClusterPartDiskMapSpec(gName.str(), mspec);
  1866. mspec.setDefaultBaseDir(defaultFolder.str());
  1867. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  1868. destination->setClusterPartDiskMapSpec(gName.str(), mspec);
  1869. const char * encryptkey = req.getEncrypt();
  1870. if(req.getCompress()||(encryptkey&&*encryptkey))
  1871. destination->setCompressed(true);
  1872. const char * decryptkey = req.getDecrypt();
  1873. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  1874. options->setEncDec(encryptkey,decryptkey);
  1875. int repo = req.getReplicateOffset();
  1876. bool isNull = req.getReplicateOffset_isNull();
  1877. if (!isNull && (repo!=1))
  1878. destination->setReplicateOffset(repo);
  1879. options->setReplicate(req.getReplicate());
  1880. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1881. const char* prefix = req.getPrefix();
  1882. if(prefix && *prefix)
  1883. options->setLengthPrefix(prefix);
  1884. if(req.getNosplit())
  1885. options->setNoSplit(true);
  1886. if(req.getNorecover())
  1887. options->setNoRecover(true);
  1888. if(req.getMaxConnections() > 0)
  1889. options->setmaxConnections(req.getMaxConnections());
  1890. if(req.getThrottle() > 0)
  1891. options->setThrottle(req.getThrottle());
  1892. if(req.getTransferBufferSize() > 0)
  1893. options->setTransferBufferSize(req.getTransferBufferSize());
  1894. if (req.getPull())
  1895. options->setPull(true);
  1896. if (req.getPush())
  1897. options->setPush(true);
  1898. if (req.getFailIfNoSourceFile())
  1899. options->setFailIfNoSourceFile(true);
  1900. if (req.getRecordStructurePresent())
  1901. options->setRecordStructurePresent(true);
  1902. options->setExpireDays(req.getExpireDays());
  1903. resp.setWuid(wu->queryId());
  1904. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1905. submitDFUWorkUnit(wu.getClear());
  1906. }
  1907. catch(IException* e)
  1908. {
  1909. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1910. }
  1911. return true;
  1912. }
  1913. bool CFileSprayEx::onReplicate(IEspContext &context, IEspReplicate &req, IEspReplicateResponse &resp)
  1914. {
  1915. try
  1916. {
  1917. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Replicate. Permission denied.");
  1918. const char* srcname = req.getSourceLogicalName();
  1919. if(!srcname || !*srcname)
  1920. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  1921. PROGLOG("Replicate %s", srcname);
  1922. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1923. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1924. StringBuffer jobname = "Replicate: ";
  1925. jobname.append(srcname);
  1926. wu->setJobName(jobname.str());
  1927. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  1928. setUserAuth(context, wu);
  1929. wu->setCommand(DFUcmd_replicate);
  1930. IDFUfileSpec *source = wu->queryUpdateSource();
  1931. if (source)
  1932. {
  1933. source->setLogicalName(srcname);
  1934. int repo = req.getReplicateOffset();
  1935. if (repo!=1)
  1936. source->setReplicateOffset(repo);
  1937. }
  1938. const char* cluster = req.getCluster();
  1939. if(cluster && *cluster)
  1940. {
  1941. IDFUoptions *opt = wu->queryUpdateOptions();
  1942. opt->setReplicateMode(DFURMmissing,cluster,req.getRepeatLast(),req.getOnlyRepeated());
  1943. }
  1944. resp.setWuid(wu->queryId());
  1945. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1946. submitDFUWorkUnit(wu.getClear());
  1947. }
  1948. catch(IException* e)
  1949. {
  1950. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1951. }
  1952. return true;
  1953. }
  1954. void CFileSprayEx::getDropZoneInfoByIP(double clientVersion, const char* ip, const char* destFileIn, StringBuffer& destFileOut, StringBuffer& umask)
  1955. {
  1956. if (destFileIn && *destFileIn)
  1957. destFileOut.set(destFileIn);
  1958. if (!ip || !*ip)
  1959. throw MakeStringExceptionDirect(ECLWATCH_INVALID_IP, "Network address must be specified for a drop zone!");
  1960. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  1961. Owned<IConstEnvironment> constEnv = factory->openEnvironment();
  1962. StringBuffer destFile;
  1963. if (isAbsolutePath(destFileIn))
  1964. {
  1965. destFile.set(destFileIn);
  1966. Owned<IConstDropZoneInfo> dropZone = constEnv->getDropZoneByAddressPath(ip, destFile.str());
  1967. if (!dropZone)
  1968. {
  1969. if (constEnv->isDropZoneRestrictionEnabled())
  1970. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "No drop zone configured for '%s' and '%s'. Check your system drop zone configuration.", ip, destFile.str());
  1971. else
  1972. {
  1973. LOG(MCdebugInfo, unknownJob, "No drop zone configured for '%s' and '%s'. Check your system drop zone configuration.", ip, destFile.str());
  1974. return;
  1975. }
  1976. }
  1977. SCMStringBuffer directory, maskBuf;
  1978. dropZone->getDirectory(directory);
  1979. destFileOut.set(destFile.str());
  1980. dropZone->getUMask(maskBuf);
  1981. if (maskBuf.length())
  1982. umask.set(maskBuf.str());
  1983. return;
  1984. }
  1985. Owned<IConstDropZoneInfoIterator> dropZoneItr = constEnv->getDropZoneIteratorByAddress(ip);
  1986. if (dropZoneItr->count() < 1)
  1987. {
  1988. if (constEnv->isDropZoneRestrictionEnabled())
  1989. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Drop zone not found for network address '%s'. Check your system drop zone configuration.", ip);
  1990. else
  1991. {
  1992. LOG(MCdebugInfo, unknownJob, "Drop zone not found for network address '%s'. Check your system drop zone configuration.", ip);
  1993. return;
  1994. }
  1995. }
  1996. bool dzFound = false;
  1997. ForEach(*dropZoneItr)
  1998. {
  1999. IConstDropZoneInfo& dropZoneInfo = dropZoneItr->query();
  2000. SCMStringBuffer dropZoneDirectory, dropZoneUMask;
  2001. dropZoneInfo.getDirectory(dropZoneDirectory);
  2002. dropZoneInfo.getUMask(dropZoneUMask);
  2003. if (!dropZoneDirectory.length())
  2004. continue;
  2005. if (!dzFound)
  2006. {
  2007. dzFound = true;
  2008. destFileOut.set(dropZoneDirectory.str());
  2009. addPathSepChar(destFileOut);
  2010. destFileOut.append(destFileIn);
  2011. if (dropZoneUMask.length())
  2012. umask.set(dropZoneUMask.str());
  2013. }
  2014. else
  2015. {
  2016. if (constEnv->isDropZoneRestrictionEnabled())
  2017. throw MakeStringException(ECLWATCH_INVALID_INPUT, "> 1 drop zones found for network address '%s'.", ip);
  2018. else
  2019. {
  2020. LOG(MCdebugInfo, unknownJob, "> 1 drop zones found for network address '%s'.", ip);
  2021. return;
  2022. }
  2023. }
  2024. }
  2025. if (!dzFound)
  2026. {
  2027. if (constEnv->isDropZoneRestrictionEnabled())
  2028. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "No valid drop zone found for network address '%s'. Check your system drop zone configuration.", ip);
  2029. else
  2030. LOG(MCdebugInfo, unknownJob, "No valid drop zone found for network address '%s'. Check your system drop zone configuration.", ip);
  2031. }
  2032. }
  2033. bool CFileSprayEx::onDespray(IEspContext &context, IEspDespray &req, IEspDesprayResponse &resp)
  2034. {
  2035. try
  2036. {
  2037. context.ensureFeatureAccess(FILE_DESPRAY_URL, SecAccess_Write, ECLWATCH_FILE_DESPRAY_ACCESS_DENIED, "Failed to do Despray. Permission denied.");
  2038. const char* srcname = req.getSourceLogicalName();
  2039. if(!srcname || !*srcname)
  2040. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2041. PROGLOG("Despray %s", srcname);
  2042. double version = context.getClientVersion();
  2043. const char* destip = req.getDestIP();
  2044. StringBuffer destPath;
  2045. const char* destfile = getStandardPosixPath(destPath, req.getDestPath()).str();
  2046. MemoryBuffer& dstxml = (MemoryBuffer&)req.getDstxml();
  2047. if(dstxml.length() == 0)
  2048. {
  2049. if(!destip || !*destip)
  2050. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination network IP not specified.");
  2051. if(!destfile || !*destfile)
  2052. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  2053. }
  2054. StringBuffer srcTitle;
  2055. ParseLogicalPath(srcname, srcTitle);
  2056. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2057. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2058. wu->setJobName(srcTitle.str());
  2059. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  2060. setUserAuth(context, wu);
  2061. wu->setCommand(DFUcmd_export);
  2062. IDFUfileSpec *source = wu->queryUpdateSource();
  2063. IDFUfileSpec *destination = wu->queryUpdateDestination();
  2064. IDFUoptions *options = wu->queryUpdateOptions();
  2065. source->setLogicalName(srcname);
  2066. if(dstxml.length() == 0)
  2067. {
  2068. RemoteFilename rfn;
  2069. SocketEndpoint ep(destip);
  2070. StringBuffer destfileWithPath, umask;
  2071. getDropZoneInfoByIP(version, destip, destfile, destfileWithPath, umask);
  2072. rfn.setPath(ep, destfileWithPath.str());
  2073. if (umask.length())
  2074. options->setUMask(umask.str());
  2075. destination->setSingleFilename(rfn);
  2076. }
  2077. else
  2078. {
  2079. dstxml.append('\0');
  2080. destination->setFromXML((const char*)dstxml.toByteArray());
  2081. }
  2082. destination->setTitle(srcTitle.str());
  2083. options->setKeepHeader(true);
  2084. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  2085. const char* splitprefix = req.getSplitprefix();
  2086. if(splitprefix && *splitprefix)
  2087. options->setSplitPrefix(splitprefix);
  2088. if (version > 1.01)
  2089. {
  2090. if(req.getMaxConnections() > 0)
  2091. options->setmaxConnections(req.getMaxConnections());
  2092. else if(req.getSingleConnection())
  2093. options->setmaxConnections(1);
  2094. }
  2095. else
  2096. {
  2097. if(req.getMaxConnections() > 0)
  2098. options->setmaxConnections(req.getMaxConnections());
  2099. }
  2100. if(req.getThrottle() > 0)
  2101. options->setThrottle(req.getThrottle());
  2102. if(req.getTransferBufferSize() > 0)
  2103. options->setTransferBufferSize(req.getTransferBufferSize());
  2104. if(req.getNorecover())
  2105. options->setNoRecover(true);
  2106. if (req.getWrap()) {
  2107. options->setPush(); // I think needed for a despray
  2108. destination->setWrap(true);
  2109. }
  2110. if (req.getMultiCopy())
  2111. destination->setMultiCopy(true);
  2112. const char * encryptkey = req.getEncrypt();
  2113. if(req.getCompress()||(encryptkey&&*encryptkey))
  2114. destination->setCompressed(true);
  2115. const char * decryptkey = req.getDecrypt();
  2116. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2117. options->setEncDec(encryptkey,decryptkey);
  2118. resp.setWuid(wu->queryId());
  2119. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2120. submitDFUWorkUnit(wu.getClear());
  2121. }
  2122. catch(IException* e)
  2123. {
  2124. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2125. }
  2126. return true;
  2127. }
  2128. bool CFileSprayEx::onCopy(IEspContext &context, IEspCopy &req, IEspCopyResponse &resp)
  2129. {
  2130. try
  2131. {
  2132. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Copy. Permission denied.");
  2133. const char* srcname = req.getSourceLogicalName();
  2134. const char* dstname = req.getDestLogicalName();
  2135. if(!srcname || !*srcname)
  2136. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2137. if(!dstname || !*dstname)
  2138. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2139. PROGLOG("Copy from %s to %s", srcname, dstname);
  2140. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  2141. StringBuffer srcNodeGroup, destNodeGroup;
  2142. bool bRoxie = false;
  2143. const char* destNodeGroupReq = req.getDestGroup();
  2144. if(!destNodeGroupReq || !*destNodeGroupReq)
  2145. {
  2146. getNodeGroupFromLFN(destNodeGroup, srcname, context.queryUserId(), context.queryPassword());
  2147. DBGLOG("Destination node group not specified, using source node group %s", destNodeGroup.str());
  2148. }
  2149. else
  2150. {
  2151. destNodeGroup = destNodeGroupReq;
  2152. const char* destRoxie = req.getDestGroupRoxie();
  2153. if (destRoxie && !stricmp(destRoxie, "Yes"))
  2154. {
  2155. bRoxie = true;
  2156. }
  2157. }
  2158. CDfsLogicalFileName lfn; // NOTE: must not be moved into block below, or dstname will point to invalid memory
  2159. if (!bRoxie)
  2160. {
  2161. if (!lfn.setValidate(dstname))
  2162. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename:'%s'", dstname);
  2163. dstname = lfn.get();
  2164. }
  2165. ParseLogicalPath(dstname, destNodeGroup.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  2166. StringBuffer fileMask;
  2167. constructFileMask(destTitle.str(), fileMask);
  2168. const char* srcDali = req.getSourceDali();
  2169. bool supercopy = req.getSuperCopy();
  2170. if (supercopy)
  2171. {
  2172. StringBuffer user, passwd;
  2173. context.getUserID(user);
  2174. context.getPassword(passwd);
  2175. StringBuffer u(user);
  2176. StringBuffer p(passwd);
  2177. Owned<INode> foreigndali;
  2178. if (srcDali)
  2179. {
  2180. SocketEndpoint ep(srcDali);
  2181. foreigndali.setown(createINode(ep));
  2182. const char* srcu = req.getSrcusername();
  2183. if(srcu && *srcu)
  2184. {
  2185. u.clear().append(srcu);
  2186. p.clear().append(req.getSrcpassword());
  2187. }
  2188. }
  2189. Owned<IUserDescriptor> udesc=createUserDescriptor();
  2190. udesc->set(u.str(),p.str());
  2191. if (!queryDistributedFileDirectory().isSuperFile(srcname,udesc,foreigndali))
  2192. supercopy = false;
  2193. }
  2194. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2195. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2196. wu->setJobName(dstname);
  2197. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  2198. setUserAuth(context, wu);
  2199. if(destNodeGroup.length() > 0)
  2200. wu->setClusterName(destNodeGroup.str());
  2201. if (supercopy)
  2202. wu->setCommand(DFUcmd_supercopy);
  2203. else
  2204. wu->setCommand(DFUcmd_copy);
  2205. IDFUfileSpec *wuFSpecSource = wu->queryUpdateSource();
  2206. IDFUfileSpec *wuFSpecDest = wu->queryUpdateDestination();
  2207. IDFUoptions *wuOptions = wu->queryUpdateOptions();
  2208. wuFSpecSource->setLogicalName(srcname);
  2209. if(srcDali && *srcDali)
  2210. {
  2211. SocketEndpoint ep(srcDali);
  2212. wuFSpecSource->setForeignDali(ep);
  2213. const char* srcusername = req.getSrcusername();
  2214. if(srcusername && *srcusername)
  2215. {
  2216. const char* srcpasswd = req.getSrcpassword();
  2217. wuFSpecSource->setForeignUser(srcusername, srcpasswd);
  2218. }
  2219. }
  2220. wuFSpecDest->setLogicalName(dstname);
  2221. wuFSpecDest->setFileMask(fileMask.str());
  2222. wuOptions->setOverwrite(req.getOverwrite());
  2223. wuOptions->setPreserveCompression(req.getPreserveCompression());
  2224. if (!req.getExpireDays_isNull())
  2225. wuOptions->setExpireDays(req.getExpireDays());
  2226. if (bRoxie)
  2227. {
  2228. setRoxieClusterPartDiskMapping(destNodeGroup.str(), defaultFolder.str(), defaultReplicateFolder.str(), supercopy, wuFSpecDest, wuOptions);
  2229. wuFSpecDest->setWrap(true); // roxie always wraps
  2230. if(req.getCompress())
  2231. wuFSpecDest->setCompressed(true);
  2232. if (!supercopy)
  2233. wuOptions->setSuppressNonKeyRepeats(true); // **** only repeat last part when src kind = key
  2234. }
  2235. else
  2236. {
  2237. const char* srcDiffKeyName = req.getSourceDiffKeyName();
  2238. const char* destDiffKeyName = req.getDestDiffKeyName();
  2239. if (srcDiffKeyName&&*srcDiffKeyName)
  2240. wuFSpecSource->setDiffKey(srcDiffKeyName);
  2241. if (destDiffKeyName&&*destDiffKeyName)
  2242. wuFSpecDest->setDiffKey(destDiffKeyName);
  2243. wuFSpecDest->setDirectory(destFolder.str());
  2244. wuFSpecDest->setGroupName(destNodeGroup.str());
  2245. wuFSpecDest->setWrap(req.getWrap());
  2246. const char * encryptkey = req.getEncrypt();
  2247. if(req.getCompress()||(encryptkey&&*encryptkey))
  2248. wuFSpecDest->setCompressed(true);
  2249. wuOptions->setReplicate(req.getReplicate());
  2250. const char * decryptkey = req.getDecrypt();
  2251. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2252. wuOptions->setEncDec(encryptkey,decryptkey);
  2253. if(req.getNorecover())
  2254. wuOptions->setNoRecover(true);
  2255. if(!req.getNosplit_isNull())
  2256. wuOptions->setNoSplit(req.getNosplit());
  2257. if(req.getMaxConnections() > 0)
  2258. wuOptions->setmaxConnections(req.getMaxConnections());
  2259. if(req.getThrottle() > 0)
  2260. wuOptions->setThrottle(req.getThrottle());
  2261. if(req.getTransferBufferSize() > 0)
  2262. wuOptions->setTransferBufferSize(req.getTransferBufferSize());
  2263. if (req.getPull())
  2264. wuOptions->setPull(true);
  2265. if (req.getPush())
  2266. wuOptions->setPush(true);
  2267. if (req.getIfnewer())
  2268. wuOptions->setIfNewer(true);
  2269. ClusterPartDiskMapSpec mspec;
  2270. wuFSpecDest->getClusterPartDiskMapSpec(destNodeGroup.str(), mspec);
  2271. mspec.setDefaultBaseDir(defaultFolder.str());
  2272. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  2273. wuFSpecDest->setClusterPartDiskMapSpec(destNodeGroup.str(), mspec);
  2274. }
  2275. resp.setResult(wu->queryId());
  2276. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2277. submitDFUWorkUnit(wu.getClear());
  2278. }
  2279. catch(IException* e)
  2280. {
  2281. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2282. }
  2283. return true;
  2284. }
  2285. bool CFileSprayEx::onRename(IEspContext &context, IEspRename &req, IEspRenameResponse &resp)
  2286. {
  2287. try
  2288. {
  2289. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Rename. Permission denied.");
  2290. const char* srcname = req.getSrcname();
  2291. const char* dstname = req.getDstname();
  2292. if(!srcname || !*srcname)
  2293. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2294. if(!dstname || !*dstname)
  2295. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2296. PROGLOG("Rename from %s to %s", srcname, dstname);
  2297. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2298. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2299. StringBuffer destTitle;
  2300. ParseLogicalPath(req.getDstname(), destTitle);
  2301. wu->setJobName(destTitle.str());
  2302. setDFUServerQueueReq(req.getDFUServerQueue(), wu);
  2303. setUserAuth(context, wu);
  2304. wu->setCommand(DFUcmd_rename);
  2305. #if 0 // TBD - Handling for multiple clusters? the cluster should be specified by user if needed
  2306. Owned<IUserDescriptor> udesc;
  2307. if(user.length() > 0)
  2308. {
  2309. const char* passwd = context.queryPassword();
  2310. udesc.setown(createUserDescriptor());
  2311. udesc->set(user.str(), passwd);
  2312. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(srcname, udesc);
  2313. if(df)
  2314. {
  2315. StringBuffer cluster0;
  2316. df->getClusterName(0,cluster0); // TBD - Handling for multiple clusters?
  2317. if (cluster0.length()!=0)
  2318. {
  2319. wu->setClusterName(cluster0.str());
  2320. }
  2321. else
  2322. {
  2323. const char *cluster = df->queryAttributes().queryProp("@group");
  2324. if (cluster && *cluster)
  2325. {
  2326. wu->setClusterName(cluster);
  2327. }
  2328. }
  2329. }
  2330. }
  2331. #endif
  2332. IDFUfileSpec *source = wu->queryUpdateSource();
  2333. source->setLogicalName(srcname);
  2334. IDFUfileSpec *destination = wu->queryUpdateDestination();
  2335. destination->setLogicalName(dstname);
  2336. IDFUoptions *options = wu->queryUpdateOptions();
  2337. options->setOverwrite(req.getOverwrite());
  2338. resp.setWuid(wu->queryId());
  2339. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2340. submitDFUWorkUnit(wu.getClear());
  2341. }
  2342. catch(IException* e)
  2343. {
  2344. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2345. }
  2346. return true;
  2347. }
  2348. bool CFileSprayEx::onDFUWUFile(IEspContext &context, IEspDFUWUFileRequest &req, IEspDFUWUFileResponse &resp)
  2349. {
  2350. try
  2351. {
  2352. context.ensureFeatureAccess(DFU_WU_URL, SecAccess_Read, ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  2353. if (*req.getWuid())
  2354. {
  2355. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2356. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  2357. if(!wu)
  2358. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  2359. PROGLOG("DFUWUFile: %s", req.getWuid());
  2360. StringBuffer xmlbuf;
  2361. xmlbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2362. const char* plainText = req.getPlainText();
  2363. if (plainText && (!stricmp(plainText, "yes")))
  2364. {
  2365. wu->toXML(xmlbuf);
  2366. resp.setFile(xmlbuf.str());
  2367. resp.setFile_mimetype(HTTP_TYPE_TEXT_PLAIN);
  2368. }
  2369. else
  2370. {
  2371. xmlbuf.append("<?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>");
  2372. wu->toXML(xmlbuf);
  2373. resp.setFile(xmlbuf.str());
  2374. resp.setFile_mimetype(HTTP_TYPE_APPLICATION_XML);
  2375. }
  2376. }
  2377. }
  2378. catch(IException* e)
  2379. {
  2380. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2381. }
  2382. return true;
  2383. }
  2384. bool CFileSprayEx::onFileList(IEspContext &context, IEspFileListRequest &req, IEspFileListResponse &resp)
  2385. {
  2386. try
  2387. {
  2388. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do FileList. Permission denied.");
  2389. const char* path = req.getPath();
  2390. if (!path || !*path)
  2391. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Path not specified.");
  2392. double version = context.getClientVersion();
  2393. const char* netaddr = req.getNetaddr();
  2394. if (!netaddr || !*netaddr)
  2395. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Network address not specified.");
  2396. const char* fileNameMask = req.getMask();
  2397. bool directoryOnly = req.getDirectoryOnly();
  2398. PROGLOG("FileList: Netaddr %s, Path %s", netaddr, path);
  2399. StringBuffer sPath(path);
  2400. const char* osStr = req.getOS();
  2401. if (osStr && *osStr)
  2402. {
  2403. int os = atoi(osStr);
  2404. const char pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2405. sPath.replace(pathSep=='\\'?'/':'\\', pathSep);
  2406. if (*(sPath.str() + sPath.length() -1) != pathSep)
  2407. sPath.append( pathSep );
  2408. }
  2409. if (!isEmptyString(fileNameMask))
  2410. {
  2411. const char* ext = pathExtension(sPath.str());
  2412. if (ext && !strieq(ext, "cfg") && !strieq(ext, "log"))
  2413. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Only cfg or log file allowed.");
  2414. }
  2415. RemoteFilename rfn;
  2416. SocketEndpoint ep;
  2417. #ifdef MACHINE_IP
  2418. ep.set(MACHINE_IP);
  2419. #else
  2420. ep.set(netaddr);
  2421. #endif
  2422. rfn.setPath(ep, sPath.str());
  2423. Owned<IFile> f = createIFile(rfn);
  2424. if(!f->isDirectory())
  2425. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2426. IArrayOf<IEspPhysicalFileStruct> files;
  2427. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2428. if(di.get() != NULL)
  2429. {
  2430. ForEach(*di)
  2431. {
  2432. StringBuffer fname;
  2433. di->getName(fname);
  2434. if (fname.length() == 0 || (directoryOnly && !di->isDir()) || (!di->isDir() && !isEmptyString(fileNameMask) && !WildMatch(fname.str(), fileNameMask, true)))
  2435. continue;
  2436. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2437. onefile->setName(fname.str());
  2438. onefile->setIsDir(di->isDir());
  2439. onefile->setFilesize(di->getFileSize());
  2440. CDateTime modtime;
  2441. StringBuffer timestr;
  2442. di->getModifiedTime(modtime);
  2443. unsigned y,m,d,h,min,sec,nsec;
  2444. modtime.getDate(y,m,d,true);
  2445. modtime.getTime(h,min,sec,nsec,true);
  2446. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2447. onefile->setModifiedtime(timestr.str());
  2448. files.append(*onefile.getLink());
  2449. }
  2450. }
  2451. sPath.replace('\\', '/');//XSLT cannot handle backslashes
  2452. resp.setPath(sPath);
  2453. resp.setFiles(files);
  2454. resp.setNetaddr(netaddr);
  2455. if (osStr && *osStr)
  2456. {
  2457. int os = atoi(osStr);
  2458. resp.setOS(os);
  2459. }
  2460. if (!isEmptyString(fileNameMask))
  2461. resp.setMask(fileNameMask);
  2462. if (version >= 1.10)
  2463. {
  2464. StringBuffer acceptLanguage;
  2465. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  2466. }
  2467. resp.setDirectoryOnly(directoryOnly);
  2468. }
  2469. catch(IException* e)
  2470. {
  2471. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2472. }
  2473. return true;
  2474. }
  2475. bool CFileSprayEx::checkDropZoneIPAndPath(double clientVersion, const char* dropZoneName, const char* netAddr, const char* path)
  2476. {
  2477. if (isEmptyString(netAddr) || isEmptyString(path))
  2478. throw MakeStringException(ECLWATCH_INVALID_INPUT, "NetworkAddress or Path not defined.");
  2479. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2480. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2481. Owned<IConstDropZoneInfoIterator> dropZoneItr = constEnv->getDropZoneIteratorByAddress(netAddr);
  2482. ForEach(*dropZoneItr)
  2483. {
  2484. SCMStringBuffer directory, name;
  2485. IConstDropZoneInfo& dropZoneInfo = dropZoneItr->query();
  2486. dropZoneInfo.getDirectory(directory);
  2487. if (directory.length() && (strnicmp(path, directory.str(), directory.length()) == 0))
  2488. {
  2489. if (isEmptyString(dropZoneName))
  2490. return true;
  2491. dropZoneInfo.getName(name);
  2492. if (strieq(name.str(), dropZoneName))
  2493. return true;
  2494. }
  2495. }
  2496. return false;
  2497. }
  2498. void CFileSprayEx::addDropZoneFile(IEspContext& context, IDirectoryIterator* di, const char* name, const char pathSep, IArrayOf<IEspPhysicalFileStruct>& files)
  2499. {
  2500. Owned<IEspPhysicalFileStruct> aFile = createPhysicalFileStruct();
  2501. const char* pName = strrchr(name, pathSep);
  2502. if (!pName)
  2503. aFile->setName(name);
  2504. else
  2505. {
  2506. StringBuffer sPath;
  2507. sPath.append(pName - name, name);
  2508. aFile->setPath(sPath.str());
  2509. pName++; //skip the PathSepChar
  2510. aFile->setName(pName);
  2511. }
  2512. aFile->setIsDir(di->isDir());
  2513. CDateTime modtime;
  2514. StringBuffer timestr;
  2515. di->getModifiedTime(modtime);
  2516. unsigned y,m,d,h,min,sec,nsec;
  2517. modtime.getDate(y,m,d,true);
  2518. modtime.getTime(h,min,sec,nsec,true);
  2519. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2520. aFile->setModifiedtime(timestr.str());
  2521. aFile->setFilesize(di->getFileSize());
  2522. files.append(*aFile.getLink());
  2523. }
  2524. void CFileSprayEx::searchDropZoneFiles(IEspContext& context, IpAddress& ip, const char* dir, const char* nameFilter, IArrayOf<IEspPhysicalFileStruct>& files, unsigned& filesFound)
  2525. {
  2526. RemoteFilename rfn;
  2527. SocketEndpoint ep;
  2528. ep.ipset(ip);
  2529. rfn.setPath(ep, dir);
  2530. Owned<IFile> f = createIFile(rfn);
  2531. if(!f->isDirectory())
  2532. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", dir);
  2533. const char pathSep = getPathSepChar(dir);
  2534. Owned<IDirectoryIterator> di = f->directoryFiles(nameFilter, true, true);
  2535. ForEach(*di)
  2536. {
  2537. StringBuffer fname;
  2538. di->getName(fname);
  2539. if (!fname.length())
  2540. continue;
  2541. filesFound++;
  2542. if (filesFound > dropZoneFileSearchMaxFiles)
  2543. break;
  2544. addDropZoneFile(context, di, fname.str(), pathSep, files);
  2545. }
  2546. }
  2547. bool CFileSprayEx::onDropZoneFileSearch(IEspContext &context, IEspDropZoneFileSearchRequest &req, IEspDropZoneFileSearchResponse &resp)
  2548. {
  2549. try
  2550. {
  2551. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Access, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do FileList. Permission denied.");
  2552. const char* dropZoneName = req.getDropZoneName();
  2553. if (isEmptyString(dropZoneName))
  2554. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone not specified.");
  2555. const char* dropZoneServerReq = req.getServer(); //IP or hostname
  2556. if (isEmptyString(dropZoneServerReq))
  2557. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone server not specified.");
  2558. const char* nameFilter = req.getNameFilter();
  2559. if (isEmptyString(nameFilter))
  2560. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Name Filter not specified.");
  2561. bool validNameFilter = false;
  2562. const char* pNameFilter = nameFilter;
  2563. while (!isEmptyString(pNameFilter))
  2564. {
  2565. if (*pNameFilter != '*')
  2566. {
  2567. validNameFilter = true;
  2568. break;
  2569. }
  2570. pNameFilter++;
  2571. }
  2572. if (!validNameFilter)
  2573. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Name Filter '*'");
  2574. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2575. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2576. Owned<IConstDropZoneInfo> dropZoneInfo = constEnv->getDropZone(dropZoneName);
  2577. if (!dropZoneInfo || (req.getECLWatchVisibleOnly() && !dropZoneInfo->isECLWatchVisible()))
  2578. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone %s not found.", dropZoneName);
  2579. SCMStringBuffer directory, computer;
  2580. dropZoneInfo->getDirectory(directory);
  2581. if (!directory.length())
  2582. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone Directory not found for %s.", dropZoneName);
  2583. IpAddress ipToMatch;
  2584. ipToMatch.ipset(dropZoneServerReq);
  2585. if (ipToMatch.isNull())
  2586. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid server %s specified.", dropZoneServerReq);
  2587. double version = context.getClientVersion();
  2588. bool serverFound = false;
  2589. unsigned filesFound = 0;
  2590. IArrayOf<IEspPhysicalFileStruct> files;
  2591. Owned<IConstDropZoneServerInfoIterator> dropZoneServerItr = dropZoneInfo->getServers();
  2592. ForEach(*dropZoneServerItr)
  2593. {
  2594. StringBuffer server, networkAddress;
  2595. IConstDropZoneServerInfo& dropZoneServer = dropZoneServerItr->query();
  2596. dropZoneServer.getServer(server);
  2597. if (server.isEmpty())
  2598. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid server for dropzone %s.", dropZoneName);
  2599. IpAddress ipAddr;
  2600. ipAddr.ipset(server.str());
  2601. if (ipAddr.ipequals(ipToMatch))
  2602. {
  2603. serverFound = true;
  2604. searchDropZoneFiles(context, ipAddr, directory.str(), nameFilter, files, filesFound);
  2605. break;
  2606. }
  2607. }
  2608. if (!serverFound)
  2609. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Server %s not found in dropzone %s.", dropZoneServerReq, dropZoneName);
  2610. if ((version >= 1.16) && (filesFound > dropZoneFileSearchMaxFiles))
  2611. {
  2612. VStringBuffer msg("More than %u files are found. Only %u files are returned.", dropZoneFileSearchMaxFiles, dropZoneFileSearchMaxFiles);
  2613. resp.setWarning(msg.str());
  2614. }
  2615. resp.setFiles(files);
  2616. }
  2617. catch(IException* e)
  2618. {
  2619. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2620. }
  2621. return true;
  2622. }
  2623. bool CFileSprayEx::onDfuMonitor(IEspContext &context, IEspDfuMonitorRequest &req, IEspDfuMonitorResponse &resp)
  2624. {
  2625. try
  2626. {
  2627. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do DfuMonitor. Permission denied.");
  2628. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2629. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2630. wu->setQueue(m_MonitorQueueLabel.str());
  2631. StringBuffer user, passwd;
  2632. wu->setUser(context.getUserID(user).str());
  2633. wu->setPassword(context.getPassword(passwd).str());
  2634. wu->setCommand(DFUcmd_monitor);
  2635. IDFUmonitor *monitor = wu->queryUpdateMonitor();
  2636. IDFUfileSpec *source = wu->queryUpdateSource();
  2637. const char *eventname = req.getEventName();
  2638. const char *lname = req.getLogicalName();
  2639. if (lname&&*lname)
  2640. source->setLogicalName(lname);
  2641. else {
  2642. const char *ip = req.getIp();
  2643. const char *filename = req.getFilename();
  2644. if (filename&&*filename) {
  2645. RemoteFilename rfn;
  2646. if (ip&&*ip) {
  2647. SocketEndpoint ep;
  2648. ep.set(ip);
  2649. rfn.setPath(ep,filename);
  2650. }
  2651. else
  2652. rfn.setRemotePath(filename);
  2653. source->setSingleFilename(rfn);
  2654. }
  2655. else
  2656. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Neither logical name nor network ip/file specified for monitor.");
  2657. }
  2658. if (eventname)
  2659. monitor->setEventName(eventname);
  2660. monitor->setShotLimit(req.getShotLimit());
  2661. monitor->setSub(req.getSub());
  2662. resp.setWuid(wu->queryId());
  2663. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2664. submitDFUWorkUnit(wu.getClear());
  2665. }
  2666. catch(IException* e)
  2667. {
  2668. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2669. }
  2670. return true;
  2671. }
  2672. bool CFileSprayEx::onOpenSave(IEspContext &context, IEspOpenSaveRequest &req, IEspOpenSaveResponse &resp)
  2673. {
  2674. try
  2675. {
  2676. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2677. const char* location = req.getLocation();
  2678. const char* path = req.getPath();
  2679. const char* name = req.getName();
  2680. const char* type = req.getType();
  2681. const char* dateTime = req.getDateTime();
  2682. if (location && *location)
  2683. resp.setLocation(location);
  2684. if (path && *path)
  2685. resp.setPath(path);
  2686. if (name && *name)
  2687. resp.setName(name);
  2688. if (type && *type)
  2689. resp.setType(type);
  2690. if (dateTime && *dateTime)
  2691. resp.setDateTime(dateTime);
  2692. if (req.getBinaryFile())
  2693. resp.setViewable(false);
  2694. }
  2695. catch(IException* e)
  2696. {
  2697. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2698. }
  2699. return true;
  2700. }
  2701. bool CFileSprayEx::getDropZoneFiles(IEspContext &context, const char* dropZone, const char* netaddr, const char* path,
  2702. IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2703. {
  2704. if (!checkDropZoneIPAndPath(context.getClientVersion(), dropZone, netaddr, path))
  2705. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2706. bool directoryOnly = req.getDirectoryOnly();
  2707. RemoteFilename rfn;
  2708. SocketEndpoint ep;
  2709. #ifdef MACHINE_IP
  2710. ep.set(MACHINE_IP);
  2711. #else
  2712. ep.set(netaddr);
  2713. #endif
  2714. rfn.setPath(ep, path);
  2715. Owned<IFile> f = createIFile(rfn);
  2716. if(!f->isDirectory())
  2717. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2718. IArrayOf<IEspPhysicalFileStruct> files;
  2719. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2720. if(di.get() != NULL)
  2721. {
  2722. ForEach(*di)
  2723. {
  2724. StringBuffer fname;
  2725. di->getName(fname);
  2726. if (fname.length() == 0 || (directoryOnly && !di->isDir()))
  2727. continue;
  2728. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2729. onefile->setName(fname.str());
  2730. onefile->setIsDir(di->isDir());
  2731. onefile->setFilesize(di->getFileSize());
  2732. CDateTime modtime;
  2733. StringBuffer timestr;
  2734. di->getModifiedTime(modtime);
  2735. unsigned y,m,d,h,min,sec,nsec;
  2736. modtime.getDate(y,m,d,true);
  2737. modtime.getTime(h,min,sec,nsec,true);
  2738. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2739. onefile->setModifiedtime(timestr.str());
  2740. files.append(*onefile.getLink());
  2741. }
  2742. }
  2743. resp.setFiles(files);
  2744. return true;
  2745. }
  2746. //This method returns all dropzones and, if NetAddress and Path specified, returns filtered list of files.
  2747. bool CFileSprayEx::onDropZoneFiles(IEspContext &context, IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2748. {
  2749. try
  2750. {
  2751. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2752. IpAddress ipToMatch;
  2753. const char* netAddress = req.getNetAddress();
  2754. if (!isEmptyString(netAddress))
  2755. {
  2756. ipToMatch.ipset(netAddress);
  2757. if (ipToMatch.isNull())
  2758. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid server %s specified.", netAddress);
  2759. }
  2760. bool filesFromALinux = false;
  2761. IArrayOf<IEspDropZone> dropZoneList;
  2762. bool ECLWatchVisibleOnly = req.getECLWatchVisibleOnly();
  2763. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2764. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2765. Owned<IConstDropZoneInfoIterator> dropZoneItr = constEnv->getDropZoneIterator();
  2766. ForEach(*dropZoneItr)
  2767. {
  2768. IConstDropZoneInfo& dropZoneInfo = dropZoneItr->query();
  2769. if (ECLWatchVisibleOnly && !dropZoneInfo.isECLWatchVisible())
  2770. continue;
  2771. SCMStringBuffer dropZoneName, directory, computerName;
  2772. dropZoneInfo.getName(dropZoneName);
  2773. dropZoneInfo.getDirectory(directory);
  2774. dropZoneInfo.getComputerName(computerName); //legacy env
  2775. if (!dropZoneName.length() || !directory.length())
  2776. continue;
  2777. bool isLinux = getPathSepChar(directory.str()) == '/' ? true : false;
  2778. Owned<IConstDropZoneServerInfoIterator> dropZoneServerItr = dropZoneInfo.getServers();
  2779. ForEach(*dropZoneServerItr)
  2780. {
  2781. IConstDropZoneServerInfo& dropZoneServer = dropZoneServerItr->query();
  2782. StringBuffer name, server, networkAddress;
  2783. dropZoneServer.getName(name);
  2784. dropZoneServer.getServer(server);
  2785. if (name.isEmpty() || server.isEmpty())
  2786. continue;
  2787. IpAddress ipAddr;
  2788. ipAddr.ipset(server.str());
  2789. ipAddr.getIpText(networkAddress);
  2790. Owned<IEspDropZone> aDropZone = createDropZone();
  2791. aDropZone->setName(dropZoneName.str());
  2792. aDropZone->setComputer(name.str());
  2793. aDropZone->setNetAddress(networkAddress.str());
  2794. aDropZone->setPath(directory.str());
  2795. if (isLinux)
  2796. aDropZone->setLinux("true");
  2797. if (!isEmptyString(netAddress) && ipAddr.ipequals(ipToMatch))
  2798. filesFromALinux = isLinux;
  2799. dropZoneList.append(*aDropZone.getClear());
  2800. }
  2801. }
  2802. if (dropZoneList.ordinality())
  2803. resp.setDropZones(dropZoneList);
  2804. const char* dzName = req.getDropZoneName();
  2805. const char* directory = req.getPath();
  2806. const char* subfolder = req.getSubfolder();
  2807. if (isEmptyString(netAddress) || (isEmptyString(directory) && isEmptyString(subfolder)))
  2808. return true;
  2809. StringBuffer netAddressStr, directoryStr, osStr;
  2810. netAddressStr.set(netAddress);
  2811. if (!isEmptyString(directory))
  2812. directoryStr.set(directory);
  2813. if (!isEmptyString(subfolder))
  2814. {
  2815. if (directoryStr.length())
  2816. addPathSepChar(directoryStr);
  2817. directoryStr.append(subfolder);
  2818. }
  2819. addPathSepChar(directoryStr);
  2820. getDropZoneFiles(context, dzName, netAddress, directoryStr.str(), req, resp);
  2821. resp.setDropZoneName(dzName);
  2822. resp.setNetAddress(netAddress);
  2823. resp.setPath(directoryStr.str());
  2824. resp.setOS(filesFromALinux);
  2825. resp.setECLWatchVisibleOnly(ECLWatchVisibleOnly);
  2826. }
  2827. catch(IException* e)
  2828. {
  2829. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2830. }
  2831. return true;
  2832. }
  2833. bool CFileSprayEx::onDeleteDropZoneFiles(IEspContext &context, IEspDeleteDropZoneFilesRequest &req, IEspDFUWorkunitsActionResponse &resp)
  2834. {
  2835. try
  2836. {
  2837. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Full, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2838. double version = context.getClientVersion();
  2839. const char* dzName = req.getDropZoneName();
  2840. const char* netAddress = req.getNetAddress();
  2841. const char* directory = req.getPath();
  2842. const char* osStr = req.getOS();
  2843. StringArray & files = req.getNames();
  2844. if (!files.ordinality())
  2845. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  2846. StringBuffer path(directory);
  2847. if (!isEmptyString(osStr))
  2848. {
  2849. char pathSep = (atoi(osStr) == OS_WINDOWS) ? '\\' : '/';
  2850. path.replace(pathSep=='\\' ? '/' : '\\', pathSep);
  2851. }
  2852. addPathSepChar(path, getPathSepChar(path.str()));
  2853. if (!checkDropZoneIPAndPath(version, dzName, netAddress, path.str()))
  2854. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2855. RemoteFilename rfn;
  2856. SocketEndpoint ep;
  2857. ep.set(netAddress);
  2858. rfn.setPath(ep, path.str());
  2859. Owned<IFile> f = createIFile(rfn);
  2860. if(!f->isDirectory())
  2861. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", directory);
  2862. bool bAllSuccess = true;
  2863. IArrayOf<IEspDFUActionResult> results;
  2864. for(unsigned i = 0; i < files.ordinality(); ++i)
  2865. {
  2866. const char* file = files.item(i);
  2867. if (!file || !*file)
  2868. continue;
  2869. PROGLOG("DeleteDropZoneFiles: netAddress %s, path %s, file %s", netAddress, directory, file);
  2870. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  2871. res->setID(files.item(i));
  2872. res->setAction("Delete");
  2873. res->setResult("Success");
  2874. try
  2875. {
  2876. StringBuffer fileToDelete = path;
  2877. fileToDelete.append(file);
  2878. rfn.setPath(ep, fileToDelete.str());
  2879. Owned<IFile> rFile = createIFile(rfn);
  2880. if (!rFile->exists())
  2881. res->setResult("Warning: this file does not exist.");
  2882. else
  2883. rFile->remove();
  2884. }
  2885. catch (IException *e)
  2886. {
  2887. bAllSuccess = false;
  2888. StringBuffer eMsg;
  2889. eMsg = e->errorMessage(eMsg);
  2890. e->Release();
  2891. StringBuffer failedMsg = "Failed: ";
  2892. failedMsg.append(eMsg);
  2893. res->setResult(failedMsg.str());
  2894. }
  2895. results.append(*res.getLink());
  2896. }
  2897. resp.setFirstColumn("File");
  2898. resp.setDFUActionResults(results);
  2899. }
  2900. catch(IException* e)
  2901. {
  2902. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2903. }
  2904. return true;
  2905. }
  2906. void CFileSprayEx::appendGroupNode(IArrayOf<IEspGroupNode>& groupNodes, const char* nodeName, const char* clusterType,
  2907. bool replicateOutputs)
  2908. {
  2909. Owned<IEspGroupNode> node = createGroupNode();
  2910. node->setName(nodeName);
  2911. node->setClusterType(clusterType);
  2912. if (replicateOutputs)
  2913. node->setReplicateOutputs(replicateOutputs);
  2914. groupNodes.append(*node.getClear());
  2915. }
  2916. bool CFileSprayEx::onGetSprayTargets(IEspContext &context, IEspGetSprayTargetsRequest &req, IEspGetSprayTargetsResponse &resp)
  2917. {
  2918. try
  2919. {
  2920. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2921. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  2922. Owned<IConstEnvironment> environment = factory->openEnvironment();
  2923. Owned<IPropertyTree> root = &environment->getPTree();
  2924. IArrayOf<IEspGroupNode> sprayTargets;
  2925. //Fetch all the group names for all the thor instances (and dedup them)
  2926. BoolHash uniqueThorClusterGroupNames;
  2927. Owned<IPropertyTreeIterator> it = root->getElements("Software/ThorCluster");
  2928. ForEach(*it)
  2929. {
  2930. IPropertyTree& cluster = it->query();
  2931. StringBuffer thorClusterGroupName;
  2932. getClusterGroupName(cluster, thorClusterGroupName);
  2933. if (!thorClusterGroupName.length())
  2934. continue;
  2935. bool* found = uniqueThorClusterGroupNames.getValue(thorClusterGroupName.str());
  2936. if (!found || !*found)
  2937. appendGroupNode(sprayTargets, thorClusterGroupName.str(), "thor", cluster.getPropBool("@replicateOutputs", false));
  2938. }
  2939. //Fetch all the group names for all the hthor instances
  2940. it.setown(root->getElements("Software/EclAgentProcess"));
  2941. ForEach(*it)
  2942. {
  2943. IPropertyTree &cluster = it->query();
  2944. const char* name = cluster.queryProp("@name");
  2945. if (!name || !*name)
  2946. continue;
  2947. unsigned ins = 0;
  2948. Owned<IPropertyTreeIterator> insts = cluster.getElements("Instance");
  2949. ForEach(*insts)
  2950. {
  2951. const char *na = insts->query().queryProp("@netAddress");
  2952. if (!na || !*na)
  2953. continue;
  2954. SocketEndpoint ep(na);
  2955. if (ep.isNull())
  2956. continue;
  2957. ins++;
  2958. VStringBuffer gname("hthor__%s", name);
  2959. if (ins>1)
  2960. gname.append('_').append(ins);
  2961. appendGroupNode(sprayTargets, gname.str(), "hthor", false);
  2962. }
  2963. }
  2964. resp.setGroupNodes(sprayTargets);
  2965. }
  2966. catch(IException* e)
  2967. {
  2968. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2969. }
  2970. return true;
  2971. }
  2972. void CFileSprayEx::setDFUServerQueueReq(const char* dfuServerQueue, IDFUWorkUnit* wu)
  2973. {
  2974. wu->setQueue((dfuServerQueue && *dfuServerQueue) ? dfuServerQueue : m_QueueLabel.str());
  2975. }
  2976. void CFileSprayEx::setUserAuth(IEspContext &context, IDFUWorkUnit* wu)
  2977. {
  2978. StringBuffer user, passwd;
  2979. wu->setUser(context.getUserID(user).str());
  2980. wu->setPassword(context.getPassword(passwd).str());
  2981. }
  2982. bool CFileSprayEx::onGetDFUServerQueues(IEspContext &context, IEspGetDFUServerQueuesRequest &req, IEspGetDFUServerQueuesResponse &resp)
  2983. {
  2984. try
  2985. {
  2986. context.ensureFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2987. StringArray qlist;
  2988. getDFUServerQueueNames(qlist, req.getDFUServerName());
  2989. resp.setNames(qlist);
  2990. }
  2991. catch(IException* e)
  2992. {
  2993. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2994. }
  2995. return true;
  2996. }