ws_fsService.cpp 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #pragma warning (disable : 4786)
  14. #pragma warning (disable : 4129)
  15. #include <math.h>
  16. #include "jsocket.hpp"
  17. #include "dasds.hpp"
  18. #include "dadfs.hpp"
  19. #include "dautils.hpp"
  20. #include "daclient.hpp"
  21. #include "wshelpers.hpp"
  22. #include "dfuwu.hpp"
  23. #include "workunit.hpp"
  24. #include "ws_fsService.hpp"
  25. #ifdef _WIN32
  26. #include "windows.h"
  27. #endif
  28. #include "TpWrapper.hpp"
  29. #include "dalienv.hpp"
  30. #include "dfuutil.hpp"
  31. #include "portlist.h"
  32. #include "sacmd.hpp"
  33. #include "exception_util.hpp"
  34. #define DFU_WU_URL "DfuWorkunitsAccess"
  35. #define DFU_EX_URL "DfuExceptionsAccess"
  36. #define FILE_SPRAY_URL "FileSprayAccess"
  37. #define FILE_DESPRAY_URL "FileDesprayAccess"
  38. #define WUDETAILS_REFRESH_MINS 1
  39. void SetResp(StringBuffer &resp, IConstDFUWorkUnit * wu, bool array);
  40. int Schedule::run()
  41. {
  42. try
  43. {
  44. PROGLOG("DfuWorkunit WUSchedule Thread started.");
  45. while(!stopping)
  46. {
  47. {
  48. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  49. Owned<IConstDFUWorkUnitIterator> itr = factory->getWorkUnitsByState(DFUstate_scheduled);
  50. itr->first();
  51. while(itr->isValid())
  52. {
  53. Owned<IConstDFUWorkUnit> wu = itr->get();
  54. CDateTime dt, now;
  55. now.setNow();
  56. try
  57. {
  58. wu->getTimeScheduled(dt);
  59. if (now.compare(dt) > 0)
  60. {
  61. StringAttr wuid(wu->queryId());
  62. wu.clear();
  63. submitDFUWorkUnit(wuid.get());
  64. }
  65. }
  66. catch(IException *e)
  67. {
  68. StringBuffer msg;
  69. ERRLOG("Exception %d:%s in WsWorkunits Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  70. e->Release();
  71. }
  72. itr->next();
  73. }
  74. }
  75. semSchedule.wait(1000*60);
  76. }
  77. }
  78. catch(IException *e)
  79. {
  80. StringBuffer msg;
  81. ERRLOG("Exception %d:%s in WS_FS Schedule::run", e->errorCode(), e->errorMessage(msg).str());
  82. e->Release();
  83. }
  84. catch(...)
  85. {
  86. ERRLOG("Unknown exception in WS_FS Schedule::run");
  87. }
  88. return 0;
  89. }
  90. void CFileSprayEx::init(IPropertyTree *cfg, const char *process, const char *service)
  91. {
  92. StringBuffer xpath;
  93. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/QueueLabel", process, service);
  94. cfg->getProp(xpath.str(), m_QueueLabel);
  95. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/MonitorQueueLabel", process, service);
  96. cfg->getProp(xpath.str(), m_MonitorQueueLabel);
  97. xpath.clear().appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/RootFolder", process, service);
  98. cfg->getProp(xpath.str(), m_RootFolder);
  99. directories.set(cfg->queryPropTree("Software/Directories"));
  100. StringBuffer prop;
  101. prop.appendf("queueLabel=%s", m_QueueLabel.str());
  102. PrintLog(prop.str());
  103. prop.clear();
  104. prop.appendf("monitorQueueLabel=%s", m_MonitorQueueLabel.str());
  105. PrintLog(prop.str());
  106. prop.clear();
  107. prop.appendf("rootFolder=%s", m_RootFolder.str());
  108. PrintLog(prop.str());
  109. if (!daliClientActive())
  110. {
  111. ERRLOG("No Dali Connection Active.");
  112. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  113. }
  114. m_sched.start();
  115. }
  116. StringBuffer& CFileSprayEx::getAcceptLanguage(IEspContext& context, StringBuffer& acceptLanguage)
  117. {
  118. context.getAcceptLanguage(acceptLanguage);
  119. if (!acceptLanguage.length())
  120. {
  121. acceptLanguage.set("en");
  122. return acceptLanguage;
  123. }
  124. acceptLanguage.setLength(2);
  125. VStringBuffer languageFile("%ssmc_xslt/nls/%s/hpcc.xml", getCFD(), acceptLanguage.str());
  126. if (!checkFileExists(languageFile.str()))
  127. acceptLanguage.set("en");
  128. return acceptLanguage;
  129. }
  130. void ParsePath(const char * fullPath, StringBuffer &ip, StringBuffer &filePath, StringBuffer &title)
  131. {
  132. ip.clear();
  133. filePath.clear();
  134. title.clear();
  135. if(fullPath == NULL || *fullPath == '\0')
  136. return;
  137. const char* ptr = fullPath;
  138. if(*ptr == '\\' && *(ptr+1) == '\\')
  139. {
  140. ptr += 2;
  141. while(*ptr != '\0' && *ptr != '\\')
  142. ptr++;
  143. ip.append(ptr - fullPath - 2, fullPath + 2);
  144. }
  145. filePath.append(ptr);
  146. ptr = fullPath + strlen(fullPath) - 1;
  147. while(ptr > fullPath && *ptr != '\\')
  148. ptr--;
  149. title.append(ptr + 1);
  150. }
  151. const char * const NODATETIME="1970-01-01T00:00:00Z";
  152. // Assign from a dfuwu workunit structure to an esp request workunit structure.
  153. static void DeepAssign(IEspContext &context, IConstDFUWorkUnit *src, IEspDFUWorkunit &dest)
  154. {
  155. if(src == NULL)
  156. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "'Source DFU workunit' doesn't exist.");
  157. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  158. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  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* groupName, 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(groupName != NULL && *groupName != '\0')
  424. {
  425. StringBuffer basedir;
  426. GroupType groupType;
  427. Owned<IGroup> group = queryNamedGroupStore().lookup(groupName, 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->openEnvironment();
  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. StringBuffer& getNodeGroupFromLFN(StringBuffer& nodeGroup, const char* lfn, 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. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(lfn, udesc);
  549. if (!df)
  550. throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Failed to find file: %s", lfn);
  551. return df->getClusterGroupName(0, nodeGroup);
  552. }
  553. StringBuffer& constructFileMask(const char* filename, StringBuffer& filemask)
  554. {
  555. filemask.clear().append(filename).toLowerCase().append("._$P$_of_$N$");
  556. return filemask;
  557. }
  558. bool CFileSprayEx::onDFUWUSearch(IEspContext &context, IEspDFUWUSearchRequest & req, IEspDFUWUSearchResponse & resp)
  559. {
  560. try
  561. {
  562. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  563. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  564. StringArray dfuclusters;
  565. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  566. Owned<IConstEnvironment> environment = factory->openEnvironment();
  567. Owned<IPropertyTree> root = &environment->getPTree();
  568. if (!root)
  569. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  570. Owned<IPropertyTreeIterator> clusterIterator = root->getElements("Software/Topology/Cluster");
  571. if (clusterIterator->first())
  572. {
  573. do {
  574. IPropertyTree &cluster = clusterIterator->query();
  575. const char *clusterName = cluster.queryProp("@name");
  576. if (!clusterName || !*clusterName)
  577. continue;
  578. dfuclusters.append(clusterName);
  579. } while (clusterIterator->next());
  580. }
  581. resp.setClusterNames(dfuclusters);
  582. }
  583. catch(IException* e)
  584. {
  585. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  586. }
  587. return true;
  588. }
  589. int readFromCommaSeparatedString(const char *commaSeparatedString, StringBuffer* output)
  590. {
  591. int numOfItems = 0;
  592. if (commaSeparatedString && *commaSeparatedString)
  593. {
  594. char *pStr = (char *) commaSeparatedString;
  595. while (pStr)
  596. {
  597. char item[1024];
  598. bool bFoundComma = false;
  599. int len = strlen(pStr);
  600. for (int i = 0; i < len; i++)
  601. {
  602. char *pStr1 = pStr + i;
  603. if (pStr1[0] != ',')
  604. continue;
  605. strncpy(item, pStr, pStr1 - pStr);
  606. item[pStr1 - pStr] = 0;
  607. bFoundComma = true;
  608. if (i < len - 1)
  609. pStr = pStr1 + 1;
  610. else
  611. pStr = NULL;
  612. break;
  613. }
  614. if (!bFoundComma && len > 0)
  615. {
  616. strcpy(item, pStr);
  617. pStr = NULL;
  618. }
  619. output[numOfItems] = item;
  620. numOfItems++;
  621. }
  622. }
  623. return numOfItems;
  624. }
  625. bool CFileSprayEx::GetArchivedDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  626. {
  627. StringBuffer user;
  628. context.getUserID(user);
  629. StringBuffer sashaAddress;
  630. IArrayOf<IConstTpSashaServer> sashaservers;
  631. CTpWrapper dummy;
  632. dummy.getTpSashaServers(sashaservers);
  633. ForEachItemIn(i, sashaservers)
  634. {
  635. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  636. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  637. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  638. }
  639. SocketEndpoint ep;
  640. ep.set(sashaAddress,DEFAULT_SASHA_PORT);
  641. Owned<INode> sashaserver = createINode(ep);
  642. __int64 count=req.getPageSize();
  643. if(count < 1)
  644. count=100;
  645. __int64 begin=req.getPageStartFrom();
  646. if (begin < 0)
  647. begin = 0;
  648. Owned<ISashaCommand> cmd = createSashaCommand();
  649. cmd->setAction(SCA_LIST);
  650. cmd->setOnline(false);
  651. cmd->setArchived(true);
  652. cmd->setDFU(true);
  653. cmd->setLimit((int) count+1);
  654. cmd->setStart((int)begin);
  655. if(req.getCluster() && *req.getCluster())
  656. cmd->setCluster(req.getCluster());
  657. if(req.getOwner() && *req.getOwner())
  658. cmd->setOwner(req.getOwner());
  659. if(req.getJobname() && *req.getJobname())
  660. cmd->setJobName(req.getJobname());
  661. if(req.getStateReq() && *req.getStateReq())
  662. cmd->setState(req.getStateReq());
  663. cmd->setOutputFormat("owner,jobname,cluster,state,command");//date range/owner/jobname/state*/
  664. if (!cmd->send(sashaserver))
  665. {
  666. StringBuffer msg;
  667. msg.appendf("Cannot connect to archive server at %s",sashaAddress.str());
  668. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  669. }
  670. IArrayOf<IEspDFUWorkunit> results;
  671. __int64 actualCount = cmd->numIds();
  672. StringBuffer s;
  673. for (unsigned j=0;j<actualCount;j++)
  674. {
  675. const char *wuidStr = cmd->queryId(j);
  676. if (!wuidStr)
  677. continue;
  678. StringBuffer strArray[6];
  679. readFromCommaSeparatedString(wuidStr, strArray);
  680. //skip any workunits without access
  681. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  682. resultWU->setArchived(true);
  683. if (strArray[0].length() > 0)
  684. resultWU->setID(strArray[0].str());
  685. if (strArray[1].length() > 0)
  686. resultWU->setUser(strArray[1].str());
  687. if (strArray[2].length() > 0)
  688. resultWU->setJobName(strArray[2].str());
  689. if (strArray[3].length() > 0)
  690. resultWU->setClusterName(strArray[3].str());
  691. if (strArray[4].length() > 0)
  692. resultWU->setStateMessage(strArray[4].str());
  693. if (strArray[5].length() > 0)
  694. resultWU->setCommand(atoi(strArray[5].str()));
  695. results.append(*resultWU.getLink());
  696. }
  697. resp.setPageStartFrom(begin+1);
  698. resp.setNextPage(-1);
  699. if(count < actualCount)
  700. {
  701. if (results.length() > count)
  702. {
  703. results.pop();
  704. }
  705. resp.setNextPage(begin + count);
  706. resp.setPageEndAt(begin + count);
  707. }
  708. else
  709. {
  710. resp.setPageEndAt(begin + actualCount);
  711. }
  712. if(begin > 0)
  713. {
  714. resp.setFirst(false);
  715. if (begin - count > 0)
  716. resp.setPrevPage(begin - count);
  717. else
  718. resp.setPrevPage(0);
  719. }
  720. resp.setPageSize(count);
  721. resp.setResults(results);
  722. StringBuffer basicQuery;
  723. if (req.getStateReq() && *req.getStateReq())
  724. {
  725. resp.setStateReq(req.getStateReq());
  726. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  727. }
  728. if (req.getCluster() && *req.getCluster())
  729. {
  730. resp.setCluster(req.getCluster());
  731. addToQueryString(basicQuery, "Cluster", req.getCluster());
  732. }
  733. if (req.getOwner() && *req.getOwner())
  734. {
  735. resp.setOwner(req.getOwner());
  736. addToQueryString(basicQuery, "Owner", req.getOwner());
  737. }
  738. if (req.getType() && *req.getType())
  739. {
  740. resp.setType(req.getType());
  741. addToQueryString(basicQuery, "Type", req.getType());
  742. }
  743. resp.setFilters(basicQuery.str());
  744. resp.setBasicQuery(basicQuery.str());
  745. return true;
  746. }
  747. bool CFileSprayEx::getOneDFUWorkunit(IEspContext& context, const char* wuid, IEspGetDFUWorkunitsResponse& resp)
  748. {
  749. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  750. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(wuid, false);
  751. if (!wu)
  752. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", wuid);
  753. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit();
  754. resultWU->setID(wuid);
  755. resultWU->setCommand(wu->getCommand());
  756. resultWU->setIsProtected(wu->isProtected());
  757. StringBuffer jobname, user, cluster;
  758. resultWU->setJobName(wu->getJobName(jobname).str());
  759. resultWU->setUser(wu->getUser(user).str());
  760. const char* clusterName = wu->getClusterName(cluster).str();
  761. if (clusterName && *clusterName)
  762. {
  763. Owned<IStringIterator> targets = getTargetClusters(NULL, clusterName);
  764. if (!targets->first())
  765. resultWU->setClusterName(clusterName);
  766. else
  767. {
  768. SCMStringBuffer targetCluster;
  769. targets->str(targetCluster);
  770. resultWU->setClusterName(targetCluster.str());
  771. }
  772. }
  773. IConstDFUprogress* prog = wu->queryProgress();
  774. if (prog)
  775. {
  776. StringBuffer statemsg;
  777. DFUstate state = prog->getState();
  778. encodeDFUstate(state, statemsg);
  779. resultWU->setState(state);
  780. resultWU->setStateMessage(statemsg.str());
  781. resultWU->setPercentDone(prog->getPercentDone());
  782. }
  783. IArrayOf<IEspDFUWorkunit> result;
  784. result.append(*resultWU.getClear());
  785. resp.setResults(result);
  786. return true;
  787. }
  788. bool CFileSprayEx::onGetDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  789. {
  790. try
  791. {
  792. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  793. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  794. StringBuffer wuidStr = req.getWuid();
  795. const char* wuid = wuidStr.trim().str();
  796. if (wuid && *wuid && looksLikeAWuid(wuid, 'D'))
  797. return getOneDFUWorkunit(context, wuid, resp);
  798. double version = context.getClientVersion();
  799. if (version > 1.02)
  800. {
  801. const char *type = req.getType();
  802. if (type && *type && !stricmp(type, "archived workunits"))
  803. {
  804. return GetArchivedDFUWorkunits(context, req, resp);
  805. }
  806. }
  807. StringBuffer clusterReq;
  808. const char *clusterName = req.getCluster();
  809. if(clusterName && *clusterName)
  810. {
  811. clusterReq.append(clusterName);
  812. }
  813. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  814. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  815. Owned<IPropertyTree> root = &constEnv->getPTree();
  816. if (!root)
  817. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  818. StringArray targetClusters, clusterProcesses;
  819. Owned<IPropertyTreeIterator> clusters= root->getElements("Software/Topology/Cluster");
  820. if (clusters->first())
  821. {
  822. do {
  823. IPropertyTree &cluster = clusters->query();
  824. const char* name = cluster.queryProp("@name");
  825. if (!name || !*name)
  826. continue;
  827. Owned<IPropertyTreeIterator> thorClusters= cluster.getElements(eqThorCluster);
  828. Owned<IPropertyTreeIterator> roxieClusters= cluster.getElements(eqRoxieCluster);
  829. if (thorClusters->first() || roxieClusters->first())
  830. {
  831. bool bFound = false;
  832. if (thorClusters->first())
  833. {
  834. IPropertyTree &thorCluster = thorClusters->query();
  835. const char* process = thorCluster.queryProp("@process");
  836. if (process && *process)
  837. {
  838. targetClusters.append(name);
  839. clusterProcesses.append(process);
  840. if (clusterName && !stricmp(clusterName, name))
  841. {
  842. clusterReq.clear().append(process);
  843. }
  844. }
  845. }
  846. if (!bFound && roxieClusters->first())
  847. {
  848. IPropertyTree &roxieCluster = roxieClusters->query();
  849. const char* process = roxieCluster.queryProp("@process");
  850. if (process && *process)
  851. {
  852. targetClusters.append(name);
  853. clusterProcesses.append(process);
  854. if (clusterName && !stricmp(clusterName, name))
  855. {
  856. clusterReq.clear().append(process);
  857. }
  858. }
  859. }
  860. }
  861. } while (clusters->next());
  862. }
  863. __int64 pagesize = req.getPageSize();
  864. __int64 pagefrom = req.getPageStartFrom();
  865. __int64 displayFrom = 0;
  866. if (pagesize < 1)
  867. {
  868. pagesize = 100;
  869. }
  870. if (pagefrom > 0)
  871. {
  872. displayFrom = pagefrom;
  873. }
  874. DFUsortfield sortorder[2] = {DFUsf_wuid, DFUsf_term};
  875. sortorder[0] = (DFUsortfield) (DFUsf_wuid + DFUsf_reverse);
  876. if(req.getSortby() && *req.getSortby())
  877. {
  878. const char *sortby = req.getSortby();
  879. if (!stricmp(sortby, "Owner"))
  880. sortorder[0] = DFUsf_user;
  881. else if (!stricmp(sortby, "JobName"))
  882. sortorder[0] = DFUsf_job;
  883. else if (!stricmp(sortby, "Cluster"))
  884. sortorder[0] = DFUsf_cluster;
  885. else if (!stricmp(sortby, "State"))
  886. sortorder[0] = DFUsf_state;
  887. else if (!stricmp(sortby, "Type"))
  888. sortorder[0] = DFUsf_command;
  889. else if (!stricmp(sortby, "Protected"))
  890. sortorder[0] = DFUsf_protected;
  891. else if (!stricmp(sortby, "PCTDone"))
  892. sortorder[0] = (DFUsortfield) (DFUsf_pcdone | DFUsf_numeric);
  893. else
  894. sortorder[0] = DFUsf_wuid;
  895. bool descending = req.getDescending();
  896. if (descending)
  897. sortorder[0] = (DFUsortfield) (sortorder[0] | DFUsf_reverse);
  898. }
  899. DFUsortfield filters[10];
  900. unsigned short filterCount = 0;
  901. MemoryBuffer filterbuf;
  902. if(req.getStateReq() && *req.getStateReq())
  903. {
  904. filters[filterCount] = DFUsf_state;
  905. filterCount++;
  906. if (stricmp(req.getStateReq(), "unknown") != 0)
  907. filterbuf.append(req.getStateReq());
  908. else
  909. filterbuf.append("");
  910. }
  911. if(wuid && *wuid)
  912. {
  913. filters[filterCount] = DFUsf_wildwuid;
  914. filterCount++;
  915. filterbuf.append(wuid);
  916. }
  917. if(clusterName && *clusterName)
  918. {
  919. filters[filterCount] = DFUsf_cluster;
  920. filterCount++;
  921. filterbuf.append(clusterReq.str());
  922. }
  923. if(req.getOwner() && *req.getOwner())
  924. {
  925. filters[filterCount] = DFUsortfield (DFUsf_user | DFUsf_nocase);
  926. filterCount++;
  927. filterbuf.append(req.getOwner());
  928. }
  929. if(req.getJobname() && *req.getJobname())
  930. {
  931. filters[filterCount] = DFUsortfield (DFUsf_job | DFUsf_nocase);
  932. filterCount++;
  933. filterbuf.append(req.getJobname());
  934. }
  935. filters[filterCount] = DFUsf_term;
  936. __int64 cacheHint = req.getCacheHint();
  937. if (cacheHint < 0) //Not set yet
  938. cacheHint = 0;
  939. IArrayOf<IEspDFUWorkunit> result;
  940. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  941. unsigned numWUs;
  942. PROGLOG("GetDFUWorkunits: getWorkUnitsSorted");
  943. Owned<IConstDFUWorkUnitIterator> itr = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), (int) displayFrom, (int) pagesize+1, req.getOwner(), &cacheHint, &numWUs);
  944. if (version >= 1.07)
  945. resp.setCacheHint(cacheHint);
  946. PROGLOG("GetDFUWorkunits: getWorkUnitsSorted done");
  947. //unsigned actualCount = 0;
  948. itr->first();
  949. while(itr->isValid())
  950. {
  951. Owned<IConstDFUWorkUnit> wu = itr->get();
  952. //actualCount++;
  953. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  954. resultWU->setID(wu->queryId());
  955. StringBuffer jobname, user, cluster;
  956. resultWU->setJobName(wu->getJobName(jobname).str());
  957. resultWU->setCommand(wu->getCommand());
  958. resultWU->setUser(wu->getUser(user).str());
  959. const char* clusterName = wu->getClusterName(cluster).str();
  960. if (clusterName)
  961. {
  962. StringBuffer clusterForDisplay(clusterName);
  963. if (clusterProcesses.ordinality())
  964. {
  965. for (unsigned i = 0; i < clusterProcesses.length(); i++)
  966. {
  967. const char* clusterProcessName = clusterProcesses.item(i);
  968. if (!stricmp(clusterProcessName, clusterName))
  969. {
  970. clusterForDisplay.clear().append(targetClusters.item(i));
  971. break;
  972. }
  973. }
  974. }
  975. resultWU->setClusterName(clusterForDisplay.str());
  976. }
  977. resultWU->setIsProtected(wu->isProtected());
  978. IConstDFUprogress *prog = wu->queryProgress();
  979. if (prog != NULL)
  980. {
  981. DFUstate state = prog->getState();
  982. resultWU->setState(state);
  983. StringBuffer statemsg;
  984. encodeDFUstate(state,statemsg);
  985. resultWU->setStateMessage(statemsg.str());
  986. resultWU->setPercentDone(prog->getPercentDone());
  987. }
  988. result.append(*resultWU.getLink());
  989. itr->next();
  990. }
  991. if (result.length() > pagesize)
  992. result.pop();
  993. resp.setPageSize(pagesize);
  994. resp.setNumWUs(numWUs);
  995. resp.setPageStartFrom(displayFrom + 1);
  996. if(displayFrom + pagesize < numWUs)
  997. {
  998. resp.setNextPage(displayFrom + pagesize);
  999. resp.setPageEndAt(pagefrom + pagesize);
  1000. __int64 last = displayFrom + pagesize;
  1001. while (last + pagesize < numWUs)
  1002. {
  1003. last += pagesize;
  1004. }
  1005. resp.setLastPage(last);
  1006. }
  1007. else
  1008. {
  1009. resp.setNextPage(-1);
  1010. resp.setPageEndAt(numWUs);
  1011. }
  1012. if(displayFrom > 0)
  1013. {
  1014. resp.setFirst(false);
  1015. if (displayFrom - pagesize > 0)
  1016. resp.setPrevPage(displayFrom - pagesize);
  1017. else
  1018. resp.setPrevPage(0);
  1019. }
  1020. StringBuffer basicQuery;
  1021. if (req.getStateReq() && *req.getStateReq())
  1022. {
  1023. resp.setStateReq(req.getStateReq());
  1024. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  1025. }
  1026. if (req.getCluster() && *req.getCluster())
  1027. {
  1028. resp.setCluster(req.getCluster());
  1029. addToQueryString(basicQuery, "Cluster", req.getCluster());
  1030. }
  1031. if (req.getOwner() && *req.getOwner())
  1032. {
  1033. resp.setOwner(req.getOwner());
  1034. addToQueryString(basicQuery, "Owner", req.getOwner());
  1035. }
  1036. resp.setFilters(basicQuery.str());
  1037. if (req.getSortby() && *req.getSortby())
  1038. {
  1039. resp.setSortby(req.getSortby());
  1040. if (req.getDescending())
  1041. resp.setDescending(req.getDescending());
  1042. StringBuffer strbuf = req.getSortby();
  1043. strbuf.append("=");
  1044. String str1(strbuf.str());
  1045. String str(basicQuery.str());
  1046. if (str.indexOf(str1) < 0)
  1047. {
  1048. addToQueryString(basicQuery, "Sortby", req.getSortby());
  1049. if (req.getDescending())
  1050. addToQueryString(basicQuery, "Descending", "1");
  1051. }
  1052. }
  1053. resp.setBasicQuery(basicQuery.str());
  1054. resp.setResults(result);
  1055. }
  1056. catch(IException* e)
  1057. {
  1058. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1059. }
  1060. return true;
  1061. }
  1062. void CFileSprayEx::addToQueryString(StringBuffer &queryString, const char *name, const char *value)
  1063. {
  1064. if (queryString.length() > 0)
  1065. {
  1066. queryString.append("&amp;");
  1067. }
  1068. queryString.append(name);
  1069. queryString.append("=");
  1070. queryString.append(value);
  1071. }
  1072. void CFileSprayEx::getInfoFromSasha(IEspContext &context, const char *sashaServer, const char* wuid, IEspDFUWorkunit *info)
  1073. {
  1074. Owned<ISashaCommand> cmd = createSashaCommand();
  1075. cmd->addId(wuid);
  1076. cmd->setAction(SCA_GET);
  1077. cmd->setArchived(true);
  1078. cmd->setDFU(true);
  1079. SocketEndpoint ep(sashaServer, DEFAULT_SASHA_PORT);
  1080. Owned<INode> node = createINode(ep);
  1081. if (!cmd->send(node,1*60*1000))
  1082. {
  1083. DBGLOG("Cannot connect to Sasha server at %s",sashaServer);
  1084. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.",sashaServer);
  1085. }
  1086. if (cmd->numIds()==0)
  1087. {
  1088. DBGLOG("Could not read archived %s",wuid);
  1089. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1090. }
  1091. unsigned num = cmd->numResults();
  1092. if (num < 1)
  1093. return;
  1094. StringBuffer res;
  1095. cmd->getResult(0,res);
  1096. if(res.length() < 1)
  1097. return;
  1098. Owned<IPropertyTree> wu = createPTreeFromXMLString(res.str());
  1099. if (!wu)
  1100. return;
  1101. const char * command = wu->queryProp("@command");
  1102. const char * submitID = wu->queryProp("@submitID");
  1103. const char * cluster = wu->queryProp("@clusterName");
  1104. const char * queue = wu->queryProp("@queue");
  1105. const char * jobName = wu->queryProp("@jobName");
  1106. const char * protectedWU = wu->queryProp("@protected");
  1107. info->setID(wuid);
  1108. info->setArchived(true);
  1109. if (command && *command)
  1110. info->setCommandMessage(command);
  1111. if (cluster && *cluster)
  1112. info->setClusterName(cluster);
  1113. if (submitID && *submitID)
  1114. info->setUser(submitID);
  1115. if (queue && *queue)
  1116. info->setQueue(queue);
  1117. if (jobName && *jobName)
  1118. info->setJobName(jobName);
  1119. if (protectedWU && stricmp(protectedWU, "0"))
  1120. info->setIsProtected(true);
  1121. else
  1122. info->setIsProtected(false);
  1123. IPropertyTree *source = wu->queryPropTree("Source");
  1124. if(source)
  1125. {
  1126. const char * directory = source->queryProp("@directory");
  1127. const char * name = source->queryProp("@name");
  1128. if (directory && *directory)
  1129. info->setSourceDirectory(directory);
  1130. if (name && *name)
  1131. info->setSourceLogicalName(name);
  1132. }
  1133. IPropertyTree *dest = wu->queryPropTree("Destination");
  1134. if(dest)
  1135. {
  1136. const char * directory = dest->queryProp("@directory");
  1137. int numParts = dest->getPropInt("@numparts", -1);
  1138. if (directory && *directory)
  1139. info->setDestDirectory(directory);
  1140. if (numParts > 0)
  1141. info->setDestNumParts(numParts);
  1142. }
  1143. IPropertyTree *progress = wu->queryPropTree("Progress");
  1144. if(progress)
  1145. {
  1146. const char * state = progress->queryProp("@state");
  1147. const char * timeStarted = progress->queryProp("@timestarted");
  1148. const char * timeStopped = progress->queryProp("@timestopped");
  1149. if (state && *state)
  1150. info->setStateMessage(state);
  1151. if (timeStarted && *timeStarted)
  1152. {
  1153. StringBuffer startStr = timeStarted;
  1154. startStr.replace('T', ' ');
  1155. info->setTimeStarted(startStr.str());
  1156. }
  1157. if (timeStopped && *timeStopped)
  1158. {
  1159. StringBuffer stopStr = timeStopped;
  1160. stopStr.replace('T', ' ');
  1161. info->setTimeStopped(stopStr.str());
  1162. }
  1163. }
  1164. return;
  1165. }
  1166. bool CFileSprayEx::getArchivedWUInfo(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1167. {
  1168. const char *wuid = req.getWuid();
  1169. if (wuid && *wuid)
  1170. {
  1171. StringBuffer sashaAddress;
  1172. IArrayOf<IConstTpSashaServer> sashaservers;
  1173. CTpWrapper dummy;
  1174. dummy.getTpSashaServers(sashaservers);
  1175. ForEachItemIn(i, sashaservers)
  1176. {
  1177. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1178. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1179. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1180. }
  1181. if (sashaAddress.length() < 1)
  1182. {
  1183. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1184. }
  1185. getInfoFromSasha(context, sashaAddress.str(), wuid, &resp.updateResult());
  1186. return true;
  1187. }
  1188. return false;
  1189. }
  1190. bool CFileSprayEx::onGetDFUWorkunit(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1191. {
  1192. try
  1193. {
  1194. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  1195. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1196. const char* wuid = req.getWuid();
  1197. if (!wuid || !*wuid)
  1198. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dfu workunit ID not specified.");
  1199. bool found = false;
  1200. double version = context.getClientVersion();
  1201. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1202. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(wuid, false);
  1203. if(wu)
  1204. {
  1205. IEspDFUWorkunit &result = resp.updateResult();
  1206. PROGLOG("GetDFUWorkunit: %s", wuid);
  1207. DeepAssign(context, wu, result);
  1208. int n = resp.getResult().getState();
  1209. if (n == DFUstate_scheduled || n == DFUstate_queued || n == DFUstate_started)
  1210. {
  1211. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1212. }
  1213. found = true;
  1214. }
  1215. else if ((version > 1.02) && getArchivedWUInfo(context, req, resp))
  1216. {
  1217. found = true;
  1218. }
  1219. if (!found)
  1220. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1221. }
  1222. catch(IException* e)
  1223. {
  1224. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1225. }
  1226. return true;
  1227. }
  1228. bool CFileSprayEx::onGetDFUProgress(IEspContext &context, IEspProgressRequest &req, IEspProgressResponse &resp)
  1229. {
  1230. try
  1231. {
  1232. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  1233. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1234. const char* wuid = req.getWuid();
  1235. if(!wuid || !*wuid)
  1236. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit ID not specified.");
  1237. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1238. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  1239. if(!wu)
  1240. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1241. resp.setWuid(req.getWuid());
  1242. PROGLOG("GetDFUProgress: %s", wuid);
  1243. IConstDFUprogress *prog = wu->queryProgress();
  1244. if (prog)
  1245. {
  1246. resp.setPercentDone(prog->getPercentDone());
  1247. resp.setKbPerSec(prog->getKbPerSec());
  1248. resp.setKbPerSecAve(prog->getKbPerSecAve());
  1249. resp.setSecsLeft(prog->getSecsLeft());
  1250. StringBuffer statestr;
  1251. encodeDFUstate(prog->getState(), statestr);
  1252. resp.setState(statestr.str());
  1253. resp.setSlavesDone(prog->getSlavesDone());
  1254. StringBuffer msg;
  1255. prog->formatProgressMessage(msg);
  1256. resp.setProgressMessage(msg.str());
  1257. prog->formatSummaryMessage(msg.clear());
  1258. resp.setSummaryMessage(msg.str());
  1259. prog->getTimeTaken(msg.clear());
  1260. resp.setTimeTaken(msg.str());
  1261. }
  1262. }
  1263. catch(IException* e)
  1264. {
  1265. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1266. }
  1267. return true;
  1268. }
  1269. bool CFileSprayEx::onCreateDFUWorkunit(IEspContext &context, IEspCreateDFUWorkunit &req, IEspCreateDFUWorkunitResponse &resp)
  1270. {
  1271. try
  1272. {
  1273. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1274. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to create DFU workunit. Permission denied.");
  1275. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1276. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1277. wu->setQueue(m_QueueLabel.str());
  1278. StringBuffer user, passwd;
  1279. wu->setUser(context.getUserID(user).str());
  1280. wu->setPassword(context.getPassword(passwd).str());
  1281. wu->commit();
  1282. const char * d = wu->queryId();
  1283. IEspDFUWorkunit &result = resp.updateResult();
  1284. DeepAssign(context, wu, result);
  1285. result.setOverwrite(false);
  1286. result.setReplicate(true);
  1287. }
  1288. catch(IException* e)
  1289. {
  1290. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1291. }
  1292. return true;
  1293. }
  1294. bool CFileSprayEx::onUpdateDFUWorkunit(IEspContext &context, IEspUpdateDFUWorkunit &req, IEspUpdateDFUWorkunitResponse &resp)
  1295. {
  1296. try
  1297. {
  1298. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1299. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1300. IConstDFUWorkunit & reqWU = req.getWu();
  1301. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1302. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(reqWU.getID());
  1303. if(!wu)
  1304. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", reqWU.getID());
  1305. PROGLOG("UpdateDFUWorkunit: %s", reqWU.getID());
  1306. IDFUprogress *prog = wu->queryUpdateProgress();
  1307. if (prog && req.getStateOrig() != reqWU.getState())
  1308. {
  1309. if (prog->getState() != req.getStateOrig())
  1310. 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());
  1311. prog->setState((enum DFUstate)reqWU.getState());
  1312. }
  1313. const char* clusterOrig = req.getClusterOrig();
  1314. const char* cluster = reqWU.getClusterName();
  1315. if(cluster && (!clusterOrig || stricmp(clusterOrig, cluster)))
  1316. {
  1317. wu->setClusterName(reqWU.getClusterName());
  1318. }
  1319. const char* jobNameOrig = req.getJobNameOrig();
  1320. const char* jobName = reqWU.getJobName();
  1321. if(jobName && (!jobNameOrig || stricmp(jobNameOrig, jobName)))
  1322. {
  1323. wu->setJobName(jobName);
  1324. }
  1325. if (reqWU.getIsProtected() != req.getIsProtectedOrig())
  1326. wu->protect(reqWU.getIsProtected());
  1327. wu->commit();
  1328. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(reqWU.getID()).str());
  1329. }
  1330. catch(IException* e)
  1331. {
  1332. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1333. }
  1334. return true;
  1335. }
  1336. bool markWUFailed(IDFUWorkUnitFactory *f, const char *wuid)
  1337. {
  1338. Owned<IDFUWorkUnit> wu = f->updateWorkUnit(wuid);
  1339. if(!wu)
  1340. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", wuid);
  1341. IDFUprogress *prog = wu->queryUpdateProgress();
  1342. if(!prog)
  1343. throw MakeStringException(ECLWATCH_PROGRESS_INFO_NOT_FOUND, "progress information not found for workunit %s.", wuid);
  1344. else if(prog->getState() == DFUstate_started)
  1345. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Cannot delete workunit %s because its state is Started.", wuid);
  1346. else
  1347. {
  1348. prog->setState(DFUstate_failed);
  1349. return true;
  1350. }
  1351. return false;
  1352. }
  1353. static unsigned NumOfDFUWUActionNames = 5;
  1354. static const char *DFUWUActionNames[] = { "Delete", "Protect" , "Unprotect" , "Restore" , "SetToFailed" };
  1355. bool CFileSprayEx::onDFUWorkunitsAction(IEspContext &context, IEspDFUWorkunitsActionRequest &req, IEspDFUWorkunitsActionResponse &resp)
  1356. {
  1357. try
  1358. {
  1359. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1360. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1361. CDFUWUActions action = req.getType();
  1362. if (action == DFUWUActions_Undefined)
  1363. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Action not defined.");
  1364. StringArray& wuids = req.getWuids();
  1365. if (!wuids.ordinality())
  1366. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit not defined.");
  1367. Owned<INode> node;
  1368. Owned<ISashaCommand> cmd;
  1369. StringBuffer sashaAddress;
  1370. if (action == CDFUWUActions_Restore)
  1371. {
  1372. IArrayOf<IConstTpSashaServer> sashaservers;
  1373. CTpWrapper dummy;
  1374. dummy.getTpSashaServers(sashaservers);
  1375. ForEachItemIn(i, sashaservers)
  1376. {
  1377. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1378. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1379. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1380. }
  1381. if (sashaAddress.length() < 1)
  1382. {
  1383. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1384. }
  1385. SocketEndpoint ep(sashaAddress.str(), DEFAULT_SASHA_PORT);
  1386. node.setown(createINode(ep));
  1387. cmd.setown(createSashaCommand());
  1388. cmd->setAction(SCA_RESTORE);
  1389. cmd->setDFU(true);
  1390. }
  1391. IArrayOf<IEspDFUActionResult> results;
  1392. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1393. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1394. {
  1395. const char* wuid = wuids.item(i);
  1396. const char* actionStr = (action < NumOfDFUWUActionNames) ? DFUWUActionNames[action] : "Unknown";
  1397. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1398. res->setID(wuid);
  1399. res->setAction(actionStr);
  1400. try
  1401. {
  1402. PROGLOG("%s %s", actionStr, wuid);
  1403. switch (action)
  1404. {
  1405. case CDFUWUActions_Delete:
  1406. if (!markWUFailed(factory, wuid))
  1407. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Failed to mark workunit failed.");
  1408. if (!factory->deleteWorkUnit(wuid))
  1409. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Failed in deleting workunit.");
  1410. res->setResult("Success");
  1411. break;
  1412. case CDFUWUActions_Restore:
  1413. cmd->addId(wuid);
  1414. if (!cmd->send(node,1*60*1000))
  1415. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.",sashaAddress.str());
  1416. {
  1417. StringBuffer reply = "Restore ID: ";
  1418. if (!cmd->getId(0, reply))
  1419. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed to get ID.");
  1420. res->setResult(reply.str());
  1421. }
  1422. break;
  1423. case CDFUWUActions_Protect:
  1424. case CDFUWUActions_Unprotect:
  1425. case CDFUWUActions_SetToFailed:
  1426. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuid);
  1427. if(!wu.get())
  1428. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed in calling updateWorkUnit().");
  1429. switch (action)
  1430. {
  1431. case CDFUWUActions_Protect:
  1432. wu->protect(true);
  1433. break;
  1434. case CDFUWUActions_Unprotect:
  1435. wu->protect(false);
  1436. break;
  1437. case CDFUWUActions_SetToFailed:
  1438. IDFUprogress *prog = wu->queryUpdateProgress();
  1439. if (!prog)
  1440. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Failed in calling queryUpdateProgress().");
  1441. prog->setState(DFUstate_failed);
  1442. break;
  1443. }
  1444. wu->commit();
  1445. res->setResult("Success");
  1446. break;
  1447. }
  1448. PROGLOG("%s %s done", actionStr, wuid);
  1449. }
  1450. catch (IException *e)
  1451. {
  1452. StringBuffer eMsg, failedMsg("Failed: ");
  1453. res->setResult(failedMsg.append(e->errorMessage(eMsg)).str());
  1454. e->Release();
  1455. }
  1456. results.append(*res.getLink());
  1457. }
  1458. resp.setDFUActionResults(results);
  1459. }
  1460. catch(IException* e)
  1461. {
  1462. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1463. }
  1464. return true;
  1465. }
  1466. bool CFileSprayEx::onDeleteDFUWorkunits(IEspContext &context, IEspDeleteDFUWorkunits &req, IEspDeleteDFUWorkunitsResponse &resp)
  1467. {
  1468. try
  1469. {
  1470. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1471. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1472. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1473. StringArray & wuids = req.getWuids();
  1474. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1475. {
  1476. const char* wuid = wuids.item(i);
  1477. if (markWUFailed(factory, wuid))
  1478. {
  1479. factory->deleteWorkUnit(wuid);
  1480. PROGLOG("DeleteDFUWorkunits: %s deleted", wuid);
  1481. }
  1482. }
  1483. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1484. }
  1485. catch(IException* e)
  1486. {
  1487. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1488. }
  1489. return true;
  1490. }
  1491. bool CFileSprayEx::onDeleteDFUWorkunit(IEspContext &context, IEspDeleteDFUWorkunit &req, IEspDeleteDFUWorkunitResponse &resp)
  1492. {
  1493. try
  1494. {
  1495. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1496. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1497. const char* wuid = req.getWuid();
  1498. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1499. if (markWUFailed(factory, wuid))
  1500. {
  1501. resp.setResult(factory->deleteWorkUnit(wuid));
  1502. PROGLOG("DeleteDFUWorkunit: %s deleted", wuid);
  1503. }
  1504. else
  1505. resp.setResult(false);
  1506. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1507. }
  1508. catch(IException* e)
  1509. {
  1510. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1511. }
  1512. return true;
  1513. }
  1514. bool CFileSprayEx::onSubmitDFUWorkunit(IEspContext &context, IEspSubmitDFUWorkunit &req, IEspSubmitDFUWorkunitResponse &resp)
  1515. {
  1516. try
  1517. {
  1518. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1519. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to submit DFU workunit. Permission denied.");
  1520. if (!req.getWuid() || !*req.getWuid())
  1521. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Workunit ID required");
  1522. PROGLOG("SubmitDFUWorkunit: %s", req.getWuid());
  1523. submitDFUWorkUnit(req.getWuid());
  1524. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1525. }
  1526. catch(IException* e)
  1527. {
  1528. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1529. }
  1530. return true;
  1531. }
  1532. bool CFileSprayEx::onAbortDFUWorkunit(IEspContext &context, IEspAbortDFUWorkunit &req, IEspAbortDFUWorkunitResponse &resp)
  1533. {
  1534. try
  1535. {
  1536. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1537. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to abort DFU workunit. Permission denied.");
  1538. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1539. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1540. if(!wu)
  1541. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1542. PROGLOG("AbortDFUWorkunit: %s", req.getWuid());
  1543. wu->requestAbort();
  1544. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1545. }
  1546. catch(IException* e)
  1547. {
  1548. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1549. }
  1550. return true;
  1551. }
  1552. bool CFileSprayEx::onGetDFUExceptions(IEspContext &context, IEspGetDFUExceptions &req, IEspGetDFUExceptionsResponse &resp)
  1553. {
  1554. try
  1555. {
  1556. if (!context.validateFeatureAccess(DFU_EX_URL, SecAccess_Read, false))
  1557. throw MakeStringException(ECLWATCH_DFU_EX_ACCESS_DENIED, "Failed to get DFU Exceptions. Permission denied.");
  1558. IArrayOf<IEspDFUException> result;
  1559. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1560. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1561. if(!wu)
  1562. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1563. PROGLOG("GetDFUExceptions: %s", req.getWuid());
  1564. Owned<IExceptionIterator> itr = wu->getExceptionIterator();
  1565. itr->first();
  1566. while(itr->isValid())
  1567. {
  1568. Owned<IEspDFUException> resultE = createDFUException("", "");
  1569. IException &e = itr->query();
  1570. resultE->setCode(e.errorCode());
  1571. StringBuffer msg;
  1572. resultE->setMessage(e.errorMessage(msg).str());
  1573. result.append(*resultE.getLink());
  1574. itr->next();
  1575. }
  1576. resp.setResult(result);
  1577. }
  1578. catch(IException* e)
  1579. {
  1580. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1581. }
  1582. return true;
  1583. }
  1584. bool CFileSprayEx::onSprayFixed(IEspContext &context, IEspSprayFixed &req, IEspSprayFixedResponse &resp)
  1585. {
  1586. try
  1587. {
  1588. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  1589. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Spray. Permission denied.");
  1590. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  1591. const char* destNodeGroup = req.getDestGroup();
  1592. if(destNodeGroup == NULL || *destNodeGroup == '\0')
  1593. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination node group not specified.");
  1594. MemoryBuffer& srcxml = (MemoryBuffer&)req.getSrcxml();
  1595. const char* srcip = req.getSourceIP();
  1596. const char* srcfile = req.getSourcePath();
  1597. if(srcxml.length() == 0)
  1598. {
  1599. if(!srcip || !*srcip)
  1600. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source network IP not specified.");
  1601. if(!srcfile || !*srcfile)
  1602. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source file not specified.");
  1603. }
  1604. const char* destname = req.getDestLogicalName();
  1605. if(!destname || !*destname)
  1606. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1607. CDfsLogicalFileName lfn;
  1608. if (!lfn.setValidate(destname))
  1609. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid destination filename");
  1610. destname = lfn.get();
  1611. PROGLOG("SprayFixed: DestLogicalName %s, DestGroup %s", destname, destNodeGroup);
  1612. StringBuffer gName, ipAddr;
  1613. const char *pTr = strchr(destNodeGroup, ' ');
  1614. if (pTr)
  1615. {
  1616. gName.append(pTr - destNodeGroup, destNodeGroup);
  1617. ipAddr.append(pTr+1);
  1618. }
  1619. else
  1620. gName.append(destNodeGroup);
  1621. if (ipAddr.length() > 0)
  1622. ParseLogicalPath(destname, ipAddr.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1623. else
  1624. ParseLogicalPath(destname, destNodeGroup, NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1625. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1626. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1627. wu->setClusterName(gName.str());
  1628. wu->setJobName(destTitle.str());
  1629. wu->setQueue(m_QueueLabel.str());
  1630. StringBuffer user, passwd;
  1631. wu->setUser(context.getUserID(user).str());
  1632. wu->setPassword(context.getPassword(passwd).str());
  1633. wu->setCommand(DFUcmd_import);
  1634. IDFUfileSpec *source = wu->queryUpdateSource();
  1635. if(srcxml.length() == 0)
  1636. {
  1637. RemoteMultiFilename rmfn;
  1638. SocketEndpoint ep(srcip);
  1639. rmfn.setEp(ep);
  1640. StringBuffer fnamebuf(srcfile);
  1641. fnamebuf.trim();
  1642. rmfn.append(fnamebuf.str()); // handles comma separated files
  1643. source->setMultiFilename(rmfn);
  1644. }
  1645. else
  1646. {
  1647. srcxml.append('\0');
  1648. source->setFromXML((const char*)srcxml.toByteArray());
  1649. }
  1650. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1651. bool nosplit = req.getNosplit();
  1652. int recordsize = req.getSourceRecordSize();
  1653. const char* format = req.getSourceFormat();
  1654. if ((recordsize == RECFMVB_RECSIZE_ESCAPE) || (format && strieq(format, "recfmvb")))
  1655. {//recordsize may be set by dfuplus; format may be set by EclWatch
  1656. source->setFormat(DFUff_recfmvb);
  1657. destination->setFormat(DFUff_variable);
  1658. }
  1659. else if ((recordsize == RECFMV_RECSIZE_ESCAPE) || (format && strieq(format, "recfmv")))
  1660. {
  1661. source->setFormat(DFUff_recfmv);
  1662. destination->setFormat(DFUff_variable);
  1663. }
  1664. else if ((recordsize == PREFIX_VARIABLE_RECSIZE_ESCAPE) || (format && strieq(format, "variable")))
  1665. {
  1666. source->setFormat(DFUff_variable);
  1667. destination->setFormat(DFUff_variable);
  1668. }
  1669. else if((recordsize == PREFIX_VARIABLE_BIGENDIAN_RECSIZE_ESCAPE) || (format && strieq(format, "variablebigendian")))
  1670. {
  1671. source->setFormat(DFUff_variablebigendian);
  1672. destination->setFormat(DFUff_variable);
  1673. }
  1674. else if(recordsize == 0 && !nosplit) // -ve record sizes for blocked
  1675. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid record size");
  1676. else
  1677. source->setRecordSize(recordsize);
  1678. destination->setLogicalName(destname);
  1679. destination->setDirectory(destFolder.str());
  1680. StringBuffer fileMask;
  1681. constructFileMask(destTitle.str(), fileMask);
  1682. destination->setFileMask(fileMask.str());
  1683. destination->setGroupName(gName.str());
  1684. const char * encryptkey = req.getEncrypt();
  1685. if(req.getCompress()||(encryptkey&&*encryptkey))
  1686. destination->setCompressed(true);
  1687. ClusterPartDiskMapSpec mspec;
  1688. destination->getClusterPartDiskMapSpec(gName.str(), mspec);
  1689. mspec.setDefaultBaseDir(defaultFolder.str());
  1690. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  1691. if (!req.getReplicate())
  1692. mspec.defaultCopies = DFD_NoCopies;
  1693. destination->setClusterPartDiskMapSpec(gName.str(), mspec);
  1694. int repo = req.getReplicateOffset();
  1695. bool isNull = req.getReplicateOffset_isNull();
  1696. if (!isNull && (repo!=1))
  1697. destination->setReplicateOffset(repo);
  1698. if (req.getWrap())
  1699. destination->setWrap(true);
  1700. IDFUoptions *options = wu->queryUpdateOptions();
  1701. const char * decryptkey = req.getDecrypt();
  1702. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  1703. options->setEncDec(encryptkey,decryptkey);
  1704. options->setReplicate(req.getReplicate());
  1705. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1706. const char* prefix = req.getPrefix();
  1707. if(prefix && *prefix)
  1708. options->setLengthPrefix(prefix);
  1709. if(req.getNosplit())
  1710. options->setNoSplit(true);
  1711. if(req.getNorecover())
  1712. options->setNoRecover(true);
  1713. if(req.getMaxConnections() > 0)
  1714. options->setmaxConnections(req.getMaxConnections());
  1715. if(req.getThrottle() > 0)
  1716. options->setThrottle(req.getThrottle());
  1717. if(req.getTransferBufferSize() > 0)
  1718. options->setTransferBufferSize(req.getTransferBufferSize());
  1719. if (req.getPull())
  1720. options->setPull(true);
  1721. if (req.getPush())
  1722. options->setPush(true);
  1723. if (req.getFailIfNoSourceFile())
  1724. options->setFailIfNoSourceFile(true);
  1725. if (req.getRecordStructurePresent())
  1726. options->setRecordStructurePresent(true);
  1727. resp.setWuid(wu->queryId());
  1728. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1729. submitDFUWorkUnit(wu.getClear());
  1730. }
  1731. catch(IException* e)
  1732. {
  1733. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1734. }
  1735. return true;
  1736. }
  1737. bool CFileSprayEx::onSprayVariable(IEspContext &context, IEspSprayVariable &req, IEspSprayResponse &resp)
  1738. {
  1739. try
  1740. {
  1741. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  1742. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Spray. Permission denied.");
  1743. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  1744. const char* destNodeGroup = req.getDestGroup();
  1745. if(destNodeGroup == NULL || *destNodeGroup == '\0')
  1746. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination node group not specified.");
  1747. StringBuffer gName, ipAddr;
  1748. const char *pTr = strchr(destNodeGroup, ' ');
  1749. if (pTr)
  1750. {
  1751. gName.append(pTr - destNodeGroup, destNodeGroup);
  1752. ipAddr.append(pTr+1);
  1753. }
  1754. else
  1755. gName.append(destNodeGroup);
  1756. MemoryBuffer& srcxml = (MemoryBuffer&)req.getSrcxml();
  1757. const char* srcip = req.getSourceIP();
  1758. const char* srcfile = req.getSourcePath();
  1759. if(srcxml.length() == 0)
  1760. {
  1761. if(!srcip || !*srcip)
  1762. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source network IP not specified.");
  1763. if(!srcfile || !*srcfile)
  1764. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source file not specified.");
  1765. }
  1766. const char* destname = req.getDestLogicalName();
  1767. if(!destname || !*destname)
  1768. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1769. CDfsLogicalFileName lfn;
  1770. if (!lfn.setValidate(destname))
  1771. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename");
  1772. destname = lfn.get();
  1773. PROGLOG("SprayVariable: DestLogicalName %s, DestGroup %s", destname, destNodeGroup);
  1774. if (ipAddr.length() > 0)
  1775. ParseLogicalPath(destname, ipAddr.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1776. else
  1777. ParseLogicalPath(destname, destNodeGroup, NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1778. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1779. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1780. wu->setClusterName(gName.str());
  1781. wu->setJobName(destTitle.str());
  1782. wu->setQueue(m_QueueLabel.str());
  1783. StringBuffer user, passwd;
  1784. wu->setUser(context.getUserID(user).str());
  1785. wu->setPassword(context.getPassword(passwd).str());
  1786. wu->setCommand(DFUcmd_import);
  1787. IDFUfileSpec *source = wu->queryUpdateSource();
  1788. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1789. IDFUoptions *options = wu->queryUpdateOptions();
  1790. if(srcxml.length() == 0)
  1791. {
  1792. RemoteMultiFilename rmfn;
  1793. SocketEndpoint ep(srcip);
  1794. rmfn.setEp(ep);
  1795. StringBuffer fnamebuf(srcfile);
  1796. fnamebuf.trim();
  1797. rmfn.append(fnamebuf.str()); // handles comma separated files
  1798. source->setMultiFilename(rmfn);
  1799. }
  1800. else
  1801. {
  1802. srcxml.append('\0');
  1803. source->setFromXML((const char*)srcxml.toByteArray());
  1804. }
  1805. source->setMaxRecordSize(req.getSourceMaxRecordSize());
  1806. source->setFormat((DFUfileformat)req.getSourceFormat());
  1807. StringBuffer rowtag;
  1808. if (req.getIsJSON())
  1809. {
  1810. const char *srcRowPath = req.getSourceRowPath();
  1811. if (!srcRowPath || *srcRowPath != '/')
  1812. rowtag.append("/");
  1813. rowtag.append(srcRowPath);
  1814. }
  1815. else
  1816. rowtag.append(req.getSourceRowTag());
  1817. // if rowTag specified, it means it's xml or json format, otherwise it's csv
  1818. if(rowtag.length())
  1819. {
  1820. source->setRowTag(rowtag);
  1821. options->setKeepHeader(true);
  1822. }
  1823. else
  1824. {
  1825. const char* cs = req.getSourceCsvSeparate();
  1826. if (req.getNoSourceCsvSeparator())
  1827. {
  1828. cs = "";
  1829. }
  1830. else if(cs == NULL || *cs == '\0')
  1831. cs = "\\,";
  1832. const char* ct = req.getSourceCsvTerminate();
  1833. if(ct == NULL || *ct == '\0')
  1834. ct = "\\n,\\r\\n";
  1835. const char* cq = req.getSourceCsvQuote();
  1836. if(cq== NULL)
  1837. cq = "\"";
  1838. source->setCsvOptions(cs, ct, cq, req.getSourceCsvEscape(), req.getQuotedTerminator());
  1839. options->setQuotedTerminator(req.getQuotedTerminator());
  1840. }
  1841. destination->setLogicalName(destname);
  1842. destination->setDirectory(destFolder.str());
  1843. StringBuffer fileMask;
  1844. constructFileMask(destTitle.str(), fileMask);
  1845. destination->setFileMask(fileMask.str());
  1846. destination->setGroupName(gName.str());
  1847. ClusterPartDiskMapSpec mspec;
  1848. destination->getClusterPartDiskMapSpec(gName.str(), mspec);
  1849. mspec.setDefaultBaseDir(defaultFolder.str());
  1850. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  1851. if (!req.getReplicate())
  1852. mspec.defaultCopies = DFD_NoCopies;
  1853. destination->setClusterPartDiskMapSpec(gName.str(), mspec);
  1854. const char * encryptkey = req.getEncrypt();
  1855. if(req.getCompress()||(encryptkey&&*encryptkey))
  1856. destination->setCompressed(true);
  1857. const char * decryptkey = req.getDecrypt();
  1858. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  1859. options->setEncDec(encryptkey,decryptkey);
  1860. int repo = req.getReplicateOffset();
  1861. bool isNull = req.getReplicateOffset_isNull();
  1862. if (!isNull && (repo!=1))
  1863. destination->setReplicateOffset(repo);
  1864. options->setReplicate(req.getReplicate());
  1865. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1866. const char* prefix = req.getPrefix();
  1867. if(prefix && *prefix)
  1868. options->setLengthPrefix(prefix);
  1869. if(req.getNosplit())
  1870. options->setNoSplit(true);
  1871. if(req.getNorecover())
  1872. options->setNoRecover(true);
  1873. if(req.getMaxConnections() > 0)
  1874. options->setmaxConnections(req.getMaxConnections());
  1875. if(req.getThrottle() > 0)
  1876. options->setThrottle(req.getThrottle());
  1877. if(req.getTransferBufferSize() > 0)
  1878. options->setTransferBufferSize(req.getTransferBufferSize());
  1879. if (req.getPull())
  1880. options->setPull(true);
  1881. if (req.getPush())
  1882. options->setPush(true);
  1883. if (req.getFailIfNoSourceFile())
  1884. options->setFailIfNoSourceFile(true);
  1885. if (req.getRecordStructurePresent())
  1886. options->setRecordStructurePresent(true);
  1887. resp.setWuid(wu->queryId());
  1888. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1889. submitDFUWorkUnit(wu.getClear());
  1890. }
  1891. catch(IException* e)
  1892. {
  1893. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1894. }
  1895. return true;
  1896. }
  1897. bool CFileSprayEx::onReplicate(IEspContext &context, IEspReplicate &req, IEspReplicateResponse &resp)
  1898. {
  1899. try
  1900. {
  1901. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  1902. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Replicate. Permission denied.");
  1903. const char* srcname = req.getSourceLogicalName();
  1904. if(!srcname || !*srcname)
  1905. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  1906. PROGLOG("Replicate %s", srcname);
  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. void CFileSprayEx::getDropZoneInfoByIP(const char* ip, const char* destFileIn, StringBuffer& destFileOut, StringBuffer& mask)
  1942. {
  1943. if (destFileIn && *destFileIn)
  1944. destFileOut.set(destFileIn);
  1945. if (!ip || !*ip)
  1946. return;
  1947. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  1948. Owned<IConstEnvironment> env = factory->openEnvironment();
  1949. if (!env)
  1950. return;
  1951. SCMStringBuffer directory;
  1952. Owned<IConstDropZoneInfo> dropZone;
  1953. StringBuffer destFile;
  1954. if (isAbsolutePath(destFileIn))
  1955. {
  1956. destFile.set(destFileIn);
  1957. dropZone.setown(env->getDropZoneByAddressPath(ip, destFile.str()));
  1958. if (!dropZone)
  1959. return;
  1960. dropZone->getDirectory(directory);
  1961. }
  1962. else
  1963. {
  1964. SCMStringBuffer computer;
  1965. Owned<IConstMachineInfo> machine = env->getMachineByAddress(ip);
  1966. if (!machine)
  1967. {
  1968. IpAddress ipAddr;
  1969. ipAddr.ipset(ip);
  1970. if (!ipAddr.isLocal())
  1971. return;
  1972. machine.setown(env->getMachineForLocalHost());
  1973. if (!machine)
  1974. return;
  1975. }
  1976. machine->getName(computer);
  1977. if (!computer.length())
  1978. return;
  1979. dropZone.setown(env->getDropZoneByComputer(computer.str()));
  1980. if (!dropZone)
  1981. return;
  1982. dropZone->getDirectory(directory);
  1983. destFile.set(directory.str());
  1984. if (destFile.length())
  1985. addPathSepChar(destFile);
  1986. destFile.append(destFileIn);
  1987. }
  1988. destFileOut.set(destFile.str());
  1989. if ((destFile.length() >= directory.length()) && !strnicmp(destFile.str(), directory.str(), directory.length()))
  1990. {
  1991. SCMStringBuffer maskBuf;
  1992. dropZone->getUMask(maskBuf);
  1993. if (maskBuf.length())
  1994. mask.set(maskBuf.str());
  1995. }
  1996. }
  1997. bool CFileSprayEx::onDespray(IEspContext &context, IEspDespray &req, IEspDesprayResponse &resp)
  1998. {
  1999. try
  2000. {
  2001. if (!context.validateFeatureAccess(FILE_DESPRAY_URL, SecAccess_Write, false))
  2002. throw MakeStringException(ECLWATCH_FILE_DESPRAY_ACCESS_DENIED, "Failed to do Despray. Permission denied.");
  2003. const char* srcname = req.getSourceLogicalName();
  2004. if(!srcname || !*srcname)
  2005. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2006. PROGLOG("Despray %s", srcname);
  2007. const char* destip = req.getDestIP();
  2008. StringBuffer fnamebuf(req.getDestPath());
  2009. const char* destfile = fnamebuf.trim().str();
  2010. MemoryBuffer& dstxml = (MemoryBuffer&)req.getDstxml();
  2011. if(dstxml.length() == 0)
  2012. {
  2013. if(!destip || !*destip)
  2014. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination network IP not specified.");
  2015. if(!destfile || !*destfile)
  2016. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  2017. }
  2018. StringBuffer srcTitle;
  2019. ParseLogicalPath(srcname, srcTitle);
  2020. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2021. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2022. wu->setJobName(srcTitle.str());
  2023. wu->setQueue(m_QueueLabel.str());
  2024. StringBuffer user, passwd;
  2025. wu->setUser(context.getUserID(user).str());
  2026. wu->setPassword(context.getPassword(passwd).str());
  2027. wu->setCommand(DFUcmd_export);
  2028. IDFUfileSpec *source = wu->queryUpdateSource();
  2029. IDFUfileSpec *destination = wu->queryUpdateDestination();
  2030. IDFUoptions *options = wu->queryUpdateOptions();
  2031. source->setLogicalName(srcname);
  2032. if(dstxml.length() == 0)
  2033. {
  2034. RemoteFilename rfn;
  2035. SocketEndpoint ep(destip);
  2036. StringBuffer destfileWithPath, umask;
  2037. getDropZoneInfoByIP(destip, destfile, destfileWithPath, umask);
  2038. rfn.setPath(ep, destfileWithPath.str());
  2039. if (umask.length())
  2040. options->setUMask(umask.str());
  2041. destination->setSingleFilename(rfn);
  2042. }
  2043. else
  2044. {
  2045. dstxml.append('\0');
  2046. destination->setFromXML((const char*)dstxml.toByteArray());
  2047. }
  2048. destination->setTitle(srcTitle.str());
  2049. options->setKeepHeader(true);
  2050. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  2051. const char* splitprefix = req.getSplitprefix();
  2052. if(splitprefix && *splitprefix)
  2053. options->setSplitPrefix(splitprefix);
  2054. double version = context.getClientVersion();
  2055. if (version > 1.01)
  2056. {
  2057. if(req.getMaxConnections() > 0)
  2058. options->setmaxConnections(req.getMaxConnections());
  2059. else if(req.getSingleConnection())
  2060. options->setmaxConnections(1);
  2061. }
  2062. else
  2063. {
  2064. if(req.getMaxConnections() > 0)
  2065. options->setmaxConnections(req.getMaxConnections());
  2066. }
  2067. if(req.getThrottle() > 0)
  2068. options->setThrottle(req.getThrottle());
  2069. if(req.getTransferBufferSize() > 0)
  2070. options->setTransferBufferSize(req.getTransferBufferSize());
  2071. if(req.getNorecover())
  2072. options->setNoRecover(true);
  2073. if (req.getWrap()) {
  2074. options->setPush(); // I think needed for a despray
  2075. destination->setWrap(true);
  2076. }
  2077. if (req.getMultiCopy())
  2078. destination->setMultiCopy(true);
  2079. const char * encryptkey = req.getEncrypt();
  2080. if(req.getCompress()||(encryptkey&&*encryptkey))
  2081. destination->setCompressed(true);
  2082. const char * decryptkey = req.getDecrypt();
  2083. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2084. options->setEncDec(encryptkey,decryptkey);
  2085. resp.setWuid(wu->queryId());
  2086. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2087. submitDFUWorkUnit(wu.getClear());
  2088. }
  2089. catch(IException* e)
  2090. {
  2091. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2092. }
  2093. return true;
  2094. }
  2095. bool CFileSprayEx::onCopy(IEspContext &context, IEspCopy &req, IEspCopyResponse &resp)
  2096. {
  2097. try
  2098. {
  2099. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  2100. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Copy. Permission denied.");
  2101. const char* srcname = req.getSourceLogicalName();
  2102. const char* dstname = req.getDestLogicalName();
  2103. if(!srcname || !*srcname)
  2104. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2105. if(!dstname || !*dstname)
  2106. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2107. PROGLOG("Copy from %s to %s", srcname, dstname);
  2108. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  2109. StringBuffer srcNodeGroup, destNodeGroup;
  2110. bool bRoxie = false;
  2111. const char* destNodeGroupReq = req.getDestGroup();
  2112. if(!destNodeGroupReq || !*destNodeGroupReq)
  2113. {
  2114. getNodeGroupFromLFN(destNodeGroup, srcname, context.queryUserId(), context.queryPassword());
  2115. DBGLOG("Destination node group not specified, using source node group %s", destNodeGroup.str());
  2116. }
  2117. else
  2118. {
  2119. destNodeGroup = destNodeGroupReq;
  2120. const char* destRoxie = req.getDestGroupRoxie();
  2121. if (destRoxie && !stricmp(destRoxie, "Yes"))
  2122. {
  2123. bRoxie = true;
  2124. }
  2125. }
  2126. CDfsLogicalFileName lfn; // NOTE: must not be moved into block below, or dstname will point to invalid memory
  2127. if (!bRoxie)
  2128. {
  2129. if (!lfn.setValidate(dstname))
  2130. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename");
  2131. dstname = lfn.get();
  2132. }
  2133. ParseLogicalPath(dstname, destNodeGroup.str(), NULL, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  2134. StringBuffer fileMask;
  2135. constructFileMask(destTitle.str(), fileMask);
  2136. const char* srcDali = req.getSourceDali();
  2137. bool supercopy = req.getSuperCopy();
  2138. if (supercopy)
  2139. {
  2140. StringBuffer user, passwd;
  2141. context.getUserID(user);
  2142. context.getPassword(passwd);
  2143. StringBuffer u(user);
  2144. StringBuffer p(passwd);
  2145. Owned<INode> foreigndali;
  2146. if (srcDali)
  2147. {
  2148. SocketEndpoint ep(srcDali);
  2149. foreigndali.setown(createINode(ep));
  2150. const char* srcu = req.getSrcusername();
  2151. if(srcu && *srcu)
  2152. {
  2153. u.clear().append(srcu);
  2154. p.clear().append(req.getSrcpassword());
  2155. }
  2156. }
  2157. Owned<IUserDescriptor> udesc=createUserDescriptor();
  2158. udesc->set(u.str(),p.str());
  2159. if (!queryDistributedFileDirectory().isSuperFile(srcname,udesc,foreigndali))
  2160. supercopy = false;
  2161. }
  2162. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2163. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2164. wu->setJobName(dstname);
  2165. wu->setQueue(m_QueueLabel.str());
  2166. StringBuffer user, passwd;
  2167. wu->setUser(context.getUserID(user).str());
  2168. wu->setPassword(context.getPassword(passwd).str());
  2169. if(destNodeGroup.length() > 0)
  2170. wu->setClusterName(destNodeGroup.str());
  2171. if (supercopy)
  2172. wu->setCommand(DFUcmd_supercopy);
  2173. else
  2174. wu->setCommand(DFUcmd_copy);
  2175. IDFUfileSpec *wuFSpecSource = wu->queryUpdateSource();
  2176. IDFUfileSpec *wuFSpecDest = wu->queryUpdateDestination();
  2177. IDFUoptions *wuOptions = wu->queryUpdateOptions();
  2178. wuFSpecSource->setLogicalName(srcname);
  2179. if(srcDali && *srcDali)
  2180. {
  2181. SocketEndpoint ep(srcDali);
  2182. wuFSpecSource->setForeignDali(ep);
  2183. const char* srcusername = req.getSrcusername();
  2184. if(srcusername && *srcusername)
  2185. {
  2186. const char* srcpasswd = req.getSrcpassword();
  2187. wuFSpecSource->setForeignUser(srcusername, srcpasswd);
  2188. }
  2189. }
  2190. wuFSpecDest->setLogicalName(dstname);
  2191. wuFSpecDest->setFileMask(fileMask.str());
  2192. wuOptions->setOverwrite(req.getOverwrite());
  2193. wuOptions->setPreserveCompression(req.getPreserveCompression());
  2194. if (bRoxie)
  2195. {
  2196. setRoxieClusterPartDiskMapping(destNodeGroup.str(), defaultFolder.str(), defaultReplicateFolder.str(), supercopy, wuFSpecDest, wuOptions);
  2197. wuFSpecDest->setWrap(true); // roxie always wraps
  2198. if(req.getCompress())
  2199. wuFSpecDest->setCompressed(true);
  2200. if (!supercopy)
  2201. wuOptions->setSuppressNonKeyRepeats(true); // **** only repeat last part when src kind = key
  2202. }
  2203. else
  2204. {
  2205. const char* srcDiffKeyName = req.getSourceDiffKeyName();
  2206. const char* destDiffKeyName = req.getDestDiffKeyName();
  2207. if (srcDiffKeyName&&*srcDiffKeyName)
  2208. wuFSpecSource->setDiffKey(srcDiffKeyName);
  2209. if (destDiffKeyName&&*destDiffKeyName)
  2210. wuFSpecDest->setDiffKey(destDiffKeyName);
  2211. wuFSpecDest->setDirectory(destFolder.str());
  2212. wuFSpecDest->setGroupName(destNodeGroup.str());
  2213. wuFSpecDest->setWrap(req.getWrap());
  2214. const char * encryptkey = req.getEncrypt();
  2215. if(req.getCompress()||(encryptkey&&*encryptkey))
  2216. wuFSpecDest->setCompressed(true);
  2217. wuOptions->setReplicate(req.getReplicate());
  2218. const char * decryptkey = req.getDecrypt();
  2219. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2220. wuOptions->setEncDec(encryptkey,decryptkey);
  2221. if(req.getNorecover())
  2222. wuOptions->setNoRecover(true);
  2223. if(!req.getNosplit_isNull())
  2224. wuOptions->setNoSplit(req.getNosplit());
  2225. if(req.getMaxConnections() > 0)
  2226. wuOptions->setmaxConnections(req.getMaxConnections());
  2227. if(req.getThrottle() > 0)
  2228. wuOptions->setThrottle(req.getThrottle());
  2229. if(req.getTransferBufferSize() > 0)
  2230. wuOptions->setTransferBufferSize(req.getTransferBufferSize());
  2231. if (req.getPull())
  2232. wuOptions->setPull(true);
  2233. if (req.getPush())
  2234. wuOptions->setPush(true);
  2235. if (req.getIfnewer())
  2236. wuOptions->setIfNewer(true);
  2237. ClusterPartDiskMapSpec mspec;
  2238. wuFSpecDest->getClusterPartDiskMapSpec(destNodeGroup.str(), mspec);
  2239. mspec.setDefaultBaseDir(defaultFolder.str());
  2240. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  2241. if (!req.getReplicate())
  2242. mspec.defaultCopies = DFD_NoCopies;
  2243. wuFSpecDest->setClusterPartDiskMapSpec(destNodeGroup.str(), mspec);
  2244. }
  2245. resp.setResult(wu->queryId());
  2246. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2247. submitDFUWorkUnit(wu.getClear());
  2248. }
  2249. catch(IException* e)
  2250. {
  2251. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2252. }
  2253. return true;
  2254. }
  2255. bool CFileSprayEx::onRename(IEspContext &context, IEspRename &req, IEspRenameResponse &resp)
  2256. {
  2257. try
  2258. {
  2259. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  2260. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Rename. Permission denied.");
  2261. const char* srcname = req.getSrcname();
  2262. const char* dstname = req.getDstname();
  2263. if(!srcname || !*srcname)
  2264. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2265. if(!dstname || !*dstname)
  2266. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2267. PROGLOG("Rename from %s to %s", srcname, dstname);
  2268. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2269. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2270. StringBuffer destTitle;
  2271. ParseLogicalPath(req.getDstname(), destTitle);
  2272. wu->setJobName(destTitle.str());
  2273. wu->setQueue(m_QueueLabel.str());
  2274. StringBuffer user, passwd;
  2275. wu->setUser(context.getUserID(user).str());
  2276. wu->setPassword(context.getPassword(passwd).str());
  2277. wu->setCommand(DFUcmd_rename);
  2278. #if 0 // TBD - Handling for multiple clusters? the cluster should be specified by user if needed
  2279. Owned<IUserDescriptor> udesc;
  2280. if(user.length() > 0)
  2281. {
  2282. const char* passwd = context.queryPassword();
  2283. udesc.setown(createUserDescriptor());
  2284. udesc->set(user.str(), passwd);
  2285. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(srcname, udesc);
  2286. if(df)
  2287. {
  2288. StringBuffer cluster0;
  2289. df->getClusterName(0,cluster0); // TBD - Handling for multiple clusters?
  2290. if (cluster0.length()!=0)
  2291. {
  2292. wu->setClusterName(cluster0.str());
  2293. }
  2294. else
  2295. {
  2296. const char *cluster = df->queryAttributes().queryProp("@group");
  2297. if (cluster && *cluster)
  2298. {
  2299. wu->setClusterName(cluster);
  2300. }
  2301. }
  2302. }
  2303. }
  2304. #endif
  2305. IDFUfileSpec *source = wu->queryUpdateSource();
  2306. source->setLogicalName(srcname);
  2307. IDFUfileSpec *destination = wu->queryUpdateDestination();
  2308. destination->setLogicalName(dstname);
  2309. IDFUoptions *options = wu->queryUpdateOptions();
  2310. options->setOverwrite(req.getOverwrite());
  2311. resp.setWuid(wu->queryId());
  2312. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2313. submitDFUWorkUnit(wu.getClear());
  2314. }
  2315. catch(IException* e)
  2316. {
  2317. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2318. }
  2319. return true;
  2320. }
  2321. bool CFileSprayEx::onDFUWUFile(IEspContext &context, IEspDFUWUFileRequest &req, IEspDFUWUFileResponse &resp)
  2322. {
  2323. try
  2324. {
  2325. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  2326. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  2327. if (*req.getWuid())
  2328. {
  2329. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2330. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  2331. if(!wu)
  2332. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  2333. PROGLOG("DFUWUFile: %s", req.getWuid());
  2334. StringBuffer xmlbuf;
  2335. xmlbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2336. const char* plainText = req.getPlainText();
  2337. if (plainText && (!stricmp(plainText, "yes")))
  2338. {
  2339. wu->toXML(xmlbuf);
  2340. resp.setFile(xmlbuf.str());
  2341. resp.setFile_mimetype(HTTP_TYPE_TEXT_PLAIN);
  2342. }
  2343. else
  2344. {
  2345. xmlbuf.append("<?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>");
  2346. wu->toXML(xmlbuf);
  2347. resp.setFile(xmlbuf.str());
  2348. resp.setFile_mimetype(HTTP_TYPE_APPLICATION_XML);
  2349. }
  2350. }
  2351. }
  2352. catch(IException* e)
  2353. {
  2354. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2355. }
  2356. return true;
  2357. }
  2358. int CFileSprayEx::doFileCheck(const char* mask, const char* netaddr, const char* osStr, const char* path)
  2359. {
  2360. int iRet = 1;
  2361. if (mask && *mask)
  2362. {
  2363. char *str = (char *) mask + strlen(mask) - 4;
  2364. if (!stricmp(str, ".cfg") || !stricmp(str, ".log"))
  2365. iRet = 0;
  2366. }
  2367. else if (netaddr && *netaddr && path && *path)
  2368. {
  2369. iRet = 2;
  2370. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2371. factory->validateCache();
  2372. Owned<IConstEnvironment> env = factory->openEnvironment();
  2373. Owned<IPropertyTree> pEnvRoot = &env->getPTree();
  2374. IPropertyTree* pEnvSoftware = pEnvRoot->queryPropTree("Software");
  2375. Owned<IPropertyTree> pRoot = createPTreeFromXMLString("<Environment/>");
  2376. IPropertyTree* pSoftware = pRoot->addPropTree("Software", createPTree("Software"));
  2377. if (pEnvSoftware && pSoftware)
  2378. {
  2379. Owned<IPropertyTreeIterator> it = pEnvSoftware->getElements("DropZone");
  2380. ForEach(*it)
  2381. {
  2382. const char* pszComputer = it->query().queryProp("@computer");
  2383. if (!strcmp(pszComputer, "."))
  2384. pszComputer = "localhost";
  2385. StringBuffer xpath, sNetAddr;
  2386. xpath.appendf("Hardware/Computer[@name='%s']/@netAddress", pszComputer);
  2387. const char* pszNetAddr = pEnvRoot->queryProp(xpath.str());
  2388. if (strcmp(pszNetAddr, "."))
  2389. {
  2390. sNetAddr.append(pszNetAddr);
  2391. }
  2392. else
  2393. {
  2394. StringBuffer ipStr;
  2395. IpAddress ipaddr = queryHostIP();
  2396. ipaddr.getIpText(ipStr);
  2397. if (ipStr.length() > 0)
  2398. {
  2399. #ifdef MACHINE_IP
  2400. sNetAddr.append(MACHINE_IP);
  2401. #else
  2402. sNetAddr.append(ipStr.str());
  2403. #endif
  2404. }
  2405. }
  2406. #ifdef MACHINE_IP
  2407. if ((sNetAddr.length() > 0) && !stricmp(sNetAddr.str(), MACHINE_IP))
  2408. #else
  2409. if ((sNetAddr.length() > 0) && !stricmp(sNetAddr.str(), netaddr))
  2410. #endif
  2411. {
  2412. StringBuffer dir;
  2413. IPropertyTree* pDropZone = pSoftware->addPropTree("DropZone", &it->get());
  2414. pDropZone->getProp("@directory", dir);
  2415. if (osStr && *osStr)
  2416. {
  2417. int os = atoi(osStr);
  2418. const char pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2419. dir.replace(pathSep=='\\'?'/':'\\', pathSep);
  2420. }
  2421. if ((dir.length() > 0) && !strnicmp(path, dir.str(), dir.length()))
  2422. {
  2423. iRet = 0;
  2424. break;
  2425. }
  2426. }
  2427. }
  2428. }
  2429. }
  2430. return iRet;
  2431. }
  2432. bool CFileSprayEx::onFileList(IEspContext &context, IEspFileListRequest &req, IEspFileListResponse &resp)
  2433. {
  2434. try
  2435. {
  2436. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2437. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do FileList. Permission denied.");
  2438. const char* path = req.getPath();
  2439. if (!path || !*path)
  2440. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Path not specified.");
  2441. double version = context.getClientVersion();
  2442. const char* netaddr = req.getNetaddr();
  2443. if (!netaddr || !*netaddr)
  2444. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Network address not specified.");
  2445. const char* mask = req.getMask();
  2446. bool directoryOnly = req.getDirectoryOnly();
  2447. PROGLOG("FileList: Netaddr %s, Path %s", netaddr, path);
  2448. StringBuffer sPath(path);
  2449. const char* osStr = req.getOS();
  2450. if (osStr && *osStr)
  2451. {
  2452. int os = atoi(osStr);
  2453. const char pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2454. sPath.replace(pathSep=='\\'?'/':'\\', pathSep);
  2455. if (*(sPath.str() + sPath.length() -1) != pathSep)
  2456. sPath.append( pathSep );
  2457. }
  2458. int checkReturn = doFileCheck(mask, netaddr, osStr, sPath.str());
  2459. if (checkReturn > 1)
  2460. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2461. else if (checkReturn > 0)
  2462. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2463. RemoteFilename rfn;
  2464. SocketEndpoint ep;
  2465. #ifdef MACHINE_IP
  2466. ep.set(MACHINE_IP);
  2467. #else
  2468. ep.set(netaddr);
  2469. #endif
  2470. rfn.setPath(ep, sPath.str());
  2471. Owned<IFile> f = createIFile(rfn);
  2472. if(!f->isDirectory())
  2473. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2474. IArrayOf<IEspPhysicalFileStruct> files;
  2475. if (mask && !*mask)
  2476. mask = NULL;
  2477. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2478. if(di.get() != NULL)
  2479. {
  2480. ForEach(*di)
  2481. {
  2482. StringBuffer fname;
  2483. di->getName(fname);
  2484. if (fname.length() == 0 || (directoryOnly && !di->isDir()) || (!di->isDir() && mask && !WildMatch(fname.str(), mask, true)))
  2485. continue;
  2486. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2487. onefile->setName(fname.str());
  2488. onefile->setIsDir(di->isDir());
  2489. onefile->setFilesize(di->getFileSize());
  2490. CDateTime modtime;
  2491. StringBuffer timestr;
  2492. di->getModifiedTime(modtime);
  2493. unsigned y,m,d,h,min,sec,nsec;
  2494. modtime.getDate(y,m,d,true);
  2495. modtime.getTime(h,min,sec,nsec,true);
  2496. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2497. onefile->setModifiedtime(timestr.str());
  2498. files.append(*onefile.getLink());
  2499. }
  2500. }
  2501. sPath.replace('\\', '/');//XSLT cannot handle backslashes
  2502. resp.setPath(sPath);
  2503. resp.setFiles(files);
  2504. resp.setNetaddr(netaddr);
  2505. if (osStr && *osStr)
  2506. {
  2507. int os = atoi(osStr);
  2508. resp.setOS(os);
  2509. }
  2510. if (mask && *mask)
  2511. resp.setMask(mask);
  2512. if (version >= 1.10)
  2513. {
  2514. StringBuffer acceptLanguage;
  2515. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  2516. }
  2517. resp.setDirectoryOnly(directoryOnly);
  2518. }
  2519. catch(IException* e)
  2520. {
  2521. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2522. }
  2523. return true;
  2524. }
  2525. void CFileSprayEx::queryDropZoneInfo(const char* dropZone, StringBuffer& path, EnvMachineOS& os, IpAddress& ip)
  2526. {
  2527. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2528. factory->validateCache();
  2529. Owned<IConstEnvironment> env = factory->openEnvironment();
  2530. if (!env)
  2531. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO,"Cannot get environment information.");
  2532. Owned<IPropertyTree> root = &env->getPTree();
  2533. VStringBuffer xpath("Software/DropZone[@name='%s']", dropZone);
  2534. IPropertyTree *pt = root->queryPropTree(xpath.str());
  2535. if (!pt)
  2536. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone %s not found.", dropZone);
  2537. const char* computer = pt->queryProp("@computer");
  2538. IConstMachineInfo* machine = env->getMachine(computer);
  2539. if (!machine)
  2540. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone %s: machine %s not found.", dropZone, computer);
  2541. SCMStringBuffer netAddr;
  2542. machine->getNetAddress(netAddr);
  2543. ip.ipset(netAddr.str());
  2544. os = machine->getOS();
  2545. pt->getProp("@directory", path);
  2546. }
  2547. void CFileSprayEx::addDropZoneFile(IEspContext& context, IDirectoryIterator* di, const char* name, const char* dropZonePath,
  2548. StringBuffer& relativePath, const char pathSep, IArrayOf<IEspPhysicalFileStruct>& filesInFolder, IArrayOf<IEspPhysicalFileStruct>& files)
  2549. {
  2550. StringBuffer path = dropZonePath;
  2551. if (!relativePath.isEmpty())
  2552. path.append(pathSep).append(relativePath.str());
  2553. Owned<IEspPhysicalFileStruct> aFile = createPhysicalFileStruct();
  2554. aFile->setName(name);
  2555. aFile->setPath(path);
  2556. aFile->setIsDir(di->isDir());
  2557. CDateTime modtime;
  2558. StringBuffer timestr;
  2559. di->getModifiedTime(modtime);
  2560. unsigned y,m,d,h,min,sec,nsec;
  2561. modtime.getDate(y,m,d,true);
  2562. modtime.getTime(h,min,sec,nsec,true);
  2563. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2564. aFile->setModifiedtime(timestr.str());
  2565. aFile->setFilesize(di->getFileSize());
  2566. if (di->isDir() && filesInFolder.ordinality())
  2567. aFile->setFiles(filesInFolder);
  2568. files.append(*aFile.getLink());
  2569. }
  2570. bool CFileSprayEx::searchDropZoneFileInFolder(IEspContext& context, IFile* f, const char* nameFilter,
  2571. bool returnAll, const char* dropZonePath, StringBuffer& relativePath, const char pathSep, IArrayOf<IEspPhysicalFileStruct>& files)
  2572. {
  2573. bool foundMatch = false;
  2574. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2575. ForEach(*di)
  2576. {
  2577. StringBuffer fname;
  2578. di->getName(fname);
  2579. if (!fname.length())
  2580. continue;
  2581. StringBuffer newPath = relativePath;
  2582. if (!newPath.isEmpty())
  2583. newPath.append(pathSep);
  2584. newPath.append(fname.str());
  2585. IArrayOf<IEspPhysicalFileStruct> filesInFolder;
  2586. if (returnAll) //Every files and subfolders in this folder have to be returned
  2587. {
  2588. if (di->isDir())
  2589. searchDropZoneFileInFolder(context, &di->get(), NULL, returnAll, dropZonePath, newPath, pathSep, filesInFolder);
  2590. addDropZoneFile(context, di, fname.str(), dropZonePath, relativePath, pathSep, filesInFolder, files);
  2591. continue;
  2592. }
  2593. bool foundMatchNew = WildMatch(fname.str(), nameFilter, true);
  2594. if (di->isDir() && searchDropZoneFileInFolder(context, &di->get(), nameFilter, foundMatchNew, dropZonePath,
  2595. newPath, pathSep, filesInFolder))
  2596. {
  2597. foundMatchNew = true;
  2598. }
  2599. if (foundMatchNew)
  2600. {
  2601. addDropZoneFile(context, di, fname.str(), dropZonePath, relativePath, pathSep, filesInFolder, files);
  2602. foundMatch = true;
  2603. }
  2604. }
  2605. return foundMatch;
  2606. }
  2607. bool CFileSprayEx::onDropZoneFileSearch(IEspContext &context, IEspDropZoneFileSearchRequest &req, IEspDropZoneFileSearchResponse &resp)
  2608. {
  2609. try
  2610. {
  2611. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Access, false))
  2612. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do FileList. Permission denied.");
  2613. const char* dropZone = req.getDropZoneName();
  2614. if (!dropZone || !*dropZone)
  2615. throw MakeStringException(ECLWATCH_INVALID_INPUT, "DropZone not specified.");
  2616. PROGLOG("DropZoneFileSearch: %s", dropZone);
  2617. IpAddress ip;
  2618. EnvMachineOS os;
  2619. StringBuffer path, relativePath;
  2620. queryDropZoneInfo(dropZone, path, os, ip);
  2621. RemoteFilename rfn;
  2622. SocketEndpoint ep;
  2623. ep.ipset(ip);
  2624. rfn.setPath(ep, path);
  2625. Owned<IFile> f = createIFile(rfn);
  2626. if(!f->isDirectory())
  2627. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path.str());
  2628. IArrayOf<IEspPhysicalFileStruct> files;
  2629. const char* nameFilter = req.getNameFilter();
  2630. searchDropZoneFileInFolder(context, f, nameFilter, !nameFilter || !*nameFilter, path.str(),
  2631. relativePath, (os == MachineOsW2K) ? '\\' : '/', files);
  2632. resp.setFiles(files);
  2633. }
  2634. catch(IException* e)
  2635. {
  2636. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2637. }
  2638. return true;
  2639. }
  2640. bool CFileSprayEx::onDfuMonitor(IEspContext &context, IEspDfuMonitorRequest &req, IEspDfuMonitorResponse &resp)
  2641. {
  2642. try
  2643. {
  2644. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2645. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do DfuMonitor. Permission denied.");
  2646. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2647. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2648. wu->setQueue(m_MonitorQueueLabel.str());
  2649. StringBuffer user, passwd;
  2650. wu->setUser(context.getUserID(user).str());
  2651. wu->setPassword(context.getPassword(passwd).str());
  2652. wu->setCommand(DFUcmd_monitor);
  2653. IDFUmonitor *monitor = wu->queryUpdateMonitor();
  2654. IDFUfileSpec *source = wu->queryUpdateSource();
  2655. const char *eventname = req.getEventName();
  2656. const char *lname = req.getLogicalName();
  2657. if (lname&&*lname)
  2658. source->setLogicalName(lname);
  2659. else {
  2660. const char *ip = req.getIp();
  2661. const char *filename = req.getFilename();
  2662. if (filename&&*filename) {
  2663. RemoteFilename rfn;
  2664. if (ip&&*ip) {
  2665. SocketEndpoint ep;
  2666. ep.set(ip);
  2667. rfn.setPath(ep,filename);
  2668. }
  2669. else
  2670. rfn.setRemotePath(filename);
  2671. source->setSingleFilename(rfn);
  2672. }
  2673. else
  2674. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Neither logical name nor network ip/file specified for monitor.");
  2675. }
  2676. if (eventname)
  2677. monitor->setEventName(eventname);
  2678. monitor->setShotLimit(req.getShotLimit());
  2679. monitor->setSub(req.getSub());
  2680. resp.setWuid(wu->queryId());
  2681. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2682. submitDFUWorkUnit(wu.getClear());
  2683. }
  2684. catch(IException* e)
  2685. {
  2686. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2687. }
  2688. return true;
  2689. }
  2690. bool CFileSprayEx::onOpenSave(IEspContext &context, IEspOpenSaveRequest &req, IEspOpenSaveResponse &resp)
  2691. {
  2692. try
  2693. {
  2694. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2695. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2696. const char* location = req.getLocation();
  2697. const char* path = req.getPath();
  2698. const char* name = req.getName();
  2699. const char* type = req.getType();
  2700. const char* dateTime = req.getDateTime();
  2701. if (location && *location)
  2702. resp.setLocation(location);
  2703. if (path && *path)
  2704. resp.setPath(path);
  2705. if (name && *name)
  2706. resp.setName(name);
  2707. if (type && *type)
  2708. resp.setType(type);
  2709. if (dateTime && *dateTime)
  2710. resp.setDateTime(dateTime);
  2711. if (req.getBinaryFile())
  2712. resp.setViewable(false);
  2713. }
  2714. catch(IException* e)
  2715. {
  2716. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2717. }
  2718. return true;
  2719. }
  2720. bool CFileSprayEx::getDropZoneFiles(IEspContext &context, const char* netaddr, const char* osStr, const char* path,
  2721. IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2722. {
  2723. bool directoryOnly = req.getDirectoryOnly();
  2724. int checkReturn = doFileCheck(NULL, netaddr, osStr, path);
  2725. if (checkReturn > 1)
  2726. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2727. else if (checkReturn > 0)
  2728. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2729. RemoteFilename rfn;
  2730. SocketEndpoint ep;
  2731. #ifdef MACHINE_IP
  2732. ep.set(MACHINE_IP);
  2733. #else
  2734. ep.set(netaddr);
  2735. #endif
  2736. rfn.setPath(ep, path);
  2737. Owned<IFile> f = createIFile(rfn);
  2738. if(!f->isDirectory())
  2739. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2740. IArrayOf<IEspPhysicalFileStruct> files;
  2741. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2742. if(di.get() != NULL)
  2743. {
  2744. ForEach(*di)
  2745. {
  2746. StringBuffer fname;
  2747. di->getName(fname);
  2748. if (fname.length() == 0 || (directoryOnly && !di->isDir()))
  2749. continue;
  2750. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2751. onefile->setName(fname.str());
  2752. onefile->setIsDir(di->isDir());
  2753. onefile->setFilesize(di->getFileSize());
  2754. CDateTime modtime;
  2755. StringBuffer timestr;
  2756. di->getModifiedTime(modtime);
  2757. unsigned y,m,d,h,min,sec,nsec;
  2758. modtime.getDate(y,m,d,true);
  2759. modtime.getTime(h,min,sec,nsec,true);
  2760. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2761. onefile->setModifiedtime(timestr.str());
  2762. files.append(*onefile.getLink());
  2763. }
  2764. }
  2765. resp.setFiles(files);
  2766. return true;
  2767. }
  2768. bool CFileSprayEx::onDropZoneFiles(IEspContext &context, IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2769. {
  2770. try
  2771. {
  2772. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2773. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2774. const char* netAddress = req.getNetAddress();
  2775. const char* directory = req.getPath();
  2776. const char* subfolder = req.getSubfolder();
  2777. StringBuffer netAddressStr, directoryStr, osStr;
  2778. if (netAddress && *netAddress && directory && *directory)
  2779. {
  2780. netAddressStr.append(netAddress);
  2781. directoryStr.append(directory);
  2782. }
  2783. IArrayOf<IEspDropZone> dropZoneList;
  2784. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2785. Owned<IConstEnvironment> m_constEnv = factory->openEnvironment();
  2786. Owned<IPropertyTree> pEnvRoot = &m_constEnv->getPTree();
  2787. IPropertyTree* pEnvSoftware = pEnvRoot->queryPropTree("Software");
  2788. if (pEnvSoftware)
  2789. {
  2790. Owned<IPropertyTreeIterator> it = pEnvSoftware->getElements("DropZone");
  2791. ForEach(*it)
  2792. {
  2793. IPropertyTree& pDropZone = it->query();
  2794. if (!pDropZone.getPropBool("@ECLWatchVisible", true))
  2795. continue;
  2796. //get IP Address of the computer associated with this drop zone
  2797. const char* pszName = pDropZone.queryProp("@name");
  2798. const char* pszComputer = pDropZone.queryProp("@computer");
  2799. if (!strcmp(pszComputer, "."))
  2800. pszComputer = "localhost";
  2801. StringBuffer xpath;
  2802. xpath.appendf("Hardware/Computer[@name='%s']/@netAddress", pszComputer);
  2803. StringBuffer sNetAddr;
  2804. const char* pszNetAddr = pEnvRoot->queryProp(xpath.str());
  2805. if (strcmp(pszNetAddr, "."))
  2806. {
  2807. sNetAddr.append(pszNetAddr);
  2808. }
  2809. else
  2810. {
  2811. StringBuffer ipStr;
  2812. IpAddress ipaddr = queryHostIP();
  2813. ipaddr.getIpText(ipStr);
  2814. if (ipStr.length() > 0)
  2815. {
  2816. #ifdef MACHINE_IP
  2817. sNetAddr.append(MACHINE_IP);
  2818. #else
  2819. sNetAddr.append(ipStr.str());
  2820. #endif
  2821. }
  2822. }
  2823. Owned<IConstMachineInfo> machine;
  2824. if (strcmp(pszNetAddr, "."))
  2825. machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
  2826. else
  2827. {
  2828. machine.setown(m_constEnv->getMachineByAddress(pszNetAddr));
  2829. if (!machine)
  2830. machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
  2831. }
  2832. StringBuffer dir;
  2833. pDropZone.getProp("@directory", dir);
  2834. Owned<IEspDropZone> aDropZone= createDropZone("","");
  2835. if (machine)
  2836. {
  2837. if (machine->getOS() == MachineOsLinux || machine->getOS() == MachineOsSolaris)
  2838. {
  2839. dir.replace('\\', '/');//replace all '\\' by '/'
  2840. aDropZone->setLinux("true");
  2841. osStr = "1";
  2842. }
  2843. else
  2844. {
  2845. dir.replace('/', '\\');
  2846. dir.replace('$', ':');
  2847. osStr = "0";
  2848. }
  2849. }
  2850. aDropZone->setComputer(pszComputer);
  2851. aDropZone->setPath(dir.str());
  2852. aDropZone->setName(pszName);
  2853. aDropZone->setNetAddress(sNetAddr.str());
  2854. dropZoneList.append(*aDropZone.getClear());
  2855. }
  2856. }
  2857. if (dropZoneList.ordinality())
  2858. resp.setDropZones(dropZoneList);
  2859. if (netAddressStr.length() < 1)
  2860. return true;
  2861. char pathSep = '/';
  2862. if (osStr && *osStr)
  2863. {
  2864. int os = atoi(osStr);
  2865. if (os == OS_WINDOWS)
  2866. pathSep = '\\';
  2867. }
  2868. directoryStr.replace(pathSep=='\\'?'/':'\\', pathSep);
  2869. if (subfolder && *subfolder)
  2870. {
  2871. if (*(directoryStr.str() + directoryStr.length() -1) != pathSep)
  2872. directoryStr.append( pathSep );
  2873. directoryStr.append(subfolder);
  2874. }
  2875. if (*(directoryStr.str() + directoryStr.length() -1) != pathSep)
  2876. directoryStr.append( pathSep );
  2877. PROGLOG("getDropZoneFiles: netAddress %s, path %s", netAddressStr.str(), directoryStr.str());
  2878. getDropZoneFiles(context, netAddressStr.str(), osStr.str(), directoryStr.str(), req, resp);
  2879. if (pathSep=='\\')
  2880. directoryStr.replaceString("\\", "\\\\");
  2881. resp.setNetAddress(netAddressStr.str());
  2882. resp.setPath(directoryStr.str());
  2883. resp.setOS(atoi(osStr.str()));
  2884. }
  2885. catch(IException* e)
  2886. {
  2887. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2888. }
  2889. return true;
  2890. }
  2891. bool CFileSprayEx::onDeleteDropZoneFiles(IEspContext &context, IEspDeleteDropZoneFilesRequest &req, IEspDFUWorkunitsActionResponse &resp)
  2892. {
  2893. try
  2894. {
  2895. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Full, false))
  2896. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2897. const char* netAddress = req.getNetAddress();
  2898. const char* directory = req.getPath();
  2899. const char* osStr = req.getOS();
  2900. StringArray & files = req.getNames();
  2901. if (!netAddress || !*netAddress || !directory || !*directory)
  2902. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone not specified.");
  2903. if (!files.ordinality())
  2904. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  2905. char pathSep = '/';
  2906. StringBuffer sPath(directory);
  2907. if (osStr && *osStr)
  2908. {
  2909. int os = atoi(osStr);
  2910. pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2911. sPath.replace(pathSep=='\\'?'/':'\\', pathSep);
  2912. if (*(sPath.str() + sPath.length() -1) != pathSep)
  2913. sPath.append( pathSep );
  2914. }
  2915. int checkReturn = doFileCheck(NULL, netAddress, osStr, sPath.str());
  2916. if (checkReturn > 1)
  2917. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2918. else if (checkReturn > 0)
  2919. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2920. RemoteFilename rfn;
  2921. SocketEndpoint ep;
  2922. #ifdef MACHINE_IP
  2923. ep.set(MACHINE_IP);
  2924. #else
  2925. ep.set(netAddress);
  2926. #endif
  2927. rfn.setPath(ep, sPath.str());
  2928. Owned<IFile> f = createIFile(rfn);
  2929. if(!f->isDirectory())
  2930. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", directory);
  2931. bool bAllSuccess = true;
  2932. IArrayOf<IEspDFUActionResult> results;
  2933. for(unsigned i = 0; i < files.ordinality(); ++i)
  2934. {
  2935. const char* file = files.item(i);
  2936. if (!file || !*file)
  2937. continue;
  2938. PROGLOG("DeleteDropZoneFiles: netAddress %s, path %s, file %s", netAddress, directory, file);
  2939. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  2940. res->setID(files.item(i));
  2941. res->setAction("Delete");
  2942. res->setResult("Success");
  2943. try
  2944. {
  2945. StringBuffer fileToDelete = sPath;
  2946. if (*(fileToDelete.str() + fileToDelete.length() -1) != pathSep)
  2947. fileToDelete.append( pathSep );
  2948. fileToDelete.append(file);
  2949. rfn.setPath(ep, fileToDelete.str());
  2950. Owned<IFile> rFile = createIFile(rfn);
  2951. if (!rFile->exists())
  2952. res->setResult("Warning: this file does not exist.");
  2953. else
  2954. rFile->remove();
  2955. }
  2956. catch (IException *e)
  2957. {
  2958. bAllSuccess = false;
  2959. StringBuffer eMsg;
  2960. eMsg = e->errorMessage(eMsg);
  2961. e->Release();
  2962. StringBuffer failedMsg = "Failed: ";
  2963. failedMsg.append(eMsg);
  2964. res->setResult(failedMsg.str());
  2965. }
  2966. results.append(*res.getLink());
  2967. }
  2968. resp.setFirstColumn("File");
  2969. resp.setDFUActionResults(results);
  2970. }
  2971. catch(IException* e)
  2972. {
  2973. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2974. }
  2975. return true;
  2976. }
  2977. void CFileSprayEx::appendGroupNode(IArrayOf<IEspGroupNode>& groupNodes, const char* nodeName, const char* clusterType,
  2978. bool replicateOutputs)
  2979. {
  2980. Owned<IEspGroupNode> node = createGroupNode();
  2981. node->setName(nodeName);
  2982. node->setClusterType(clusterType);
  2983. if (replicateOutputs)
  2984. node->setReplicateOutputs(replicateOutputs);
  2985. groupNodes.append(*node.getClear());
  2986. }
  2987. bool CFileSprayEx::onGetSprayTargets(IEspContext &context, IEspGetSprayTargetsRequest &req, IEspGetSprayTargetsResponse &resp)
  2988. {
  2989. try
  2990. {
  2991. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2992. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2993. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2994. Owned<IConstEnvironment> environment = factory->openEnvironment();
  2995. Owned<IPropertyTree> root = &environment->getPTree();
  2996. if (!root)
  2997. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  2998. IArrayOf<IEspGroupNode> sprayTargets;
  2999. //Fetch all the group names for all the thor instances (and dedup them)
  3000. BoolHash uniqueThorClusterGroupNames;
  3001. Owned<IPropertyTreeIterator> it = root->getElements("Software/ThorCluster");
  3002. ForEach(*it)
  3003. {
  3004. IPropertyTree& cluster = it->query();
  3005. StringBuffer thorClusterGroupName;
  3006. getClusterGroupName(cluster, thorClusterGroupName);
  3007. if (!thorClusterGroupName.length())
  3008. continue;
  3009. bool* found = uniqueThorClusterGroupNames.getValue(thorClusterGroupName.str());
  3010. if (!found || !*found)
  3011. appendGroupNode(sprayTargets, thorClusterGroupName.str(), "thor", cluster.getPropBool("@replicateOutputs", false));
  3012. }
  3013. //Fetch all the group names for all the hthor instances
  3014. it.setown(root->getElements("Software/EclAgentProcess"));
  3015. ForEach(*it)
  3016. {
  3017. IPropertyTree &cluster = it->query();
  3018. const char* name = cluster.queryProp("@name");
  3019. if (!name || !*name)
  3020. continue;
  3021. unsigned ins = 0;
  3022. Owned<IPropertyTreeIterator> insts = cluster.getElements("Instance");
  3023. ForEach(*insts)
  3024. {
  3025. const char *na = insts->query().queryProp("@netAddress");
  3026. if (!na || !*na)
  3027. continue;
  3028. SocketEndpoint ep(na);
  3029. if (ep.isNull())
  3030. continue;
  3031. ins++;
  3032. VStringBuffer gname("hthor__%s", name);
  3033. if (ins>1)
  3034. gname.append('_').append(ins);
  3035. appendGroupNode(sprayTargets, gname.str(), "hthor", false);
  3036. }
  3037. }
  3038. resp.setGroupNodes(sprayTargets);
  3039. }
  3040. catch(IException* e)
  3041. {
  3042. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  3043. }
  3044. return true;
  3045. }