ws_machineService.cpp 86 KB

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