ws_fsService.cpp 113 KB

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