ws_machineService.cpp 76 KB

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