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