ws_fsService.cpp 113 KB

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