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