ws_fsService.cpp 128 KB

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