ws_fsService.cpp 113 KB

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