ws_fsService.cpp 111 KB

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