ws_fsService.cpp 112 KB

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