ws_machineService.cpp 85 KB

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