ws_fsService.cpp 113 KB

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