ws_fsService.cpp 125 KB

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