ws_fsService.cpp 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165
  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; // Number of "spare" copies of the data
  493. unsigned channelsPerNode = 1; // Overloaded and cyclic modes
  494. int replicateOffset = 1; // Used In cyclic mode only
  495. unsigned numDataCopies = process.getPropInt("@numDataCopies", 1);
  496. ClusterPartDiskMapSpec spec;
  497. spec.setDefaultBaseDir(defaultFolder);
  498. if (strieq(slaveConfig, "overloaded"))
  499. {
  500. channelsPerNode = process.getPropInt("@channelsPernode", 1);
  501. spec.setDefaultReplicateDir(defaultReplicateFolder);
  502. }
  503. else if (strieq(slaveConfig, "full redundancy"))
  504. {
  505. redundancy = numDataCopies-1;
  506. replicateOffset = 0;
  507. replicate = true;
  508. }
  509. else if (strieq(slaveConfig, "cyclic redundancy"))
  510. {
  511. redundancy = numDataCopies-1;
  512. channelsPerNode = numDataCopies;
  513. replicateOffset = process.getPropInt("@cyclicOffset", 1);
  514. spec.setDefaultReplicateDir(defaultReplicateFolder);
  515. replicate = true;
  516. }
  517. spec.setRoxie (redundancy, channelsPerNode, replicateOffset);
  518. if (!supercopy)
  519. spec.setRepeatedCopies(CPDMSRP_lastRepeated,false);
  520. wuFSpecDest->setClusterPartDiskMapSpec(clusterName,spec);
  521. wuOptions->setReplicate(replicate);
  522. }
  523. void getClusterFromLFN(const char* lfn, StringBuffer& cluster, const char* username, const char* passwd)
  524. {
  525. Owned<IUserDescriptor> udesc;
  526. if(username != NULL && *username != '\0')
  527. {
  528. udesc.setown(createUserDescriptor());
  529. udesc->set(username, passwd);
  530. }
  531. LogicFileWrapper lfw;
  532. lfw.FindClusterName(lfn, cluster, udesc);
  533. }
  534. StringBuffer& constructFileMask(const char* filename, StringBuffer& filemask)
  535. {
  536. filemask.clear().append(filename).toLowerCase().append("._$P$_of_$N$");
  537. return filemask;
  538. }
  539. bool CFileSprayEx::onDFUWUSearch(IEspContext &context, IEspDFUWUSearchRequest & req, IEspDFUWUSearchResponse & resp)
  540. {
  541. try
  542. {
  543. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  544. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  545. StringArray dfuclusters;
  546. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  547. Owned<IConstEnvironment> environment = factory->openEnvironmentByFile();
  548. Owned<IPropertyTree> root = &environment->getPTree();
  549. if (!root)
  550. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  551. Owned<IPropertyTreeIterator> clusterIterator = root->getElements("Software/Topology/Cluster");
  552. if (clusterIterator->first())
  553. {
  554. do {
  555. IPropertyTree &cluster = clusterIterator->query();
  556. const char *clusterName = cluster.queryProp("@name");
  557. if (!clusterName || !*clusterName)
  558. continue;
  559. dfuclusters.append(clusterName);
  560. } while (clusterIterator->next());
  561. }
  562. resp.setClusterNames(dfuclusters);
  563. }
  564. catch(IException* e)
  565. {
  566. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  567. }
  568. return true;
  569. }
  570. int readFromCommaSeparatedString(const char *commaSeparatedString, StringBuffer* output)
  571. {
  572. int numOfItems = 0;
  573. if (commaSeparatedString && *commaSeparatedString)
  574. {
  575. char *pStr = (char *) commaSeparatedString;
  576. while (pStr)
  577. {
  578. char item[1024];
  579. bool bFoundComma = false;
  580. int len = strlen(pStr);
  581. for (int i = 0; i < len; i++)
  582. {
  583. char *pStr1 = pStr + i;
  584. if (pStr1[0] != ',')
  585. continue;
  586. strncpy(item, pStr, pStr1 - pStr);
  587. item[pStr1 - pStr] = 0;
  588. bFoundComma = true;
  589. if (i < len - 1)
  590. pStr = pStr1 + 1;
  591. else
  592. pStr = NULL;
  593. break;
  594. }
  595. if (!bFoundComma && len > 0)
  596. {
  597. strcpy(item, pStr);
  598. pStr = NULL;
  599. }
  600. output[numOfItems] = item;
  601. numOfItems++;
  602. }
  603. }
  604. return numOfItems;
  605. }
  606. bool CFileSprayEx::GetArchivedDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  607. {
  608. StringBuffer user;
  609. context.getUserID(user);
  610. StringBuffer sashaAddress;
  611. IArrayOf<IConstTpSashaServer> sashaservers;
  612. CTpWrapper dummy;
  613. dummy.getTpSashaServers(sashaservers);
  614. ForEachItemIn(i, sashaservers)
  615. {
  616. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  617. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  618. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  619. }
  620. SocketEndpoint ep;
  621. ep.set(sashaAddress,DEFAULT_SASHA_PORT);
  622. Owned<INode> sashaserver = createINode(ep);
  623. __int64 count=req.getPageSize();
  624. if(count < 1)
  625. count=100;
  626. __int64 begin=req.getPageStartFrom();
  627. if (begin < 0)
  628. begin = 0;
  629. Owned<ISashaCommand> cmd = createSashaCommand();
  630. cmd->setAction(SCA_LIST);
  631. cmd->setOnline(false);
  632. cmd->setArchived(true);
  633. cmd->setDFU(true);
  634. cmd->setLimit((int) count+1);
  635. cmd->setStart((int)begin);
  636. if(req.getCluster() && *req.getCluster())
  637. cmd->setCluster(req.getCluster());
  638. if(req.getOwner() && *req.getOwner())
  639. cmd->setOwner(req.getOwner());
  640. if(req.getJobname() && *req.getJobname())
  641. cmd->setJobName(req.getJobname());
  642. if(req.getStateReq() && *req.getStateReq())
  643. cmd->setState(req.getStateReq());
  644. cmd->setOutputFormat("owner,jobname,cluster,state,command");//date range/owner/jobname/state*/
  645. if (!cmd->send(sashaserver))
  646. {
  647. StringBuffer msg;
  648. msg.appendf("Cannot connect to archive server at %s",sashaAddress.str());
  649. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER, "%s", msg.str());
  650. }
  651. IArrayOf<IEspDFUWorkunit> results;
  652. __int64 actualCount = cmd->numIds();
  653. StringBuffer s;
  654. for (unsigned j=0;j<actualCount;j++)
  655. {
  656. const char *wuidStr = cmd->queryId(j);
  657. if (!wuidStr)
  658. continue;
  659. StringBuffer strArray[6];
  660. readFromCommaSeparatedString(wuidStr, strArray);
  661. //skip any workunits without access
  662. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  663. resultWU->setArchived(true);
  664. if (strArray[0].length() > 0)
  665. resultWU->setID(strArray[0].str());
  666. if (strArray[1].length() > 0)
  667. resultWU->setUser(strArray[1].str());
  668. if (strArray[2].length() > 0)
  669. resultWU->setJobName(strArray[2].str());
  670. if (strArray[3].length() > 0)
  671. resultWU->setClusterName(strArray[3].str());
  672. if (strArray[4].length() > 0)
  673. resultWU->setStateMessage(strArray[4].str());
  674. if (strArray[5].length() > 0)
  675. resultWU->setCommand(atoi(strArray[5].str()));
  676. results.append(*resultWU.getLink());
  677. }
  678. resp.setPageStartFrom(begin+1);
  679. resp.setNextPage(-1);
  680. if(count < actualCount)
  681. {
  682. if (results.length() > count)
  683. {
  684. results.pop();
  685. }
  686. resp.setNextPage(begin + count);
  687. resp.setPageEndAt(begin + count);
  688. }
  689. else
  690. {
  691. resp.setPageEndAt(begin + actualCount);
  692. }
  693. if(begin > 0)
  694. {
  695. resp.setFirst(false);
  696. if (begin - count > 0)
  697. resp.setPrevPage(begin - count);
  698. else
  699. resp.setPrevPage(0);
  700. }
  701. resp.setPageSize(count);
  702. resp.setResults(results);
  703. StringBuffer basicQuery;
  704. if (req.getStateReq() && *req.getStateReq())
  705. {
  706. resp.setStateReq(req.getStateReq());
  707. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  708. }
  709. if (req.getCluster() && *req.getCluster())
  710. {
  711. resp.setCluster(req.getCluster());
  712. addToQueryString(basicQuery, "Cluster", req.getCluster());
  713. }
  714. if (req.getOwner() && *req.getOwner())
  715. {
  716. resp.setOwner(req.getOwner());
  717. addToQueryString(basicQuery, "Owner", req.getOwner());
  718. }
  719. if (req.getType() && *req.getType())
  720. {
  721. resp.setType(req.getType());
  722. addToQueryString(basicQuery, "Type", req.getType());
  723. }
  724. resp.setFilters(basicQuery.str());
  725. resp.setBasicQuery(basicQuery.str());
  726. return true;
  727. }
  728. bool CFileSprayEx::onGetDFUWorkunits(IEspContext &context, IEspGetDFUWorkunits &req, IEspGetDFUWorkunitsResponse &resp)
  729. {
  730. try
  731. {
  732. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  733. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  734. double version = context.getClientVersion();
  735. if (version > 1.02)
  736. {
  737. const char *type = req.getType();
  738. if (type && *type && !stricmp(type, "archived workunits"))
  739. {
  740. return GetArchivedDFUWorkunits(context, req, resp);
  741. }
  742. }
  743. StringBuffer clusterReq;
  744. const char *clusterName = req.getCluster();
  745. if(clusterName && *clusterName)
  746. {
  747. clusterReq.append(clusterName);
  748. }
  749. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory();
  750. Owned<IConstEnvironment> constEnv = envFactory->openEnvironmentByFile();
  751. Owned<IPropertyTree> root = &constEnv->getPTree();
  752. if (!root)
  753. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  754. StringArray targetClusters, clusterProcesses;
  755. Owned<IPropertyTreeIterator> clusters= root->getElements("Software/Topology/Cluster");
  756. if (clusters->first())
  757. {
  758. do {
  759. IPropertyTree &cluster = clusters->query();
  760. const char* name = cluster.queryProp("@name");
  761. if (!name || !*name)
  762. continue;
  763. Owned<IPropertyTreeIterator> thorClusters= cluster.getElements(eqThorCluster);
  764. Owned<IPropertyTreeIterator> roxieClusters= cluster.getElements(eqRoxieCluster);
  765. if (thorClusters->first() || roxieClusters->first())
  766. {
  767. bool bFound = false;
  768. if (thorClusters->first())
  769. {
  770. IPropertyTree &thorCluster = thorClusters->query();
  771. const char* process = thorCluster.queryProp("@process");
  772. if (process && *process)
  773. {
  774. targetClusters.append(name);
  775. clusterProcesses.append(process);
  776. if (clusterName && !stricmp(clusterName, name))
  777. {
  778. clusterReq.clear().append(process);
  779. }
  780. }
  781. }
  782. if (!bFound && roxieClusters->first())
  783. {
  784. IPropertyTree &roxieCluster = roxieClusters->query();
  785. const char* process = roxieCluster.queryProp("@process");
  786. if (process && *process)
  787. {
  788. targetClusters.append(name);
  789. clusterProcesses.append(process);
  790. if (clusterName && !stricmp(clusterName, name))
  791. {
  792. clusterReq.clear().append(process);
  793. }
  794. }
  795. }
  796. }
  797. } while (clusters->next());
  798. }
  799. __int64 pagesize = req.getPageSize();
  800. __int64 pagefrom = req.getPageStartFrom();
  801. __int64 displayFrom = 0;
  802. if (pagesize < 1)
  803. {
  804. pagesize = 100;
  805. }
  806. if (pagefrom > 0)
  807. {
  808. displayFrom = pagefrom;
  809. }
  810. DFUsortfield sortorder[2] = {DFUsf_wuid, DFUsf_term};
  811. sortorder[0] = (DFUsortfield) (DFUsf_wuid + DFUsf_reverse);
  812. if(req.getSortby() && *req.getSortby())
  813. {
  814. const char *sortby = req.getSortby();
  815. if (!stricmp(sortby, "Owner"))
  816. sortorder[0] = DFUsf_user;
  817. else if (!stricmp(sortby, "JobName"))
  818. sortorder[0] = DFUsf_job;
  819. else if (!stricmp(sortby, "Cluster"))
  820. sortorder[0] = DFUsf_cluster;
  821. else if (!stricmp(sortby, "State"))
  822. sortorder[0] = DFUsf_state;
  823. else if (!stricmp(sortby, "Type"))
  824. sortorder[0] = DFUsf_command;
  825. else if (!stricmp(sortby, "Protected"))
  826. sortorder[0] = DFUsf_protected;
  827. else if (!stricmp(sortby, "PCTDone"))
  828. sortorder[0] = (DFUsortfield) (DFUsf_pcdone | DFUsf_numeric);
  829. else
  830. sortorder[0] = DFUsf_wuid;
  831. bool descending = req.getDescending();
  832. if (descending)
  833. sortorder[0] = (DFUsortfield) (sortorder[0] | DFUsf_reverse);
  834. }
  835. DFUsortfield filters[10];
  836. unsigned short filterCount = 0;
  837. MemoryBuffer filterbuf;
  838. if(req.getStateReq() && *req.getStateReq())
  839. {
  840. filters[filterCount] = DFUsf_state;
  841. filterCount++;
  842. if (stricmp(req.getStateReq(), "unknown") != 0)
  843. filterbuf.append(req.getStateReq());
  844. else
  845. filterbuf.append("");
  846. }
  847. if(clusterName && *clusterName)
  848. {
  849. filters[filterCount] = DFUsf_cluster;
  850. filterCount++;
  851. filterbuf.append(clusterReq.str());
  852. }
  853. if(req.getOwner() && *req.getOwner())
  854. {
  855. filters[filterCount] = DFUsortfield (DFUsf_user | DFUsf_nocase);
  856. filterCount++;
  857. filterbuf.append(req.getOwner());
  858. }
  859. if(req.getJobname() && *req.getJobname())
  860. {
  861. filters[filterCount] = DFUsortfield (DFUsf_job | DFUsf_nocase);
  862. filterCount++;
  863. filterbuf.append(req.getJobname());
  864. }
  865. filters[filterCount] = DFUsf_term;
  866. __int64 cacheHint = req.getCacheHint();
  867. if (cacheHint < 0) //Not set yet
  868. cacheHint = 0;
  869. IArrayOf<IEspDFUWorkunit> result;
  870. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  871. unsigned numWUs;
  872. Owned<IConstDFUWorkUnitIterator> itr = factory->getWorkUnitsSorted(sortorder, filters, filterbuf.bufferBase(), (int) displayFrom, (int) pagesize+1, req.getOwner(), &cacheHint, &numWUs);
  873. if (version >= 1.07)
  874. resp.setCacheHint(cacheHint);
  875. //unsigned actualCount = 0;
  876. itr->first();
  877. while(itr->isValid())
  878. {
  879. Owned<IConstDFUWorkUnit> wu = itr->get();
  880. //actualCount++;
  881. Owned<IEspDFUWorkunit> resultWU = createDFUWorkunit("", "");
  882. resultWU->setID(wu->queryId());
  883. StringBuffer jobname, user, cluster;
  884. resultWU->setJobName(wu->getJobName(jobname).str());
  885. resultWU->setCommand(wu->getCommand());
  886. resultWU->setUser(wu->getUser(user).str());
  887. const char* clusterName = wu->getClusterName(cluster).str();
  888. if (clusterName)
  889. {
  890. StringBuffer clusterForDisplay(clusterName);
  891. if (clusterProcesses.ordinality())
  892. {
  893. for (unsigned i = 0; i < clusterProcesses.length(); i++)
  894. {
  895. const char* clusterProcessName = clusterProcesses.item(i);
  896. if (!stricmp(clusterProcessName, clusterName))
  897. {
  898. clusterForDisplay.clear().append(targetClusters.item(i));
  899. break;
  900. }
  901. }
  902. }
  903. resultWU->setClusterName(clusterForDisplay.str());
  904. }
  905. resultWU->setIsProtected(wu->isProtected());
  906. IConstDFUprogress *prog = wu->queryProgress();
  907. if (prog != NULL)
  908. {
  909. DFUstate state = prog->getState();
  910. resultWU->setState(state);
  911. StringBuffer statemsg;
  912. encodeDFUstate(state,statemsg);
  913. resultWU->setStateMessage(statemsg.str());
  914. resultWU->setPercentDone(prog->getPercentDone());
  915. }
  916. result.append(*resultWU.getLink());
  917. itr->next();
  918. }
  919. if (result.length() > pagesize)
  920. result.pop();
  921. resp.setPageSize(pagesize);
  922. resp.setNumWUs(numWUs);
  923. resp.setPageStartFrom(displayFrom + 1);
  924. if(displayFrom + pagesize < numWUs)
  925. {
  926. resp.setNextPage(displayFrom + pagesize);
  927. resp.setPageEndAt(pagefrom + pagesize);
  928. __int64 last = displayFrom + pagesize;
  929. while (last + pagesize < numWUs)
  930. {
  931. last += pagesize;
  932. }
  933. resp.setLastPage(last);
  934. }
  935. else
  936. {
  937. resp.setNextPage(-1);
  938. resp.setPageEndAt(numWUs);
  939. }
  940. if(displayFrom > 0)
  941. {
  942. resp.setFirst(false);
  943. if (displayFrom - pagesize > 0)
  944. resp.setPrevPage(displayFrom - pagesize);
  945. else
  946. resp.setPrevPage(0);
  947. }
  948. StringBuffer basicQuery;
  949. if (req.getStateReq() && *req.getStateReq())
  950. {
  951. resp.setStateReq(req.getStateReq());
  952. addToQueryString(basicQuery, "StateReq", req.getStateReq());
  953. }
  954. if (req.getCluster() && *req.getCluster())
  955. {
  956. resp.setCluster(req.getCluster());
  957. addToQueryString(basicQuery, "Cluster", req.getCluster());
  958. }
  959. if (req.getOwner() && *req.getOwner())
  960. {
  961. resp.setOwner(req.getOwner());
  962. addToQueryString(basicQuery, "Owner", req.getOwner());
  963. }
  964. resp.setFilters(basicQuery.str());
  965. if (req.getSortby() && *req.getSortby())
  966. {
  967. resp.setSortby(req.getSortby());
  968. if (req.getDescending())
  969. resp.setDescending(req.getDescending());
  970. StringBuffer strbuf = req.getSortby();
  971. strbuf.append("=");
  972. String str1(strbuf.str());
  973. String str(basicQuery.str());
  974. if (str.indexOf(str1) < 0)
  975. {
  976. addToQueryString(basicQuery, "Sortby", req.getSortby());
  977. if (req.getDescending())
  978. addToQueryString(basicQuery, "Descending", "1");
  979. }
  980. }
  981. resp.setBasicQuery(basicQuery.str());
  982. resp.setResults(result);
  983. }
  984. catch(IException* e)
  985. {
  986. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  987. }
  988. return true;
  989. }
  990. void CFileSprayEx::addToQueryString(StringBuffer &queryString, const char *name, const char *value)
  991. {
  992. if (queryString.length() > 0)
  993. {
  994. queryString.append("&amp;");
  995. }
  996. queryString.append(name);
  997. queryString.append("=");
  998. queryString.append(value);
  999. }
  1000. void CFileSprayEx::getInfoFromSasha(IEspContext &context, const char *sashaServer, const char* wuid, IEspDFUWorkunit *info)
  1001. {
  1002. Owned<ISashaCommand> cmd = createSashaCommand();
  1003. cmd->addId(wuid);
  1004. cmd->setAction(SCA_GET);
  1005. cmd->setArchived(true);
  1006. cmd->setDFU(true);
  1007. SocketEndpoint ep(sashaServer, DEFAULT_SASHA_PORT);
  1008. Owned<INode> node = createINode(ep);
  1009. if (!cmd->send(node,1*60*1000))
  1010. {
  1011. DBGLOG("Cannot connect to Sasha server at %s",sashaServer);
  1012. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.",sashaServer);
  1013. }
  1014. if (cmd->numIds()==0)
  1015. {
  1016. DBGLOG("Could not read archived %s",wuid);
  1017. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT,"Cannot read workunit %s.",wuid);
  1018. }
  1019. unsigned num = cmd->numResults();
  1020. if (num < 1)
  1021. return;
  1022. StringBuffer res;
  1023. cmd->getResult(0,res);
  1024. if(res.length() < 1)
  1025. return;
  1026. Owned<IPropertyTree> wu = createPTreeFromXMLString(res.str());
  1027. if (!wu)
  1028. return;
  1029. const char * command = wu->queryProp("@command");
  1030. const char * submitID = wu->queryProp("@submitID");
  1031. const char * cluster = wu->queryProp("@clusterName");
  1032. const char * queue = wu->queryProp("@queue");
  1033. const char * jobName = wu->queryProp("@jobName");
  1034. const char * protectedWU = wu->queryProp("@protected");
  1035. info->setID(wuid);
  1036. info->setArchived(true);
  1037. if (command && *command)
  1038. info->setCommandMessage(command);
  1039. if (cluster && *cluster)
  1040. info->setClusterName(cluster);
  1041. if (submitID && *submitID)
  1042. info->setUser(submitID);
  1043. if (queue && *queue)
  1044. info->setQueue(queue);
  1045. if (jobName && *jobName)
  1046. info->setJobName(jobName);
  1047. if (protectedWU && stricmp(protectedWU, "0"))
  1048. info->setIsProtected(true);
  1049. else
  1050. info->setIsProtected(false);
  1051. IPropertyTree *source = wu->queryPropTree("Source");
  1052. if(source)
  1053. {
  1054. const char * directory = source->queryProp("@directory");
  1055. const char * name = source->queryProp("@name");
  1056. if (directory && *directory)
  1057. info->setSourceDirectory(directory);
  1058. if (name && *name)
  1059. info->setSourceLogicalName(name);
  1060. }
  1061. IPropertyTree *dest = wu->queryPropTree("Destination");
  1062. if(dest)
  1063. {
  1064. const char * directory = dest->queryProp("@directory");
  1065. int numParts = dest->getPropInt("@numparts", -1);
  1066. if (directory && *directory)
  1067. info->setDestDirectory(directory);
  1068. if (numParts > 0)
  1069. info->setDestNumParts(numParts);
  1070. }
  1071. IPropertyTree *progress = wu->queryPropTree("Progress");
  1072. if(progress)
  1073. {
  1074. const char * state = progress->queryProp("@state");
  1075. const char * timeStarted = progress->queryProp("@timestarted");
  1076. const char * timeStopped = progress->queryProp("@timestopped");
  1077. if (state && *state)
  1078. info->setStateMessage(state);
  1079. if (timeStarted && *timeStarted)
  1080. {
  1081. StringBuffer startStr = timeStarted;
  1082. startStr.replace('T', ' ');
  1083. info->setTimeStarted(startStr.str());
  1084. }
  1085. if (timeStopped && *timeStopped)
  1086. {
  1087. StringBuffer stopStr = timeStopped;
  1088. stopStr.replace('T', ' ');
  1089. info->setTimeStopped(stopStr.str());
  1090. }
  1091. }
  1092. return;
  1093. }
  1094. bool CFileSprayEx::getArchivedWUInfo(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1095. {
  1096. const char *wuid = req.getWuid();
  1097. if (wuid && *wuid)
  1098. {
  1099. StringBuffer sashaAddress;
  1100. IArrayOf<IConstTpSashaServer> sashaservers;
  1101. CTpWrapper dummy;
  1102. dummy.getTpSashaServers(sashaservers);
  1103. ForEachItemIn(i, sashaservers)
  1104. {
  1105. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1106. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1107. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1108. }
  1109. if (sashaAddress.length() < 1)
  1110. {
  1111. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1112. }
  1113. getInfoFromSasha(context, sashaAddress.str(), wuid, &resp.updateResult());
  1114. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1115. return true;
  1116. }
  1117. return false;
  1118. }
  1119. bool CFileSprayEx::onGetDFUWorkunit(IEspContext &context, IEspGetDFUWorkunit &req, IEspGetDFUWorkunitResponse &resp)
  1120. {
  1121. try
  1122. {
  1123. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  1124. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1125. const char* wuid = req.getWuid();
  1126. if (!wuid || !*wuid)
  1127. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dfu workunit ID not specified.");
  1128. bool found = false;
  1129. double version = context.getClientVersion();
  1130. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1131. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(wuid, false);
  1132. if(wu)
  1133. {
  1134. IEspDFUWorkunit &result = resp.updateResult();
  1135. DeepAssign(context, wu, result);
  1136. int n = resp.getResult().getState();
  1137. if (n == DFUstate_scheduled || n == DFUstate_queued || n == DFUstate_started)
  1138. {
  1139. resp.setAutoRefresh(WUDETAILS_REFRESH_MINS);
  1140. }
  1141. found = true;
  1142. }
  1143. else if ((version > 1.02) && getArchivedWUInfo(context, req, resp))
  1144. {
  1145. found = true;
  1146. }
  1147. if (!found)
  1148. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1149. }
  1150. catch(IException* e)
  1151. {
  1152. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1153. }
  1154. return true;
  1155. }
  1156. bool CFileSprayEx::onGetDFUProgress(IEspContext &context, IEspProgressRequest &req, IEspProgressResponse &resp)
  1157. {
  1158. try
  1159. {
  1160. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  1161. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  1162. const char* wuid = req.getWuid();
  1163. if(!wuid || !*wuid)
  1164. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit ID not specified.");
  1165. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1166. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  1167. if(!wu)
  1168. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1169. resp.setWuid(req.getWuid());
  1170. IConstDFUprogress *prog = wu->queryProgress();
  1171. if (prog)
  1172. {
  1173. resp.setPercentDone(prog->getPercentDone());
  1174. resp.setKbPerSec(prog->getKbPerSec());
  1175. resp.setKbPerSecAve(prog->getKbPerSecAve());
  1176. resp.setSecsLeft(prog->getSecsLeft());
  1177. StringBuffer statestr;
  1178. encodeDFUstate(prog->getState(), statestr);
  1179. resp.setState(statestr.str());
  1180. resp.setSlavesDone(prog->getSlavesDone());
  1181. StringBuffer msg;
  1182. prog->formatProgressMessage(msg);
  1183. resp.setProgressMessage(msg.str());
  1184. prog->formatSummaryMessage(msg.clear());
  1185. resp.setSummaryMessage(msg.str());
  1186. prog->getTimeTaken(msg.clear());
  1187. resp.setTimeTaken(msg.str());
  1188. }
  1189. }
  1190. catch(IException* e)
  1191. {
  1192. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1193. }
  1194. return true;
  1195. }
  1196. bool CFileSprayEx::onCreateDFUWorkunit(IEspContext &context, IEspCreateDFUWorkunit &req, IEspCreateDFUWorkunitResponse &resp)
  1197. {
  1198. try
  1199. {
  1200. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1201. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to create DFU workunit. Permission denied.");
  1202. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1203. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1204. wu->setQueue(m_QueueLabel.str());
  1205. StringBuffer user, passwd;
  1206. wu->setUser(context.getUserID(user).str());
  1207. wu->setPassword(context.getPassword(passwd).str());
  1208. wu->commit();
  1209. const char * d = wu->queryId();
  1210. IEspDFUWorkunit &result = resp.updateResult();
  1211. DeepAssign(context, wu, result);
  1212. result.setOverwrite(false);
  1213. result.setReplicate(true);
  1214. }
  1215. catch(IException* e)
  1216. {
  1217. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1218. }
  1219. return true;
  1220. }
  1221. bool CFileSprayEx::onUpdateDFUWorkunit(IEspContext &context, IEspUpdateDFUWorkunit &req, IEspUpdateDFUWorkunitResponse &resp)
  1222. {
  1223. try
  1224. {
  1225. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1226. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1227. IConstDFUWorkunit & reqWU = req.getWu();
  1228. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1229. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(reqWU.getID());
  1230. if(!wu)
  1231. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", reqWU.getID());
  1232. IDFUprogress *prog = wu->queryUpdateProgress();
  1233. if (prog && req.getStateOrig() != reqWU.getState())
  1234. {
  1235. if (prog->getState() != req.getStateOrig())
  1236. 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());
  1237. prog->setState((enum DFUstate)reqWU.getState());
  1238. }
  1239. const char* clusterOrig = req.getClusterOrig();
  1240. const char* cluster = reqWU.getClusterName();
  1241. if(cluster && (!clusterOrig || stricmp(clusterOrig, cluster)))
  1242. {
  1243. wu->setClusterName(reqWU.getClusterName());
  1244. }
  1245. const char* jobNameOrig = req.getJobNameOrig();
  1246. const char* jobName = reqWU.getJobName();
  1247. if(jobName && (!jobNameOrig || stricmp(jobNameOrig, jobName)))
  1248. {
  1249. wu->setJobName(jobName);
  1250. }
  1251. if (reqWU.getIsProtected() != req.getIsProtectedOrig())
  1252. wu->protect(reqWU.getIsProtected());
  1253. wu->commit();
  1254. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(reqWU.getID()).str());
  1255. }
  1256. catch(IException* e)
  1257. {
  1258. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1259. }
  1260. return true;
  1261. }
  1262. bool markWUFailed(IDFUWorkUnitFactory *f, const char *wuid)
  1263. {
  1264. Owned<IDFUWorkUnit> wu = f->updateWorkUnit(wuid);
  1265. if(!wu)
  1266. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Dfu workunit %s not found.", wuid);
  1267. IDFUprogress *prog = wu->queryUpdateProgress();
  1268. if(!prog)
  1269. throw MakeStringException(ECLWATCH_PROGRESS_INFO_NOT_FOUND, "progress information not found for workunit %s.", wuid);
  1270. else if(prog->getState() == DFUstate_started)
  1271. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Cannot delete workunit %s because its state is Started.", wuid);
  1272. else
  1273. {
  1274. prog->setState(DFUstate_failed);
  1275. return true;
  1276. }
  1277. return false;
  1278. }
  1279. bool CFileSprayEx::onDFUWorkunitsAction(IEspContext &context, IEspDFUWorkunitsActionRequest &req, IEspDFUWorkunitsActionResponse &resp)
  1280. {
  1281. try
  1282. {
  1283. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1284. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to update DFU workunit. Permission denied.");
  1285. bool bAllSuccess = true;
  1286. IArrayOf<IEspDFUActionResult> results;
  1287. const char* action = req.getType();
  1288. if(!action || !*action || !strcmp(action, "Delete"))
  1289. {
  1290. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1291. StringArray & wuids = req.getWuids();
  1292. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1293. {
  1294. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1295. res->setID(wuids.item(i));
  1296. res->setAction("Delete");
  1297. res->setResult("Success");
  1298. try
  1299. {
  1300. if (markWUFailed(factory, wuids.item(i)))
  1301. {
  1302. if (!factory->deleteWorkUnit(wuids.item(i)))
  1303. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT, "Failed in deleting workunit %s.", wuids.item(i));
  1304. }
  1305. }
  1306. catch (IException *e)
  1307. {
  1308. bAllSuccess = false;
  1309. StringBuffer eMsg;
  1310. eMsg = e->errorMessage(eMsg);
  1311. e->Release();
  1312. StringBuffer failedMsg = "Failed: ";
  1313. failedMsg.append(eMsg);
  1314. res->setResult(failedMsg.str());
  1315. }
  1316. results.append(*res.getLink());
  1317. }
  1318. }
  1319. else if (!strcmp(action, "Restore"))
  1320. {
  1321. StringBuffer sashaAddress;
  1322. IArrayOf<IConstTpSashaServer> sashaservers;
  1323. CTpWrapper dummy;
  1324. dummy.getTpSashaServers(sashaservers);
  1325. ForEachItemIn(i, sashaservers)
  1326. {
  1327. IConstTpSashaServer& sashaserver = sashaservers.item(i);
  1328. IArrayOf<IConstTpMachine> &sashaservermachine = sashaserver.getTpMachines();
  1329. sashaAddress.append(sashaservermachine.item(0).getNetaddress());
  1330. }
  1331. if (sashaAddress.length() < 1)
  1332. {
  1333. throw MakeStringException(ECLWATCH_ARCHIVE_SERVER_NOT_FOUND,"Archive server not found.");
  1334. }
  1335. SocketEndpoint ep(sashaAddress.str(), DEFAULT_SASHA_PORT);
  1336. Owned<INode> node = createINode(ep);
  1337. Owned<ISashaCommand> cmd = createSashaCommand();
  1338. cmd->setAction(SCA_RESTORE);
  1339. cmd->setDFU(true);
  1340. StringArray & wuids = req.getWuids();
  1341. for(unsigned ii = 0; ii < wuids.ordinality(); ++ii)
  1342. {
  1343. StringBuffer msg;
  1344. const char *wuid = wuids.item(ii);
  1345. cmd->addId(wuid);
  1346. if (!cmd->send(node,1*60*1000))
  1347. {
  1348. throw MakeStringException(ECLWATCH_CANNOT_CONNECT_ARCHIVE_SERVER,"Cannot connect to archive server at %s.",sashaAddress.str());
  1349. }
  1350. if (cmd->numIds()==0)
  1351. {
  1352. bAllSuccess = false;
  1353. msg.appendf("Restore failed for %s", wuid);
  1354. }
  1355. else
  1356. {
  1357. StringBuffer reply;
  1358. cmd->getId(0,reply);
  1359. msg.appendf("Restore: %s, reply: %s", wuid, reply.str());
  1360. }
  1361. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1362. res->setID(wuid);
  1363. res->setAction("Restore");
  1364. res->setResult(msg.str());
  1365. results.append(*res.getLink());
  1366. }
  1367. }
  1368. else if(!strcmp(action, "Protect"))
  1369. {
  1370. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1371. StringArray & wuids = req.getWuids();
  1372. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1373. {
  1374. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1375. res->setID(wuids.item(i));
  1376. res->setAction("Protect");
  1377. res->setResult("Success");
  1378. try
  1379. {
  1380. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1381. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuids.item(i));
  1382. if(!wu.get())
  1383. continue;
  1384. wu->protect(true);
  1385. wu->commit();
  1386. }
  1387. catch (IException *e)
  1388. {
  1389. bAllSuccess = false;
  1390. StringBuffer eMsg;
  1391. eMsg = e->errorMessage(eMsg);
  1392. e->Release();
  1393. StringBuffer failedMsg = "Failed: ";
  1394. failedMsg.append(eMsg);
  1395. res->setResult(failedMsg.str());
  1396. }
  1397. results.append(*res.getLink());
  1398. }
  1399. }
  1400. else if(!strcmp(action, "Unprotect"))
  1401. {
  1402. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1403. StringArray & wuids = req.getWuids();
  1404. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1405. {
  1406. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1407. res->setID(wuids.item(i));
  1408. res->setAction("Unprotect");
  1409. res->setResult("Success");
  1410. try
  1411. {
  1412. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1413. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuids.item(i));
  1414. if(!wu.get())
  1415. continue;
  1416. wu->protect(false);
  1417. wu->commit();
  1418. }
  1419. catch (IException *e)
  1420. {
  1421. bAllSuccess = false;
  1422. StringBuffer eMsg;
  1423. eMsg = e->errorMessage(eMsg);
  1424. e->Release();
  1425. StringBuffer failedMsg = "Failed: ";
  1426. failedMsg.append(eMsg);
  1427. res->setResult(failedMsg.str());
  1428. }
  1429. results.append(*res.getLink());
  1430. }
  1431. }
  1432. else if(!strcmp(action, "SetToFailed"))
  1433. {
  1434. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1435. StringArray & wuids = req.getWuids();
  1436. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1437. {
  1438. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  1439. res->setID(wuids.item(i));
  1440. res->setAction("SetToFailed");
  1441. res->setResult("Success");
  1442. try
  1443. {
  1444. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(wuids.item(i));
  1445. if(wu)
  1446. {
  1447. IDFUprogress *prog = wu->queryUpdateProgress();
  1448. if (prog)
  1449. {
  1450. prog->setState(DFUstate_failed);
  1451. wu->commit();
  1452. }
  1453. }
  1454. }
  1455. catch (IException *e)
  1456. {
  1457. bAllSuccess = false;
  1458. StringBuffer eMsg;
  1459. eMsg = e->errorMessage(eMsg);
  1460. e->Release();
  1461. StringBuffer failedMsg = "Failed: ";
  1462. failedMsg.append(eMsg);
  1463. res->setResult(failedMsg.str());
  1464. }
  1465. results.append(*res.getLink());
  1466. }
  1467. }
  1468. else
  1469. throw MakeStringException(ECLWATCH_INVALID_ACTION, "Unknown action type %s", action);
  1470. resp.setDFUActionResults(results);
  1471. }
  1472. catch(IException* e)
  1473. {
  1474. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1475. }
  1476. return true;
  1477. }
  1478. bool CFileSprayEx::onDeleteDFUWorkunits(IEspContext &context, IEspDeleteDFUWorkunits &req, IEspDeleteDFUWorkunitsResponse &resp)
  1479. {
  1480. try
  1481. {
  1482. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1483. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1484. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1485. StringArray & wuids = req.getWuids();
  1486. for(unsigned i = 0; i < wuids.ordinality(); ++i)
  1487. {
  1488. if (markWUFailed(factory, wuids.item(i)))
  1489. factory->deleteWorkUnit(wuids.item(i));
  1490. }
  1491. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1492. }
  1493. catch(IException* e)
  1494. {
  1495. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1496. }
  1497. return true;
  1498. }
  1499. bool CFileSprayEx::onDeleteDFUWorkunit(IEspContext &context, IEspDeleteDFUWorkunit &req, IEspDeleteDFUWorkunitResponse &resp)
  1500. {
  1501. try
  1502. {
  1503. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1504. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to delete DFU workunit. Permission denied.");
  1505. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1506. if (markWUFailed(factory, req.getWuid()))
  1507. resp.setResult(factory->deleteWorkUnit(req.getWuid()));
  1508. else
  1509. resp.setResult(false);
  1510. resp.setRedirectUrl("/FileSpray/GetDFUWorkunits");
  1511. }
  1512. catch(IException* e)
  1513. {
  1514. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1515. }
  1516. return true;
  1517. }
  1518. bool CFileSprayEx::onSubmitDFUWorkunit(IEspContext &context, IEspSubmitDFUWorkunit &req, IEspSubmitDFUWorkunitResponse &resp)
  1519. {
  1520. try
  1521. {
  1522. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1523. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to submit DFU workunit. Permission denied.");
  1524. submitDFUWorkUnit(req.getWuid());
  1525. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1526. }
  1527. catch(IException* e)
  1528. {
  1529. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1530. }
  1531. return true;
  1532. }
  1533. bool CFileSprayEx::onAbortDFUWorkunit(IEspContext &context, IEspAbortDFUWorkunit &req, IEspAbortDFUWorkunitResponse &resp)
  1534. {
  1535. try
  1536. {
  1537. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Write, false))
  1538. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Failed to abort DFU workunit. Permission denied.");
  1539. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1540. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1541. if(!wu)
  1542. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1543. wu->requestAbort();
  1544. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(req.getWuid()).str());
  1545. }
  1546. catch(IException* e)
  1547. {
  1548. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1549. }
  1550. return true;
  1551. }
  1552. bool CFileSprayEx::onGetDFUExceptions(IEspContext &context, IEspGetDFUExceptions &req, IEspGetDFUExceptionsResponse &resp)
  1553. {
  1554. try
  1555. {
  1556. if (!context.validateFeatureAccess(DFU_EX_URL, SecAccess_Read, false))
  1557. throw MakeStringException(ECLWATCH_DFU_EX_ACCESS_DENIED, "Failed to get DFU Exceptions. Permission denied.");
  1558. IArrayOf<IEspDFUException> result;
  1559. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1560. Owned<IDFUWorkUnit> wu = factory->updateWorkUnit(req.getWuid());
  1561. if(!wu)
  1562. throw MakeStringException(ECLWATCH_CANNOT_GET_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  1563. Owned<IExceptionIterator> itr = wu->getExceptionIterator();
  1564. itr->first();
  1565. while(itr->isValid())
  1566. {
  1567. Owned<IEspDFUException> resultE = createDFUException("", "");
  1568. IException &e = itr->query();
  1569. resultE->setCode(e.errorCode());
  1570. StringBuffer msg;
  1571. resultE->setMessage(e.errorMessage(msg).str());
  1572. result.append(*resultE.getLink());
  1573. itr->next();
  1574. }
  1575. resp.setResult(result);
  1576. }
  1577. catch(IException* e)
  1578. {
  1579. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1580. }
  1581. return true;
  1582. }
  1583. bool CFileSprayEx::onSprayFixed(IEspContext &context, IEspSprayFixed &req, IEspSprayFixedResponse &resp)
  1584. {
  1585. try
  1586. {
  1587. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  1588. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Spray. Permission denied.");
  1589. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  1590. const char* destCluster = req.getDestGroup();
  1591. if(destCluster == NULL || *destCluster == '\0')
  1592. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination cluster/group not specified.");
  1593. MemoryBuffer& srcxml = (MemoryBuffer&)req.getSrcxml();
  1594. const char* srcip = req.getSourceIP();
  1595. const char* srcfile = req.getSourcePath();
  1596. if(srcxml.length() == 0)
  1597. {
  1598. if(!srcip || !*srcip)
  1599. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source network IP not specified.");
  1600. if(!srcfile || !*srcfile)
  1601. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source file not specified.");
  1602. }
  1603. const char* destname = req.getDestLogicalName();
  1604. if(!destname || !*destname)
  1605. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1606. CDfsLogicalFileName lfn;
  1607. if (!lfn.setValidate(destname))
  1608. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid destination filename");
  1609. destname = lfn.get();
  1610. StringBuffer gName, ipAddr;
  1611. const char *pTr = strchr(destCluster, ' ');
  1612. if (pTr)
  1613. {
  1614. gName.append(pTr - destCluster, destCluster);
  1615. ipAddr.append(pTr+1);
  1616. }
  1617. else
  1618. gName.append(destCluster);
  1619. if (ipAddr.length() > 0)
  1620. ParseLogicalPath(destname, ipAddr.str(), destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1621. else
  1622. ParseLogicalPath(destname, destCluster, destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  1623. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1624. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1625. wu->setClusterName(gName.str());
  1626. wu->setJobName(destTitle.str());
  1627. wu->setQueue(m_QueueLabel.str());
  1628. StringBuffer user, passwd;
  1629. wu->setUser(context.getUserID(user).str());
  1630. wu->setPassword(context.getPassword(passwd).str());
  1631. wu->setCommand(DFUcmd_import);
  1632. IDFUfileSpec *source = wu->queryUpdateSource();
  1633. if(srcxml.length() == 0)
  1634. {
  1635. RemoteMultiFilename rmfn;
  1636. SocketEndpoint ep(srcip);
  1637. rmfn.setEp(ep);
  1638. StringBuffer fnamebuf(srcfile);
  1639. fnamebuf.trim();
  1640. rmfn.append(fnamebuf.str()); // handles comma separated files
  1641. source->setMultiFilename(rmfn);
  1642. }
  1643. else
  1644. {
  1645. srcxml.append('\0');
  1646. source->setFromXML((const char*)srcxml.toByteArray());
  1647. }
  1648. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1649. bool nosplit = req.getNosplit();
  1650. int recordsize = req.getSourceRecordSize();
  1651. const char* format = req.getSourceFormat();
  1652. if ((recordsize == RECFMVB_RECSIZE_ESCAPE) || (format && strieq(format, "recfmvb")))
  1653. {//recordsize may be set by dfuplus; format may be set by EclWatch
  1654. source->setFormat(DFUff_recfmvb);
  1655. destination->setFormat(DFUff_variable);
  1656. }
  1657. else if ((recordsize == RECFMV_RECSIZE_ESCAPE) || (format && strieq(format, "recfmv")))
  1658. {
  1659. source->setFormat(DFUff_recfmv);
  1660. destination->setFormat(DFUff_variable);
  1661. }
  1662. else if ((recordsize == PREFIX_VARIABLE_RECSIZE_ESCAPE) || (format && strieq(format, "variable")))
  1663. {
  1664. source->setFormat(DFUff_variable);
  1665. destination->setFormat(DFUff_variable);
  1666. }
  1667. else if((recordsize == PREFIX_VARIABLE_BIGENDIAN_RECSIZE_ESCAPE) || (format && strieq(format, "variablebigendian")))
  1668. {
  1669. source->setFormat(DFUff_variablebigendian);
  1670. destination->setFormat(DFUff_variable);
  1671. }
  1672. else if(recordsize == 0 && !nosplit) // -ve record sizes for blocked
  1673. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid record size");
  1674. else
  1675. source->setRecordSize(recordsize);
  1676. destination->setLogicalName(destname);
  1677. destination->setDirectory(destFolder.str());
  1678. StringBuffer fileMask;
  1679. constructFileMask(destTitle.str(), fileMask);
  1680. destination->setFileMask(fileMask.str());
  1681. destination->setGroupName(gName.str());
  1682. const char * encryptkey = req.getEncrypt();
  1683. if(req.getCompress()||(encryptkey&&*encryptkey))
  1684. destination->setCompressed(true);
  1685. ClusterPartDiskMapSpec mspec;
  1686. destination->getClusterPartDiskMapSpec(gName.str(), mspec);
  1687. mspec.setDefaultBaseDir(defaultFolder.str());
  1688. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  1689. destination->setClusterPartDiskMapSpec(gName.str(), mspec);
  1690. int repo = req.getReplicateOffset();
  1691. bool isNull = req.getReplicateOffset_isNull();
  1692. if (!isNull && (repo!=1))
  1693. destination->setReplicateOffset(repo);
  1694. if (req.getWrap())
  1695. destination->setWrap(true);
  1696. IDFUoptions *options = wu->queryUpdateOptions();
  1697. const char * decryptkey = req.getDecrypt();
  1698. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  1699. options->setEncDec(encryptkey,decryptkey);
  1700. options->setReplicate(req.getReplicate());
  1701. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1702. const char* prefix = req.getPrefix();
  1703. if(prefix && *prefix)
  1704. options->setLengthPrefix(prefix);
  1705. if(req.getNosplit())
  1706. options->setNoSplit(true);
  1707. if(req.getNorecover())
  1708. options->setNoRecover(true);
  1709. if(req.getMaxConnections() > 0)
  1710. options->setmaxConnections(req.getMaxConnections());
  1711. if(req.getThrottle() > 0)
  1712. options->setThrottle(req.getThrottle());
  1713. if(req.getTransferBufferSize() > 0)
  1714. options->setTransferBufferSize(req.getTransferBufferSize());
  1715. if (req.getPull())
  1716. options->setPull(true);
  1717. if (req.getPush())
  1718. options->setPush(true);
  1719. if (req.getFailIfNoSourceFile())
  1720. options->setFailIfNoSourceFile(true);
  1721. if (req.getRecordStructurePresent())
  1722. options->setRecordStructurePresent(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. if (req.getFailIfNoSourceFile())
  1867. options->setFailIfNoSourceFile(true);
  1868. if (req.getRecordStructurePresent())
  1869. options->setRecordStructurePresent(true);
  1870. resp.setWuid(wu->queryId());
  1871. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1872. submitDFUWorkUnit(wu.getClear());
  1873. }
  1874. catch(IException* e)
  1875. {
  1876. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1877. }
  1878. return true;
  1879. }
  1880. bool CFileSprayEx::onReplicate(IEspContext &context, IEspReplicate &req, IEspReplicateResponse &resp)
  1881. {
  1882. try
  1883. {
  1884. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  1885. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Replicate. Permission denied.");
  1886. const char* srcname = req.getSourceLogicalName();
  1887. if(!srcname || !*srcname)
  1888. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  1889. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1890. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1891. StringBuffer jobname = "Replicate: ";
  1892. jobname.append(srcname);
  1893. wu->setJobName(jobname.str());
  1894. wu->setQueue(m_QueueLabel.str());
  1895. StringBuffer user, passwd;
  1896. wu->setUser(context.getUserID(user).str());
  1897. wu->setPassword(context.getPassword(passwd).str());
  1898. wu->setCommand(DFUcmd_replicate);
  1899. IDFUfileSpec *source = wu->queryUpdateSource();
  1900. if (source)
  1901. {
  1902. source->setLogicalName(srcname);
  1903. int repo = req.getReplicateOffset();
  1904. if (repo!=1)
  1905. source->setReplicateOffset(repo);
  1906. }
  1907. const char* cluster = req.getCluster();
  1908. if(cluster && *cluster)
  1909. {
  1910. IDFUoptions *opt = wu->queryUpdateOptions();
  1911. opt->setReplicateMode(DFURMmissing,cluster,req.getRepeatLast(),req.getOnlyRepeated());
  1912. }
  1913. resp.setWuid(wu->queryId());
  1914. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  1915. submitDFUWorkUnit(wu.getClear());
  1916. }
  1917. catch(IException* e)
  1918. {
  1919. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1920. }
  1921. return true;
  1922. }
  1923. bool CFileSprayEx::onDespray(IEspContext &context, IEspDespray &req, IEspDesprayResponse &resp)
  1924. {
  1925. try
  1926. {
  1927. if (!context.validateFeatureAccess(FILE_DESPRAY_URL, SecAccess_Write, false))
  1928. throw MakeStringException(ECLWATCH_FILE_DESPRAY_ACCESS_DENIED, "Failed to do Despray. Permission denied.");
  1929. const char* srcname = req.getSourceLogicalName();
  1930. if(!srcname || !*srcname)
  1931. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  1932. const char* destip = req.getDestIP();
  1933. StringBuffer fnamebuf(req.getDestPath());
  1934. const char* destfile = fnamebuf.trim().str();
  1935. MemoryBuffer& dstxml = (MemoryBuffer&)req.getDstxml();
  1936. if(dstxml.length() == 0)
  1937. {
  1938. if(!destip || !*destip)
  1939. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination network IP not specified.");
  1940. if(!destfile || !*destfile)
  1941. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination file not specified.");
  1942. }
  1943. StringBuffer srcTitle;
  1944. ParseLogicalPath(srcname, srcTitle);
  1945. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  1946. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  1947. wu->setJobName(srcTitle.str());
  1948. wu->setQueue(m_QueueLabel.str());
  1949. StringBuffer user, passwd;
  1950. wu->setUser(context.getUserID(user).str());
  1951. wu->setPassword(context.getPassword(passwd).str());
  1952. wu->setCommand(DFUcmd_export);
  1953. IDFUfileSpec *source = wu->queryUpdateSource();
  1954. IDFUfileSpec *destination = wu->queryUpdateDestination();
  1955. IDFUoptions *options = wu->queryUpdateOptions();
  1956. source->setLogicalName(srcname);
  1957. if(dstxml.length() == 0)
  1958. {
  1959. RemoteFilename rfn;
  1960. SocketEndpoint ep(destip);
  1961. rfn.setPath(ep, destfile);
  1962. destination->setSingleFilename(rfn);
  1963. }
  1964. else
  1965. {
  1966. dstxml.append('\0');
  1967. destination->setFromXML((const char*)dstxml.toByteArray());
  1968. }
  1969. destination->setTitle(srcTitle.str());
  1970. options->setKeepHeader(true);
  1971. options->setOverwrite(req.getOverwrite()); // needed if target already exists
  1972. const char* splitprefix = req.getSplitprefix();
  1973. if(splitprefix && *splitprefix)
  1974. options->setSplitPrefix(splitprefix);
  1975. double version = context.getClientVersion();
  1976. if (version > 1.01)
  1977. {
  1978. if(req.getMaxConnections() > 0)
  1979. options->setmaxConnections(req.getMaxConnections());
  1980. else if(req.getSingleConnection())
  1981. options->setmaxConnections(1);
  1982. }
  1983. else
  1984. {
  1985. if(req.getMaxConnections() > 0)
  1986. options->setmaxConnections(req.getMaxConnections());
  1987. }
  1988. if(req.getThrottle() > 0)
  1989. options->setThrottle(req.getThrottle());
  1990. if(req.getTransferBufferSize() > 0)
  1991. options->setTransferBufferSize(req.getTransferBufferSize());
  1992. if(req.getNorecover())
  1993. options->setNoRecover(true);
  1994. if (req.getWrap()) {
  1995. options->setPush(); // I think needed for a despray
  1996. destination->setWrap(true);
  1997. }
  1998. if (req.getMultiCopy())
  1999. destination->setMultiCopy(true);
  2000. const char * encryptkey = req.getEncrypt();
  2001. if(req.getCompress()||(encryptkey&&*encryptkey))
  2002. destination->setCompressed(true);
  2003. const char * decryptkey = req.getDecrypt();
  2004. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2005. options->setEncDec(encryptkey,decryptkey);
  2006. resp.setWuid(wu->queryId());
  2007. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2008. submitDFUWorkUnit(wu.getClear());
  2009. }
  2010. catch(IException* e)
  2011. {
  2012. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2013. }
  2014. return true;
  2015. }
  2016. bool CFileSprayEx::onCopy(IEspContext &context, IEspCopy &req, IEspCopyResponse &resp)
  2017. {
  2018. try
  2019. {
  2020. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  2021. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Copy. Permission denied.");
  2022. const char* srcname = req.getSourceLogicalName();
  2023. const char* dstname = req.getDestLogicalName();
  2024. if(!srcname || !*srcname)
  2025. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2026. if(!dstname || !*dstname)
  2027. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2028. StringBuffer destFolder, destTitle, defaultFolder, defaultReplicateFolder;
  2029. StringBuffer srcCluster, destCluster, destClusterName;
  2030. bool bRoxie = false;
  2031. const char* destCluster0 = req.getDestGroup();
  2032. if(destCluster0 == NULL || *destCluster0 == '\0')
  2033. {
  2034. getClusterFromLFN(srcname, srcCluster, context.queryUserId(), context.queryPassword());
  2035. DBGLOG("Destination cluster/group not specified, using source cluster %s", srcCluster.str());
  2036. destCluster = srcCluster.str();
  2037. destClusterName = srcCluster.str();
  2038. }
  2039. else
  2040. {
  2041. destCluster = destCluster0;
  2042. destClusterName = destCluster0;
  2043. const char* destClusterRoxie = req.getDestGroupRoxie();
  2044. if (destClusterRoxie && !stricmp(destClusterRoxie, "Yes"))
  2045. {
  2046. bRoxie = true;
  2047. }
  2048. }
  2049. CDfsLogicalFileName lfn; // NOTE: must not be moved into block below, or dstname will point to invalid memory
  2050. if (!bRoxie)
  2051. {
  2052. if (!lfn.setValidate(dstname))
  2053. throw MakeStringException(ECLWATCH_INVALID_INPUT, "invalid destination filename");
  2054. dstname = lfn.get();
  2055. }
  2056. ParseLogicalPath(dstname, destCluster.str(), destFolder, destTitle, defaultFolder, defaultReplicateFolder);
  2057. StringBuffer fileMask;
  2058. constructFileMask(destTitle.str(), fileMask);
  2059. const char* srcDali = req.getSourceDali();
  2060. bool supercopy = req.getSuperCopy();
  2061. if (supercopy)
  2062. {
  2063. StringBuffer user, passwd;
  2064. context.getUserID(user);
  2065. context.getPassword(passwd);
  2066. StringBuffer u(user);
  2067. StringBuffer p(passwd);
  2068. Owned<INode> foreigndali;
  2069. if (srcDali)
  2070. {
  2071. SocketEndpoint ep(srcDali);
  2072. foreigndali.setown(createINode(ep));
  2073. const char* srcu = req.getSrcusername();
  2074. if(srcu && *srcu)
  2075. {
  2076. u.clear().append(srcu);
  2077. p.clear().append(req.getSrcpassword());
  2078. }
  2079. }
  2080. Owned<IUserDescriptor> udesc=createUserDescriptor();
  2081. udesc->set(u.str(),p.str());
  2082. if (!queryDistributedFileDirectory().isSuperFile(srcname,udesc,foreigndali))
  2083. supercopy = false;
  2084. }
  2085. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2086. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2087. wu->setJobName(dstname);
  2088. wu->setQueue(m_QueueLabel.str());
  2089. StringBuffer user, passwd;
  2090. wu->setUser(context.getUserID(user).str());
  2091. wu->setPassword(context.getPassword(passwd).str());
  2092. if(destCluster.length() > 0)
  2093. wu->setClusterName(destCluster.str());
  2094. if (supercopy)
  2095. wu->setCommand(DFUcmd_supercopy);
  2096. else
  2097. wu->setCommand(DFUcmd_copy);
  2098. IDFUfileSpec *wuFSpecSource = wu->queryUpdateSource();
  2099. IDFUfileSpec *wuFSpecDest = wu->queryUpdateDestination();
  2100. IDFUoptions *wuOptions = wu->queryUpdateOptions();
  2101. wuFSpecSource->setLogicalName(srcname);
  2102. if(srcDali && *srcDali)
  2103. {
  2104. SocketEndpoint ep(srcDali);
  2105. wuFSpecSource->setForeignDali(ep);
  2106. const char* srcusername = req.getSrcusername();
  2107. if(srcusername && *srcusername)
  2108. {
  2109. const char* srcpasswd = req.getSrcpassword();
  2110. wuFSpecSource->setForeignUser(srcusername, srcpasswd);
  2111. }
  2112. }
  2113. wuFSpecDest->setLogicalName(dstname);
  2114. wuFSpecDest->setFileMask(fileMask.str());
  2115. wuOptions->setOverwrite(req.getOverwrite());
  2116. if (bRoxie)
  2117. {
  2118. setRoxieClusterPartDiskMapping(destCluster.str(), defaultFolder.str(), defaultReplicateFolder.str(), supercopy, wuFSpecDest, wuOptions);
  2119. wuFSpecDest->setWrap(true); // roxie always wraps
  2120. if(req.getCompress())
  2121. wuFSpecDest->setCompressed(true);
  2122. if (!supercopy)
  2123. wuOptions->setSuppressNonKeyRepeats(true); // **** only repeat last part when src kind = key
  2124. }
  2125. else
  2126. {
  2127. const char* srcDiffKeyName = req.getSourceDiffKeyName();
  2128. const char* destDiffKeyName = req.getDestDiffKeyName();
  2129. if (srcDiffKeyName&&*srcDiffKeyName)
  2130. wuFSpecSource->setDiffKey(srcDiffKeyName);
  2131. if (destDiffKeyName&&*destDiffKeyName)
  2132. wuFSpecDest->setDiffKey(destDiffKeyName);
  2133. wuFSpecDest->setDirectory(destFolder.str());
  2134. wuFSpecDest->setGroupName(destCluster.str());
  2135. wuFSpecDest->setWrap(req.getWrap());
  2136. const char * encryptkey = req.getEncrypt();
  2137. if(req.getCompress()||(encryptkey&&*encryptkey))
  2138. wuFSpecDest->setCompressed(true);
  2139. wuOptions->setReplicate(req.getReplicate());
  2140. const char * decryptkey = req.getDecrypt();
  2141. if ((encryptkey&&*encryptkey)||(decryptkey&&*decryptkey))
  2142. wuOptions->setEncDec(encryptkey,decryptkey);
  2143. if(req.getNorecover())
  2144. wuOptions->setNoRecover(true);
  2145. if(!req.getNosplit_isNull())
  2146. wuOptions->setNoSplit(req.getNosplit());
  2147. if(req.getMaxConnections() > 0)
  2148. wuOptions->setmaxConnections(req.getMaxConnections());
  2149. if(req.getThrottle() > 0)
  2150. wuOptions->setThrottle(req.getThrottle());
  2151. if(req.getTransferBufferSize() > 0)
  2152. wuOptions->setTransferBufferSize(req.getTransferBufferSize());
  2153. if (req.getPull())
  2154. wuOptions->setPull(true);
  2155. if (req.getPush())
  2156. wuOptions->setPush(true);
  2157. if (req.getIfnewer())
  2158. wuOptions->setIfNewer(true);
  2159. ClusterPartDiskMapSpec mspec;
  2160. wuFSpecDest->getClusterPartDiskMapSpec(destCluster.str(), mspec);
  2161. mspec.setDefaultBaseDir(defaultFolder.str());
  2162. mspec.setDefaultReplicateDir(defaultReplicateFolder.str());
  2163. wuFSpecDest->setClusterPartDiskMapSpec(destCluster.str(), mspec);
  2164. }
  2165. resp.setResult(wu->queryId());
  2166. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2167. submitDFUWorkUnit(wu.getClear());
  2168. }
  2169. catch(IException* e)
  2170. {
  2171. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2172. }
  2173. return true;
  2174. }
  2175. bool CFileSprayEx::onRename(IEspContext &context, IEspRename &req, IEspRenameResponse &resp)
  2176. {
  2177. try
  2178. {
  2179. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Write, false))
  2180. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do Rename. Permission denied.");
  2181. const char* srcname = req.getSrcname();
  2182. const char* dstname = req.getDstname();
  2183. if(!srcname || !*srcname)
  2184. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Source logical file not specified.");
  2185. if(!dstname || !*dstname)
  2186. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Destination logical file not specified.");
  2187. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2188. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2189. StringBuffer destTitle;
  2190. ParseLogicalPath(req.getDstname(), destTitle);
  2191. wu->setJobName(destTitle.str());
  2192. wu->setQueue(m_QueueLabel.str());
  2193. StringBuffer user, passwd;
  2194. wu->setUser(context.getUserID(user).str());
  2195. wu->setPassword(context.getPassword(passwd).str());
  2196. wu->setCommand(DFUcmd_rename);
  2197. #if 0 // TBD - Handling for multiple clusters? the cluster should be specified by user if needed
  2198. Owned<IUserDescriptor> udesc;
  2199. if(user.length() > 0)
  2200. {
  2201. const char* passwd = context.queryPassword();
  2202. udesc.setown(createUserDescriptor());
  2203. udesc->set(user.str(), passwd);
  2204. Owned<IDistributedFile> df = queryDistributedFileDirectory().lookup(srcname, udesc);
  2205. if(df)
  2206. {
  2207. StringBuffer cluster0;
  2208. df->getClusterName(0,cluster0); // TBD - Handling for multiple clusters?
  2209. if (cluster0.length()!=0)
  2210. {
  2211. wu->setClusterName(cluster0.str());
  2212. }
  2213. else
  2214. {
  2215. const char *cluster = df->queryAttributes().queryProp("@group");
  2216. if (cluster && *cluster)
  2217. {
  2218. wu->setClusterName(cluster);
  2219. }
  2220. }
  2221. }
  2222. }
  2223. #endif
  2224. IDFUfileSpec *source = wu->queryUpdateSource();
  2225. source->setLogicalName(srcname);
  2226. IDFUfileSpec *destination = wu->queryUpdateDestination();
  2227. destination->setLogicalName(dstname);
  2228. IDFUoptions *options = wu->queryUpdateOptions();
  2229. options->setOverwrite(req.getOverwrite());
  2230. resp.setWuid(wu->queryId());
  2231. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2232. submitDFUWorkUnit(wu.getClear());
  2233. }
  2234. catch(IException* e)
  2235. {
  2236. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2237. }
  2238. return true;
  2239. }
  2240. bool CFileSprayEx::onDFUWUFile(IEspContext &context, IEspDFUWUFileRequest &req, IEspDFUWUFileResponse &resp)
  2241. {
  2242. try
  2243. {
  2244. if (!context.validateFeatureAccess(DFU_WU_URL, SecAccess_Read, false))
  2245. throw MakeStringException(ECLWATCH_DFU_WU_ACCESS_DENIED, "Access to DFU workunit is denied.");
  2246. if (*req.getWuid())
  2247. {
  2248. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2249. Owned<IConstDFUWorkUnit> wu = factory->openWorkUnit(req.getWuid(), false);
  2250. if(!wu)
  2251. throw MakeStringException(ECLWATCH_CANNOT_OPEN_WORKUNIT, "Dfu workunit %s not found.", req.getWuid());
  2252. StringBuffer xmlbuf;
  2253. xmlbuf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  2254. const char* plainText = req.getPlainText();
  2255. if (plainText && (!stricmp(plainText, "yes")))
  2256. {
  2257. wu->toXML(xmlbuf);
  2258. resp.setFile(xmlbuf.str());
  2259. resp.setFile_mimetype(HTTP_TYPE_TEXT_PLAIN);
  2260. }
  2261. else
  2262. {
  2263. xmlbuf.append("<?xml-stylesheet href=\"../esp/xslt/xmlformatter.xsl\" type=\"text/xsl\"?>");
  2264. wu->toXML(xmlbuf);
  2265. resp.setFile(xmlbuf.str());
  2266. resp.setFile_mimetype(HTTP_TYPE_APPLICATION_XML);
  2267. }
  2268. }
  2269. }
  2270. catch(IException* e)
  2271. {
  2272. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2273. }
  2274. return true;
  2275. }
  2276. int CFileSprayEx::doFileCheck(const char* mask, const char* netaddr, const char* osStr, const char* path)
  2277. {
  2278. int iRet = 1;
  2279. if (mask && *mask)
  2280. {
  2281. char *str = (char *) mask + strlen(mask) - 4;
  2282. if (!stricmp(str, ".cfg") || !stricmp(str, ".log"))
  2283. iRet = 0;
  2284. }
  2285. else if (netaddr && *netaddr && path && *path)
  2286. {
  2287. iRet = 2;
  2288. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2289. factory->validateCache();
  2290. Owned<IConstEnvironment> env = factory->openEnvironmentByFile();
  2291. Owned<IPropertyTree> pEnvRoot = &env->getPTree();
  2292. IPropertyTree* pEnvSoftware = pEnvRoot->queryPropTree("Software");
  2293. Owned<IPropertyTree> pRoot = createPTreeFromXMLString("<Environment/>");
  2294. IPropertyTree* pSoftware = pRoot->addPropTree("Software", createPTree("Software"));
  2295. if (pEnvSoftware && pSoftware)
  2296. {
  2297. Owned<IPropertyTreeIterator> it = pEnvSoftware->getElements("DropZone");
  2298. ForEach(*it)
  2299. {
  2300. const char* pszComputer = it->query().queryProp("@computer");
  2301. if (!strcmp(pszComputer, "."))
  2302. pszComputer = "localhost";
  2303. StringBuffer xpath, sNetAddr;
  2304. xpath.appendf("Hardware/Computer[@name='%s']/@netAddress", pszComputer);
  2305. const char* pszNetAddr = pEnvRoot->queryProp(xpath.str());
  2306. if (strcmp(pszNetAddr, "."))
  2307. {
  2308. sNetAddr.append(pszNetAddr);
  2309. }
  2310. else
  2311. {
  2312. StringBuffer ipStr;
  2313. IpAddress ipaddr = queryHostIP();
  2314. ipaddr.getIpText(ipStr);
  2315. if (ipStr.length() > 0)
  2316. {
  2317. #ifdef MACHINE_IP
  2318. sNetAddr.append(MACHINE_IP);
  2319. #else
  2320. sNetAddr.append(ipStr.str());
  2321. #endif
  2322. }
  2323. }
  2324. #ifdef MACHINE_IP
  2325. if ((sNetAddr.length() > 0) && !stricmp(sNetAddr.str(), MACHINE_IP))
  2326. #else
  2327. if ((sNetAddr.length() > 0) && !stricmp(sNetAddr.str(), netaddr))
  2328. #endif
  2329. {
  2330. StringBuffer dir;
  2331. IPropertyTree* pDropZone = pSoftware->addPropTree("DropZone", &it->get());
  2332. pDropZone->getProp("@directory", dir);
  2333. if (osStr && *osStr)
  2334. {
  2335. int os = atoi(osStr);
  2336. const char pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2337. dir.replace(pathSep=='\\'?'/':'\\', pathSep);
  2338. }
  2339. if ((dir.length() > 0) && !strnicmp(path, dir.str(), dir.length()))
  2340. {
  2341. iRet = 0;
  2342. break;
  2343. }
  2344. }
  2345. }
  2346. }
  2347. }
  2348. return iRet;
  2349. }
  2350. bool CFileSprayEx::onFileList(IEspContext &context, IEspFileListRequest &req, IEspFileListResponse &resp)
  2351. {
  2352. try
  2353. {
  2354. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2355. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do FileList. Permission denied.");
  2356. const char* path = req.getPath();
  2357. if (!path || !*path)
  2358. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Path not specified.");
  2359. const char* netaddr = req.getNetaddr();
  2360. const char* mask = req.getMask();
  2361. bool directoryOnly = req.getDirectoryOnly();
  2362. StringBuffer sPath(path);
  2363. const char* osStr = req.getOS();
  2364. if (osStr && *osStr)
  2365. {
  2366. int os = atoi(osStr);
  2367. const char pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2368. sPath.replace(pathSep=='\\'?'/':'\\', pathSep);
  2369. if (*(sPath.str() + sPath.length() -1) != pathSep)
  2370. sPath.append( pathSep );
  2371. }
  2372. int checkReturn = doFileCheck(mask, netaddr, osStr, sPath.str());
  2373. if (checkReturn > 1)
  2374. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2375. else if (checkReturn > 0)
  2376. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2377. RemoteFilename rfn;
  2378. SocketEndpoint ep;
  2379. #ifdef MACHINE_IP
  2380. ep.set(MACHINE_IP);
  2381. #else
  2382. ep.set(netaddr);
  2383. #endif
  2384. rfn.setPath(ep, sPath.str());
  2385. Owned<IFile> f = createIFile(rfn);
  2386. if(!f->isDirectory())
  2387. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2388. IArrayOf<IEspPhysicalFileStruct> files;
  2389. if (mask && !*mask)
  2390. mask = NULL;
  2391. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2392. if(di.get() != NULL)
  2393. {
  2394. ForEach(*di)
  2395. {
  2396. StringBuffer fname;
  2397. di->getName(fname);
  2398. if (fname.length() == 0 || (directoryOnly && !di->isDir()) || (!di->isDir() && mask && !WildMatch(fname.str(), mask, true)))
  2399. continue;
  2400. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2401. onefile->setName(fname.str());
  2402. onefile->setIsDir(di->isDir());
  2403. onefile->setFilesize(di->getFileSize());
  2404. CDateTime modtime;
  2405. StringBuffer timestr;
  2406. di->getModifiedTime(modtime);
  2407. unsigned y,m,d,h,min,sec,nsec;
  2408. modtime.getDate(y,m,d,true);
  2409. modtime.getTime(h,min,sec,nsec,true);
  2410. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2411. onefile->setModifiedtime(timestr.str());
  2412. files.append(*onefile.getLink());
  2413. }
  2414. }
  2415. sPath.replace('\\', '/');//XSLT cannot handle backslashes
  2416. resp.setPath(sPath);
  2417. resp.setFiles(files);
  2418. resp.setNetaddr(netaddr);
  2419. if (osStr && *osStr)
  2420. {
  2421. int os = atoi(osStr);
  2422. resp.setOS(os);
  2423. }
  2424. if (mask && *mask)
  2425. resp.setMask(mask);
  2426. resp.setDirectoryOnly(directoryOnly);
  2427. }
  2428. catch(IException* e)
  2429. {
  2430. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2431. }
  2432. return true;
  2433. }
  2434. bool CFileSprayEx::onDfuMonitor(IEspContext &context, IEspDfuMonitorRequest &req, IEspDfuMonitorResponse &resp)
  2435. {
  2436. try
  2437. {
  2438. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2439. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Failed to do DfuMonitor. Permission denied.");
  2440. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  2441. Owned<IDFUWorkUnit> wu = factory->createWorkUnit();
  2442. wu->setQueue(m_MonitorQueueLabel.str());
  2443. StringBuffer user, passwd;
  2444. wu->setUser(context.getUserID(user).str());
  2445. wu->setPassword(context.getPassword(passwd).str());
  2446. wu->setCommand(DFUcmd_monitor);
  2447. IDFUmonitor *monitor = wu->queryUpdateMonitor();
  2448. IDFUfileSpec *source = wu->queryUpdateSource();
  2449. const char *eventname = req.getEventName();
  2450. const char *lname = req.getLogicalName();
  2451. if (lname&&*lname)
  2452. source->setLogicalName(lname);
  2453. else {
  2454. const char *ip = req.getIp();
  2455. const char *filename = req.getFilename();
  2456. if (filename&&*filename) {
  2457. RemoteFilename rfn;
  2458. if (ip&&*ip) {
  2459. SocketEndpoint ep;
  2460. ep.set(ip);
  2461. rfn.setPath(ep,filename);
  2462. }
  2463. else
  2464. rfn.setRemotePath(filename);
  2465. source->setSingleFilename(rfn);
  2466. }
  2467. else
  2468. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Neither logical name nor network ip/file specified for monitor.");
  2469. }
  2470. if (eventname)
  2471. monitor->setEventName(eventname);
  2472. monitor->setShotLimit(req.getShotLimit());
  2473. monitor->setSub(req.getSub());
  2474. resp.setWuid(wu->queryId());
  2475. resp.setRedirectUrl(StringBuffer("/FileSpray/GetDFUWorkunit?wuid=").append(wu->queryId()).str());
  2476. submitDFUWorkUnit(wu.getClear());
  2477. }
  2478. catch(IException* e)
  2479. {
  2480. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2481. }
  2482. return true;
  2483. }
  2484. bool CFileSprayEx::onOpenSave(IEspContext &context, IEspOpenSaveRequest &req, IEspOpenSaveResponse &resp)
  2485. {
  2486. try
  2487. {
  2488. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2489. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2490. const char* location = req.getLocation();
  2491. const char* path = req.getPath();
  2492. const char* name = req.getName();
  2493. const char* type = req.getType();
  2494. const char* dateTime = req.getDateTime();
  2495. if (location && *location)
  2496. resp.setLocation(location);
  2497. if (path && *path)
  2498. resp.setPath(path);
  2499. if (name && *name)
  2500. resp.setName(name);
  2501. if (type && *type)
  2502. resp.setType(type);
  2503. if (dateTime && *dateTime)
  2504. resp.setDateTime(dateTime);
  2505. if (req.getBinaryFile())
  2506. resp.setViewable(false);
  2507. }
  2508. catch(IException* e)
  2509. {
  2510. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2511. }
  2512. return true;
  2513. }
  2514. bool CFileSprayEx::getDropZoneFiles(IEspContext &context, const char* netaddr, const char* osStr, const char* path,
  2515. IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2516. {
  2517. bool directoryOnly = req.getDirectoryOnly();
  2518. int checkReturn = doFileCheck(NULL, netaddr, osStr, path);
  2519. if (checkReturn > 1)
  2520. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2521. else if (checkReturn > 0)
  2522. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2523. RemoteFilename rfn;
  2524. SocketEndpoint ep;
  2525. #ifdef MACHINE_IP
  2526. ep.set(MACHINE_IP);
  2527. #else
  2528. ep.set(netaddr);
  2529. #endif
  2530. rfn.setPath(ep, path);
  2531. Owned<IFile> f = createIFile(rfn);
  2532. if(!f->isDirectory())
  2533. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", path);
  2534. IArrayOf<IEspPhysicalFileStruct> files;
  2535. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  2536. if(di.get() != NULL)
  2537. {
  2538. ForEach(*di)
  2539. {
  2540. StringBuffer fname;
  2541. di->getName(fname);
  2542. if (fname.length() == 0 || (directoryOnly && !di->isDir()))
  2543. continue;
  2544. Owned<IEspPhysicalFileStruct> onefile = createPhysicalFileStruct();
  2545. onefile->setName(fname.str());
  2546. onefile->setIsDir(di->isDir());
  2547. onefile->setFilesize(di->getFileSize());
  2548. CDateTime modtime;
  2549. StringBuffer timestr;
  2550. di->getModifiedTime(modtime);
  2551. unsigned y,m,d,h,min,sec,nsec;
  2552. modtime.getDate(y,m,d,true);
  2553. modtime.getTime(h,min,sec,nsec,true);
  2554. timestr.appendf("%04d-%02d-%02d %02d:%02d:%02d", y,m,d,h,min,sec);
  2555. onefile->setModifiedtime(timestr.str());
  2556. files.append(*onefile.getLink());
  2557. }
  2558. }
  2559. resp.setFiles(files);
  2560. return true;
  2561. }
  2562. bool CFileSprayEx::onDropZoneFiles(IEspContext &context, IEspDropZoneFilesRequest &req, IEspDropZoneFilesResponse &resp)
  2563. {
  2564. try
  2565. {
  2566. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Read, false))
  2567. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2568. const char* netAddress = req.getNetAddress();
  2569. const char* directory = req.getPath();
  2570. const char* subfolder = req.getSubfolder();
  2571. StringBuffer netAddressStr, directoryStr, osStr;
  2572. if (netAddress && *netAddress && directory && *directory)
  2573. {
  2574. netAddressStr.append(netAddress);
  2575. directoryStr.append(directory);
  2576. }
  2577. IArrayOf<IEspDropZone> dropZoneList;
  2578. Owned<IEnvironmentFactory> factory = getEnvironmentFactory();
  2579. Owned<IConstEnvironment> m_constEnv = factory->openEnvironmentByFile();
  2580. Owned<IPropertyTree> pEnvRoot = &m_constEnv->getPTree();
  2581. IPropertyTree* pEnvSoftware = pEnvRoot->queryPropTree("Software");
  2582. if (pEnvSoftware)
  2583. {
  2584. Owned<IPropertyTreeIterator> it = pEnvSoftware->getElements("DropZone");
  2585. ForEach(*it)
  2586. {
  2587. IPropertyTree& pDropZone = it->query();
  2588. //get IP Address of the computer associated with this drop zone
  2589. const char* pszName = pDropZone.queryProp("@name");
  2590. const char* pszComputer = pDropZone.queryProp("@computer");
  2591. if (!strcmp(pszComputer, "."))
  2592. pszComputer = "localhost";
  2593. StringBuffer xpath;
  2594. xpath.appendf("Hardware/Computer[@name='%s']/@netAddress", pszComputer);
  2595. StringBuffer sNetAddr;
  2596. const char* pszNetAddr = pEnvRoot->queryProp(xpath.str());
  2597. if (strcmp(pszNetAddr, "."))
  2598. {
  2599. sNetAddr.append(pszNetAddr);
  2600. }
  2601. else
  2602. {
  2603. StringBuffer ipStr;
  2604. IpAddress ipaddr = queryHostIP();
  2605. ipaddr.getIpText(ipStr);
  2606. if (ipStr.length() > 0)
  2607. {
  2608. #ifdef MACHINE_IP
  2609. sNetAddr.append(MACHINE_IP);
  2610. #else
  2611. sNetAddr.append(ipStr.str());
  2612. #endif
  2613. }
  2614. }
  2615. Owned<IConstMachineInfo> machine;
  2616. if (strcmp(pszNetAddr, "."))
  2617. machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
  2618. else
  2619. {
  2620. machine.setown(m_constEnv->getMachineByAddress(pszNetAddr));
  2621. if (!machine)
  2622. machine.setown(m_constEnv->getMachineByAddress(sNetAddr.str()));
  2623. }
  2624. StringBuffer dir;
  2625. pDropZone.getProp("@directory", dir);
  2626. Owned<IEspDropZone> aDropZone= createDropZone("","");
  2627. if (machine)
  2628. {
  2629. if (machine->getOS() == MachineOsLinux || machine->getOS() == MachineOsSolaris)
  2630. {
  2631. dir.replace('\\', '/');//replace all '\\' by '/'
  2632. aDropZone->setLinux("true");
  2633. osStr = "1";
  2634. }
  2635. else
  2636. {
  2637. dir.replace('/', '\\');
  2638. dir.replace('$', ':');
  2639. osStr = "0";
  2640. }
  2641. }
  2642. aDropZone->setComputer(pszComputer);
  2643. aDropZone->setPath(dir.str());
  2644. aDropZone->setName(pszName);
  2645. aDropZone->setNetAddress(sNetAddr.str());
  2646. if (netAddressStr.length() < 1)
  2647. {
  2648. netAddressStr = sNetAddr;
  2649. directoryStr = dir;
  2650. }
  2651. dropZoneList.append(*aDropZone.getClear());
  2652. }
  2653. }
  2654. if (dropZoneList.ordinality())
  2655. resp.setDropZones(dropZoneList);
  2656. char pathSep = '/';
  2657. if (osStr && *osStr)
  2658. {
  2659. int os = atoi(osStr);
  2660. if (os == OS_WINDOWS)
  2661. pathSep = '\\';
  2662. }
  2663. directoryStr.replace(pathSep=='\\'?'/':'\\', pathSep);
  2664. if (subfolder && *subfolder)
  2665. {
  2666. if (*(directoryStr.str() + directoryStr.length() -1) != pathSep)
  2667. directoryStr.append( pathSep );
  2668. directoryStr.append(subfolder);
  2669. }
  2670. if (*(directoryStr.str() + directoryStr.length() -1) != pathSep)
  2671. directoryStr.append( pathSep );
  2672. getDropZoneFiles(context, netAddressStr.str(), osStr.str(), directoryStr.str(), req, resp);
  2673. if (pathSep=='\\')
  2674. directoryStr.replaceString("\\", "\\\\");
  2675. resp.setNetAddress(netAddressStr.str());
  2676. resp.setPath(directoryStr.str());
  2677. resp.setOS(atoi(osStr.str()));
  2678. }
  2679. catch(IException* e)
  2680. {
  2681. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2682. }
  2683. return true;
  2684. }
  2685. bool CFileSprayEx::onDeleteDropZoneFiles(IEspContext &context, IEspDeleteDropZoneFilesRequest &req, IEspDFUWorkunitsActionResponse &resp)
  2686. {
  2687. try
  2688. {
  2689. if (!context.validateFeatureAccess(FILE_SPRAY_URL, SecAccess_Full, false))
  2690. throw MakeStringException(ECLWATCH_FILE_SPRAY_ACCESS_DENIED, "Permission denied.");
  2691. const char* netAddress = req.getNetAddress();
  2692. const char* directory = req.getPath();
  2693. const char* osStr = req.getOS();
  2694. StringArray & files = req.getNames();
  2695. if (!netAddress || !*netAddress || !directory || !*directory)
  2696. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone not specified.");
  2697. if (!files.ordinality())
  2698. throw MakeStringException(ECLWATCH_INVALID_INPUT, "File not specified.");
  2699. char pathSep = '/';
  2700. StringBuffer sPath(directory);
  2701. if (osStr && *osStr)
  2702. {
  2703. int os = atoi(osStr);
  2704. pathSep = (os == OS_WINDOWS) ? '\\' : '/';
  2705. sPath.replace(pathSep=='\\'?'/':'\\', pathSep);
  2706. if (*(sPath.str() + sPath.length() -1) != pathSep)
  2707. sPath.append( pathSep );
  2708. }
  2709. int checkReturn = doFileCheck(NULL, netAddress, osStr, sPath.str());
  2710. if (checkReturn > 1)
  2711. throw MakeStringException(ECLWATCH_DROP_ZONE_NOT_FOUND, "Dropzone is not found in the environment settings.");
  2712. else if (checkReturn > 0)
  2713. throw MakeStringException(ECLWATCH_ACCESS_TO_FILE_DENIED, "Access to the file path denied.");
  2714. RemoteFilename rfn;
  2715. SocketEndpoint ep;
  2716. #ifdef MACHINE_IP
  2717. ep.set(MACHINE_IP);
  2718. #else
  2719. ep.set(netAddress);
  2720. #endif
  2721. rfn.setPath(ep, sPath.str());
  2722. Owned<IFile> f = createIFile(rfn);
  2723. if(!f->isDirectory())
  2724. throw MakeStringException(ECLWATCH_INVALID_DIRECTORY, "%s is not a directory.", directory);
  2725. bool bAllSuccess = true;
  2726. IArrayOf<IEspDFUActionResult> results;
  2727. for(unsigned i = 0; i < files.ordinality(); ++i)
  2728. {
  2729. const char* file = files.item(i);
  2730. if (!file || !*file)
  2731. continue;
  2732. Owned<IEspDFUActionResult> res = createDFUActionResult("", "");
  2733. res->setID(files.item(i));
  2734. res->setAction("Delete");
  2735. res->setResult("Success");
  2736. try
  2737. {
  2738. StringBuffer fileToDelete = sPath;
  2739. if (*(fileToDelete.str() + fileToDelete.length() -1) != pathSep)
  2740. fileToDelete.append( pathSep );
  2741. fileToDelete.append(file);
  2742. rfn.setPath(ep, fileToDelete.str());
  2743. Owned<IFile> rFile = createIFile(rfn);
  2744. if (!rFile->exists())
  2745. res->setResult("Warning: this file does not exist.");
  2746. else
  2747. rFile->remove();
  2748. }
  2749. catch (IException *e)
  2750. {
  2751. bAllSuccess = false;
  2752. StringBuffer eMsg;
  2753. eMsg = e->errorMessage(eMsg);
  2754. e->Release();
  2755. StringBuffer failedMsg = "Failed: ";
  2756. failedMsg.append(eMsg);
  2757. res->setResult(failedMsg.str());
  2758. }
  2759. results.append(*res.getLink());
  2760. }
  2761. resp.setFirstColumn("File");
  2762. resp.setDFUActionResults(results);
  2763. }
  2764. catch(IException* e)
  2765. {
  2766. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2767. }
  2768. return true;
  2769. }