ws_fsService.cpp 113 KB

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