ws_fsService.cpp 114 KB

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