ws_fsService.cpp 118 KB

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