ws_fsService.cpp 113 KB

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