ws_machineService.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  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. #include "ws_machineService.hpp"
  14. #include "jarray.hpp"
  15. #include "dadfs.hpp"
  16. #include "exception_util.hpp"
  17. #include "workunit.hpp"
  18. #include "roxiecommlib.hpp"
  19. #include "componentstatus.hpp"
  20. #include "rmtssh.hpp"
  21. #include "platform.h"
  22. #ifndef eqHoleCluster
  23. #define eqHoleCluster "HoleCluster"
  24. #endif
  25. #ifndef eqThorCluster
  26. #define eqThorCluster "ThorCluster"
  27. #endif
  28. #ifndef eqRoxieCluster
  29. #define eqRoxieCluster "RoxieCluster"
  30. #endif
  31. #ifndef eqEclCCServer
  32. #define eqEclCCServer "EclCCServerProcess"
  33. #endif
  34. #ifndef eqEclServer
  35. #define eqEclServer "EclServerProcess"
  36. #endif
  37. #ifndef eqEclAgent
  38. #define eqEclAgent "EclAgentProcess"
  39. #endif
  40. #ifndef eqAgentExec
  41. #define eqAgentExec "AgentExecProcess"
  42. #endif
  43. #ifndef eqEclScheduler
  44. #define eqEclScheduler "EclSchedulerProcess"
  45. #endif
  46. #ifndef eqThorMasterProcess
  47. #define eqThorMasterProcess "ThorMasterProcess"
  48. #endif
  49. #ifndef eqThorSlaveProcess
  50. #define eqThorSlaveProcess "ThorSlaveProcess"
  51. #endif
  52. #ifndef eqThorSpareProcess
  53. #define eqThorSpareProcess "ThorSpareProcess"
  54. #endif
  55. #ifndef eqRoxieServerProcess
  56. #define eqRoxieServerProcess "RoxieServerProcess"
  57. #endif
  58. static const int THREAD_POOL_SIZE = 40;
  59. static const int THREAD_POOL_STACK_SIZE = 64000;
  60. static const char* FEATURE_URL = "MachineInfoAccess";
  61. const unsigned ROXIECONTROLSTATETIMEOUT = 5000; //5 second
  62. class CMachineInfoThreadParam : public CWsMachineThreadParam
  63. {
  64. public:
  65. IMPLEMENT_IINTERFACE;
  66. IEspContext& m_context;
  67. CGetMachineInfoUserOptions& m_options; //From request
  68. CMachineData& m_machineData; //From request
  69. IArrayOf<IEspMachineInfoEx>& m_machineInfoTable; //For response
  70. StringArray& m_machineInfoColumns; //For response
  71. CMachineInfoThreadParam(Cws_machineEx* pService, IEspContext& context, CGetMachineInfoUserOptions& options,
  72. CMachineData& machineData, IArrayOf<IEspMachineInfoEx>& machineInfoTable, StringArray& machineInfoColumns )
  73. : CWsMachineThreadParam(NULL, NULL, NULL, pService),
  74. m_context(context),
  75. m_options(options),
  76. m_machineData(machineData),
  77. m_machineInfoTable(machineInfoTable),
  78. m_machineInfoColumns(machineInfoColumns)
  79. {
  80. }
  81. virtual void doWork()
  82. {
  83. m_pService->doGetMachineInfo(m_context, this);
  84. }
  85. void addColumn(const char* columnName)
  86. {
  87. synchronized block(s_mutex);
  88. if (m_machineInfoColumns.find(columnName) == NotFound)
  89. m_machineInfoColumns.append(columnName);
  90. }
  91. private:
  92. static Mutex s_mutex;
  93. };
  94. Mutex CMachineInfoThreadParam::s_mutex;
  95. class CRoxieStateInfoThreadParam : public CWsMachineThreadParam
  96. {
  97. public:
  98. StringAttr clusterName;
  99. IArrayOf<IEspMachineInfoEx>& machineInfoTable; //For response
  100. CRoxieStateInfoThreadParam(Cws_machineEx* pService, const char* _clusterName, IArrayOf<IEspMachineInfoEx>& _machineInfoTable)
  101. : CWsMachineThreadParam(pService), clusterName(_clusterName), machineInfoTable(_machineInfoTable)
  102. {
  103. }
  104. virtual void doWork()
  105. {
  106. m_pService->getRoxieStateInfo(this);
  107. }
  108. };
  109. void Cws_machineEx::init(IPropertyTree *cfg, const char *process, const char *service)
  110. {
  111. //Read settings from esp.xml
  112. StringBuffer xpath;
  113. xpath.appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]", process, service);
  114. Owned<IPropertyTree> pServiceNode = cfg->getPropTree(xpath.str());
  115. m_bMonitorDaliFileServer = pServiceNode->getPropBool("@monitorDaliFileServer", false);
  116. m_processFilters.setown( pServiceNode->getPropTree("ProcessFilters") );
  117. const char* pchExcludePartitions = pServiceNode->queryProp("@excludePartitions");
  118. if (pchExcludePartitions && *pchExcludePartitions)
  119. {
  120. StringArray sPartitions;
  121. sPartitions.appendList(pchExcludePartitions, ", ;");
  122. unsigned int numOfPartitions = sPartitions.ordinality();
  123. for (unsigned int i=0; i<numOfPartitions; i++)
  124. {
  125. const char* partition = sPartitions.item(i);
  126. if (!partition || !*partition)
  127. continue;
  128. if (strchr(partition, '*'))
  129. m_excludePartitionPatterns.insert( partition );
  130. else
  131. m_excludePartitions.insert( partition );
  132. }
  133. }
  134. m_useDefaultHPCCInit = pServiceNode->getPropBool("UseDefaultHPCCInit", true);//Still used by Rexec for now
  135. m_SSHConnectTimeoutSeconds = pServiceNode->getPropInt("SSHConnectTimeoutSeconds", 5);
  136. const char* machineInfoScript = pServiceNode->queryProp("MachineInfoFile");
  137. if (machineInfoScript && *machineInfoScript)
  138. m_machineInfoFile.append(machineInfoScript);
  139. else
  140. m_machineInfoFile.append("preflight");
  141. //Read settings from environment.xml
  142. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  143. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  144. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  145. Owned<IPropertyTree> pEnvSettings = pEnvironmentRoot->getPropTree("EnvSettings");
  146. if (pEnvSettings)
  147. {
  148. pEnvSettings->getProp("configs", environmentConfData.m_configsPath.clear());
  149. pEnvSettings->getProp("path", environmentConfData.m_executionPath.clear());
  150. pEnvSettings->getProp("runtime", environmentConfData.m_runtimePath.clear());
  151. pEnvSettings->getProp("lock", environmentConfData.m_lockPath.clear());
  152. pEnvSettings->getProp("pid", environmentConfData.m_pidPath.clear());
  153. pEnvSettings->getProp("user", environmentConfData.m_user.clear());
  154. }
  155. m_threadPoolSize = pServiceNode->getPropInt("ThreadPoolSize", THREAD_POOL_SIZE);
  156. m_threadPoolStackSize = pServiceNode->getPropInt("ThreadPoolStackSize", THREAD_POOL_STACK_SIZE);
  157. //Start thread pool
  158. Owned<IThreadFactory> pThreadFactory = new CWsMachineThreadFactory();
  159. m_threadPool.setown(createThreadPool("WsMachine Thread Pool", pThreadFactory,
  160. NULL, m_threadPoolSize, 10000, m_threadPoolStackSize)); //10 sec timeout for available thread; use stack size of 2MB
  161. setupLegacyFilters();
  162. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  163. factory->init(pServiceNode);
  164. }
  165. StringBuffer& Cws_machineEx::getAcceptLanguage(IEspContext& context, StringBuffer& acceptLanguage)
  166. {
  167. context.getAcceptLanguage(acceptLanguage);
  168. if (!acceptLanguage.length())
  169. {
  170. acceptLanguage.set("en");
  171. return acceptLanguage;
  172. }
  173. acceptLanguage.setLength(2);
  174. VStringBuffer languageFile("%ssmc_xslt/nls/%s/hpcc.xml", getCFD(), acceptLanguage.str());
  175. if (!checkFileExists(languageFile.str()))
  176. acceptLanguage.set("en");
  177. return acceptLanguage;
  178. }
  179. bool Cws_machineEx::onGetMachineInfo(IEspContext &context, IEspGetMachineInfoRequest & req,
  180. IEspGetMachineInfoResponse & resp)
  181. {
  182. try
  183. {
  184. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  185. StringArray& addresses = req.getAddresses();
  186. if (addresses.empty())
  187. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  188. CGetMachineInfoData machineInfoData;
  189. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  190. req.getApplyProcessFilter(), addresses, req.getAddProcessesToFilter(), machineInfoData);
  191. getMachineInfo(context, machineInfoData);
  192. setMachineInfoResponse(context, req, machineInfoData, resp);
  193. }
  194. catch(IException* e)
  195. {
  196. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  197. }
  198. return true;
  199. }
  200. bool Cws_machineEx::onGetMachineInfoEx(IEspContext &context, IEspGetMachineInfoRequestEx & req, IEspGetMachineInfoResponseEx & resp)
  201. {
  202. try
  203. {
  204. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  205. StringArray& addresses = req.getAddresses();
  206. if (addresses.empty())
  207. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  208. double version = context.getClientVersion();
  209. CGetMachineInfoData machineInfoData;
  210. readMachineInfoRequest(context, true, true, true, true, true, addresses, NULL, machineInfoData);
  211. getMachineInfo(context, machineInfoData);
  212. if (machineInfoData.getMachineInfoTable().ordinality())
  213. resp.setMachines(machineInfoData.getMachineInfoTable());
  214. if (version >= 1.12)
  215. {
  216. StringBuffer acceptLanguage;
  217. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  218. }
  219. }
  220. catch(IException* e)
  221. {
  222. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  223. }
  224. return true;
  225. }
  226. bool Cws_machineEx::onGetTargetClusterInfo(IEspContext &context, IEspGetTargetClusterInfoRequest & req,
  227. IEspGetTargetClusterInfoResponse & resp)
  228. {
  229. try
  230. {
  231. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Target Cluster Information. Permission denied.");
  232. StringArray& targetClusters = req.getTargetClusters();
  233. if (targetClusters.empty())
  234. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No target cluster specified.");
  235. CGetMachineInfoData machineInfoData;
  236. Owned<IPropertyTree> targetClustersOut = createPTreeFromXMLString("<Root/>");
  237. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  238. req.getApplyProcessFilter(), req.getAddProcessesToFilter(), targetClusters, machineInfoData, targetClustersOut);
  239. getMachineInfo(context, machineInfoData);
  240. setTargetClusterInfoResponse(context, req, machineInfoData, targetClustersOut, resp);
  241. }
  242. catch(IException* e)
  243. {
  244. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  245. }
  246. return true;
  247. }
  248. ////////////////////////////////////////////////////////////////////////////////////////
  249. // Read Machine Infomation request and collect related settings from environment.xml //
  250. ////////////////////////////////////////////////////////////////////////////////////////
  251. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  252. StringArray& processes, const char* addProcessesToFilters, CGetMachineInfoData& machineInfoData)
  253. {
  254. StringBuffer userID, password;
  255. context.getUserID(userID);
  256. context.getPassword(password);
  257. machineInfoData.getOptions().setUserName(userID.str());
  258. machineInfoData.getOptions().setPassword(password.str());
  259. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  260. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  261. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  262. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  263. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  264. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  265. BoolHash uniqueProcesses;
  266. for (unsigned i=0; i<processes.ordinality(); i++)
  267. {
  268. StringArray address;
  269. address.appendList(processes.item(i), ":");
  270. StringBuffer address1, address2, processType, compName, path;
  271. unsigned processNumber = 0;
  272. if (!machineInfoData.getOptions().getGetSoftwareInfo())
  273. {
  274. parseAddresses(address.item(0), address1, address2);
  275. }
  276. else
  277. {
  278. if (address.ordinality() < 5)
  279. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Invalid address format in '%s'.", processes.item(i));
  280. parseProcessString(address, address1, address2, processType, compName, path, processNumber);
  281. }
  282. setProcessRequest(machineInfoData, uniqueProcesses, address1.str(), address2.str(), processType.str(), compName.str(), path.str(), processNumber);
  283. if (strieq(processType.str(), eqRoxieServerProcess))
  284. machineInfoData.appendRoxieClusters(compName.str());
  285. }
  286. }
  287. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  288. const char* addProcessesToFilters, StringArray& targetClustersIn, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClusterTreeOut)
  289. {
  290. StringBuffer userID, password;
  291. context.getUserID(userID);
  292. context.getPassword(password);
  293. machineInfoData.getOptions().setUserName(userID.str());
  294. machineInfoData.getOptions().setPassword(password.str());
  295. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  296. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  297. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  298. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  299. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  300. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  301. readSettingsForTargetClusters(context, targetClustersIn, machineInfoData, targetClusterTreeOut);
  302. }
  303. //Parses address request from machine information request in the form "192.168.1.4-6|."
  304. //The second address is the address retrieved from environment setting (could be a '.').
  305. void Cws_machineEx::parseAddresses(const char *address, StringBuffer& address1, StringBuffer& address2)
  306. {
  307. address1 = address;
  308. address2.clear();
  309. const char* props1 = strchr(address, '|');
  310. if (props1)
  311. {
  312. address2 = props1+1;
  313. address1.setLength(props1 - address);
  314. }
  315. address1.trim();
  316. address2.trim();
  317. }
  318. //Parses machine information request for each process in the form "192.168.1.4-6|.:ThorSlaveProcess:thor1:2:/var/lib/..."
  319. void Cws_machineEx::parseProcessString(StringArray& process, StringBuffer& address1, StringBuffer& address2,
  320. StringBuffer& processType, StringBuffer& compName, StringBuffer& path, unsigned& processNumber)
  321. {
  322. parseAddresses(process.item(0), address1, address2);
  323. processType.clear().append( process.item(1) ).trim();
  324. compName.clear().append( process.item(2) ).trim();
  325. EnvMachineOS os = (EnvMachineOS) atoi( process.item(3) );
  326. path.clear().append( process.item(4) ).trim();
  327. if (path.length())
  328. {
  329. char pat1, pat2;
  330. char rep1, rep2;
  331. if (os == MachineOsLinux)
  332. {
  333. pat1 = ':'; rep1 = '$';
  334. pat2 = '\\';rep2 = '/';
  335. }
  336. else
  337. {
  338. pat1 = '$'; rep1 = ':';
  339. pat2 = '/';rep2 = '\\';
  340. }
  341. path.replace( pat1, rep1 );
  342. path.replace( pat2, rep2 );
  343. if ((os == MachineOsLinux) && (path.charAt(0) != '/'))
  344. path.insert(0, '/');
  345. }
  346. if (process.ordinality() < 6)
  347. return;
  348. processNumber = atoi( process.item(5) );
  349. }
  350. void Cws_machineEx::setProcessRequest(CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses, const char* address1, const char* address2,
  351. const char* processType, const char* compName, const char* path, unsigned processNumber)
  352. {
  353. IpAddress ipAddr;
  354. unsigned numIps = ipAddr.ipsetrange(address1);
  355. //address is like 192.168.1.4-6
  356. //so process each address in the range
  357. if (!ipAddr.isIp4())
  358. IPV6_NOT_IMPLEMENTED();
  359. //Always use "EclAgentProcess" to retrieve machine info for "AgentExecProcess"
  360. StringBuffer processTypeStr;
  361. if (processType && *processType)
  362. {
  363. if (strieq(processType, eqAgentExec))
  364. processTypeStr.append(eqEclAgent);
  365. else
  366. processTypeStr = processType;
  367. }
  368. while (numIps--)
  369. {
  370. unsigned numAddr;
  371. if (ipAddr.getNetAddress(sizeof(numAddr),&numAddr)!=sizeof(numAddr))
  372. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid network address.");
  373. ipAddr.ipincrement(1);
  374. //Clean possible duplication
  375. StringBuffer valuesToBeChecked;
  376. valuesToBeChecked.append(numAddr);
  377. if (machineInfoData.getOptions().getGetSoftwareInfo())
  378. valuesToBeChecked.appendf(":%s:%s:%d", processTypeStr.str(), compName, processNumber);
  379. bool* found = uniqueProcesses.getValue(valuesToBeChecked.str());
  380. if (found && *found)
  381. continue;
  382. uniqueProcesses.setValue(valuesToBeChecked.str(), true);
  383. addProcessRequestToMachineInfoData(machineInfoData, address1, address2, processTypeStr.str(), compName, path, processNumber);
  384. }
  385. }
  386. void Cws_machineEx::addProcessRequestToMachineInfoData(CGetMachineInfoData& machineInfoData, const char* address1, const char* address2,
  387. const char* processType, const char* compName, const char* path, unsigned processNumber)
  388. {
  389. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  390. ForEachItemIn(idx, machines)
  391. {
  392. CMachineData& machine = machines.item(idx);
  393. if (streq(address1, machine.getNetworkAddress()))
  394. {
  395. addProcessData(&machine, processType, compName, path, processNumber);
  396. return;
  397. }
  398. }
  399. char pathSep;
  400. EnvMachineOS os;
  401. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  402. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(address1);
  403. if (pMachineInfo.get())
  404. os = pMachineInfo->getOS();
  405. else
  406. os = MachineOsUnknown;
  407. if (os == MachineOsW2K)
  408. pathSep = '\\';
  409. else
  410. pathSep = '/';
  411. Owned<CMachineData> machineNew = new CMachineData(address1, address2, os, pathSep);
  412. //Read possible dependencies for all processes
  413. set<string>& dependenciesForAllProcesses = machineNew->getDependencies();
  414. StringBuffer xPath;
  415. xPath.appendf("Platform[@name='%s']/ProcessFilter[@name='any']/Process", machineNew->getOS() == MachineOsW2K ? "Windows" : "Linux");
  416. Owned<IPropertyTreeIterator> processes = m_processFilters->getElements(xPath.str());
  417. ForEach (*processes)
  418. {
  419. StringBuffer processName;
  420. processes->query().getProp("@name", processName);
  421. processName.toLowerCase().replaceString(".exe", "");
  422. if ((processName.length() > 0) && (!streq(processName.str(), "hoagentd"))) //hoagentd is not needed anymore
  423. dependenciesForAllProcesses.insert(processName.str());
  424. }
  425. if (m_bMonitorDaliFileServer && (dependenciesForAllProcesses.find("dafilesrv") == dependenciesForAllProcesses.end()))
  426. dependenciesForAllProcesses.insert("dafilesrv");
  427. addProcessData(machineNew, processType, compName, path, processNumber);
  428. machines.append(*machineNew.getClear());
  429. }
  430. //Create a CProcessData object and add it to CMachineData
  431. void Cws_machineEx::addProcessData(CMachineData* machine, const char* processType, const char* compName,
  432. const char* path, unsigned processNumber)
  433. {
  434. if (!machine)
  435. return;
  436. StringBuffer pathStr = path;
  437. if (pathStr.length() > 0)
  438. {
  439. char pathSep = machine->getPathSep();
  440. if (pathStr.charAt(pathStr.length() - 1) != pathSep)
  441. pathStr.append(pathSep);
  442. }
  443. Owned<CProcessData> process = new CProcessData(compName, processType, pathStr.str(), processNumber);
  444. //Copy dependencies for all processes
  445. set<string>& dependenciesForThisProcess = process->getDependencies();
  446. set<string>& dependenciesForAllProcesses = machine->getDependencies();
  447. set<string>::const_iterator it = dependenciesForAllProcesses.begin();
  448. set<string>::const_iterator iEnd = dependenciesForAllProcesses.end();
  449. for (; it != iEnd; it++) //add in sorted order simply by traversing the map
  450. dependenciesForThisProcess.insert((*it).c_str());
  451. //now collect "process-specific" dependencies
  452. StringBuffer xPath;
  453. xPath.appendf("Platform[@name='%s']/ProcessFilter[@name='%s']", machine->getOS() == MachineOsW2K ? "Windows" : "Linux", processType);
  454. IPropertyTree* processFilterNode = m_processFilters->queryPropTree( xPath.str() );
  455. if (!processFilterNode)
  456. {
  457. machine->getProcesses().append(*process.getClear());
  458. return;
  459. }
  460. Owned<IPropertyTreeIterator> processes = processFilterNode->getElements("Process");
  461. ForEach (*processes)
  462. {
  463. IPropertyTree* pProcess = &processes->query();
  464. const char* name = pProcess->queryProp("@name");
  465. if (!name || streq(name, "."))
  466. continue;
  467. StringBuffer processName = name;
  468. processName.toLowerCase().replaceString(".exe", "");
  469. if (processName.length() < 1)
  470. continue;
  471. //Environment.xml may contain old filter settings.
  472. if (isLegacyFilter(processType, processName.str()))
  473. continue;
  474. if (pProcess->getPropBool("@remove", false))
  475. dependenciesForThisProcess.erase(processName.str());
  476. else
  477. dependenciesForThisProcess.insert(processName.str());
  478. }
  479. process->setMultipleInstances(machine->getOS() == MachineOsLinux && processFilterNode->getPropBool("@multipleInstances", false));
  480. machine->getProcesses().append(*process.getClear());
  481. }
  482. //Collect process settings for the requested target clusters
  483. void Cws_machineEx::readSettingsForTargetClusters(IEspContext& context, StringArray& targetClusters, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClustersOut)
  484. {
  485. unsigned ordinality= targetClusters.ordinality();
  486. if (ordinality < 1)
  487. return;
  488. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  489. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  490. if (!pEnvironmentRoot)
  491. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  492. BoolHash uniqueProcesses;
  493. for (unsigned index=0; index<ordinality; index++)
  494. {
  495. StringBuffer clusterType;
  496. const char* clusterName = targetClusters.item(index);
  497. const char* pClusterName = strchr(clusterName, ':');
  498. if (pClusterName)
  499. {
  500. clusterType.append(clusterName, 0, pClusterName - clusterName);
  501. pClusterName++;
  502. }
  503. if (!pClusterName || !*pClusterName)
  504. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name not specified.");
  505. if (clusterType.length() < 1)
  506. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster type not specified.");
  507. StringBuffer path;
  508. path.appendf("Software/Topology/Cluster[@name='%s']", pClusterName);
  509. IPropertyTree* pCluster = pEnvironmentRoot->queryPropTree(path.str());
  510. if (!pCluster)
  511. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", pClusterName);
  512. Owned<IPropertyTreeIterator> clusterProcesses;
  513. if (strieq(clusterType.str(), eqThorCluster) || strieq(clusterType.str(), eqRoxieCluster))
  514. {
  515. clusterProcesses.setown(pCluster->getElements(clusterType.str()));
  516. if (!clusterProcesses->first())
  517. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", clusterType.str());
  518. }
  519. Owned<IPropertyTreeIterator> eclCCServerProcesses= pCluster->getElements(eqEclCCServer);
  520. Owned<IPropertyTreeIterator> eclServerProcesses= pCluster->getElements(eqEclServer);
  521. Owned<IPropertyTreeIterator> eclAgentProcesses= pCluster->getElements(eqEclAgent);
  522. Owned<IPropertyTreeIterator> eclSchedulerProcesses= pCluster->getElements(eqEclScheduler);
  523. IPropertyTree *targetClusterOut = targetClustersOut->addPropTree("TargetCluster", createPTree("TargetCluster"));
  524. targetClusterOut->setProp("@Name", pClusterName);
  525. targetClusterOut->setProp("@Type", clusterType.str());
  526. //Read Cluster processes
  527. if (clusterProcesses && clusterProcesses->first())
  528. ForEach(*clusterProcesses)
  529. readTargetClusterProcesses(clusterProcesses->query(), clusterType.str(), uniqueProcesses, machineInfoData, targetClusterOut);
  530. //Read eclCCServer process
  531. if (eclCCServerProcesses->first())
  532. readTargetClusterProcesses(eclCCServerProcesses->query(), eqEclCCServer, uniqueProcesses, machineInfoData, targetClusterOut);
  533. //Read eclServer process
  534. if (eclServerProcesses->first())
  535. readTargetClusterProcesses(eclServerProcesses->query(), eqEclServer, uniqueProcesses, machineInfoData, targetClusterOut);
  536. //Read eclAgent process
  537. if (eclAgentProcesses->first())
  538. readTargetClusterProcesses(eclAgentProcesses->query(), eqEclAgent, uniqueProcesses, machineInfoData, targetClusterOut);
  539. //Read eclScheduler process
  540. if (eclSchedulerProcesses->first())
  541. readTargetClusterProcesses(eclSchedulerProcesses->query(), eqEclScheduler, uniqueProcesses, machineInfoData, targetClusterOut);
  542. }
  543. }
  544. //Collect settings for one group of target cluster processes
  545. void Cws_machineEx::readTargetClusterProcesses(IPropertyTree &processNode, const char* nodeType, BoolHash& uniqueProcesses, CGetMachineInfoData& machineInfoData,
  546. IPropertyTree* targetClustersOut)
  547. {
  548. const char* process = processNode.queryProp("@process");
  549. if (!process || !*process)
  550. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process attribute not set for ECLCCServer in environment setting.");
  551. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  552. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  553. if (!pEnvironmentRoot)
  554. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  555. IPropertyTree* pEnvironmentSoftware = pEnvironmentRoot->queryPropTree("Software");
  556. if (!pEnvironmentSoftware)
  557. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  558. IPropertyTree* pClusterProcess = NULL;
  559. if (strieq(nodeType, eqThorCluster) || strieq(nodeType, eqRoxieCluster))
  560. {
  561. StringBuffer path;
  562. path.appendf("Software/%s[@name='%s']", nodeType, process);
  563. pClusterProcess = pEnvironmentRoot->queryPropTree(path.str());
  564. if (!pClusterProcess)
  565. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process not set for %s in environment setting.", path.str());
  566. if (strieq(nodeType, eqRoxieCluster))
  567. machineInfoData.appendRoxieClusters(process);
  568. }
  569. IPropertyTree *pInfo = targetClustersOut->addPropTree("Process", createPTree("Process"));
  570. pInfo->setProp("@Name", process);
  571. pInfo->setProp("@Type", nodeType);
  572. StringBuffer dirStr;
  573. IPropertyTree* pEnvironmentDirectories = pEnvironmentSoftware->queryPropTree("Directories");
  574. if (!pClusterProcess)
  575. {
  576. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  577. dirStr.clear().append(processNode.queryProp("@directory"));
  578. getProcesses(constEnv, pEnvironmentSoftware, process, nodeType, dirStr.str(), machineInfoData, false, uniqueProcesses);
  579. return;
  580. }
  581. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  582. dirStr.clear().append(pClusterProcess->queryProp("@directory"));
  583. if (strieq(nodeType, eqThorCluster))
  584. {
  585. getProcesses(constEnv, pClusterProcess, process, eqThorMasterProcess, dirStr.str(), machineInfoData, true, uniqueProcesses);
  586. getThorProcesses(constEnv, pClusterProcess, process, eqThorSlaveProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  587. getThorProcesses(constEnv, pClusterProcess, process, eqThorSpareProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  588. }
  589. else if (strieq(nodeType, eqRoxieCluster))
  590. {
  591. BoolHash uniqueRoxieProcesses;
  592. getProcesses(constEnv, pClusterProcess, process, eqRoxieServerProcess, dirStr.str(), machineInfoData, true, uniqueProcesses, &uniqueRoxieProcesses);
  593. }
  594. }
  595. void Cws_machineEx::getThorProcesses(IConstEnvironment* constEnv, IPropertyTree* cluster, const char* processName,
  596. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses)
  597. {
  598. if (!constEnv || !cluster)
  599. return;
  600. StringBuffer groupName;
  601. if (strieq(processType, eqThorSlaveProcess))
  602. getClusterGroupName(*cluster, groupName);
  603. else if (strieq(processType, eqThorSpareProcess))
  604. getClusterSpareGroupName(*cluster, groupName);
  605. if (groupName.length() < 1)
  606. return;
  607. Owned<IGroup> nodeGroup = queryNamedGroupStore().lookup(groupName.str());
  608. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  609. return;
  610. unsigned processNumber = 0;
  611. Owned<INodeIterator> gi = nodeGroup->getIterator();
  612. ForEach(*gi)
  613. {
  614. StringBuffer addressRead;
  615. gi->query().endpoint().getIpText(addressRead);
  616. if (addressRead.length() == 0)
  617. {
  618. WARNLOG("Network address not found for a node in node group %s", groupName.str());
  619. continue;
  620. }
  621. processNumber++;
  622. StringBuffer netAddress;
  623. const char* ip = addressRead.str();
  624. if (!streq(ip, "."))
  625. {
  626. netAddress.append(ip);
  627. }
  628. else
  629. {
  630. IpAddress ipaddr = queryHostIP();
  631. ipaddr.getIpText(netAddress);
  632. }
  633. if (netAddress.length() == 0)
  634. {
  635. WARNLOG("Network address not found for a node in node group %s", groupName.str());
  636. continue;
  637. }
  638. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(addressRead.str());
  639. if (!pMachineInfo.get())
  640. {
  641. WARNLOG("Machine not found at network address %s", addressRead.str());
  642. continue;
  643. }
  644. setProcessRequest(machineInfoData, uniqueProcesses, netAddress.str(), addressRead.str(), processType, processName, directory, processNumber);
  645. }
  646. return;
  647. }
  648. void Cws_machineEx::getProcesses(IConstEnvironment* constEnv, IPropertyTree* environment, const char* processName,
  649. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData,
  650. bool isThorOrRoxieProcess, BoolHash& uniqueProcesses, BoolHash* uniqueRoxieProcesses)
  651. {
  652. Owned<IPropertyTreeIterator> processes= environment->getElements(processType);
  653. ForEach(*processes)
  654. {
  655. StringArray processInstances, directories;
  656. IPropertyTree &process = processes->query();
  657. //Thor master and roxie server has been checked before this call.
  658. if (!isThorOrRoxieProcess)
  659. {
  660. const char* name = process.queryProp("@name");
  661. if (!name || !*name || !streq(name, processName))
  662. continue;
  663. }
  664. const char* computerName = process.queryProp("@computer");
  665. if (computerName && *computerName)
  666. appendProcessInstance(computerName, directory, NULL, processInstances, directories);
  667. else
  668. {
  669. Owned<IPropertyTreeIterator> instances= process.getElements("Instance");
  670. ForEach(*instances)
  671. {
  672. IPropertyTree &instance = instances->query();
  673. appendProcessInstance(instance.queryProp("@computer"), directory, instance.queryProp("@directory"), processInstances, directories);
  674. }
  675. }
  676. if (processInstances.length() < 1)
  677. continue;
  678. for (unsigned i = 0; i < processInstances.length(); i++)
  679. {
  680. const char* name0 = processInstances.item(i);
  681. const char* directory0 = directories.item(i);
  682. if (uniqueRoxieProcesses)//to avoid duplicate entries for roxie (one machine has only one roxie process).
  683. {
  684. bool* found = uniqueRoxieProcesses->getValue(name0);
  685. if (found && *found)
  686. continue;
  687. uniqueRoxieProcesses->setValue(name0, true);
  688. }
  689. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachine(name0);
  690. if (!pMachineInfo.get())
  691. {
  692. WARNLOG("Machine %s not found in environment setting", name0);
  693. continue;
  694. }
  695. SCMStringBuffer ep;
  696. pMachineInfo->getNetAddress(ep);
  697. const char* ip = ep.str();
  698. if (!ip)
  699. {
  700. WARNLOG("Network address not found for machine %s", name0);
  701. continue;
  702. }
  703. StringBuffer netAddress, configNetAddress = ip;
  704. if (!streq(ip, "."))
  705. {
  706. netAddress.append(ip);
  707. }
  708. else
  709. {
  710. IpAddress ipaddr = queryHostIP();
  711. ipaddr.getIpText(netAddress);
  712. }
  713. setProcessRequest(machineInfoData, uniqueProcesses, netAddress.str(), configNetAddress.str(), processType, processName, directory0);
  714. }
  715. }
  716. return;
  717. }
  718. void Cws_machineEx::setupLegacyFilters()
  719. {
  720. unsigned idx = 0;
  721. while (legacyFilterStrings[idx])
  722. {
  723. m_legacyFilters.setValue(legacyFilterStrings[idx], true);
  724. idx++;
  725. }
  726. return;
  727. }
  728. bool Cws_machineEx::isLegacyFilter(const char* processType, const char* dependency)
  729. {
  730. if (!processType || !*processType || !dependency || !*dependency)
  731. return false;
  732. StringBuffer filterString;
  733. filterString.appendf("%s:%s", processType, dependency);
  734. bool* found = m_legacyFilters.getValue(filterString.str());
  735. if (found && *found)
  736. return true;
  737. return false;
  738. }
  739. //The stateHashes stores different state hashes in one roxie cluster.
  740. //It also stores how many roxie nodes have the same state hashes.
  741. unsigned Cws_machineEx::addRoxieStateHash(const char* hash, StateHashes& stateHashes, unsigned& totalUniqueHashes)
  742. {
  743. if (!hash || !*hash)
  744. return -1;
  745. unsigned hashID = 0;
  746. IStateHash* stateHash = stateHashes.getValue(hash);
  747. if (stateHash)
  748. {
  749. //if the stateHashes already has the same 'hash', increases the count for the 'stateHash'.
  750. //The 'StateHash' with the highest count will be the 'Major StateHash'.
  751. //If a roxie node does not contain the 'Major StateHash', it has a 'mismatch' state hash.
  752. hashID = stateHash->queryID();
  753. stateHash->incrementCount();
  754. }
  755. else
  756. {
  757. //Add a new 'StateHash'. Set its hashID to totalUniqueHashes and set its count to 1.
  758. hashID = totalUniqueHashes;
  759. Owned<IStateHash> newStateHash = new CStateHash(hashID, 1);
  760. stateHashes.setValue(hash, newStateHash);
  761. totalUniqueHashes++;
  762. }
  763. return hashID;
  764. }
  765. void Cws_machineEx::updateMajorRoxieStateHash(StateHashes& stateHashes, CIArrayOf<CRoxieStateData>& roxieStates)
  766. {
  767. //Find out which state hash is for the most of the roxie nodes inside this roxie cluster.
  768. unsigned majorHashID = 0;
  769. unsigned majorHashCount = 0;
  770. HashIterator hashes(stateHashes);
  771. ForEach(hashes)
  772. {
  773. IStateHash *hash = stateHashes.mapToValue(&hashes.query());
  774. unsigned hashCount = hash->queryCount();
  775. if (majorHashCount >= hashCount)
  776. continue;
  777. majorHashCount = hashCount;
  778. majorHashID = hash->queryID();
  779. }
  780. //Set the MajorHash to false if the roxie node's HashID() != majorHashID.
  781. ForEachItemIn(ii, roxieStates)
  782. {
  783. CRoxieStateData& roxieState = roxieStates.item(ii);
  784. if (roxieState.getHashID() != majorHashID)
  785. roxieState.setMajorHash(false);
  786. }
  787. }
  788. void Cws_machineEx::readRoxieStatus(const Owned<IPropertyTree> controlResp, CIArrayOf<CRoxieStateData>& roxieStates)
  789. {
  790. StateHashes stateHashes;
  791. unsigned totalUniqueHashes = 0;
  792. Owned<IPropertyTreeIterator> roxieEndpoints = controlResp->getElements("Endpoint");
  793. ForEach(*roxieEndpoints)
  794. {
  795. IPropertyTree& roxieEndpoint = roxieEndpoints->query();
  796. const char *ep = roxieEndpoint.queryProp("@ep");
  797. if (!ep || !*ep)
  798. continue;
  799. bool ok = false, attached = false, detached = false;
  800. const char *status = roxieEndpoint.queryProp("Status");
  801. if (status && strieq(status, "ok"))
  802. ok = true;
  803. const char *stateHash = roxieEndpoint.queryProp("State/@hash");
  804. if (roxieEndpoint.hasProp("Dali/@connected"))
  805. {
  806. if (roxieEndpoint.getPropBool("Dali/@connected"))
  807. attached = true;
  808. else
  809. detached = true;
  810. }
  811. StringArray locations;
  812. locations.appendListUniq(ep, ":");
  813. Owned<CRoxieStateData> roxieState = new CRoxieStateData(locations.item(0), addRoxieStateHash(stateHash, stateHashes, totalUniqueHashes));
  814. roxieState->setState(ok, attached, detached, stateHash);
  815. roxieStates.append(*roxieState.getClear());
  816. }
  817. if (totalUniqueHashes > 1)
  818. updateMajorRoxieStateHash(stateHashes, roxieStates);
  819. }
  820. void Cws_machineEx::getRoxieStateInfo(CRoxieStateInfoThreadParam* param)
  821. {
  822. const char* clusterName = param->clusterName.get();
  823. if (!clusterName || !*clusterName)
  824. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Roxie cluster not specified.");
  825. SocketEndpointArray servers;
  826. getRoxieProcessServers(clusterName, servers);
  827. if (!servers.length())
  828. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Roxie Process server not found.");
  829. Owned<IRoxieCommunicationClient> roxieClient = createRoxieCommunicationClient(servers.item(0), ROXIECONTROLSTATETIMEOUT);
  830. Owned<IPropertyTree> controlResp = roxieClient->sendRoxieControlAllNodes("<control:state/>", true);
  831. if (!controlResp)
  832. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get control response from roxie %s.", clusterName);
  833. CIArrayOf<CRoxieStateData> roxieStates;
  834. readRoxieStatus(controlResp, roxieStates);
  835. ForEachItemIn(i, param->machineInfoTable)
  836. {
  837. IEspMachineInfoEx& machineInfo = param->machineInfoTable.item(i);
  838. if (!streq(machineInfo.getProcessType(), eqRoxieServerProcess) || !streq(machineInfo.getComponentName(), clusterName))
  839. continue;
  840. //This method is thread safe because each machineInfo (for one roxie node) belongs to only one Roxie cluster.
  841. //It is impossible for different threads to update the same machineInfo.
  842. bool foundRoxieState = false;
  843. ForEachItemIn(ii, roxieStates)
  844. {
  845. CRoxieStateData& roxieState = roxieStates.item(ii);
  846. if (!roxieState.matchIPAddress(machineInfo.getAddress()))
  847. continue;
  848. StringBuffer state, stateDetails;
  849. roxieState.reportState(state, stateDetails);
  850. machineInfo.setRoxieState(state.str());
  851. machineInfo.setRoxieStateDetails(stateDetails.str());
  852. foundRoxieState = true;
  853. }
  854. if (!foundRoxieState)
  855. {
  856. machineInfo.setRoxieState("??");
  857. machineInfo.setRoxieStateDetails("Roxie state not found");
  858. }
  859. }
  860. }
  861. void Cws_machineEx::getMachineInfo(IEspContext& context, bool getRoxieState, CGetMachineInfoData& machineInfoData)
  862. {
  863. UnsignedArray threadHandles;
  864. if (!getRoxieState)
  865. {
  866. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  867. ForEachItemIn(idx, machines)
  868. {
  869. Owned<CMachineInfoThreadParam> pThreadReq = new CMachineInfoThreadParam(this, context, machineInfoData.getOptions(),
  870. machines.item(idx), machineInfoData.getMachineInfoTable(), machineInfoData.getMachineInfoColumns());
  871. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  872. threadHandles.append(handle);
  873. }
  874. }
  875. else
  876. {
  877. StringArray& roxieClusters = machineInfoData.getRoxieClusters();
  878. ForEachItemIn(i, roxieClusters)
  879. {
  880. Owned<CRoxieStateInfoThreadParam> pThreadReq = new CRoxieStateInfoThreadParam(this, roxieClusters.item(i),
  881. machineInfoData.getMachineInfoTable());
  882. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  883. threadHandles.append(handle);
  884. }
  885. machineInfoData.getMachineInfoColumns().append("Roxie State");
  886. }
  887. //Block for worker threads to finish, if necessary and then collect results
  888. //Not use joinAll() because multiple threads may call this method. Each call uses the pool to create
  889. //its own threads of checking query state. Each call should only join the ones created by that call.
  890. ForEachItemIn(i, threadHandles)
  891. m_threadPool->join(threadHandles.item(i));
  892. }
  893. ////////////////////////////////////////////////////////////////////
  894. // Get Machine Information based on Machine Information request //
  895. ////////////////////////////////////////////////////////////////////
  896. void Cws_machineEx::getMachineInfo(IEspContext& context, CGetMachineInfoData& machineInfoData)
  897. {
  898. double version = context.getClientVersion();
  899. getMachineInfo(context, false, machineInfoData);
  900. if ((version >= 1.13) && !machineInfoData.getRoxieClusters().empty())
  901. getMachineInfo(context, true, machineInfoData);
  902. }
  903. // the following method is invoked on worker threads of CMachineInfoThreadParam
  904. void Cws_machineEx::doGetMachineInfo(IEspContext& context, CMachineInfoThreadParam* pParam)
  905. {
  906. #ifdef DETECT_WS_MC_MEM_LEAKS
  907. static bool firstTime = true;
  908. if (firstTime)
  909. {
  910. firstTime = false;
  911. unsigned t = setAllocHook(true);
  912. }
  913. #endif //DETECT_WS_MC_MEM_LEAKS
  914. int error = 0;
  915. StringBuffer preflightCommand, response;
  916. buildPreflightCommand(context, pParam, preflightCommand);
  917. if (preflightCommand.length() < 1)
  918. {
  919. response.append("Failed in creating Machine Information command.\n");
  920. error = -1;
  921. }
  922. else
  923. {
  924. error = runCommand(context, pParam->m_machineData.getNetworkAddress(), pParam->m_machineData.getNetworkAddressInEnvSetting(), pParam->m_machineData.getOS(), preflightCommand.str(), pParam->m_options.getUserName(), pParam->m_options.getPassword(), response);
  925. if ((error == 0) && (response.length() > 0))
  926. readPreflightResponse(context, pParam, response.str(), error);
  927. }
  928. //Set IArrayOf<IEspMachineInfoEx> based on Preflight Response
  929. setMachineInfo(context, pParam, response.str(), error);
  930. #ifdef DETECT_WS_MC_MEM_LEAKS
  931. DBGLOG("Allocated=%d", setAllocHook(false));
  932. #endif //DETECT_WS_MC_MEM_LEAKS
  933. }
  934. void Cws_machineEx::buildPreflightCommand(IEspContext& context, CMachineInfoThreadParam* pParam, StringBuffer& preflightCommand)
  935. {
  936. preflightCommand.clear().appendf("/%s/sbin/%s -p=%s", environmentConfData.m_executionPath.str(),
  937. m_machineInfoFile.str(), environmentConfData.m_pidPath.str());
  938. if (preflightCommand.charAt(preflightCommand.length() - 1) == pParam->m_machineData.getPathSep())
  939. preflightCommand.remove(preflightCommand.length()-1, 1);
  940. bool checkDependency = false;
  941. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  942. ForEachItemIn(idx, processes)
  943. {
  944. CProcessData& process = processes.item(idx);
  945. if (!process.getName() || !*process.getName())
  946. continue;
  947. StringBuffer procName;
  948. if (streq(process.getType(), eqThorSlaveProcess))
  949. procName.appendf("thorslave_%s_%d,%s_slave_%d", process.getName(), process.getProcessNumber(), process.getName(), process.getProcessNumber());
  950. else if (streq(process.getType(), eqThorMasterProcess))
  951. procName.appendf("%s,%s_master", process.getName(), process.getName());
  952. else
  953. procName.append(process.getName());
  954. if (idx < 1)
  955. preflightCommand.appendf(" -n=%s", procName.str());
  956. else
  957. preflightCommand.appendf(",%s", procName.str());
  958. if (!process.getDependencies().empty())
  959. checkDependency = true;
  960. }
  961. if (checkDependency || !pParam->m_options.getApplyProcessFilter())
  962. preflightCommand.append(" -d=ALL");
  963. if (pParam->m_options.getGetStorageInfo() && !pParam->m_options.getLocalFileSystemsOnly())
  964. preflightCommand.append(" -m=YES");
  965. }
  966. int Cws_machineEx::runCommand(IEspContext& context, const char* sAddress, const char* sConfigAddress, EnvMachineOS os,
  967. const char* sCommand, const char* sUserId, const char* sPassword, StringBuffer& response)
  968. {
  969. int exitCode = -1;
  970. try
  971. {
  972. StringBuffer command(sCommand);
  973. StringBuffer userId;
  974. StringBuffer password;
  975. bool bLinux;
  976. if (sConfigAddress && *sConfigAddress)
  977. getAccountAndPlatformInfo(sConfigAddress, userId, password, bLinux);
  978. else
  979. getAccountAndPlatformInfo(sAddress, userId, password, bLinux);
  980. if (!sUserId || !*sUserId || !sPassword ||!*sPassword)
  981. {
  982. //BUG: 9825 - remote execution on linux needs to use individual accounts
  983. //use userid/password in ESP context for remote execution...
  984. if (bLinux)
  985. {
  986. userId.clear();
  987. password.clear();
  988. context.getUserID(userId);
  989. context.getPassword(password);
  990. }
  991. }
  992. else
  993. {
  994. userId.clear().append(sUserId);
  995. password.clear().append(sPassword);
  996. }
  997. // make sure there actually is something in command before we run a remote connection
  998. if (command.length() < 1)
  999. return exitCode;
  1000. Owned<IFRunSSH> connection = createFRunSSH();
  1001. connection->init(command.str(),NULL,NULL,NULL,m_SSHConnectTimeoutSeconds,0);
  1002. // executed as single connection
  1003. connection->exec(IpAddress(sAddress),NULL,false);
  1004. response.append(connection->getReplyText()[0]);
  1005. exitCode = connection->getReply()[0];
  1006. int len = response.length();
  1007. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1008. response.setLength(len);
  1009. if (response.length() && !exitCode)
  1010. response.insert(0, "Response: ");
  1011. else if (!exitCode)
  1012. response.insert(0, "No response recieved.\n");
  1013. }
  1014. // CFRunSSH uses a MakeStringExceptionDirect throw to pass code and result string
  1015. catch(IException* e)
  1016. {
  1017. exitCode = e->errorCode();
  1018. // errorCode == -1 on successful CFRunSSH execution
  1019. if(exitCode == -1)
  1020. exitCode = 0;
  1021. StringBuffer buf;
  1022. e->errorMessage(buf);
  1023. response.append(buf.str());
  1024. int len = response.length();
  1025. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1026. response.setLength(len);
  1027. // on successful connection
  1028. if (response.length() && !exitCode)
  1029. response.insert(0,"Response: ");
  1030. else if (!exitCode)
  1031. response.insert(0, "No response recieved.\n");
  1032. e->Release();
  1033. }
  1034. #ifndef NO_CATCHALL
  1035. catch(...)
  1036. {
  1037. response.append("An unknown exception occurred!");
  1038. exitCode = -1;
  1039. }
  1040. #endif
  1041. return exitCode;
  1042. }
  1043. int Cws_machineEx::invokeProgram(const char *command_line, StringBuffer& response)
  1044. {
  1045. char buffer[128];
  1046. FILE *fp;
  1047. // Run the command so that it writes its output to a pipe. Open this
  1048. // pipe with read text attribute so that we can read it
  1049. // like a text file.
  1050. if (getEspLogLevel()>LogNormal)
  1051. {
  1052. DBGLOG("command_line=<%s>", command_line);
  1053. }
  1054. #ifndef NO_CONNECTION_DEBUG
  1055. if( (fp = popen( command_line, "r" )) == NULL )
  1056. return -1;
  1057. #else
  1058. if( (fp = fopen( "c:\\temp\\preflight_result.txt", "r" )) == NULL )
  1059. return -1;
  1060. #endif
  1061. // Read pipe until end of file. End of file indicates that
  1062. //the stream closed its standard out (probably meaning it
  1063. //terminated).
  1064. while ( !feof(fp) )
  1065. if ( fgets( buffer, 128, fp) )
  1066. response.append( buffer );
  1067. if (getEspLogLevel()>LogNormal)
  1068. {
  1069. DBGLOG("response=<%s>", response.str());
  1070. }
  1071. // Close pipe and print return value of CHKDSK.
  1072. #ifndef NO_CONNECTION_DEBUG
  1073. return pclose( fp );
  1074. #else
  1075. return fclose( fp );
  1076. #endif
  1077. }
  1078. void Cws_machineEx::readPreflightResponse(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response, int error)
  1079. {
  1080. if (!response || !*response)
  1081. return;
  1082. StringBuffer computerUpTime;
  1083. readALineFromResult(response, "ComputerUpTime:", computerUpTime, true);
  1084. if (computerUpTime.length() < 1)
  1085. computerUpTime.append("-");
  1086. else
  1087. {
  1088. const char* pStr = strchr(computerUpTime.str(), ' ');
  1089. if (pStr)
  1090. {
  1091. pStr++;
  1092. pStr = strchr(pStr, ' ');
  1093. if (pStr)
  1094. {
  1095. pStr++;
  1096. if (pStr)
  1097. pParam->m_machineData.setComputerUpTime(pStr);
  1098. }
  1099. }
  1100. if (!pStr)
  1101. pParam->m_machineData.setComputerUpTime(computerUpTime);
  1102. }
  1103. if (pParam->m_options.getGetProcessorInfo())
  1104. {
  1105. StringBuffer CPUIdle;
  1106. readALineFromResult(response, "CPU-Idle:", CPUIdle, true);
  1107. if (CPUIdle.length() < 1)
  1108. pParam->m_machineData.setCPULoad(0);
  1109. else
  1110. {
  1111. if (CPUIdle.charAt(CPUIdle.length() - 1) == '%')
  1112. CPUIdle.setLength(CPUIdle.length() - 1);
  1113. pParam->m_machineData.setCPULoad(100-atoi(CPUIdle.str()));
  1114. }
  1115. }
  1116. if (pParam->m_options.getGetStorageInfo())
  1117. readStorageData(response, pParam);
  1118. if (pParam->m_options.getGetSoftwareInfo())
  1119. readProcessData(response, pParam);
  1120. }
  1121. void Cws_machineEx::readALineFromResult(const char *result, const char *start, StringBuffer& value, bool trim)
  1122. {
  1123. if (!result || !*result)
  1124. return;
  1125. const char* pStr = strstr(result, start);
  1126. if (!pStr)
  1127. return;
  1128. pStr += strlen(start);
  1129. if (!pStr)
  1130. return;
  1131. const char* pStr1 = strchr(pStr, 0x0a);
  1132. if (pStr1)
  1133. value.append(pStr, 0, pStr1 - pStr);
  1134. else
  1135. value.append(pStr);
  1136. if (trim)
  1137. value.trim();
  1138. }
  1139. void Cws_machineEx::readStorageData(const char* response, CMachineInfoThreadParam* pParam)
  1140. {
  1141. if (!response || !*response)
  1142. return;
  1143. const char* pStr = strstr(response, "---SpaceUsedAndFree---");
  1144. if (!pStr)
  1145. DBGLOG("Storage information not found on %s", pParam->m_machineData.getNetworkAddress());
  1146. bool isTitleLine = true;
  1147. CIArrayOf<CStorageData>& storage = pParam->m_machineData.getStorage();
  1148. while (pStr)
  1149. {
  1150. StringBuffer buf;
  1151. const char* pStr1 = strchr(pStr, 0x0a);
  1152. if (pStr1)
  1153. {
  1154. buf.append(pStr, 0, pStr1 - pStr);
  1155. pStr = pStr1+1;
  1156. }
  1157. else
  1158. {
  1159. buf.append(pStr);
  1160. pStr = NULL;
  1161. }
  1162. if (isTitleLine)
  1163. {
  1164. isTitleLine = false;
  1165. continue;
  1166. }
  1167. if (buf.length() > 0)
  1168. {
  1169. StringBuffer diskSpaceTitle;
  1170. int diskSpacePercentAvail = 0;
  1171. __int64 diskSpaceAvailable = 0, diskSpaceTotal = 0;
  1172. if (!readStorageSpace(buf.str(), diskSpaceTitle, diskSpaceAvailable, diskSpaceTotal, diskSpacePercentAvail))
  1173. DBGLOG("Invalid storage information on %s: %s", pParam->m_machineData.getNetworkAddress(), buf.str());
  1174. else if ((diskSpaceTitle.length() > 0) && !excludePartition(diskSpaceTitle.str()))
  1175. {
  1176. Owned<CStorageData> diskData = new CStorageData(diskSpaceTitle, diskSpaceAvailable, diskSpaceTotal, diskSpacePercentAvail);
  1177. storage.append(*diskData.getClear());
  1178. }
  1179. }
  1180. if (!pStr || (strnicmp(pStr, "---ProcessList1---", 18)==0))
  1181. break;
  1182. }
  1183. }
  1184. bool Cws_machineEx::readStorageSpace(const char *line, StringBuffer& title, __int64& free, __int64& total, int& percentAvail)
  1185. {
  1186. if (!line || !*line)
  1187. return false;
  1188. StringBuffer freeStr, usedStr;
  1189. const char* pStr = line;
  1190. const char* pStr1 = strchr(pStr, ':');
  1191. if (!pStr1)
  1192. return false;
  1193. title.clear().append(pStr, 0, pStr1 - pStr);
  1194. pStr = pStr1 + 2;
  1195. pStr1 = (char*) strchr(pStr, ' ');
  1196. if (!pStr1)
  1197. return false;
  1198. usedStr.append(pStr, 0, pStr1 - pStr);
  1199. pStr = pStr1 + 1;
  1200. if (!pStr)
  1201. return false;
  1202. freeStr.append(pStr);
  1203. __int64 factor1 = 1;
  1204. if (freeStr.length() > 9)
  1205. {
  1206. freeStr.setLength(freeStr.length()-6);
  1207. factor1 = 1000000;
  1208. }
  1209. free = atol(freeStr.str())*factor1;
  1210. __int64 factor2 = 1;
  1211. if (usedStr.length() > 9)
  1212. {
  1213. usedStr.setLength(usedStr.length()-6);
  1214. factor2 = 1000000;
  1215. }
  1216. __int64 used = atol(usedStr.str())*factor2;
  1217. total = free + used;
  1218. if (total > 0)
  1219. percentAvail = (int) ((free*100)/total);
  1220. free = (__int64) free /1000; //MByte
  1221. total = (__int64) total /1000; //MByte
  1222. return true;
  1223. }
  1224. void Cws_machineEx::buildProcessPath(StringBuffer &processPath, const char * processName, CMachineInfoThreadParam * pParam)
  1225. {
  1226. if (environmentConfData.m_pidPath.charAt(environmentConfData.m_pidPath.length() - 1) != pParam->m_machineData.getPathSep())
  1227. processPath.setf("%s%c%s:", environmentConfData.m_pidPath.str(), pParam->m_machineData.getPathSep(), processName);
  1228. else
  1229. processPath.setf("%s%s:", environmentConfData.m_pidPath.str(), processName);
  1230. }
  1231. void Cws_machineEx::readProcessData(const char* response, CMachineInfoThreadParam* pParam)
  1232. {
  1233. if (!response || !*response)
  1234. return;
  1235. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1236. ForEachItemIn(idx, processes)
  1237. {
  1238. CProcessData& process = processes.item(idx);
  1239. if (!process.getName() || !*process.getName())
  1240. continue;
  1241. StringBuffer procName, catError, processPath, processData;
  1242. if (streq(process.getType(), eqThorSlaveProcess))
  1243. {
  1244. procName.appendf("thorslave_%s_%d", process.getName(), process.getProcessNumber());
  1245. buildProcessPath(processPath,procName.str(),pParam);
  1246. catError.setf("cat: %s",processPath.str());
  1247. catError.insert(catError.length()-1,".pid");
  1248. if (!strstr(response,catError.str()))
  1249. readALineFromResult(response, processPath.str(), processData, true);
  1250. else
  1251. {
  1252. procName.setf("%s_slave_%d", process.getName(), process.getProcessNumber());
  1253. buildProcessPath(processPath,procName.str(),pParam);
  1254. readALineFromResult(response, processPath.str(), processData, true);
  1255. }
  1256. }
  1257. else if (streq(process.getType(), eqThorMasterProcess))
  1258. {
  1259. procName.appendf("%s", process.getName());
  1260. buildProcessPath(processPath,procName.str(),pParam);
  1261. catError.setf("cat: %s",processPath.str());
  1262. catError.insert(catError.length()-1,".pid");
  1263. if (!strstr(response,catError.str()))
  1264. readALineFromResult(response, processPath.str(), processData, true);
  1265. else
  1266. {
  1267. procName.setf("%s_master", process.getName());
  1268. buildProcessPath(processPath,procName.str(),pParam);
  1269. readALineFromResult(response, processPath.str(), processData, true);
  1270. }
  1271. }
  1272. else
  1273. {
  1274. procName.append(process.getName());
  1275. buildProcessPath(processPath,procName.str(),pParam);
  1276. readALineFromResult(response, processPath.str(), processData, true);
  1277. }
  1278. if (processData.length() < 1)
  1279. {
  1280. DBGLOG("Information for process %s not found", processPath.str());
  1281. continue;
  1282. }
  1283. const char* pStr = strchr(processData.str(), ' ');
  1284. if (!pStr)
  1285. {
  1286. DBGLOG("incorrect data for process %s: %s", processPath.str(), processData.str());
  1287. continue;
  1288. }
  1289. unsigned len = pStr - processData.str();
  1290. StringBuffer pid, upTime;
  1291. pid.append(processData.str(), 0, len);
  1292. len++;
  1293. upTime.append(processData.str(), len, processData.length() - len);
  1294. upTime.replaceString("-", " day(s) ");
  1295. process.setPID(pid.str());
  1296. process.setUpTime(upTime.str());
  1297. }
  1298. readRunningProcesses(response, pParam);
  1299. }
  1300. void Cws_machineEx::readRunningProcesses(const char* response, CMachineInfoThreadParam* pParam)
  1301. {
  1302. if (!response || !*response)
  1303. return;
  1304. const char* pStr = strstr(response, "---ProcessList2---");
  1305. if (!pStr)
  1306. DBGLOG("Running process not found on %s", pParam->m_machineData.getNetworkAddress());
  1307. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1308. while (pStr)
  1309. {
  1310. //read a line
  1311. StringBuffer lineStr;
  1312. const char* pStr1 = strchr(pStr, 0x0a);
  1313. if (!pStr1)
  1314. {
  1315. lineStr.append(pStr);
  1316. pStr = NULL;
  1317. }
  1318. else
  1319. {
  1320. lineStr.append(pStr, 0, pStr1 - pStr);
  1321. pStr = pStr1+1;
  1322. }
  1323. if (lineStr.length() < 1)
  1324. continue;
  1325. StringBuffer pidStr, desc, param;
  1326. pStr1 = lineStr.str();
  1327. const char* pStr2 = strchr(pStr1, ' ');
  1328. if (!pStr2)
  1329. continue;
  1330. pidStr.append(pStr1, 0, pStr2 - pStr1);
  1331. param.append(pStr2+1);
  1332. if (param.length() < 1)
  1333. continue;
  1334. if (streq(param.str(), "ps"))
  1335. continue;
  1336. bool isNumber = true;
  1337. for (unsigned i = 0; i < pidStr.length(); i++)
  1338. {
  1339. if (!isdigit(pidStr.charAt(i)))
  1340. {
  1341. isNumber = false;
  1342. break;
  1343. }
  1344. }
  1345. if (!isNumber)
  1346. continue;
  1347. int pid = atoi(pidStr.str());
  1348. desc = param;
  1349. if ((desc.charAt(0) == '.') && (param.charAt(1) == '/'))
  1350. desc.remove(0, 2);
  1351. if (desc.charAt(desc.length() - 1) == '/')
  1352. desc.remove(desc.length() - 1, 1);
  1353. if (desc.charAt(0) == '[')
  1354. {
  1355. desc.remove(0, 1);
  1356. if (desc.charAt(desc.length() - 1) == ']')
  1357. desc.remove(desc.length() - 1, 1);
  1358. }
  1359. Owned<IEspProcessInfo> info = createProcessInfo("","");
  1360. info->setPID(pid);
  1361. info->setParameter(param.str());
  1362. info->setDescription(desc.str());
  1363. runningProcesses.append(*info.getClear());
  1364. }
  1365. }
  1366. void Cws_machineEx::setMachineInfo(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response, int error)
  1367. {
  1368. //Read additionalProcessFilters which will be used in setProcessInfo()/setProcessComponent()
  1369. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1370. StringArray& additionalProcessFilters = pParam->m_options.getAdditionalProcessFilters();
  1371. if (pParam->m_options.getApplyProcessFilter() && !additionalProcessFilters.empty())
  1372. {
  1373. int len = additionalProcessFilters.length();
  1374. for (int i=0; i<len; i++)
  1375. {
  1376. StringBuffer processName = additionalProcessFilters.item(i);
  1377. processName.toLowerCase().replaceString(".exe", "");
  1378. if (processName.length() > 0)
  1379. additionalProcesses.insert(processName.str());
  1380. }
  1381. }
  1382. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1383. ForEachItemIn(idx, processes)
  1384. {
  1385. CProcessData& process = processes.item(idx);
  1386. Owned<IEspMachineInfoEx> pMachineInfo = static_cast<IEspMachineInfoEx*>(new CMachineInfoEx(""));
  1387. setProcessInfo(context, pParam, response, error, process, idx<1, pMachineInfo);
  1388. synchronized block(mutex_machine_info_table);
  1389. pParam->m_machineInfoTable.append(*pMachineInfo.getLink());
  1390. }
  1391. }
  1392. void Cws_machineEx::setProcessInfo(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response,
  1393. int error, CProcessData& process, bool firstProcess, IEspMachineInfoEx* pMachineInfo)
  1394. {
  1395. double version = context.getClientVersion();
  1396. bool isEclAgentProcess = process.getType() && strieq(process.getType(), eqEclAgent);
  1397. pMachineInfo->setAddress(pParam->m_machineData.getNetworkAddress());
  1398. pMachineInfo->setConfigAddress(pParam->m_machineData.getNetworkAddressInEnvSetting());
  1399. pMachineInfo->setOS(pParam->m_machineData.getOS());
  1400. if (process.getName() && *process.getName())
  1401. pMachineInfo->setComponentName(process.getName());
  1402. if (process.getPath() && *process.getPath())
  1403. pMachineInfo->setComponentPath(process.getPath());
  1404. //set DisplayType
  1405. if (process.getType() && *process.getType())
  1406. {
  1407. if (isEclAgentProcess)
  1408. {
  1409. pMachineInfo->setProcessType(eqAgentExec);
  1410. pMachineInfo->setDisplayType("Agent Exec");
  1411. }
  1412. else
  1413. {
  1414. pMachineInfo->setProcessType(process.getType());
  1415. StringBuffer displayName;
  1416. getProcessDisplayName(process.getType(), displayName);
  1417. pMachineInfo->setDisplayType(displayName.str());
  1418. }
  1419. }
  1420. else if (process.getName() && *process.getName())
  1421. {
  1422. pMachineInfo->setDisplayType(process.getName());
  1423. }
  1424. if ((version > 1.09) && process.getType() && strieq(process.getType(), eqThorSlaveProcess))
  1425. {
  1426. pMachineInfo->setProcessNumber(process.getProcessNumber());
  1427. }
  1428. if (error != 0 || !response || !*response)
  1429. {
  1430. StringBuffer description;
  1431. if (!response || !*response)
  1432. description.append("Failed in getting Machine Information");
  1433. else
  1434. description = response;
  1435. pMachineInfo->setDescription(description.str());
  1436. }
  1437. else
  1438. {
  1439. //Now, add more columns based on 'response'
  1440. pMachineInfo->setUpTime(pParam->m_machineData.getComputerUpTime());
  1441. pParam->addColumn("Up Time");
  1442. if (pParam->m_options.getGetStorageInfo())
  1443. {
  1444. IArrayOf<IEspStorageInfo> storageArray;
  1445. CIArrayOf<CStorageData>& storage = pParam->m_machineData.getStorage();
  1446. ForEachItemIn(idx, storage)
  1447. {
  1448. CStorageData& diskData = storage.item(idx);
  1449. Owned<IEspStorageInfo> info = static_cast<IEspStorageInfo*>(new CStorageInfo(""));
  1450. info->setDescription(diskData.getDiskSpaceTitle());
  1451. info->setTotal(diskData.getDiskSpaceTotal());
  1452. info->setAvailable(diskData.getDiskSpaceAvailable());
  1453. info->setPercentAvail(diskData.getDiskSpacePercentAvail());
  1454. storageArray.append(*info.getLink());
  1455. pParam->addColumn(diskData.getDiskSpaceTitle());
  1456. }
  1457. pMachineInfo->setStorage(storageArray);
  1458. storageArray.kill();
  1459. }
  1460. if (pParam->m_options.getGetProcessorInfo())
  1461. {
  1462. IArrayOf<IEspProcessorInfo> processorArray;
  1463. Owned<IEspProcessorInfo> info = static_cast<IEspProcessorInfo*>(new CProcessorInfo(""));
  1464. info->setLoad(pParam->m_machineData.getCPULoad());
  1465. processorArray.append(*info.getLink());
  1466. pMachineInfo->setProcessors(processorArray);
  1467. processorArray.kill();
  1468. pParam->addColumn("CPU Load");
  1469. }
  1470. if (pParam->m_options.getGetSoftwareInfo())
  1471. {
  1472. IArrayOf<IEspSWRunInfo> processArray;
  1473. IEspComponentInfo* pComponentInfo = &pMachineInfo->updateComponentInfo();
  1474. setProcessComponent(context, pParam, process, firstProcess, processArray, pComponentInfo);
  1475. if (processArray.ordinality())
  1476. {
  1477. //Set running processes if ApplyProcessFilter is set to false
  1478. //Set processes not running if ApplyProcessFilter is set to true
  1479. pMachineInfo->setRunning(processArray);
  1480. }
  1481. pParam->addColumn("Processes");
  1482. pParam->addColumn("Condition");
  1483. pParam->addColumn("State");
  1484. pParam->addColumn("UpTime");
  1485. }
  1486. }
  1487. }
  1488. void Cws_machineEx::setProcessComponent(IEspContext& context, CMachineInfoThreadParam* pParam, CProcessData& process,
  1489. bool firstProcess, IArrayOf<IEspSWRunInfo>& processArray, IEspComponentInfo* pComponentInfo)
  1490. {
  1491. const char* procType = process.getType();
  1492. const char* procPID = process.getPID();
  1493. //If a component (ex. dropzone) has no process type, it is not a process and does not have a PID.
  1494. //FTSlaveProcess may not have a PID since it is launched dynamically during a spray.
  1495. if (pParam->m_options.getApplyProcessFilter() && (isEmptyString(procPID) &&
  1496. !isEmptyString(procType) && !strieq(procType, "FTSlaveProcess")))
  1497. {
  1498. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1499. info->setName(process.getName());
  1500. info->setInstances(0);
  1501. processArray.append( *info.getLink() );
  1502. }
  1503. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1504. map<string, Linked<IEspSWRunInfo> > runningProcessMap; //save only one description of each process
  1505. set<string>& dependencies = process.getDependencies();
  1506. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1507. if (runningProcesses.length() > 0)
  1508. {
  1509. if (!pParam->m_options.getApplyProcessFilter()) //need to display all of the running processes
  1510. enumerateRunningProcesses( pParam, process, &runningProcessMap, firstProcess);
  1511. else if (!dependencies.empty() || !additionalProcesses.empty())
  1512. enumerateRunningProcesses(pParam, process, NULL, firstProcess);
  1513. }
  1514. map<string, Linked<IEspSWRunInfo> >::const_iterator it = runningProcessMap.begin();
  1515. map<string, Linked<IEspSWRunInfo> >::const_iterator iEnd = runningProcessMap.end();
  1516. for (; it != iEnd; it++) //add in sorted order simply by traversing the map
  1517. {
  1518. Linked<IEspSWRunInfo> info( (*it).second );
  1519. processArray.append( *info.getLink() );
  1520. }
  1521. bool dependencyDown = false;
  1522. if (!dependencies.empty())
  1523. {
  1524. dependencyDown = true;
  1525. if (pParam->m_options.getApplyProcessFilter())
  1526. {
  1527. set<string>::const_iterator it = dependencies.begin();
  1528. set<string>::const_iterator iEnd = dependencies.end();
  1529. for (; it != iEnd; it++)
  1530. {
  1531. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1532. info->setName(it->c_str());
  1533. info->setInstances(0);
  1534. processArray.append( *info.getLink() );
  1535. }
  1536. }
  1537. }
  1538. if (pParam->m_options.getApplyProcessFilter() && !additionalProcesses.empty())
  1539. {
  1540. set<string>::const_iterator it = additionalProcesses.begin();
  1541. set<string>::const_iterator iEnd = additionalProcesses.end();
  1542. for (; it != iEnd; it++)
  1543. {
  1544. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1545. info->setName(it->c_str());
  1546. info->setInstances(0);
  1547. processArray.append( *info.getLink() );
  1548. }
  1549. }
  1550. if (!dependencyDown && (!isEmptyString(procPID) || isEmptyString(procType) || strieq(procType, "FTSlaveProcess")))
  1551. {
  1552. //conditions: unknown, normal, warning, minor, major, critical, fatal
  1553. pComponentInfo->setCondition( 1 );
  1554. pComponentInfo->setState(5);
  1555. if (process.getUpTime() && *process.getUpTime())
  1556. pComponentInfo->setUpTime( process.getUpTime() );
  1557. }
  1558. else
  1559. {
  1560. pComponentInfo->setCondition(2); //Warnning
  1561. pComponentInfo->setState(0);
  1562. }
  1563. }
  1564. //Erase this process from dependencies and, if firstProcess, additionalProcesses;
  1565. //If processMap is not NULL, add this process to processMap
  1566. void Cws_machineEx::enumerateRunningProcesses(CMachineInfoThreadParam* pParam, CProcessData& process, map<string, Linked<IEspSWRunInfo> >* runningProcessMap, bool firstProcess)
  1567. {
  1568. set<string>& dependencies = process.getDependencies();
  1569. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1570. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1571. ForEachItemIn(k, runningProcesses)
  1572. {
  1573. IEspProcessInfo& processInfo = runningProcesses.item(k);
  1574. //Erase this process from dependencies and, if firstProcess, additionalProcesses
  1575. const char* pName = processInfo.getDescription();
  1576. if (pParam->m_machineData.getOS() == MachineOsW2K)
  1577. {
  1578. StringBuffer sName = pName;
  1579. pName = sName.toLowerCase().replaceString(".exe", "").str();
  1580. if (!dependencies.empty())
  1581. dependencies.erase(pName);
  1582. if (pParam->m_options.getApplyProcessFilter() && firstProcess && !additionalProcesses.empty())
  1583. additionalProcesses.erase(pName);
  1584. }
  1585. else
  1586. {
  1587. //dafilesrv would probably be running from a global directory
  1588. //and not component's installation directory so ignore their paths
  1589. const char* pPath = pName;
  1590. if ( !strieq(pName, "dafilesrv"))
  1591. {
  1592. const char* param = processInfo.getParameter();
  1593. if (param && *param)
  1594. {
  1595. if (strncmp(param, "bash ", 5))
  1596. pPath = param;
  1597. else
  1598. pPath = param + 5;
  1599. if (!pPath || !*pPath)
  1600. continue;
  1601. //params typically is like "/c$/esp_dir/esp [parameters...]"
  1602. //so just pick the full path
  1603. const char* pch = strchr(pPath, ' ');
  1604. if (pch)
  1605. {
  1606. StringBuffer sPath = pPath;
  1607. sPath.setLength( pch - pPath );
  1608. pPath = sPath.str();
  1609. }
  1610. }
  1611. }
  1612. if (!dependencies.empty())
  1613. {
  1614. const char* pProcessName;
  1615. if (process.getType() && !strncmp(process.getType(), "Thor", 4) && !strnicmp(pName, "thor", 4))
  1616. {
  1617. const char* pch = strrchr(pPath, pParam->m_machineData.getPathSep());
  1618. pProcessName = pch ? pch+1 : pName;
  1619. }
  1620. else
  1621. {
  1622. const char* pName0 = process.getMultipleInstances() ? pPath : pName;
  1623. const char* pch = strrchr(pName0, pParam->m_machineData.getPathSep());
  1624. pProcessName = pch ? pch+1 : pName0;
  1625. }
  1626. dependencies.erase(pProcessName);
  1627. if (pParam->m_options.getApplyProcessFilter() && firstProcess && !additionalProcesses.empty())
  1628. additionalProcesses.erase(pProcessName);
  1629. }
  1630. pName = pPath;
  1631. }
  1632. if (!runningProcessMap)
  1633. continue;
  1634. //Add this process to runningProcessMap
  1635. map<string, Linked<IEspSWRunInfo> >::iterator it = runningProcessMap->find(pName);
  1636. if ( it != runningProcessMap->end()) //not in the set
  1637. {
  1638. Linked<IEspSWRunInfo>& linkedPtr = (*it).second;
  1639. linkedPtr->setInstances( linkedPtr->getInstances() + 1);
  1640. }
  1641. else
  1642. {
  1643. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1644. info->setName(pName);
  1645. info->setInstances(1);
  1646. runningProcessMap->insert(pair<string, Linked<IEspSWRunInfo> >(pName, info));
  1647. }
  1648. }
  1649. }
  1650. void Cws_machineEx::getProcessDisplayName(const char* processName, StringBuffer& displayName)
  1651. {
  1652. //produces "LDAPServerProcess" as "LDAP Server" and "EspService" as "Esp Service", etc.
  1653. const char* end = strstr(processName, "Process");
  1654. if (!end)
  1655. end = processName + strlen(processName);
  1656. displayName.append(*processName);
  1657. processName++;
  1658. bool bLower = false;
  1659. while (processName < end)
  1660. {
  1661. char ch = *processName;
  1662. if (!isupper(ch))
  1663. bLower = true;
  1664. else
  1665. {
  1666. if (bLower || //last char was uppercase or the following character is lowercase?
  1667. ((processName+1 < end) && islower(*(processName+1))))
  1668. {
  1669. displayName.append(' ');
  1670. }
  1671. bLower = false;
  1672. }
  1673. displayName.append(*processName);
  1674. processName++;
  1675. }
  1676. displayName.append('\0');
  1677. return;
  1678. }
  1679. bool Cws_machineEx::excludePartition(const char* partition) const
  1680. {
  1681. //first see if this partition is meant to be excluded as is - for instance
  1682. //if partition is /dev and /dev is one of the predefined partitions to be excluded
  1683. set<string>::const_iterator it = m_excludePartitions.find( partition );
  1684. set<string>::const_iterator itEnd = m_excludePartitions.end();
  1685. bool found = false;
  1686. if (it != itEnd)
  1687. found = true;
  1688. else
  1689. {
  1690. //now check if /dev* is one of the partitions to be excluded
  1691. set<string>::const_iterator itBegin = m_excludePartitionPatterns.begin();
  1692. itEnd = m_excludePartitionPatterns.end();
  1693. unsigned int partitionLen = strlen(partition);
  1694. for (it=itBegin; it != itEnd; it++)
  1695. {
  1696. const string& pattern = *it;
  1697. if ((found = ::WildMatch(partition, partitionLen, pattern.c_str(), pattern.length(), false)))
  1698. break;
  1699. }
  1700. }
  1701. return found;
  1702. }
  1703. void Cws_machineEx::appendProcessInstance(const char* name, const char* directory1, const char* directory2, StringArray& processInstances, StringArray& directories)
  1704. {
  1705. if (!name || !*name)
  1706. return;
  1707. processInstances.append(name);
  1708. if (directory1 && *directory1)
  1709. directories.append(directory1);
  1710. else if (directory2 && *directory2)
  1711. directories.append(directory2);
  1712. else
  1713. directories.append("Setting not found");
  1714. }
  1715. //////////////////////////////////////////////////////////////////
  1716. // Set Machine Infomation for response //
  1717. //////////////////////////////////////////////////////////////////
  1718. void Cws_machineEx::setMachineInfoResponse(IEspContext& context, IEspGetMachineInfoRequest& req,
  1719. CGetMachineInfoData& machineInfoData, IEspGetMachineInfoResponse& resp)
  1720. {
  1721. IEspRequestInfoStruct& reqInfo = resp.updateRequestInfo();
  1722. #if 0
  1723. StringBuffer user;
  1724. StringBuffer pw;
  1725. context.getUserID(user);
  1726. context.getPassword(pw);
  1727. reqInfo.setUserName(user.str());
  1728. reqInfo.setPassword(pw.str());
  1729. #endif
  1730. reqInfo.setSecurityString(req.getSecurityString());
  1731. reqInfo.setGetProcessorInfo(req.getGetProcessorInfo());
  1732. reqInfo.setGetStorageInfo(req.getGetStorageInfo());
  1733. double version = context.getClientVersion();
  1734. if (version > 1.10)
  1735. reqInfo.setLocalFileSystemsOnly(req.getLocalFileSystemsOnly());
  1736. reqInfo.setGetSoftwareInfo(req.getGetSoftwareInfo());
  1737. reqInfo.setAutoRefresh( req.getAutoRefresh() );
  1738. reqInfo.setMemThreshold(req.getMemThreshold());
  1739. reqInfo.setDiskThreshold(req.getDiskThreshold());
  1740. reqInfo.setCpuThreshold(req.getCpuThreshold());
  1741. reqInfo.setMemThresholdType(req.getMemThresholdType());
  1742. reqInfo.setDiskThresholdType(req.getDiskThresholdType());
  1743. reqInfo.setApplyProcessFilter( req.getApplyProcessFilter() );
  1744. reqInfo.setClusterType( req.getClusterType() );
  1745. reqInfo.setCluster( req.getCluster() );
  1746. reqInfo.setAddProcessesToFilter( req.getAddProcessesToFilter() );
  1747. reqInfo.setOldIP( req.getOldIP() );
  1748. reqInfo.setPath( req.getPath() );
  1749. reqInfo.setSortBy("Address");
  1750. if (machineInfoData.getMachineInfoColumns().ordinality())
  1751. resp.setColumns(machineInfoData.getMachineInfoColumns());
  1752. if (machineInfoData.getMachineInfoTable().ordinality())
  1753. resp.setMachines(machineInfoData.getMachineInfoTable());
  1754. char timeStamp[32];
  1755. getTimeStamp(timeStamp);
  1756. resp.setTimeStamp( timeStamp );
  1757. if (version >= 1.12)
  1758. {
  1759. StringBuffer acceptLanguage;
  1760. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  1761. }
  1762. }
  1763. void Cws_machineEx::getTimeStamp(char* timeStamp)
  1764. {
  1765. //set time stamp in the result for this machine
  1766. time_t tNow;
  1767. time(&tNow);
  1768. #ifdef _WIN32
  1769. struct tm *ltNow;
  1770. ltNow = localtime(&tNow);
  1771. strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S", ltNow);
  1772. #else
  1773. struct tm ltNow;
  1774. localtime_r(&tNow, &ltNow);
  1775. strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S", &ltNow);
  1776. #endif
  1777. }
  1778. void Cws_machineEx::setTargetClusterInfoResponse(IEspContext& context, IEspGetTargetClusterInfoRequest& req,
  1779. CGetMachineInfoData& machineInfoData, IPropertyTree* targetClusterTree, IEspGetTargetClusterInfoResponse& resp)
  1780. {
  1781. IEspRequestInfoStruct& reqInfo = resp.updateRequestInfo();
  1782. #if 0
  1783. StringBuffer user;
  1784. StringBuffer pw;
  1785. context.getUserID(user);
  1786. context.getPassword(pw);
  1787. reqInfo.setUserName(user.str());
  1788. reqInfo.setPassword(pw.str());
  1789. #endif
  1790. reqInfo.setGetProcessorInfo(req.getGetProcessorInfo());
  1791. reqInfo.setGetStorageInfo(req.getGetStorageInfo());
  1792. double version = context.getClientVersion();
  1793. if (version > 1.10)
  1794. reqInfo.setLocalFileSystemsOnly(req.getLocalFileSystemsOnly());
  1795. reqInfo.setGetSoftwareInfo(req.getGetSoftwareInfo());
  1796. reqInfo.setAutoRefresh( req.getAutoRefresh() );
  1797. reqInfo.setMemThreshold(req.getMemThreshold());
  1798. reqInfo.setDiskThreshold(req.getDiskThreshold());
  1799. reqInfo.setCpuThreshold(req.getCpuThreshold());
  1800. reqInfo.setMemThresholdType(req.getMemThresholdType());
  1801. reqInfo.setDiskThresholdType(req.getDiskThresholdType());
  1802. reqInfo.setApplyProcessFilter( req.getApplyProcessFilter() );
  1803. reqInfo.setAddProcessesToFilter( req.getAddProcessesToFilter() );
  1804. reqInfo.setSortBy("Address");
  1805. if (machineInfoData.getMachineInfoColumns().ordinality())
  1806. resp.setColumns(machineInfoData.getMachineInfoColumns());
  1807. if (machineInfoData.getMachineInfoTable().ordinality())
  1808. {
  1809. IArrayOf<IEspTargetClusterInfo> targetClusterInfoList;
  1810. setTargetClusterInfo(targetClusterTree, machineInfoData.getMachineInfoTable(), targetClusterInfoList);
  1811. if (targetClusterInfoList.ordinality())
  1812. resp.setTargetClusterInfoList(targetClusterInfoList);
  1813. }
  1814. char timeStamp[32];
  1815. getTimeStamp(timeStamp);
  1816. resp.setTimeStamp( timeStamp );
  1817. if (version >= 1.12)
  1818. {
  1819. StringBuffer acceptLanguage;
  1820. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  1821. }
  1822. }
  1823. void Cws_machineEx::setTargetClusterInfo(IPropertyTree* pTargetClusterTree, IArrayOf<IEspMachineInfoEx>& machineArray, IArrayOf<IEspTargetClusterInfo>& targetClusterInfoList)
  1824. {
  1825. if (!pTargetClusterTree)
  1826. return;
  1827. unsigned machineCount = machineArray.ordinality();
  1828. if (machineCount < 1)
  1829. return;
  1830. Owned<IPropertyTreeIterator> targetClusters = pTargetClusterTree->getElements("TargetCluster");
  1831. ForEach(*targetClusters)
  1832. {
  1833. IPropertyTree& targetCluster = targetClusters->query();
  1834. StringBuffer targetName, targetType;
  1835. targetCluster.getProp("@Name", targetName);
  1836. targetCluster.getProp("@Type", targetType);
  1837. Owned<IEspTargetClusterInfo> targetClusterInfo = static_cast<IEspTargetClusterInfo*>(new CTargetClusterInfo(""));
  1838. targetClusterInfo->setName( targetName.str() );
  1839. targetClusterInfo->setType( targetType.str() );
  1840. IArrayOf<IEspMachineInfoEx> machineArrayNew;
  1841. Owned<IPropertyTreeIterator> processes = targetCluster.getElements("Process");
  1842. ForEach(*processes)
  1843. {
  1844. IPropertyTree& process = processes->query();
  1845. StringBuffer processName, processType;
  1846. process.getProp("@Name", processName);
  1847. process.getProp("@Type", processType);
  1848. for (unsigned i = 0; i < machineCount; i++)
  1849. {
  1850. IEspMachineInfoEx& machineInfoEx = machineArray.item(i);
  1851. const char* name = machineInfoEx.getComponentName();
  1852. const char* type = machineInfoEx.getProcessType();
  1853. if (!name || !type || !strieq(name, processName.str()) || !strieq(getProcessTypeFromMachineType(type), processType.str()))
  1854. continue;
  1855. Owned<IEspMachineInfoEx> pMachineInfo = static_cast<IEspMachineInfoEx*>(new CMachineInfoEx(""));
  1856. pMachineInfo->copy(machineInfoEx);
  1857. machineArrayNew.append(*pMachineInfo.getLink());
  1858. //Cannot break here because more than one processes match (ex. EclAgent/AgentExec)
  1859. }
  1860. }
  1861. if (machineArrayNew.ordinality())
  1862. targetClusterInfo->setProcesses(machineArrayNew);
  1863. targetClusterInfoList.append(*targetClusterInfo.getLink());
  1864. }
  1865. }
  1866. const char* Cws_machineEx::getProcessTypeFromMachineType(const char* machineType)
  1867. {
  1868. const char* processType ="Unknown";
  1869. if (!machineType || !*machineType)
  1870. return processType;
  1871. if (strieq(machineType, eqThorMasterProcess) || strieq(machineType, eqThorSlaveProcess) || strieq(machineType, eqThorSpareProcess))
  1872. {
  1873. processType = eqThorCluster;
  1874. }
  1875. else if (strieq(machineType, eqRoxieServerProcess))
  1876. {
  1877. processType = eqRoxieCluster;
  1878. }
  1879. else if (strieq(machineType, eqAgentExec))
  1880. {
  1881. processType = eqEclAgent;
  1882. }
  1883. else
  1884. {
  1885. processType = machineType;
  1886. }
  1887. return processType;
  1888. }
  1889. IConstEnvironment* Cws_machineEx::getConstEnvironment()
  1890. {
  1891. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  1892. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1893. if (!constEnv)
  1894. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  1895. return constEnv.getLink();
  1896. }
  1897. //Used in Rexec
  1898. IPropertyTree* Cws_machineEx::getComponent(const char* compType, const char* compName)
  1899. {
  1900. StringBuffer xpath;
  1901. xpath.append("Software/").append(compType).append("[@name='").append(compName).append("']");
  1902. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  1903. Owned<IPropertyTree> pEnvRoot = &constEnv->getPTree();
  1904. return pEnvRoot->getPropTree( xpath.str() );
  1905. }
  1906. void Cws_machineEx::getAccountAndPlatformInfo(const char* address, StringBuffer& userId, StringBuffer& password, bool& bLinux)
  1907. {
  1908. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  1909. Owned<IConstMachineInfo> machine = constEnv->getMachineByAddress(address);
  1910. if (!machine && strieq(address, "."))
  1911. {
  1912. machine.setown(constEnv->getMachineByAddress("127.0.0.1"));
  1913. }
  1914. if (!machine)
  1915. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Machine %s is not defined in environment!", address);
  1916. Owned<IConstDomainInfo> domain = machine->getDomain();
  1917. if (!domain)
  1918. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Machine %s does not have any domain information!", address);
  1919. userId.clear();
  1920. password.clear();
  1921. StringBufferAdaptor strval1(userId);
  1922. StringBufferAdaptor strval2(password);
  1923. domain->getAccountInfo(strval1, strval2);
  1924. StringBuffer domainName;
  1925. StringBufferAdaptor strval3(domainName);
  1926. domain->getName(strval3);
  1927. if ((machine->getOS() == MachineOsW2K) && domainName.length())
  1928. {
  1929. domainName.append('\\');
  1930. userId.insert(0, domainName);
  1931. }
  1932. bLinux = machine->getOS() == MachineOsLinux;
  1933. }
  1934. bool Cws_machineEx::onGetComponentStatus(IEspContext &context, IEspGetComponentStatusRequest &req, IEspGetComponentStatusResponse &resp)
  1935. {
  1936. try
  1937. {
  1938. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Component Status. Permission denied.");
  1939. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  1940. Owned<IESPComponentStatusInfo> status = factory->getComponentStatus();
  1941. if (!status) //Should never happen
  1942. return false;
  1943. int statusID = status->getComponentStatusID();
  1944. if (statusID < 0)
  1945. {
  1946. resp.setStatus("Not reported");
  1947. }
  1948. else
  1949. {
  1950. resp.setComponentType(status->getComponentType());
  1951. resp.setEndPoint(status->getEndPoint());
  1952. resp.setReporter(status->getReporter());
  1953. resp.setComponentStatus(status->getComponentStatus());
  1954. resp.setTimeReportedStr(status->getTimeReportedStr());
  1955. IConstStatusReport* componentStatus = status->getStatusReport();
  1956. if (componentStatus)
  1957. resp.setStatusReport(*componentStatus);
  1958. resp.setComponentStatusList(status->getComponentStatusList());
  1959. }
  1960. resp.setComponentStatusID(statusID);
  1961. resp.setStatusCode(0);
  1962. }
  1963. catch(IException* e)
  1964. {
  1965. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1966. }
  1967. return true;
  1968. }
  1969. bool Cws_machineEx::onUpdateComponentStatus(IEspContext &context, IEspUpdateComponentStatusRequest &req, IEspUpdateComponentStatusResponse &resp)
  1970. {
  1971. try
  1972. {
  1973. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Update Component Status. Permission denied.");
  1974. const char* reporter = req.getReporter();
  1975. if (!reporter || !*reporter)
  1976. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Report not specified.");
  1977. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  1978. factory->updateComponentStatus(reporter, req.getComponentStatusList());
  1979. resp.setStatusCode(0);
  1980. }
  1981. catch(IException* e)
  1982. {
  1983. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1984. }
  1985. return true;
  1986. }