ws_fsService.cpp 122 KB

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