ws_fsService.cpp 113 KB

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