ws_fsService.cpp 124 KB

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