ws_machineService.cpp 86 KB

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