ws_fsService.cpp 127 KB

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