ws_machineService.cpp 135 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502
  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. #include "TpWrapper.hpp"
  23. #include <math.h>
  24. static const int THREAD_POOL_SIZE = 40;
  25. static const int THREAD_POOL_STACK_SIZE = 64000;
  26. static const char* FEATURE_URL = "MachineInfoAccess";
  27. const unsigned ROXIECONTROLSTATETIMEOUT = 5000; //5 second
  28. class CMachineInfoThreadParam : public CWsMachineThreadParam
  29. {
  30. public:
  31. IMPLEMENT_IINTERFACE;
  32. IEspContext& m_context;
  33. CGetMachineInfoUserOptions& m_options; //From request
  34. CMachineData& m_machineData; //From request
  35. IArrayOf<IEspMachineInfoEx>& m_machineInfoTable; //For response
  36. StringArray& m_machineInfoColumns; //For response
  37. MapStringTo<int>& channelsMap; //For response
  38. CMachineInfoThreadParam(Cws_machineEx* pService, IEspContext& context, CGetMachineInfoUserOptions& options,
  39. CMachineData& machineData, IArrayOf<IEspMachineInfoEx>& machineInfoTable, StringArray& machineInfoColumns,
  40. MapStringTo<int>& _channelsMap)
  41. : CWsMachineThreadParam(NULL, NULL, NULL, pService),
  42. m_context(context),
  43. m_options(options),
  44. m_machineData(machineData),
  45. m_machineInfoTable(machineInfoTable),
  46. m_machineInfoColumns(machineInfoColumns),
  47. channelsMap(_channelsMap)
  48. {
  49. }
  50. virtual void doWork()
  51. {
  52. m_pService->doGetMachineInfo(m_context, this);
  53. }
  54. void addColumn(const char* columnName)
  55. {
  56. synchronized block(s_mutex);
  57. if (m_machineInfoColumns.find(columnName) == NotFound)
  58. m_machineInfoColumns.append(columnName);
  59. }
  60. int* getChannels(const char* key) { return channelsMap.getValue(key); };
  61. private:
  62. static Mutex s_mutex;
  63. };
  64. Mutex CMachineInfoThreadParam::s_mutex;
  65. class CRoxieStateInfoThreadParam : public CWsMachineThreadParam
  66. {
  67. public:
  68. StringAttr clusterName;
  69. IArrayOf<IEspMachineInfoEx>& machineInfoTable; //For response
  70. MapStringTo<int>& channelsMap; //For response
  71. CRoxieStateInfoThreadParam(Cws_machineEx* pService, const char* _clusterName,
  72. IArrayOf<IEspMachineInfoEx>& _machineInfoTable, MapStringTo<int>& _channelsMap)
  73. : CWsMachineThreadParam(pService), clusterName(_clusterName), machineInfoTable(_machineInfoTable),
  74. channelsMap(_channelsMap)
  75. {
  76. }
  77. virtual void doWork()
  78. {
  79. m_pService->getRoxieStateInfo(this);
  80. }
  81. int* getChannels(const char* key) { return channelsMap.getValue(key); };
  82. };
  83. class CGetMachineUsageThreadParam : public CWsMachineThreadParam
  84. {
  85. public:
  86. IEspContext& espContext;
  87. IPropertyTree* request;
  88. CGetMachineUsageThreadParam(Cws_machineEx* pService, IEspContext& _espContext, IPropertyTree* _request)
  89. : CWsMachineThreadParam(pService), espContext(_espContext), request(_request) {}
  90. virtual void doWork()
  91. {
  92. m_pService->getMachineUsage(espContext, this);
  93. }
  94. };
  95. const char* findComponentTypeFromProcessType(const char* ProcessType)
  96. {
  97. if (strieq(ProcessType, eqDali))
  98. return "dali";
  99. if (strieq(ProcessType, eqEclAgent))
  100. return "eclagent";
  101. if (strieq(ProcessType, eqDfu))
  102. return "dfuserver";
  103. if (strieq(ProcessType, eqEsp))
  104. return "esp";
  105. if (strieq(ProcessType, eqEclCCServer) || strieq(ProcessType, eqEclServer))
  106. return "eclserver";
  107. if (strieq(ProcessType, eqEclScheduler))
  108. return "eclscheduler";
  109. if (strieq(ProcessType, eqSashaServer))
  110. return "sasha";
  111. return nullptr;
  112. }
  113. void Cws_machineEx::init(IPropertyTree *cfg, const char *process, const char *service)
  114. {
  115. //Read settings from esp.xml
  116. StringBuffer xpath;
  117. xpath.appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]", process, service);
  118. Owned<IPropertyTree> pServiceNode = cfg->getPropTree(xpath.str());
  119. m_bMonitorDaliFileServer = pServiceNode->getPropBool("@monitorDaliFileServer", false);
  120. m_processFilters.setown( pServiceNode->getPropTree("ProcessFilters") );
  121. const char* pchExcludePartitions = pServiceNode->queryProp("@excludePartitions");
  122. if (pchExcludePartitions && *pchExcludePartitions)
  123. {
  124. StringArray sPartitions;
  125. sPartitions.appendList(pchExcludePartitions, ", ;");
  126. unsigned int numOfPartitions = sPartitions.ordinality();
  127. for (unsigned int i=0; i<numOfPartitions; i++)
  128. {
  129. const char* partition = sPartitions.item(i);
  130. if (!partition || !*partition)
  131. continue;
  132. if (strchr(partition, '*'))
  133. m_excludePartitionPatterns.insert( partition );
  134. else
  135. m_excludePartitions.insert( partition );
  136. }
  137. }
  138. m_useDefaultHPCCInit = pServiceNode->getPropBool("UseDefaultHPCCInit", true);//Still used by Rexec for now
  139. m_SSHConnectTimeoutSeconds = pServiceNode->getPropInt("SSHConnectTimeoutSeconds", 5);
  140. const char* machineInfoScript = pServiceNode->queryProp("MachineInfoFile");
  141. if (machineInfoScript && *machineInfoScript)
  142. m_machineInfoFile.append(machineInfoScript);
  143. else
  144. m_machineInfoFile.append("preflight");
  145. //Read settings from environment.xml
  146. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  147. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  148. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  149. Owned<IPropertyTree> pEnvSettings = pEnvironmentRoot->getPropTree("EnvSettings");
  150. if (pEnvSettings)
  151. {
  152. pEnvSettings->getProp("configs", environmentConfData.m_configsPath.clear());
  153. pEnvSettings->getProp("path", environmentConfData.m_executionPath.clear());
  154. pEnvSettings->getProp("runtime", environmentConfData.m_runtimePath.clear());
  155. pEnvSettings->getProp("lock", environmentConfData.m_lockPath.clear());
  156. pEnvSettings->getProp("pid", environmentConfData.m_pidPath.clear());
  157. pEnvSettings->getProp("user", environmentConfData.m_user.clear());
  158. }
  159. m_threadPoolSize = pServiceNode->getPropInt("ThreadPoolSize", THREAD_POOL_SIZE);
  160. m_threadPoolStackSize = pServiceNode->getPropInt("ThreadPoolStackSize", THREAD_POOL_STACK_SIZE);
  161. //Start thread pool
  162. Owned<IThreadFactory> pThreadFactory = new CWsMachineThreadFactory();
  163. m_threadPool.setown(createThreadPool("WsMachine Thread Pool", pThreadFactory,
  164. NULL, m_threadPoolSize, 10000, m_threadPoolStackSize)); //10 sec timeout for available thread; use stack size of 2MB
  165. setupLegacyFilters();
  166. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  167. factory->init(pServiceNode);
  168. unsigned machineUsageCacheForceRebuildMinutes = pServiceNode->getPropInt("MachineUsageCacheMinutes", machineUsageCacheMinutes);
  169. unsigned machineUsageCacheAutoRebuildMinutes = pServiceNode->getPropInt("MachineUsageCacheAutoRebuildMinutes", defaultMachineUsageCacheAutoBuildMinutes);
  170. usageCacheReader.setown(new CUsageCacheReader(this, "Usage Reader", machineUsageCacheAutoRebuildMinutes*60, machineUsageCacheForceRebuildMinutes*60));
  171. }
  172. StringBuffer& Cws_machineEx::getAcceptLanguage(IEspContext& context, StringBuffer& acceptLanguage)
  173. {
  174. context.getAcceptLanguage(acceptLanguage);
  175. if (!acceptLanguage.length())
  176. {
  177. acceptLanguage.set("en");
  178. return acceptLanguage;
  179. }
  180. acceptLanguage.setLength(2);
  181. VStringBuffer languageFile("%ssmc_xslt/nls/%s/hpcc.xml", getCFD(), acceptLanguage.str());
  182. if (!checkFileExists(languageFile.str()))
  183. acceptLanguage.set("en");
  184. return acceptLanguage;
  185. }
  186. bool Cws_machineEx::onGetMachineInfo(IEspContext &context, IEspGetMachineInfoRequest & req,
  187. IEspGetMachineInfoResponse & resp)
  188. {
  189. try
  190. {
  191. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  192. StringArray& addresses = req.getAddresses();
  193. if (addresses.empty())
  194. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  195. CGetMachineInfoData machineInfoData;
  196. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  197. req.getApplyProcessFilter(), addresses, req.getAddProcessesToFilter(), machineInfoData);
  198. getMachineInfo(context, machineInfoData);
  199. setMachineInfoResponse(context, req, machineInfoData, resp);
  200. }
  201. catch(IException* e)
  202. {
  203. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  204. }
  205. return true;
  206. }
  207. bool Cws_machineEx::onGetMachineInfoEx(IEspContext &context, IEspGetMachineInfoRequestEx & req, IEspGetMachineInfoResponseEx & resp)
  208. {
  209. try
  210. {
  211. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  212. StringArray& addresses = req.getAddresses();
  213. if (addresses.empty())
  214. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  215. double version = context.getClientVersion();
  216. CGetMachineInfoData machineInfoData;
  217. readMachineInfoRequest(context, true, true, true, true, true, addresses, NULL, machineInfoData);
  218. getMachineInfo(context, machineInfoData);
  219. if (machineInfoData.getMachineInfoTable().ordinality())
  220. resp.setMachines(machineInfoData.getMachineInfoTable());
  221. if (version >= 1.12)
  222. {
  223. StringBuffer acceptLanguage;
  224. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  225. }
  226. }
  227. catch(IException* e)
  228. {
  229. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  230. }
  231. return true;
  232. }
  233. bool Cws_machineEx::onGetTargetClusterInfo(IEspContext &context, IEspGetTargetClusterInfoRequest & req,
  234. IEspGetTargetClusterInfoResponse & resp)
  235. {
  236. try
  237. {
  238. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Target Cluster Information. Permission denied.");
  239. StringArray& targetClusters = req.getTargetClusters();
  240. if (targetClusters.empty())
  241. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No target cluster specified.");
  242. CGetMachineInfoData machineInfoData;
  243. Owned<IPropertyTree> targetClustersOut = createPTreeFromXMLString("<Root/>");
  244. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  245. req.getApplyProcessFilter(), req.getAddProcessesToFilter(), targetClusters, machineInfoData, targetClustersOut);
  246. getMachineInfo(context, machineInfoData);
  247. setTargetClusterInfoResponse(context, req, machineInfoData, targetClustersOut, resp);
  248. }
  249. catch(IException* e)
  250. {
  251. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  252. }
  253. return true;
  254. }
  255. void Cws_machineEx::addChannels(CGetMachineInfoData& machineInfoData, IPropertyTree* envRoot,
  256. const char* componentType, const char* componentName)
  257. {
  258. VStringBuffer key("%s|%s", componentType, componentName);
  259. int* channels = machineInfoData.getChannels(key);
  260. if (channels)
  261. return;
  262. StringBuffer path("Software/");
  263. if (strieq(componentType, eqThorSlaveProcess))
  264. path.append(eqThorCluster);
  265. else if (strieq(componentType, eqRoxieServerProcess))
  266. path.append(eqRoxieCluster);
  267. else
  268. throw MakeStringException(ECLWATCH_INVALID_COMPONENT_TYPE, "Invalid %s in Cws_machineEx::addChannels().", componentType);
  269. path.appendf("[@name=\"%s\"]", componentName);
  270. Owned<IPropertyTree> component;
  271. if (envRoot)
  272. {
  273. component.setown(envRoot->getPropTree(path));
  274. }
  275. else
  276. {
  277. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  278. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  279. Owned<IPropertyTree> root = &constEnv->getPTree();
  280. component.setown(root->getPropTree(path));
  281. }
  282. if (!component)
  283. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "%s not found.", componentName);
  284. StringAttr attr;
  285. if (strieq(componentType, eqThorSlaveProcess))
  286. attr.set("@channelsPerSlave");
  287. else
  288. attr.set("@channelsPerNode");
  289. if (component->hasProp(attr.get()))
  290. machineInfoData.addToChannelsMap(key, component->getPropInt(attr.get()));
  291. }
  292. ////////////////////////////////////////////////////////////////////////////////////////
  293. // Read Machine Infomation request and collect related settings from environment.xml //
  294. ////////////////////////////////////////////////////////////////////////////////////////
  295. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  296. StringArray& processes, const char* addProcessesToFilters, CGetMachineInfoData& machineInfoData)
  297. {
  298. double version = context.getClientVersion();
  299. StringBuffer userID, password;
  300. context.getUserID(userID);
  301. context.getPassword(password);
  302. machineInfoData.getOptions().setUserName(userID.str());
  303. machineInfoData.getOptions().setPassword(password.str());
  304. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  305. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  306. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  307. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  308. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  309. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  310. BoolHash uniqueProcesses;
  311. for (unsigned i=0; i<processes.ordinality(); i++)
  312. {
  313. StringArray address;
  314. address.appendList(processes.item(i), ":");
  315. StringBuffer address1, address2, processType, compName, path;
  316. unsigned processNumber = 0;
  317. if (!machineInfoData.getOptions().getGetSoftwareInfo())
  318. {
  319. parseAddresses(address.item(0), address1, address2);
  320. }
  321. else
  322. {
  323. if (address.ordinality() < 5)
  324. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Invalid address format in '%s'.", processes.item(i));
  325. parseProcessString(address, address1, address2, processType, compName, path, processNumber);
  326. }
  327. setProcessRequest(machineInfoData, uniqueProcesses, address1.str(), address2.str(), processType.str(), compName.str(), path.str(), processNumber);
  328. if (strieq(processType.str(), eqRoxieServerProcess))
  329. machineInfoData.appendRoxieClusters(compName.str());
  330. if ((version >= 1.16) && (strieq(processType, eqThorSlaveProcess) || strieq(processType, eqRoxieServerProcess)))
  331. addChannels(machineInfoData, nullptr, processType, compName);
  332. }
  333. }
  334. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  335. const char* addProcessesToFilters, StringArray& targetClustersIn, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClusterTreeOut)
  336. {
  337. StringBuffer userID, password;
  338. context.getUserID(userID);
  339. context.getPassword(password);
  340. machineInfoData.getOptions().setUserName(userID.str());
  341. machineInfoData.getOptions().setPassword(password.str());
  342. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  343. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  344. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  345. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  346. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  347. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  348. readSettingsForTargetClusters(context, targetClustersIn, machineInfoData, targetClusterTreeOut);
  349. }
  350. //Parses address request from machine information request in the form "192.168.1.4-6|."
  351. //The second address is the address retrieved from environment setting (could be a '.').
  352. void Cws_machineEx::parseAddresses(const char *address, StringBuffer& address1, StringBuffer& address2)
  353. {
  354. address1 = address;
  355. address2.clear();
  356. const char* props1 = strchr(address, '|');
  357. if (props1)
  358. {
  359. address2 = props1+1;
  360. address1.setLength(props1 - address);
  361. }
  362. address1.trim();
  363. address2.trim();
  364. }
  365. //Parses machine information request for each process in the form "192.168.1.4-6|.:ThorSlaveProcess:thor1:2:/var/lib/..."
  366. void Cws_machineEx::parseProcessString(StringArray& process, StringBuffer& address1, StringBuffer& address2,
  367. StringBuffer& processType, StringBuffer& compName, StringBuffer& path, unsigned& processNumber)
  368. {
  369. parseAddresses(process.item(0), address1, address2);
  370. processType.clear().append( process.item(1) ).trim();
  371. compName.clear().append( process.item(2) ).trim();
  372. EnvMachineOS os = (EnvMachineOS) atoi( process.item(3) );
  373. path.clear().append( process.item(4) ).trim();
  374. if (path.length())
  375. {
  376. char pat1, pat2;
  377. char rep1, rep2;
  378. if (os == MachineOsLinux)
  379. {
  380. pat1 = ':'; rep1 = '$';
  381. pat2 = '\\';rep2 = '/';
  382. }
  383. else
  384. {
  385. pat1 = '$'; rep1 = ':';
  386. pat2 = '/';rep2 = '\\';
  387. }
  388. path.replace( pat1, rep1 );
  389. path.replace( pat2, rep2 );
  390. if ((os == MachineOsLinux) && (path.charAt(0) != '/'))
  391. path.insert(0, '/');
  392. }
  393. if (process.ordinality() < 6)
  394. return;
  395. processNumber = atoi( process.item(5) );
  396. }
  397. void Cws_machineEx::setProcessRequest(CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses, const char* address1, const char* address2,
  398. const char* processType, const char* compName, const char* path, unsigned processNumber)
  399. {
  400. IpAddress ipAddr;
  401. unsigned numIps = ipAddr.ipsetrange(address1);
  402. //address is like 192.168.1.4-6
  403. //so process each address in the range
  404. if (!ipAddr.isIp4())
  405. IPV6_NOT_IMPLEMENTED();
  406. //Always use "EclAgentProcess" to retrieve machine info for "AgentExecProcess"
  407. StringBuffer processTypeStr;
  408. if (processType && *processType)
  409. {
  410. if (strieq(processType, eqAgentExec))
  411. processTypeStr.append(eqEclAgent);
  412. else
  413. processTypeStr = processType;
  414. }
  415. while (numIps--)
  416. {
  417. unsigned numAddr;
  418. if (ipAddr.getNetAddress(sizeof(numAddr),&numAddr)!=sizeof(numAddr))
  419. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid network address.");
  420. ipAddr.ipincrement(1);
  421. //Clean possible duplication
  422. StringBuffer valuesToBeChecked;
  423. valuesToBeChecked.append(numAddr);
  424. if (machineInfoData.getOptions().getGetSoftwareInfo())
  425. valuesToBeChecked.appendf(":%s:%s:%d", processTypeStr.str(), compName, processNumber);
  426. bool* found = uniqueProcesses.getValue(valuesToBeChecked.str());
  427. if (found && *found)
  428. continue;
  429. uniqueProcesses.setValue(valuesToBeChecked.str(), true);
  430. addProcessRequestToMachineInfoData(machineInfoData, address1, address2, processTypeStr.str(), compName, path, processNumber);
  431. }
  432. }
  433. void Cws_machineEx::addProcessRequestToMachineInfoData(CGetMachineInfoData& machineInfoData, const char* address1, const char* address2,
  434. const char* processType, const char* compName, const char* path, unsigned processNumber)
  435. {
  436. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  437. ForEachItemIn(idx, machines)
  438. {
  439. CMachineData& machine = machines.item(idx);
  440. if (streq(address1, machine.getNetworkAddress()))
  441. {
  442. addProcessData(&machine, processType, compName, path, processNumber);
  443. return;
  444. }
  445. }
  446. char pathSep;
  447. EnvMachineOS os;
  448. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  449. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(address1);
  450. if (pMachineInfo.get())
  451. os = pMachineInfo->getOS();
  452. else
  453. os = MachineOsUnknown;
  454. if (os == MachineOsW2K)
  455. pathSep = '\\';
  456. else
  457. pathSep = '/';
  458. if (!m_processFilters)
  459. return;
  460. Owned<CMachineData> machineNew = new CMachineData(address1, address2, os, pathSep);
  461. //Read possible dependencies for all processes
  462. set<string>& dependenciesForAllProcesses = machineNew->getDependencies();
  463. StringBuffer xPath;
  464. xPath.appendf("Platform[@name='%s']/ProcessFilter[@name='any']/Process", machineNew->getOS() == MachineOsW2K ? "Windows" : "Linux");
  465. Owned<IPropertyTreeIterator> processes = m_processFilters->getElements(xPath.str());
  466. ForEach (*processes)
  467. {
  468. StringBuffer processName;
  469. processes->query().getProp("@name", processName);
  470. processName.toLowerCase().replaceString(".exe", "");
  471. if ((processName.length() > 0) && (!streq(processName.str(), "hoagentd"))) //hoagentd is not needed anymore
  472. dependenciesForAllProcesses.insert(processName.str());
  473. }
  474. if (m_bMonitorDaliFileServer && (dependenciesForAllProcesses.find("dafilesrv") == dependenciesForAllProcesses.end()))
  475. dependenciesForAllProcesses.insert("dafilesrv");
  476. addProcessData(machineNew, processType, compName, path, processNumber);
  477. machines.append(*machineNew.getClear());
  478. }
  479. //Create a CProcessData object and add it to CMachineData
  480. void Cws_machineEx::addProcessData(CMachineData* machine, const char* processType, const char* compName,
  481. const char* path, unsigned processNumber)
  482. {
  483. if (!machine)
  484. return;
  485. StringBuffer pathStr(path);
  486. if (pathStr.length() > 0)
  487. {
  488. char pathSep = machine->getPathSep();
  489. if (pathStr.charAt(pathStr.length() - 1) != pathSep)
  490. pathStr.append(pathSep);
  491. }
  492. Owned<CProcessData> process = new CProcessData(compName, processType, pathStr.str(), processNumber);
  493. //Copy dependencies for all processes
  494. set<string>& dependenciesForThisProcess = process->getDependencies();
  495. set<string>& dependenciesForAllProcesses = machine->getDependencies();
  496. set<string>::const_iterator it = dependenciesForAllProcesses.begin();
  497. set<string>::const_iterator iEnd = dependenciesForAllProcesses.end();
  498. for (; it != iEnd; it++) //add in sorted order simply by traversing the map
  499. dependenciesForThisProcess.insert((*it).c_str());
  500. //now collect "process-specific" dependencies
  501. IPropertyTree* processFilterNode = nullptr;
  502. if (m_processFilters)
  503. {
  504. VStringBuffer xPath("Platform[@name='%s']/ProcessFilter[@name='%s']", machine->getOS() == MachineOsW2K ? "Windows" : "Linux", processType);
  505. processFilterNode = m_processFilters->queryPropTree( xPath.str() );
  506. }
  507. if (!processFilterNode)
  508. {
  509. machine->getProcesses().append(*process.getClear());
  510. return;
  511. }
  512. Owned<IPropertyTreeIterator> processes = processFilterNode->getElements("Process");
  513. ForEach (*processes)
  514. {
  515. IPropertyTree* pProcess = &processes->query();
  516. const char* name = pProcess->queryProp("@name");
  517. if (!name || streq(name, "."))
  518. continue;
  519. StringBuffer processName(name);
  520. processName.toLowerCase().replaceString(".exe", "");
  521. if (processName.length() < 1)
  522. continue;
  523. //Environment.xml may contain old filter settings.
  524. if (isLegacyFilter(processType, processName.str()))
  525. continue;
  526. if (pProcess->getPropBool("@remove", false))
  527. dependenciesForThisProcess.erase(processName.str());
  528. else
  529. dependenciesForThisProcess.insert(processName.str());
  530. }
  531. process->setMultipleInstances(machine->getOS() == MachineOsLinux && processFilterNode->getPropBool("@multipleInstances", false));
  532. machine->getProcesses().append(*process.getClear());
  533. }
  534. //Collect process settings for the requested target clusters
  535. void Cws_machineEx::readSettingsForTargetClusters(IEspContext& context, StringArray& targetClusters, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClustersOut)
  536. {
  537. unsigned ordinality= targetClusters.ordinality();
  538. if (ordinality < 1)
  539. return;
  540. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  541. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  542. if (!pEnvironmentRoot)
  543. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  544. BoolHash uniqueProcesses;
  545. for (unsigned index=0; index<ordinality; index++)
  546. {
  547. StringBuffer clusterType;
  548. const char* clusterName = targetClusters.item(index);
  549. const char* pClusterName = strchr(clusterName, ':');
  550. if (pClusterName)
  551. {
  552. clusterType.append(clusterName, 0, pClusterName - clusterName);
  553. pClusterName++;
  554. }
  555. if (!pClusterName || !*pClusterName)
  556. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name not specified.");
  557. if (clusterType.length() < 1)
  558. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster type not specified.");
  559. StringBuffer path;
  560. path.appendf("Software/Topology/Cluster[@name='%s']", pClusterName);
  561. IPropertyTree* pCluster = pEnvironmentRoot->queryPropTree(path.str());
  562. if (!pCluster)
  563. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", pClusterName);
  564. Owned<IPropertyTreeIterator> clusterProcesses;
  565. if (strieq(clusterType.str(), eqThorCluster) || strieq(clusterType.str(), eqRoxieCluster))
  566. {
  567. clusterProcesses.setown(pCluster->getElements(clusterType.str()));
  568. if (!clusterProcesses->first())
  569. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", clusterType.str());
  570. }
  571. Owned<IPropertyTreeIterator> eclCCServerProcesses= pCluster->getElements(eqEclCCServer);
  572. Owned<IPropertyTreeIterator> eclServerProcesses= pCluster->getElements(eqEclServer);
  573. Owned<IPropertyTreeIterator> eclAgentProcesses= pCluster->getElements(eqEclAgent);
  574. Owned<IPropertyTreeIterator> eclSchedulerProcesses= pCluster->getElements(eqEclScheduler);
  575. IPropertyTree *targetClusterOut = targetClustersOut->addPropTree("TargetCluster", createPTree("TargetCluster"));
  576. targetClusterOut->setProp("@Name", pClusterName);
  577. targetClusterOut->setProp("@Type", clusterType.str());
  578. //Read Cluster processes
  579. if (clusterProcesses && clusterProcesses->first())
  580. ForEach(*clusterProcesses)
  581. readTargetClusterProcesses(context, clusterProcesses->query(), clusterType.str(), uniqueProcesses, machineInfoData, targetClusterOut);
  582. //Read eclCCServer process
  583. if (eclCCServerProcesses->first())
  584. readTargetClusterProcesses(context, eclCCServerProcesses->query(), eqEclCCServer, uniqueProcesses, machineInfoData, targetClusterOut);
  585. //Read eclServer process
  586. if (eclServerProcesses->first())
  587. readTargetClusterProcesses(context, eclServerProcesses->query(), eqEclServer, uniqueProcesses, machineInfoData, targetClusterOut);
  588. //Read eclAgent process
  589. if (eclAgentProcesses->first())
  590. readTargetClusterProcesses(context, eclAgentProcesses->query(), eqEclAgent, uniqueProcesses, machineInfoData, targetClusterOut);
  591. //Read eclScheduler process
  592. if (eclSchedulerProcesses->first())
  593. readTargetClusterProcesses(context, eclSchedulerProcesses->query(), eqEclScheduler, uniqueProcesses, machineInfoData, targetClusterOut);
  594. }
  595. }
  596. //Collect settings for one group of target cluster processes
  597. void Cws_machineEx::readTargetClusterProcesses(IEspContext& context, IPropertyTree &processNode, const char* nodeType, BoolHash& uniqueProcesses, CGetMachineInfoData& machineInfoData,
  598. IPropertyTree* targetClustersOut)
  599. {
  600. const char* process = processNode.queryProp("@process");
  601. if (!process || !*process)
  602. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process attribute not set for ECLCCServer in environment setting.");
  603. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  604. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  605. if (!pEnvironmentRoot)
  606. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  607. IPropertyTree* pEnvironmentSoftware = pEnvironmentRoot->queryPropTree("Software");
  608. if (!pEnvironmentSoftware)
  609. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  610. double version = context.getClientVersion();
  611. IPropertyTree* pClusterProcess = NULL;
  612. if (strieq(nodeType, eqThorCluster) || strieq(nodeType, eqRoxieCluster))
  613. {
  614. StringBuffer path;
  615. path.appendf("Software/%s[@name='%s']", nodeType, process);
  616. pClusterProcess = pEnvironmentRoot->queryPropTree(path.str());
  617. if (!pClusterProcess)
  618. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process not set for %s in environment setting.", path.str());
  619. if (strieq(nodeType, eqRoxieCluster))
  620. machineInfoData.appendRoxieClusters(process);
  621. }
  622. IPropertyTree *pInfo = targetClustersOut->addPropTree("Process", createPTree("Process"));
  623. pInfo->setProp("@Name", process);
  624. pInfo->setProp("@Type", nodeType);
  625. StringBuffer dirStr;
  626. IPropertyTree* pEnvironmentDirectories = pEnvironmentSoftware->queryPropTree("Directories");
  627. if (!pClusterProcess)
  628. {
  629. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  630. dirStr.clear().append(processNode.queryProp("@directory"));
  631. getProcesses(constEnv, pEnvironmentSoftware, process, nodeType, dirStr.str(), machineInfoData, false, uniqueProcesses);
  632. return;
  633. }
  634. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  635. dirStr.clear().append(pClusterProcess->queryProp("@directory"));
  636. if (strieq(nodeType, eqThorCluster))
  637. {
  638. getProcesses(constEnv, pClusterProcess, process, eqThorMasterProcess, dirStr.str(), machineInfoData, true, uniqueProcesses);
  639. getThorProcesses(constEnv, pClusterProcess, process, eqThorSlaveProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  640. getThorProcesses(constEnv, pClusterProcess, process, eqThorSpareProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  641. if (version >= 1.16)
  642. addChannels(machineInfoData, pEnvironmentRoot, eqThorSlaveProcess, process);
  643. }
  644. else if (strieq(nodeType, eqRoxieCluster))
  645. {
  646. BoolHash uniqueRoxieProcesses;
  647. getProcesses(constEnv, pClusterProcess, process, eqRoxieServerProcess, dirStr.str(), machineInfoData, true, uniqueProcesses, &uniqueRoxieProcesses);
  648. if (version >= 1.16)
  649. addChannels(machineInfoData, pEnvironmentRoot, eqRoxieServerProcess, process);
  650. }
  651. }
  652. void Cws_machineEx::getThorProcesses(IConstEnvironment* constEnv, IPropertyTree* cluster, const char* processName,
  653. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses)
  654. {
  655. if (!constEnv || !cluster)
  656. return;
  657. Owned<IGroup> nodeGroup;
  658. StringBuffer groupName;
  659. if (strieq(processType, eqThorSlaveProcess))
  660. {
  661. getClusterGroupName(*cluster, groupName);
  662. if (groupName.length() < 1)
  663. {
  664. OWARNLOG("Cannot find group name for %s", processName);
  665. return;
  666. }
  667. nodeGroup.setown(getClusterProcessNodeGroup(processName, eqThorCluster));
  668. }
  669. else
  670. {
  671. getClusterSpareGroupName(*cluster, groupName);
  672. if (groupName.length() < 1)
  673. {
  674. OWARNLOG("Cannot find group name for %s", processName);
  675. return;
  676. }
  677. nodeGroup.setown(queryNamedGroupStore().lookup(groupName.str()));
  678. }
  679. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  680. {
  681. OWARNLOG("Cannot find node group for %s", processName);
  682. return;
  683. }
  684. int slavesPerNode = cluster->getPropInt("@slavesPerNode");
  685. Owned<INodeIterator> gi = nodeGroup->getIterator();
  686. ForEach(*gi)
  687. {
  688. StringBuffer addressRead;
  689. gi->query().endpoint().getIpText(addressRead);
  690. if (addressRead.length() == 0)
  691. {
  692. OWARNLOG("Network address not found for a node in node group %s", groupName.str());
  693. continue;
  694. }
  695. StringBuffer netAddress;
  696. const char* ip = addressRead.str();
  697. if (!streq(ip, "."))
  698. {
  699. netAddress.append(ip);
  700. }
  701. else
  702. {
  703. IpAddress ipaddr = queryHostIP();
  704. ipaddr.getIpText(netAddress);
  705. }
  706. if (netAddress.length() == 0)
  707. {
  708. OWARNLOG("Network address not found for a node in node group %s", groupName.str());
  709. continue;
  710. }
  711. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(addressRead.str());
  712. if (!pMachineInfo.get())
  713. {
  714. OWARNLOG("Machine not found at network address %s", addressRead.str());
  715. continue;
  716. }
  717. //Each thor slave is a process. The i is used to check whether the process is running or not.
  718. for (unsigned i = 1; i <= slavesPerNode; i++)
  719. setProcessRequest(machineInfoData, uniqueProcesses, netAddress.str(), addressRead.str(),
  720. processType, processName, directory, i);
  721. }
  722. return;
  723. }
  724. void Cws_machineEx::getProcesses(IConstEnvironment* constEnv, IPropertyTree* environment, const char* processName,
  725. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData,
  726. bool isThorOrRoxieProcess, BoolHash& uniqueProcesses, BoolHash* uniqueRoxieProcesses)
  727. {
  728. Owned<IPropertyTreeIterator> processes= environment->getElements(processType);
  729. ForEach(*processes)
  730. {
  731. StringArray processInstances, directories;
  732. IPropertyTree &process = processes->query();
  733. //Thor master and roxie server has been checked before this call.
  734. if (!isThorOrRoxieProcess)
  735. {
  736. const char* name = process.queryProp("@name");
  737. if (!name || !*name || !streq(name, processName))
  738. continue;
  739. }
  740. const char* computerName = process.queryProp("@computer");
  741. if (computerName && *computerName)
  742. appendProcessInstance(computerName, directory, NULL, processInstances, directories);
  743. else
  744. {
  745. Owned<IPropertyTreeIterator> instances= process.getElements("Instance");
  746. ForEach(*instances)
  747. {
  748. IPropertyTree &instance = instances->query();
  749. appendProcessInstance(instance.queryProp("@computer"), directory, instance.queryProp("@directory"), processInstances, directories);
  750. }
  751. }
  752. if (processInstances.length() < 1)
  753. continue;
  754. for (unsigned i = 0; i < processInstances.length(); i++)
  755. {
  756. const char* name0 = processInstances.item(i);
  757. const char* directory0 = directories.item(i);
  758. if (uniqueRoxieProcesses)//to avoid duplicate entries for roxie (one machine has only one roxie process).
  759. {
  760. bool* found = uniqueRoxieProcesses->getValue(name0);
  761. if (found && *found)
  762. continue;
  763. uniqueRoxieProcesses->setValue(name0, true);
  764. }
  765. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachine(name0);
  766. if (!pMachineInfo.get())
  767. {
  768. OWARNLOG("Machine %s not found in environment setting", name0);
  769. continue;
  770. }
  771. SCMStringBuffer ep;
  772. pMachineInfo->getNetAddress(ep);
  773. if (ep.length() == 0)
  774. {
  775. OWARNLOG("Network address not found for machine %s", name0);
  776. continue;
  777. }
  778. setProcessRequest(machineInfoData, uniqueProcesses, ep.str(), ep.str(), processType, processName, directory0);
  779. }
  780. }
  781. return;
  782. }
  783. void Cws_machineEx::setupLegacyFilters()
  784. {
  785. unsigned idx = 0;
  786. while (legacyFilterStrings[idx])
  787. {
  788. m_legacyFilters.setValue(legacyFilterStrings[idx], true);
  789. idx++;
  790. }
  791. return;
  792. }
  793. bool Cws_machineEx::isLegacyFilter(const char* processType, const char* dependency)
  794. {
  795. if (!processType || !*processType || !dependency || !*dependency)
  796. return false;
  797. StringBuffer filterString;
  798. filterString.appendf("%s:%s", processType, dependency);
  799. bool* found = m_legacyFilters.getValue(filterString.str());
  800. if (found && *found)
  801. return true;
  802. return false;
  803. }
  804. //The stateHashes stores different state hashes in one roxie cluster.
  805. //It also stores how many roxie nodes have the same state hashes.
  806. unsigned Cws_machineEx::addRoxieStateHash(const char* hash, StateHashes& stateHashes, unsigned& totalUniqueHashes)
  807. {
  808. if (!hash || !*hash)
  809. return -1;
  810. unsigned hashID = 0;
  811. IStateHash* stateHash = stateHashes.getValue(hash);
  812. if (stateHash)
  813. {
  814. //if the stateHashes already has the same 'hash', increases the count for the 'stateHash'.
  815. //The 'StateHash' with the highest count will be the 'Major StateHash'.
  816. //If a roxie node does not contain the 'Major StateHash', it has a 'mismatch' state hash.
  817. hashID = stateHash->queryID();
  818. stateHash->incrementCount();
  819. }
  820. else
  821. {
  822. //Add a new 'StateHash'. Set its hashID to totalUniqueHashes and set its count to 1.
  823. hashID = totalUniqueHashes;
  824. Owned<IStateHash> newStateHash = new CStateHash(hashID, 1);
  825. stateHashes.setValue(hash, newStateHash);
  826. totalUniqueHashes++;
  827. }
  828. return hashID;
  829. }
  830. void Cws_machineEx::updateMajorRoxieStateHash(StateHashes& stateHashes, CIArrayOf<CRoxieStateData>& roxieStates)
  831. {
  832. //Find out which state hash is for the most of the roxie nodes inside this roxie cluster.
  833. unsigned majorHashID = 0;
  834. unsigned majorHashCount = 0;
  835. HashIterator hashes(stateHashes);
  836. ForEach(hashes)
  837. {
  838. IStateHash *hash = stateHashes.mapToValue(&hashes.query());
  839. unsigned hashCount = hash->queryCount();
  840. if (majorHashCount >= hashCount)
  841. continue;
  842. majorHashCount = hashCount;
  843. majorHashID = hash->queryID();
  844. }
  845. //Set the MajorHash to false if the roxie node's HashID() != majorHashID.
  846. ForEachItemIn(ii, roxieStates)
  847. {
  848. CRoxieStateData& roxieState = roxieStates.item(ii);
  849. if (roxieState.getHashID() != majorHashID)
  850. roxieState.setMajorHash(false);
  851. }
  852. }
  853. void Cws_machineEx::readRoxieStatus(const Owned<IPropertyTree> controlResp, CIArrayOf<CRoxieStateData>& roxieStates)
  854. {
  855. StateHashes stateHashes;
  856. unsigned totalUniqueHashes = 0;
  857. Owned<IPropertyTreeIterator> roxieEndpoints = controlResp->getElements("Endpoint");
  858. ForEach(*roxieEndpoints)
  859. {
  860. IPropertyTree& roxieEndpoint = roxieEndpoints->query();
  861. const char *ep = roxieEndpoint.queryProp("@ep");
  862. if (!ep || !*ep)
  863. continue;
  864. bool ok = false, attached = false, detached = false;
  865. const char *status = roxieEndpoint.queryProp("Status");
  866. if (status && strieq(status, "ok"))
  867. ok = true;
  868. const char *stateHash = roxieEndpoint.queryProp("State/@hash");
  869. if (roxieEndpoint.hasProp("Dali/@connected"))
  870. {
  871. if (roxieEndpoint.getPropBool("Dali/@connected"))
  872. attached = true;
  873. else
  874. detached = true;
  875. }
  876. StringArray locations;
  877. locations.appendListUniq(ep, ":");
  878. Owned<CRoxieStateData> roxieState = new CRoxieStateData(locations.item(0), addRoxieStateHash(stateHash, stateHashes, totalUniqueHashes));
  879. roxieState->setState(ok, attached, detached, stateHash);
  880. roxieStates.append(*roxieState.getClear());
  881. }
  882. if (totalUniqueHashes > 1)
  883. updateMajorRoxieStateHash(stateHashes, roxieStates);
  884. }
  885. void Cws_machineEx::getRoxieStateInfo(CRoxieStateInfoThreadParam* param)
  886. {
  887. const char* clusterName = param->clusterName.get();
  888. if (!clusterName || !*clusterName)
  889. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Roxie cluster not specified.");
  890. SocketEndpointArray servers;
  891. getRoxieProcessServers(clusterName, servers);
  892. if (!servers.length())
  893. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Roxie Process server not found.");
  894. Owned<IRoxieCommunicationClient> roxieClient = createRoxieCommunicationClient(servers.item(0), ROXIECONTROLSTATETIMEOUT);
  895. Owned<IPropertyTree> controlResp = roxieClient->sendRoxieControlAllNodes("<control:state/>", true);
  896. if (!controlResp)
  897. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get control response from roxie %s.", clusterName);
  898. CIArrayOf<CRoxieStateData> roxieStates;
  899. readRoxieStatus(controlResp, roxieStates);
  900. ForEachItemIn(i, param->machineInfoTable)
  901. {
  902. IEspMachineInfoEx& machineInfo = param->machineInfoTable.item(i);
  903. if (!streq(machineInfo.getProcessType(), eqRoxieServerProcess) || !streq(machineInfo.getComponentName(), clusterName))
  904. continue;
  905. //This method is thread safe because each machineInfo (for one roxie node) belongs to only one Roxie cluster.
  906. //It is impossible for different threads to update the same machineInfo.
  907. bool foundRoxieState = false;
  908. ForEachItemIn(ii, roxieStates)
  909. {
  910. CRoxieStateData& roxieState = roxieStates.item(ii);
  911. if (!roxieState.matchIPAddress(machineInfo.getAddress()))
  912. continue;
  913. StringBuffer state, stateDetails;
  914. roxieState.reportState(state, stateDetails);
  915. machineInfo.setRoxieState(state.str());
  916. machineInfo.setRoxieStateDetails(stateDetails.str());
  917. foundRoxieState = true;
  918. }
  919. if (!foundRoxieState)
  920. {
  921. machineInfo.setRoxieState("??");
  922. machineInfo.setRoxieStateDetails("Roxie state not found");
  923. }
  924. }
  925. }
  926. void Cws_machineEx::getMachineInfo(IEspContext& context, bool getRoxieState, CGetMachineInfoData& machineInfoData)
  927. {
  928. UnsignedArray threadHandles;
  929. if (!getRoxieState)
  930. {
  931. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  932. ForEachItemIn(idx, machines)
  933. {
  934. Owned<CMachineInfoThreadParam> pThreadReq = new CMachineInfoThreadParam(this, context, machineInfoData.getOptions(),
  935. machines.item(idx), machineInfoData.getMachineInfoTable(), machineInfoData.getMachineInfoColumns(),
  936. machineInfoData.getChannelsMap());
  937. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  938. threadHandles.append(handle);
  939. }
  940. }
  941. else
  942. {
  943. StringArray& roxieClusters = machineInfoData.getRoxieClusters();
  944. ForEachItemIn(i, roxieClusters)
  945. {
  946. Owned<CRoxieStateInfoThreadParam> pThreadReq = new CRoxieStateInfoThreadParam(this, roxieClusters.item(i),
  947. machineInfoData.getMachineInfoTable(), machineInfoData.getChannelsMap());
  948. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  949. threadHandles.append(handle);
  950. }
  951. machineInfoData.getMachineInfoColumns().append("Roxie State");
  952. }
  953. //Block for worker threads to finish, if necessary and then collect results
  954. //Not use joinAll() because multiple threads may call this method. Each call uses the pool to create
  955. //its own threads of checking query state. Each call should only join the ones created by that call.
  956. ForEachItemIn(i, threadHandles)
  957. m_threadPool->join(threadHandles.item(i));
  958. }
  959. ////////////////////////////////////////////////////////////////////
  960. // Get Machine Information based on Machine Information request //
  961. ////////////////////////////////////////////////////////////////////
  962. void Cws_machineEx::getMachineInfo(IEspContext& context, CGetMachineInfoData& machineInfoData)
  963. {
  964. double version = context.getClientVersion();
  965. getMachineInfo(context, false, machineInfoData);
  966. if ((version >= 1.13) && !machineInfoData.getRoxieClusters().empty())
  967. getMachineInfo(context, true, machineInfoData);
  968. }
  969. // the following method is invoked on worker threads of CMachineInfoThreadParam
  970. void Cws_machineEx::doGetMachineInfo(IEspContext& context, CMachineInfoThreadParam* pParam)
  971. {
  972. #ifdef DETECT_WS_MC_MEM_LEAKS
  973. static bool firstTime = true;
  974. if (firstTime)
  975. {
  976. firstTime = false;
  977. unsigned t = setAllocHook(true);
  978. }
  979. #endif //DETECT_WS_MC_MEM_LEAKS
  980. int error = 0;
  981. StringBuffer preflightCommand, response;
  982. buildPreflightCommand(context, pParam, preflightCommand);
  983. if (preflightCommand.length() < 1)
  984. {
  985. response.append("Failed in creating Machine Information command.\n");
  986. error = -1;
  987. }
  988. else
  989. {
  990. 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);
  991. if ((error == 0) && (response.length() > 0))
  992. readPreflightResponse(context, pParam, response.str(), error);
  993. }
  994. //Set IArrayOf<IEspMachineInfoEx> based on Preflight Response
  995. setMachineInfo(context, pParam, response.str(), error);
  996. #ifdef DETECT_WS_MC_MEM_LEAKS
  997. DBGLOG("Allocated=%d", setAllocHook(false));
  998. #endif //DETECT_WS_MC_MEM_LEAKS
  999. }
  1000. void Cws_machineEx::buildPreflightCommand(IEspContext& context, CMachineInfoThreadParam* pParam, StringBuffer& preflightCommand)
  1001. {
  1002. preflightCommand.clear().appendf("/%s/sbin/%s -p=%s", environmentConfData.m_executionPath.str(),
  1003. m_machineInfoFile.str(), environmentConfData.m_pidPath.str());
  1004. if (preflightCommand.charAt(preflightCommand.length() - 1) == pParam->m_machineData.getPathSep())
  1005. preflightCommand.remove(preflightCommand.length()-1, 1);
  1006. bool checkDependency = false;
  1007. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1008. ForEachItemIn(idx, processes)
  1009. {
  1010. CProcessData& process = processes.item(idx);
  1011. if (!process.getName() || !*process.getName())
  1012. continue;
  1013. StringBuffer procName;
  1014. if (streq(process.getType(), eqThorSlaveProcess))
  1015. procName.appendf("thorslave_%s_%d,%s_slave_%d", process.getName(), process.getProcessNumber(), process.getName(), process.getProcessNumber());
  1016. else if (streq(process.getType(), eqThorMasterProcess))
  1017. procName.appendf("%s,%s_master", process.getName(), process.getName());
  1018. else
  1019. procName.append(process.getName());
  1020. if (idx < 1)
  1021. preflightCommand.appendf(" -n=%s", procName.str());
  1022. else
  1023. preflightCommand.appendf(",%s", procName.str());
  1024. if (!process.getDependencies().empty())
  1025. checkDependency = true;
  1026. }
  1027. if (checkDependency || !pParam->m_options.getApplyProcessFilter())
  1028. preflightCommand.append(" -d=ALL");
  1029. if (pParam->m_options.getGetStorageInfo() && !pParam->m_options.getLocalFileSystemsOnly())
  1030. preflightCommand.append(" -m=YES");
  1031. }
  1032. int Cws_machineEx::runCommand(IEspContext& context, const char* sAddress, const char* sConfigAddress, EnvMachineOS os,
  1033. const char* sCommand, const char* sUserId, const char* sPassword, StringBuffer& response)
  1034. {
  1035. int exitCode = -1;
  1036. try
  1037. {
  1038. StringBuffer command(sCommand);
  1039. StringBuffer userId;
  1040. StringBuffer password;
  1041. bool bLinux;
  1042. if (sConfigAddress && *sConfigAddress)
  1043. getAccountAndPlatformInfo(sConfigAddress, userId, password, bLinux);
  1044. else
  1045. getAccountAndPlatformInfo(sAddress, userId, password, bLinux);
  1046. if (!sUserId || !*sUserId || !sPassword ||!*sPassword)
  1047. {
  1048. //BUG: 9825 - remote execution on linux needs to use individual accounts
  1049. //use userid/password in ESP context for remote execution...
  1050. if (bLinux)
  1051. {
  1052. userId.clear();
  1053. password.clear();
  1054. context.getUserID(userId);
  1055. context.getPassword(password);
  1056. }
  1057. }
  1058. else
  1059. {
  1060. userId.clear().append(sUserId);
  1061. password.clear().append(sPassword);
  1062. }
  1063. // make sure there actually is something in command before we run a remote connection
  1064. if (command.length() < 1)
  1065. return exitCode;
  1066. Owned<IFRunSSH> connection = createFRunSSH();
  1067. connection->init(command.str(),NULL,NULL,NULL,m_SSHConnectTimeoutSeconds,0);
  1068. // executed as single connection
  1069. connection->exec(IpAddress(sAddress),NULL,false);
  1070. response.append(connection->getReplyText()[0]);
  1071. exitCode = connection->getReply()[0];
  1072. int len = response.length();
  1073. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1074. response.setLength(len);
  1075. if (response.length() && !exitCode)
  1076. response.insert(0, "Response: ");
  1077. else if (!exitCode)
  1078. response.insert(0, "No response recieved.\n");
  1079. }
  1080. // CFRunSSH uses a MakeStringExceptionDirect throw to pass code and result string
  1081. catch(IException* e)
  1082. {
  1083. exitCode = e->errorCode();
  1084. // errorCode == -1 on successful CFRunSSH execution
  1085. if(exitCode == -1)
  1086. exitCode = 0;
  1087. StringBuffer buf;
  1088. e->errorMessage(buf);
  1089. response.append(buf.str());
  1090. int len = response.length();
  1091. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1092. response.setLength(len);
  1093. // on successful connection
  1094. if (response.length() && !exitCode)
  1095. response.insert(0,"Response: ");
  1096. else if (!exitCode)
  1097. response.insert(0, "No response recieved.\n");
  1098. e->Release();
  1099. }
  1100. #ifndef NO_CATCHALL
  1101. catch(...)
  1102. {
  1103. response.append("An unknown exception occurred!");
  1104. exitCode = -1;
  1105. }
  1106. #endif
  1107. return exitCode;
  1108. }
  1109. int Cws_machineEx::invokeProgram(const char *command_line, StringBuffer& response)
  1110. {
  1111. char buffer[128];
  1112. FILE *fp;
  1113. // Run the command so that it writes its output to a pipe. Open this
  1114. // pipe with read text attribute so that we can read it
  1115. // like a text file.
  1116. if (getEspLogLevel()>LogNormal)
  1117. {
  1118. DBGLOG("command_line=<%s>", command_line);
  1119. }
  1120. #ifndef NO_CONNECTION_DEBUG
  1121. if( (fp = popen( command_line, "r" )) == NULL )
  1122. return -1;
  1123. #else
  1124. if( (fp = fopen( "c:\\temp\\preflight_result.txt", "r" )) == NULL )
  1125. return -1;
  1126. #endif
  1127. // Read pipe until end of file. End of file indicates that
  1128. //the stream closed its standard out (probably meaning it
  1129. //terminated).
  1130. while ( !feof(fp) )
  1131. if ( fgets( buffer, 128, fp) )
  1132. response.append( buffer );
  1133. if (getEspLogLevel()>LogNormal)
  1134. {
  1135. DBGLOG("response=<%s>", response.str());
  1136. }
  1137. // Close pipe and print return value of CHKDSK.
  1138. #ifndef NO_CONNECTION_DEBUG
  1139. return pclose( fp );
  1140. #else
  1141. return fclose( fp );
  1142. #endif
  1143. }
  1144. void Cws_machineEx::readPreflightResponse(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response, int error)
  1145. {
  1146. if (!response || !*response)
  1147. return;
  1148. StringBuffer computerUpTime;
  1149. readALineFromResult(response, "ComputerUpTime:", computerUpTime, true);
  1150. if (computerUpTime.length() < 1)
  1151. computerUpTime.append("-");
  1152. else
  1153. {
  1154. const char* pStr = strchr(computerUpTime.str(), ' ');
  1155. if (pStr)
  1156. {
  1157. pStr++;
  1158. pStr = strchr(pStr, ' ');
  1159. if (pStr)
  1160. {
  1161. pStr++;
  1162. if (pStr)
  1163. pParam->m_machineData.setComputerUpTime(pStr);
  1164. }
  1165. }
  1166. if (!pStr)
  1167. pParam->m_machineData.setComputerUpTime(computerUpTime);
  1168. }
  1169. if (pParam->m_options.getGetProcessorInfo())
  1170. {
  1171. StringBuffer CPUIdle;
  1172. readALineFromResult(response, "CPU-Idle:", CPUIdle, true);
  1173. if (CPUIdle.length() < 1)
  1174. pParam->m_machineData.setCPULoad(0);
  1175. else
  1176. {
  1177. if (CPUIdle.charAt(CPUIdle.length() - 1) == '%')
  1178. CPUIdle.setLength(CPUIdle.length() - 1);
  1179. pParam->m_machineData.setCPULoad(100-atoi(CPUIdle.str()));
  1180. }
  1181. }
  1182. if (pParam->m_options.getGetStorageInfo())
  1183. readStorageData(response, pParam);
  1184. if (pParam->m_options.getGetSoftwareInfo())
  1185. readProcessData(response, pParam);
  1186. }
  1187. void Cws_machineEx::readALineFromResult(const char *result, const char *start, StringBuffer& value, bool trim)
  1188. {
  1189. if (!result || !*result)
  1190. return;
  1191. const char* pStr = strstr(result, start);
  1192. if (!pStr)
  1193. return;
  1194. pStr += strlen(start);
  1195. if (!pStr)
  1196. return;
  1197. const char* pStr1 = strchr(pStr, 0x0a);
  1198. if (pStr1)
  1199. value.append(pStr, 0, pStr1 - pStr);
  1200. else
  1201. value.append(pStr);
  1202. if (trim)
  1203. value.trim();
  1204. }
  1205. void Cws_machineEx::readStorageData(const char* response, CMachineInfoThreadParam* pParam)
  1206. {
  1207. if (!response || !*response)
  1208. return;
  1209. const char* pStr = strstr(response, "---SpaceUsedAndFree---");
  1210. if (!pStr)
  1211. DBGLOG("Storage information not found on %s", pParam->m_machineData.getNetworkAddress());
  1212. bool isTitleLine = true;
  1213. CIArrayOf<CStorageData>& storage = pParam->m_machineData.getStorage();
  1214. while (pStr)
  1215. {
  1216. StringBuffer buf;
  1217. const char* pStr1 = strchr(pStr, 0x0a);
  1218. if (pStr1)
  1219. {
  1220. buf.append(pStr, 0, pStr1 - pStr);
  1221. pStr = pStr1+1;
  1222. }
  1223. else
  1224. {
  1225. buf.append(pStr);
  1226. pStr = NULL;
  1227. }
  1228. if (isTitleLine)
  1229. {
  1230. isTitleLine = false;
  1231. continue;
  1232. }
  1233. if (buf.length() > 0)
  1234. {
  1235. Owned<CStorageData> sData = new CStorageData(true, false, true);
  1236. if (!sData->read(buf))
  1237. DBGLOG("Invalid storage information on %s: %s", pParam->m_machineData.getNetworkAddress(), buf.str());
  1238. else
  1239. {
  1240. const char* title = sData->getDiskSpaceTitle();
  1241. if (!isEmptyString(title) && !excludePartition(title))
  1242. storage.append(*sData.getClear());
  1243. }
  1244. }
  1245. if (!pStr || (strnicmp(pStr, "---ProcessList1---", 18)==0))
  1246. break;
  1247. }
  1248. }
  1249. bool CStorageData::read(const char* s)
  1250. {
  1251. if (isEmptyString(s))
  1252. return false;
  1253. const char* pStr = s;
  1254. if (m_readTitle)
  1255. {
  1256. const char* finger = strchr(pStr, ':');
  1257. if (!finger)
  1258. return false;
  1259. m_diskSpaceTitle.append(pStr, 0, finger - pStr);
  1260. pStr = finger + 2;
  1261. }
  1262. StringArray data;
  1263. data.appendList(pStr, " ");
  1264. if (data.length() < 2)
  1265. return false;
  1266. m_diskSpaceUsed = atol(data.item(0));
  1267. m_diskSpaceAvailable = atol(data.item(1));
  1268. if (m_toMByte)
  1269. {
  1270. //Convert from kilobytes to megabytes
  1271. m_diskSpaceAvailable = llround((double)m_diskSpaceAvailable/1024);
  1272. m_diskSpaceUsed = llround((double)m_diskSpaceUsed/1024);
  1273. }
  1274. m_diskSpaceTotal = m_diskSpaceAvailable + m_diskSpaceUsed;
  1275. if (m_diskSpaceTotal > 0)
  1276. m_diskSpacePercentAvail = round((float)m_diskSpaceAvailable*100/m_diskSpaceTotal);
  1277. if (data.length() > 2)
  1278. {
  1279. pStr = data.item(2);
  1280. if (isdigit(*pStr))
  1281. {
  1282. m_diskSpaceActualSize = atol(pStr);
  1283. if (m_toMByte)
  1284. m_diskSpaceActualSize = llround((double)m_diskSpaceActualSize/1024);
  1285. //If a given path (ex. /var/lib/HPCCSystems/hpcc-mirror/thor) in the usage request does not exist,
  1286. //the data.item(3) is the path (ex. /var/lib/HPCCSystems/hpcc-mirror/) the usage script is used
  1287. //to read the DiskSpace.
  1288. if (m_readPath && (data.length() > 3))
  1289. m_path.set(data.item(3));
  1290. }
  1291. else if (m_readPath)
  1292. m_path.set(pStr);
  1293. }
  1294. return true;
  1295. }
  1296. void Cws_machineEx::buildProcessPath(StringBuffer &processPath, const char * processName, CMachineInfoThreadParam * pParam)
  1297. {
  1298. if (environmentConfData.m_pidPath.charAt(environmentConfData.m_pidPath.length() - 1) != pParam->m_machineData.getPathSep())
  1299. processPath.setf("%s%c%s:", environmentConfData.m_pidPath.str(), pParam->m_machineData.getPathSep(), processName);
  1300. else
  1301. processPath.setf("%s%s:", environmentConfData.m_pidPath.str(), processName);
  1302. }
  1303. void Cws_machineEx::readProcessData(const char* response, CMachineInfoThreadParam* pParam)
  1304. {
  1305. if (!response || !*response)
  1306. return;
  1307. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1308. ForEachItemIn(idx, processes)
  1309. {
  1310. CProcessData& process = processes.item(idx);
  1311. if (!process.getName() || !*process.getName())
  1312. continue;
  1313. StringBuffer procName, catError, processPath, processData;
  1314. if (streq(process.getType(), eqThorSlaveProcess))
  1315. {
  1316. procName.appendf("thorslave_%s_%d", process.getName(), process.getProcessNumber());
  1317. buildProcessPath(processPath,procName.str(),pParam);
  1318. catError.setf("cat: %s",processPath.str());
  1319. catError.insert(catError.length()-1,".pid");
  1320. if (!strstr(response,catError.str()))
  1321. readALineFromResult(response, processPath.str(), processData, true);
  1322. else
  1323. {
  1324. procName.setf("%s_slave_%d", process.getName(), process.getProcessNumber());
  1325. buildProcessPath(processPath,procName.str(),pParam);
  1326. readALineFromResult(response, processPath.str(), processData, true);
  1327. }
  1328. }
  1329. else if (streq(process.getType(), eqThorMasterProcess))
  1330. {
  1331. procName.appendf("%s", process.getName());
  1332. buildProcessPath(processPath,procName.str(),pParam);
  1333. catError.setf("cat: %s",processPath.str());
  1334. catError.insert(catError.length()-1,".pid");
  1335. if (!strstr(response,catError.str()))
  1336. readALineFromResult(response, processPath.str(), processData, true);
  1337. else
  1338. {
  1339. procName.setf("%s_master", process.getName());
  1340. buildProcessPath(processPath,procName.str(),pParam);
  1341. readALineFromResult(response, processPath.str(), processData, true);
  1342. }
  1343. }
  1344. else
  1345. {
  1346. procName.append(process.getName());
  1347. buildProcessPath(processPath,procName.str(),pParam);
  1348. readALineFromResult(response, processPath.str(), processData, true);
  1349. }
  1350. if (processData.length() < 1)
  1351. {
  1352. DBGLOG("Information for process %s not found", processPath.str());
  1353. continue;
  1354. }
  1355. const char* pStr = strchr(processData.str(), ' ');
  1356. if (!pStr)
  1357. {
  1358. DBGLOG("incorrect data for process %s: %s", processPath.str(), processData.str());
  1359. continue;
  1360. }
  1361. unsigned len = pStr - processData.str();
  1362. StringBuffer pid, upTime;
  1363. pid.append(processData.str(), 0, len);
  1364. len++;
  1365. upTime.append(processData.str(), len, processData.length() - len);
  1366. upTime.replaceString("-", " day(s) ");
  1367. process.setPID(pid.str());
  1368. process.setUpTime(upTime.str());
  1369. }
  1370. readRunningProcesses(response, pParam);
  1371. }
  1372. void Cws_machineEx::readRunningProcesses(const char* response, CMachineInfoThreadParam* pParam)
  1373. {
  1374. if (!response || !*response)
  1375. return;
  1376. const char* pStr = strstr(response, "---ProcessList2---");
  1377. if (!pStr)
  1378. DBGLOG("Running process not found on %s", pParam->m_machineData.getNetworkAddress());
  1379. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1380. while (pStr)
  1381. {
  1382. //read a line
  1383. StringBuffer lineStr;
  1384. const char* pStr1 = strchr(pStr, 0x0a);
  1385. if (!pStr1)
  1386. {
  1387. lineStr.append(pStr);
  1388. pStr = NULL;
  1389. }
  1390. else
  1391. {
  1392. lineStr.append(pStr, 0, pStr1 - pStr);
  1393. pStr = pStr1+1;
  1394. }
  1395. if (lineStr.length() < 1)
  1396. continue;
  1397. StringBuffer pidStr, desc, param;
  1398. pStr1 = lineStr.str();
  1399. const char* pStr2 = strchr(pStr1, ' ');
  1400. if (!pStr2)
  1401. continue;
  1402. pidStr.append(pStr1, 0, pStr2 - pStr1);
  1403. param.append(pStr2+1);
  1404. if (param.length() < 1)
  1405. continue;
  1406. if (streq(param.str(), "ps"))
  1407. continue;
  1408. bool isNumber = true;
  1409. for (unsigned i = 0; i < pidStr.length(); i++)
  1410. {
  1411. if (!isdigit(pidStr.charAt(i)))
  1412. {
  1413. isNumber = false;
  1414. break;
  1415. }
  1416. }
  1417. if (!isNumber)
  1418. continue;
  1419. int pid = atoi(pidStr.str());
  1420. desc = param;
  1421. if ((desc.charAt(0) == '.') && (param.charAt(1) == '/'))
  1422. desc.remove(0, 2);
  1423. if (desc.charAt(desc.length() - 1) == '/')
  1424. desc.remove(desc.length() - 1, 1);
  1425. if (desc.charAt(0) == '[')
  1426. {
  1427. desc.remove(0, 1);
  1428. if (desc.charAt(desc.length() - 1) == ']')
  1429. desc.remove(desc.length() - 1, 1);
  1430. }
  1431. Owned<IEspProcessInfo> info = createProcessInfo("","");
  1432. info->setPID(pid);
  1433. info->setParameter(param.str());
  1434. info->setDescription(desc.str());
  1435. runningProcesses.append(*info.getClear());
  1436. }
  1437. }
  1438. void Cws_machineEx::setMachineInfo(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response, int error)
  1439. {
  1440. //Read additionalProcessFilters which will be used in setProcessInfo()/setProcessComponent()
  1441. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1442. StringArray& additionalProcessFilters = pParam->m_options.getAdditionalProcessFilters();
  1443. if (pParam->m_options.getApplyProcessFilter() && !additionalProcessFilters.empty())
  1444. {
  1445. int len = additionalProcessFilters.length();
  1446. for (int i=0; i<len; i++)
  1447. {
  1448. StringBuffer processName(additionalProcessFilters.item(i));
  1449. processName.toLowerCase().replaceString(".exe", "");
  1450. if (processName.length() > 0)
  1451. additionalProcesses.insert(processName.str());
  1452. }
  1453. }
  1454. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1455. ForEachItemIn(idx, processes)
  1456. {
  1457. CProcessData& process = processes.item(idx);
  1458. Owned<IEspMachineInfoEx> pMachineInfo = static_cast<IEspMachineInfoEx*>(new CMachineInfoEx(""));
  1459. setProcessInfo(context, pParam, response, error, process, idx<1, pMachineInfo);
  1460. synchronized block(mutex_machine_info_table);
  1461. pParam->m_machineInfoTable.append(*pMachineInfo.getLink());
  1462. }
  1463. }
  1464. void Cws_machineEx::setProcessInfo(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response,
  1465. int error, CProcessData& process, bool firstProcess, IEspMachineInfoEx* pMachineInfo)
  1466. {
  1467. double version = context.getClientVersion();
  1468. bool isEclAgentProcess = process.getType() && strieq(process.getType(), eqEclAgent);
  1469. pMachineInfo->setAddress(pParam->m_machineData.getNetworkAddress());
  1470. pMachineInfo->setConfigAddress(pParam->m_machineData.getNetworkAddressInEnvSetting());
  1471. pMachineInfo->setOS(pParam->m_machineData.getOS());
  1472. if (process.getName() && *process.getName())
  1473. pMachineInfo->setComponentName(process.getName());
  1474. if (process.getPath() && *process.getPath())
  1475. pMachineInfo->setComponentPath(process.getPath());
  1476. //set DisplayType
  1477. if (process.getType() && *process.getType())
  1478. {
  1479. if (isEclAgentProcess)
  1480. {
  1481. pMachineInfo->setProcessType(eqAgentExec);
  1482. pMachineInfo->setDisplayType("Agent Exec");
  1483. }
  1484. else
  1485. {
  1486. pMachineInfo->setProcessType(process.getType());
  1487. StringBuffer displayName;
  1488. getProcessDisplayName(process.getType(), displayName);
  1489. pMachineInfo->setDisplayType(displayName.str());
  1490. }
  1491. }
  1492. else if (process.getName() && *process.getName())
  1493. {
  1494. pMachineInfo->setDisplayType(process.getName());
  1495. }
  1496. if ((version > 1.09) && process.getType() && strieq(process.getType(), eqThorSlaveProcess))
  1497. {
  1498. pMachineInfo->setProcessNumber(process.getProcessNumber());
  1499. }
  1500. if ((version >= 1.16) && (strieq(process.getType(), eqThorSlaveProcess) || strieq(process.getType(), eqRoxieServerProcess)))
  1501. {
  1502. VStringBuffer key("%s|%s", process.getType(), process.getName());
  1503. int* channels = pParam->getChannels(key);
  1504. if (channels)
  1505. pMachineInfo->setChannels(*channels);
  1506. }
  1507. if (error != 0 || !response || !*response)
  1508. {
  1509. StringBuffer description;
  1510. if (!response || !*response)
  1511. description.append("Failed in getting Machine Information");
  1512. else
  1513. description = response;
  1514. if (version < 1.17)
  1515. pMachineInfo->setDescription(description.str());
  1516. else
  1517. pMachineInfo->setException(description.str());
  1518. }
  1519. else
  1520. {
  1521. //Now, add more columns based on 'response'
  1522. pMachineInfo->setUpTime(pParam->m_machineData.getComputerUpTime());
  1523. pParam->addColumn("Up Time");
  1524. if (pParam->m_options.getGetStorageInfo())
  1525. {
  1526. IArrayOf<IEspStorageInfo> storageArray;
  1527. CIArrayOf<CStorageData>& storage = pParam->m_machineData.getStorage();
  1528. ForEachItemIn(idx, storage)
  1529. {
  1530. CStorageData& diskData = storage.item(idx);
  1531. Owned<IEspStorageInfo> info = static_cast<IEspStorageInfo*>(new CStorageInfo(""));
  1532. info->setDescription(diskData.getDiskSpaceTitle());
  1533. info->setTotal(diskData.getDiskSpaceTotal());
  1534. info->setAvailable(diskData.getDiskSpaceAvailable());
  1535. info->setPercentAvail(diskData.getDiskSpacePercentAvail());
  1536. storageArray.append(*info.getLink());
  1537. pParam->addColumn(diskData.getDiskSpaceTitle());
  1538. }
  1539. pMachineInfo->setStorage(storageArray);
  1540. storageArray.kill();
  1541. }
  1542. if (pParam->m_options.getGetProcessorInfo())
  1543. {
  1544. IArrayOf<IEspProcessorInfo> processorArray;
  1545. Owned<IEspProcessorInfo> info = static_cast<IEspProcessorInfo*>(new CProcessorInfo(""));
  1546. info->setLoad(pParam->m_machineData.getCPULoad());
  1547. processorArray.append(*info.getLink());
  1548. pMachineInfo->setProcessors(processorArray);
  1549. processorArray.kill();
  1550. pParam->addColumn("CPU Load");
  1551. }
  1552. if (pParam->m_options.getGetSoftwareInfo())
  1553. {
  1554. IArrayOf<IEspSWRunInfo> processArray;
  1555. IEspComponentInfo* pComponentInfo = &pMachineInfo->updateComponentInfo();
  1556. setProcessComponent(context, pParam, process, firstProcess, processArray, pComponentInfo);
  1557. if (processArray.ordinality())
  1558. {
  1559. //Set running processes if ApplyProcessFilter is set to false
  1560. //Set processes not running if ApplyProcessFilter is set to true
  1561. pMachineInfo->setRunning(processArray);
  1562. }
  1563. pParam->addColumn("Processes");
  1564. pParam->addColumn("Condition");
  1565. pParam->addColumn("State");
  1566. pParam->addColumn("UpTime");
  1567. }
  1568. }
  1569. }
  1570. void Cws_machineEx::setProcessComponent(IEspContext& context, CMachineInfoThreadParam* pParam, CProcessData& process,
  1571. bool firstProcess, IArrayOf<IEspSWRunInfo>& processArray, IEspComponentInfo* pComponentInfo)
  1572. {
  1573. const char* procType = process.getType();
  1574. const char* procPID = process.getPID();
  1575. //If a component (ex. dropzone) has no process type, it is not a process and does not have a PID.
  1576. //FTSlaveProcess may not have a PID since it is launched dynamically during a spray.
  1577. if (pParam->m_options.getApplyProcessFilter() && (isEmptyString(procPID) &&
  1578. !isEmptyString(procType) && !strieq(procType, "FTSlaveProcess")))
  1579. {
  1580. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1581. info->setName(process.getName());
  1582. info->setInstances(0);
  1583. processArray.append( *info.getLink() );
  1584. }
  1585. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1586. map<string, Linked<IEspSWRunInfo> > runningProcessMap; //save only one description of each process
  1587. set<string>& dependencies = process.getDependencies();
  1588. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1589. if (runningProcesses.length() > 0)
  1590. {
  1591. if (!pParam->m_options.getApplyProcessFilter()) //need to display all of the running processes
  1592. enumerateRunningProcesses( pParam, process, &runningProcessMap, firstProcess);
  1593. else if (!dependencies.empty() || !additionalProcesses.empty())
  1594. enumerateRunningProcesses(pParam, process, NULL, firstProcess);
  1595. }
  1596. map<string, Linked<IEspSWRunInfo> >::const_iterator it = runningProcessMap.begin();
  1597. map<string, Linked<IEspSWRunInfo> >::const_iterator iEnd = runningProcessMap.end();
  1598. for (; it != iEnd; it++) //add in sorted order simply by traversing the map
  1599. {
  1600. Linked<IEspSWRunInfo> info( (*it).second );
  1601. processArray.append( *info.getLink() );
  1602. }
  1603. bool dependencyDown = false;
  1604. if (!dependencies.empty())
  1605. {
  1606. dependencyDown = true;
  1607. if (pParam->m_options.getApplyProcessFilter())
  1608. {
  1609. set<string>::const_iterator it = dependencies.begin();
  1610. set<string>::const_iterator iEnd = dependencies.end();
  1611. for (; it != iEnd; it++)
  1612. {
  1613. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1614. info->setName(it->c_str());
  1615. info->setInstances(0);
  1616. processArray.append( *info.getLink() );
  1617. }
  1618. }
  1619. }
  1620. if (pParam->m_options.getApplyProcessFilter() && !additionalProcesses.empty())
  1621. {
  1622. set<string>::const_iterator it = additionalProcesses.begin();
  1623. set<string>::const_iterator iEnd = additionalProcesses.end();
  1624. for (; it != iEnd; it++)
  1625. {
  1626. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1627. info->setName(it->c_str());
  1628. info->setInstances(0);
  1629. processArray.append( *info.getLink() );
  1630. }
  1631. }
  1632. if (!dependencyDown && (!isEmptyString(procPID) || isEmptyString(procType) || strieq(procType, "FTSlaveProcess")))
  1633. {
  1634. //conditions: unknown, normal, warning, minor, major, critical, fatal
  1635. pComponentInfo->setCondition( 1 );
  1636. pComponentInfo->setState(5);
  1637. if (process.getUpTime() && *process.getUpTime())
  1638. pComponentInfo->setUpTime( process.getUpTime() );
  1639. }
  1640. else
  1641. {
  1642. pComponentInfo->setCondition(2); //Warnning
  1643. pComponentInfo->setState(0);
  1644. }
  1645. }
  1646. //Erase this process from dependencies and, if firstProcess, additionalProcesses;
  1647. //If processMap is not NULL, add this process to processMap
  1648. void Cws_machineEx::enumerateRunningProcesses(CMachineInfoThreadParam* pParam, CProcessData& process, map<string, Linked<IEspSWRunInfo> >* runningProcessMap, bool firstProcess)
  1649. {
  1650. set<string>& dependencies = process.getDependencies();
  1651. set<string>& additionalProcesses = pParam->m_machineData.getAdditinalProcessFilters();
  1652. IArrayOf<IEspProcessInfo>& runningProcesses = pParam->m_machineData.getRunningProcesses();
  1653. ForEachItemIn(k, runningProcesses)
  1654. {
  1655. IEspProcessInfo& processInfo = runningProcesses.item(k);
  1656. //Erase this process from dependencies and, if firstProcess, additionalProcesses
  1657. const char* pName = processInfo.getDescription();
  1658. if (pParam->m_machineData.getOS() == MachineOsW2K)
  1659. {
  1660. StringBuffer sName(pName);
  1661. pName = sName.toLowerCase().replaceString(".exe", "").str();
  1662. if (!dependencies.empty())
  1663. dependencies.erase(pName);
  1664. if (pParam->m_options.getApplyProcessFilter() && firstProcess && !additionalProcesses.empty())
  1665. additionalProcesses.erase(pName);
  1666. }
  1667. else
  1668. {
  1669. //dafilesrv would probably be running from a global directory
  1670. //and not component's installation directory so ignore their paths
  1671. const char* pPath = pName;
  1672. if ( !strieq(pName, "dafilesrv"))
  1673. {
  1674. const char* param = processInfo.getParameter();
  1675. if (param && *param)
  1676. {
  1677. if (strncmp(param, "bash ", 5))
  1678. pPath = param;
  1679. else
  1680. pPath = param + 5;
  1681. if (!pPath || !*pPath)
  1682. continue;
  1683. //params typically is like "/c$/esp_dir/esp [parameters...]"
  1684. //so just pick the full path
  1685. const char* pch = strchr(pPath, ' ');
  1686. if (pch)
  1687. {
  1688. StringBuffer sPath(pPath);
  1689. sPath.setLength( pch - pPath );
  1690. pPath = sPath.str();
  1691. }
  1692. }
  1693. }
  1694. if (!dependencies.empty())
  1695. {
  1696. const char* pProcessName;
  1697. if (process.getType() && !strncmp(process.getType(), "Thor", 4) && !strnicmp(pName, "thor", 4))
  1698. {
  1699. const char* pch = strrchr(pPath, pParam->m_machineData.getPathSep());
  1700. pProcessName = pch ? pch+1 : pName;
  1701. }
  1702. else
  1703. {
  1704. const char* pName0 = process.getMultipleInstances() ? pPath : pName;
  1705. const char* pch = strrchr(pName0, pParam->m_machineData.getPathSep());
  1706. pProcessName = pch ? pch+1 : pName0;
  1707. }
  1708. dependencies.erase(pProcessName);
  1709. if (pParam->m_options.getApplyProcessFilter() && firstProcess && !additionalProcesses.empty())
  1710. additionalProcesses.erase(pProcessName);
  1711. }
  1712. pName = pPath;
  1713. }
  1714. if (!runningProcessMap)
  1715. continue;
  1716. //Add this process to runningProcessMap
  1717. map<string, Linked<IEspSWRunInfo> >::iterator it = runningProcessMap->find(pName);
  1718. if ( it != runningProcessMap->end()) //not in the set
  1719. {
  1720. Linked<IEspSWRunInfo>& linkedPtr = (*it).second;
  1721. linkedPtr->setInstances( linkedPtr->getInstances() + 1);
  1722. }
  1723. else
  1724. {
  1725. Owned<IEspSWRunInfo> info = static_cast<IEspSWRunInfo*>(new CSWRunInfo(""));
  1726. info->setName(pName);
  1727. info->setInstances(1);
  1728. runningProcessMap->insert(pair<string, Linked<IEspSWRunInfo> >(pName, info));
  1729. }
  1730. }
  1731. }
  1732. void Cws_machineEx::getProcessDisplayName(const char* processName, StringBuffer& displayName)
  1733. {
  1734. //produces "LDAPServerProcess" as "LDAP Server" and "EspService" as "Esp Service", etc.
  1735. const char* end = strstr(processName, "Process");
  1736. if (!end)
  1737. end = processName + strlen(processName);
  1738. displayName.append(*processName);
  1739. processName++;
  1740. bool bLower = false;
  1741. while (processName < end)
  1742. {
  1743. char ch = *processName;
  1744. if (!isupper(ch))
  1745. bLower = true;
  1746. else
  1747. {
  1748. if (bLower || //last char was uppercase or the following character is lowercase?
  1749. ((processName+1 < end) && islower(*(processName+1))))
  1750. {
  1751. displayName.append(' ');
  1752. }
  1753. bLower = false;
  1754. }
  1755. displayName.append(*processName);
  1756. processName++;
  1757. }
  1758. displayName.append('\0');
  1759. return;
  1760. }
  1761. bool Cws_machineEx::excludePartition(const char* partition) const
  1762. {
  1763. //first see if this partition is meant to be excluded as is - for instance
  1764. //if partition is /dev and /dev is one of the predefined partitions to be excluded
  1765. set<string>::const_iterator it = m_excludePartitions.find( partition );
  1766. set<string>::const_iterator itEnd = m_excludePartitions.end();
  1767. bool found = false;
  1768. if (it != itEnd)
  1769. found = true;
  1770. else
  1771. {
  1772. //now check if /dev* is one of the partitions to be excluded
  1773. set<string>::const_iterator itBegin = m_excludePartitionPatterns.begin();
  1774. itEnd = m_excludePartitionPatterns.end();
  1775. unsigned int partitionLen = strlen(partition);
  1776. for (it=itBegin; it != itEnd; it++)
  1777. {
  1778. const string& pattern = *it;
  1779. if ((found = ::WildMatch(partition, partitionLen, pattern.c_str(), pattern.length(), false)))
  1780. break;
  1781. }
  1782. }
  1783. return found;
  1784. }
  1785. void Cws_machineEx::appendProcessInstance(const char* name, const char* directory1, const char* directory2, StringArray& processInstances, StringArray& directories)
  1786. {
  1787. if (!name || !*name)
  1788. return;
  1789. processInstances.append(name);
  1790. if (directory1 && *directory1)
  1791. directories.append(directory1);
  1792. else if (directory2 && *directory2)
  1793. directories.append(directory2);
  1794. else
  1795. directories.append("Setting not found");
  1796. }
  1797. //////////////////////////////////////////////////////////////////
  1798. // Set Machine Infomation for response //
  1799. //////////////////////////////////////////////////////////////////
  1800. void Cws_machineEx::setMachineInfoResponse(IEspContext& context, IEspGetMachineInfoRequest& req,
  1801. CGetMachineInfoData& machineInfoData, IEspGetMachineInfoResponse& resp)
  1802. {
  1803. IEspRequestInfoStruct& reqInfo = resp.updateRequestInfo();
  1804. #if 0
  1805. StringBuffer user;
  1806. StringBuffer pw;
  1807. context.getUserID(user);
  1808. context.getPassword(pw);
  1809. reqInfo.setUserName(user.str());
  1810. reqInfo.setPassword(pw.str());
  1811. #endif
  1812. reqInfo.setSecurityString(req.getSecurityString());
  1813. reqInfo.setGetProcessorInfo(req.getGetProcessorInfo());
  1814. reqInfo.setGetStorageInfo(req.getGetStorageInfo());
  1815. double version = context.getClientVersion();
  1816. if (version > 1.10)
  1817. reqInfo.setLocalFileSystemsOnly(req.getLocalFileSystemsOnly());
  1818. reqInfo.setGetSoftwareInfo(req.getGetSoftwareInfo());
  1819. reqInfo.setAutoRefresh( req.getAutoRefresh() );
  1820. reqInfo.setMemThreshold(req.getMemThreshold());
  1821. reqInfo.setDiskThreshold(req.getDiskThreshold());
  1822. reqInfo.setCpuThreshold(req.getCpuThreshold());
  1823. reqInfo.setMemThresholdType(req.getMemThresholdType());
  1824. reqInfo.setDiskThresholdType(req.getDiskThresholdType());
  1825. reqInfo.setApplyProcessFilter( req.getApplyProcessFilter() );
  1826. reqInfo.setClusterType( req.getClusterType() );
  1827. reqInfo.setCluster( req.getCluster() );
  1828. reqInfo.setAddProcessesToFilter( req.getAddProcessesToFilter() );
  1829. reqInfo.setOldIP( req.getOldIP() );
  1830. reqInfo.setPath( req.getPath() );
  1831. reqInfo.setSortBy("Address");
  1832. if (machineInfoData.getMachineInfoColumns().ordinality())
  1833. resp.setColumns(machineInfoData.getMachineInfoColumns());
  1834. if (machineInfoData.getMachineInfoTable().ordinality())
  1835. resp.setMachines(machineInfoData.getMachineInfoTable());
  1836. char timeStamp[32];
  1837. getTimeStamp(timeStamp);
  1838. resp.setTimeStamp( timeStamp );
  1839. if (version >= 1.12)
  1840. {
  1841. StringBuffer acceptLanguage;
  1842. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  1843. }
  1844. }
  1845. void Cws_machineEx::getTimeStamp(char* timeStamp)
  1846. {
  1847. //set time stamp in the result for this machine
  1848. time_t tNow;
  1849. time(&tNow);
  1850. #ifdef _WIN32
  1851. struct tm *ltNow;
  1852. ltNow = localtime(&tNow);
  1853. strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S", ltNow);
  1854. #else
  1855. struct tm ltNow;
  1856. localtime_r(&tNow, &ltNow);
  1857. strftime(timeStamp, 32, "%m/%d/%y %H:%M:%S", &ltNow);
  1858. #endif
  1859. }
  1860. void Cws_machineEx::setTargetClusterInfoResponse(IEspContext& context, IEspGetTargetClusterInfoRequest& req,
  1861. CGetMachineInfoData& machineInfoData, IPropertyTree* targetClusterTree, IEspGetTargetClusterInfoResponse& resp)
  1862. {
  1863. IEspRequestInfoStruct& reqInfo = resp.updateRequestInfo();
  1864. #if 0
  1865. StringBuffer user;
  1866. StringBuffer pw;
  1867. context.getUserID(user);
  1868. context.getPassword(pw);
  1869. reqInfo.setUserName(user.str());
  1870. reqInfo.setPassword(pw.str());
  1871. #endif
  1872. reqInfo.setGetProcessorInfo(req.getGetProcessorInfo());
  1873. reqInfo.setGetStorageInfo(req.getGetStorageInfo());
  1874. double version = context.getClientVersion();
  1875. if (version > 1.10)
  1876. reqInfo.setLocalFileSystemsOnly(req.getLocalFileSystemsOnly());
  1877. reqInfo.setGetSoftwareInfo(req.getGetSoftwareInfo());
  1878. reqInfo.setAutoRefresh( req.getAutoRefresh() );
  1879. reqInfo.setMemThreshold(req.getMemThreshold());
  1880. reqInfo.setDiskThreshold(req.getDiskThreshold());
  1881. reqInfo.setCpuThreshold(req.getCpuThreshold());
  1882. reqInfo.setMemThresholdType(req.getMemThresholdType());
  1883. reqInfo.setDiskThresholdType(req.getDiskThresholdType());
  1884. reqInfo.setApplyProcessFilter( req.getApplyProcessFilter() );
  1885. reqInfo.setAddProcessesToFilter( req.getAddProcessesToFilter() );
  1886. reqInfo.setSortBy("Address");
  1887. if (machineInfoData.getMachineInfoColumns().ordinality())
  1888. resp.setColumns(machineInfoData.getMachineInfoColumns());
  1889. if (machineInfoData.getMachineInfoTable().ordinality())
  1890. {
  1891. IArrayOf<IEspTargetClusterInfo> targetClusterInfoList;
  1892. setTargetClusterInfo(targetClusterTree, machineInfoData.getMachineInfoTable(), targetClusterInfoList);
  1893. if (targetClusterInfoList.ordinality())
  1894. resp.setTargetClusterInfoList(targetClusterInfoList);
  1895. }
  1896. char timeStamp[32];
  1897. getTimeStamp(timeStamp);
  1898. resp.setTimeStamp( timeStamp );
  1899. if (version >= 1.12)
  1900. {
  1901. StringBuffer acceptLanguage;
  1902. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  1903. }
  1904. }
  1905. void Cws_machineEx::setTargetClusterInfo(IPropertyTree* pTargetClusterTree, IArrayOf<IEspMachineInfoEx>& machineArray, IArrayOf<IEspTargetClusterInfo>& targetClusterInfoList)
  1906. {
  1907. if (!pTargetClusterTree)
  1908. return;
  1909. unsigned machineCount = machineArray.ordinality();
  1910. if (machineCount < 1)
  1911. return;
  1912. Owned<IPropertyTreeIterator> targetClusters = pTargetClusterTree->getElements("TargetCluster");
  1913. ForEach(*targetClusters)
  1914. {
  1915. IPropertyTree& targetCluster = targetClusters->query();
  1916. StringBuffer targetName, targetType;
  1917. targetCluster.getProp("@Name", targetName);
  1918. targetCluster.getProp("@Type", targetType);
  1919. Owned<IEspTargetClusterInfo> targetClusterInfo = static_cast<IEspTargetClusterInfo*>(new CTargetClusterInfo(""));
  1920. targetClusterInfo->setName( targetName.str() );
  1921. targetClusterInfo->setType( targetType.str() );
  1922. IArrayOf<IEspMachineInfoEx> machineArrayNew;
  1923. Owned<IPropertyTreeIterator> processes = targetCluster.getElements("Process");
  1924. ForEach(*processes)
  1925. {
  1926. IPropertyTree& process = processes->query();
  1927. StringBuffer processName, processType;
  1928. process.getProp("@Name", processName);
  1929. process.getProp("@Type", processType);
  1930. for (unsigned i = 0; i < machineCount; i++)
  1931. {
  1932. IEspMachineInfoEx& machineInfoEx = machineArray.item(i);
  1933. const char* name = machineInfoEx.getComponentName();
  1934. const char* type = machineInfoEx.getProcessType();
  1935. if (!name || !type || !strieq(name, processName.str()) || !strieq(getProcessTypeFromMachineType(type), processType.str()))
  1936. continue;
  1937. Owned<IEspMachineInfoEx> pMachineInfo = static_cast<IEspMachineInfoEx*>(new CMachineInfoEx(""));
  1938. pMachineInfo->copy(machineInfoEx);
  1939. machineArrayNew.append(*pMachineInfo.getLink());
  1940. //Cannot break here because more than one processes match (ex. EclAgent/AgentExec)
  1941. }
  1942. }
  1943. if (machineArrayNew.ordinality())
  1944. targetClusterInfo->setProcesses(machineArrayNew);
  1945. targetClusterInfoList.append(*targetClusterInfo.getLink());
  1946. }
  1947. }
  1948. const char* Cws_machineEx::getProcessTypeFromMachineType(const char* machineType)
  1949. {
  1950. const char* processType ="Unknown";
  1951. if (!machineType || !*machineType)
  1952. return processType;
  1953. if (strieq(machineType, eqThorMasterProcess) || strieq(machineType, eqThorSlaveProcess) || strieq(machineType, eqThorSpareProcess))
  1954. {
  1955. processType = eqThorCluster;
  1956. }
  1957. else if (strieq(machineType, eqRoxieServerProcess))
  1958. {
  1959. processType = eqRoxieCluster;
  1960. }
  1961. else if (strieq(machineType, eqAgentExec))
  1962. {
  1963. processType = eqEclAgent;
  1964. }
  1965. else
  1966. {
  1967. processType = machineType;
  1968. }
  1969. return processType;
  1970. }
  1971. IConstEnvironment* Cws_machineEx::getConstEnvironment()
  1972. {
  1973. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  1974. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  1975. if (!constEnv)
  1976. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  1977. return constEnv.getLink();
  1978. }
  1979. //Used in Rexec
  1980. IPropertyTree* Cws_machineEx::getComponent(const char* compType, const char* compName)
  1981. {
  1982. StringBuffer xpath;
  1983. xpath.append("Software/").append(compType).append("[@name='").append(compName).append("']");
  1984. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  1985. Owned<IPropertyTree> pEnvRoot = &constEnv->getPTree();
  1986. return pEnvRoot->getPropTree( xpath.str() );
  1987. }
  1988. void Cws_machineEx::getAccountAndPlatformInfo(const char* address, StringBuffer& userId, StringBuffer& password, bool& bLinux)
  1989. {
  1990. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  1991. Owned<IConstMachineInfo> machine = constEnv->getMachineByAddress(address);
  1992. if (!machine && strieq(address, "."))
  1993. {
  1994. machine.setown(constEnv->getMachineByAddress("127.0.0.1"));
  1995. }
  1996. if (!machine)
  1997. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Machine %s is not defined in environment!", address);
  1998. Owned<IConstDomainInfo> domain = machine->getDomain();
  1999. if (!domain)
  2000. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Machine %s does not have any domain information!", address);
  2001. userId.clear();
  2002. password.clear();
  2003. StringBufferAdaptor strval1(userId);
  2004. StringBufferAdaptor strval2(password);
  2005. domain->getAccountInfo(strval1, strval2);
  2006. StringBuffer domainName;
  2007. StringBufferAdaptor strval3(domainName);
  2008. domain->getName(strval3);
  2009. if ((machine->getOS() == MachineOsW2K) && domainName.length())
  2010. {
  2011. domainName.append('\\');
  2012. userId.insert(0, domainName);
  2013. }
  2014. bLinux = machine->getOS() == MachineOsLinux;
  2015. }
  2016. IPropertyTree* Cws_machineEx::createDiskUsageReq(IPropertyTree* envDirectories, const char* pathName,
  2017. const char* componentType, const char* componentName)
  2018. {
  2019. StringBuffer path;
  2020. if (!getConfigurationDirectory(envDirectories, pathName, componentType, componentName, path))
  2021. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get %s Disk Path for component %s", pathName, componentName);
  2022. Owned<IPropertyTree> diskReq = createPTree("Folder");
  2023. diskReq->addProp("@name", pathName);
  2024. diskReq->addProp("@path", path);
  2025. return diskReq.getClear();
  2026. }
  2027. IPropertyTree* Cws_machineEx::createMachineUsageReq(IConstEnvironment* constEnv, const char* computer)
  2028. {
  2029. Owned<IConstMachineInfo> machine = constEnv->getMachine(computer);
  2030. if (!machine)
  2031. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get machine %s", computer);
  2032. Owned<IPropertyTree> machineReq = createPTree("Machine");
  2033. machineReq->addProp("@name", computer);
  2034. SCMStringBuffer netAddress;
  2035. machine->getNetAddress(netAddress);
  2036. machineReq->addProp("@netAddress", netAddress.str());
  2037. machineReq->addPropInt("@OS", machine->getOS());
  2038. return machineReq.getClear();
  2039. }
  2040. void Cws_machineEx::readThorUsageReq(const char* name, IConstEnvironment* constEnv, IPropertyTree* usageReq)
  2041. {
  2042. if (isEmptyString(name))
  2043. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Thor name");
  2044. Owned<IPropertyTree> componentReq = createPTree("Component");
  2045. componentReq->addProp("@name", name);
  2046. componentReq->addProp("@type", eqThorCluster);
  2047. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2048. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  2049. Owned<IPropertyTree> logFolder = createDiskUsageReq(envDirectories, "log", "thor", name);
  2050. Owned<IPropertyTree> dataFolder = createDiskUsageReq(envDirectories, "data", "thor", name);
  2051. Owned<IPropertyTree> repFolder = createDiskUsageReq(envDirectories, "mirror", "thor", name);
  2052. VStringBuffer xpath("Software/ThorCluster[@name='%s']/ThorSlaveProcess", name);
  2053. Owned<IPropertyTreeIterator> slaveProcesses= envRoot->getElements(xpath);
  2054. ForEach(*slaveProcesses)
  2055. {
  2056. IPropertyTree& slaveProcess = slaveProcesses->query();
  2057. const char* computer = slaveProcess.queryProp("@computer");
  2058. if (isEmptyString(computer))
  2059. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  2060. Owned<IPropertyTree> newMachineReq = createMachineUsageReq(constEnv, computer);
  2061. //Not sure we need those folders here. Add them just in case.
  2062. if (logFolder)
  2063. newMachineReq->addPropTree(logFolder->queryName(), LINK(logFolder));
  2064. if (dataFolder)
  2065. newMachineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2066. if (repFolder)
  2067. newMachineReq->addPropTree(repFolder->queryName(), LINK(repFolder));
  2068. componentReq->addPropTree(newMachineReq->queryName(), LINK(newMachineReq));
  2069. }
  2070. //Read ThorMasterProcess in case it is on a different machine
  2071. xpath.setf("Software/ThorCluster[@name='%s']/ThorMasterProcess/@computer", name);
  2072. const char* computer = envRoot->queryProp(xpath);
  2073. if (isEmptyString(computer))
  2074. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get %s", xpath.str());
  2075. Owned<IPropertyTree> machineReq = createMachineUsageReq(constEnv, computer);
  2076. xpath.setf("Machine[@netAddress='%s']", machineReq->queryProp("@netAddress"));
  2077. if (componentReq->hasProp(xpath))
  2078. { //ThorMasterProcess is running on one of the ThorSlaveProcess machines.
  2079. //So, we do not add this machine again.
  2080. usageReq->addPropTree(componentReq->queryName(), LINK(componentReq));
  2081. return;
  2082. }
  2083. //Not sure we need those folders here. Add them just in case.
  2084. if (logFolder)
  2085. machineReq->addPropTree(logFolder->queryName(), LINK(logFolder));
  2086. if (dataFolder)
  2087. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2088. if (repFolder)
  2089. machineReq->addPropTree(repFolder->queryName(), LINK(repFolder));
  2090. componentReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2091. usageReq->addPropTree(componentReq->queryName(), LINK(componentReq));
  2092. }
  2093. void Cws_machineEx::readRoxieUsageReq(const char* name, IConstEnvironment* constEnv, IPropertyTree* usageReq)
  2094. {
  2095. if (isEmptyString(name))
  2096. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Roxie name");
  2097. Owned<IPropertyTree> componentReq = createPTree("Component");
  2098. componentReq->addProp("@name", name);
  2099. componentReq->addProp("@type", eqRoxieCluster);
  2100. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2101. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  2102. Owned<IPropertyTree> logFolder = createDiskUsageReq(envDirectories, "log", "roxie", name);
  2103. Owned<IPropertyTree> dataFolder = createDiskUsageReq(envDirectories, "data", "roxie", name);
  2104. VStringBuffer xpath("Software/RoxieCluster[@name='%s']/RoxieServerProcess", name);
  2105. Owned<IPropertyTreeIterator> slaveProcesses= envRoot->getElements(xpath);
  2106. ForEach(*slaveProcesses)
  2107. {
  2108. IPropertyTree& slaveProcess = slaveProcesses->query();
  2109. const char* computer = slaveProcess.queryProp("@computer");
  2110. if (isEmptyString(computer))
  2111. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  2112. Owned<IPropertyTree> newMachineReq = createMachineUsageReq(constEnv, computer);
  2113. //Not sure we need those folders here. Add them just in case.
  2114. if (logFolder)
  2115. newMachineReq->addPropTree(logFolder->queryName(), LINK(logFolder));
  2116. if (dataFolder)
  2117. newMachineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2118. componentReq->addPropTree(newMachineReq->queryName(), LINK(newMachineReq));
  2119. }
  2120. usageReq->addPropTree(componentReq->queryName(), LINK(componentReq));
  2121. }
  2122. void Cws_machineEx::readDropZoneUsageReq(const char* name, IConstEnvironment* constEnv, IPropertyTree* usageReq)
  2123. {
  2124. if (isEmptyString(name))
  2125. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty DropZone name");
  2126. Owned<IConstDropZoneInfo> envDropZone = constEnv->getDropZone(name);
  2127. if (!envDropZone || !envDropZone->isECLWatchVisible())
  2128. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dropzone %s not found", name);
  2129. SCMStringBuffer directory;
  2130. envDropZone->getDirectory(directory);
  2131. if (directory.length() == 0)
  2132. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get directory for DropZone %s", name);
  2133. Owned<IPropertyTree> dataFolder = createPTree("Folder");
  2134. dataFolder->addProp("@name", "data");
  2135. dataFolder->addProp("@path", directory.str());
  2136. Owned<IPropertyTree> componentReq = createPTree("Component");
  2137. componentReq->addProp("@name", name);
  2138. componentReq->addProp("@type", eqDropZone);
  2139. SCMStringBuffer computerName;
  2140. envDropZone->getComputerName(computerName);
  2141. if (computerName.length() == 0)
  2142. {
  2143. OS_TYPE os = (getPathSepChar(directory.str()) == '/') ? OS_LINUX : OS_WINDOWS;
  2144. Owned<IConstDropZoneServerInfoIterator> servers = envDropZone->getServers();
  2145. ForEach(*servers)
  2146. {
  2147. IConstDropZoneServerInfo &server = servers->query();
  2148. StringBuffer serverNetAddress;
  2149. server.getServer(serverNetAddress.clear());
  2150. Owned<IPropertyTree> machineReq = createPTree("Machine");
  2151. machineReq->addProp("@name", serverNetAddress.str());
  2152. machineReq->addProp("@netAddress", serverNetAddress.str());
  2153. machineReq->addPropInt("@OS", os);
  2154. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2155. componentReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2156. }
  2157. }
  2158. else
  2159. { //legacy dropzone settings
  2160. Owned<IPropertyTree> machineReq = createMachineUsageReq(constEnv, computerName.str());
  2161. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2162. componentReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2163. }
  2164. usageReq->addPropTree(componentReq->queryName(), LINK(componentReq));
  2165. }
  2166. void Cws_machineEx::readOtherComponentUsageReq(const char* name, const char* type, IConstEnvironment* constEnv, IPropertyTree* usageReq)
  2167. {
  2168. if (isEmptyString(name))
  2169. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component name");
  2170. const char* componentType = findComponentTypeFromProcessType(type);
  2171. if (!componentType)
  2172. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Component usage function is not supported for %s", type);
  2173. Owned<IPropertyTree> componentReq = createPTree("Component");
  2174. componentReq->addProp("@name", name);
  2175. componentReq->addProp("@type", type);
  2176. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2177. VStringBuffer xpath("Software/%s[@name='%s']/Instance", type, name);
  2178. Owned<IPropertyTreeIterator> it = envRoot->getElements(xpath);
  2179. ForEach(*it)
  2180. {
  2181. IPropertyTree& instance = it->query();
  2182. const char* computer = instance.queryProp("@computer");
  2183. if (isEmptyString(computer))
  2184. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get %s", xpath.str());
  2185. Owned<IPropertyTree> machineReq = createMachineUsageReq(constEnv, computer);
  2186. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  2187. Owned<IPropertyTree> logFolder = createDiskUsageReq(envDirectories, "log", type, name);
  2188. if (logFolder)
  2189. machineReq->addPropTree(logFolder->queryName(), LINK(logFolder));
  2190. Owned<IPropertyTree> dataFolder = createDiskUsageReq(envDirectories, "data", componentType, name);
  2191. if (dataFolder)
  2192. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2193. if (strieq(type, eqDali))
  2194. {
  2195. Owned<IPropertyTree> repFolder = createDiskUsageReq(envDirectories, "mirror", "dali", name);
  2196. if (repFolder)
  2197. machineReq->addPropTree(repFolder->queryName(), LINK(repFolder));
  2198. }
  2199. componentReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2200. }
  2201. usageReq->addPropTree(componentReq->queryName(), LINK(componentReq));
  2202. }
  2203. void Cws_machineEx::setUniqueMachineUsageReq(IPropertyTree* usageReq, IPropertyTree* uniqueUsages)
  2204. {
  2205. Owned<IPropertyTreeIterator> components= usageReq->getElements("Component");
  2206. ForEach(*components)
  2207. {
  2208. IPropertyTree& component = components->query();
  2209. Owned<IPropertyTreeIterator> machines= component.getElements("Machine");
  2210. ForEach(*machines)
  2211. {
  2212. IPropertyTree& machine = machines->query();
  2213. const char* netAddress = machine.queryProp("@netAddress");
  2214. VStringBuffer xpath("Machine[@netAddress='%s']", netAddress);
  2215. IPropertyTree* uniqueMachineReqTree = uniqueUsages->queryPropTree(xpath);
  2216. if (!uniqueMachineReqTree)
  2217. {
  2218. uniqueUsages->addPropTree(machine.queryName(), LINK(&machine));
  2219. continue;
  2220. }
  2221. //Add unique disk folders from the usageReq.
  2222. Owned<IPropertyTreeIterator> folders = machine.getElements("Folder");
  2223. ForEach(*folders)
  2224. {
  2225. IPropertyTree& folder = folders->query();
  2226. const char* aDiskPath = folder.queryProp("@path");
  2227. xpath.setf("Folder[@path='%s']", aDiskPath);
  2228. IPropertyTree* uniqueFolderReqTree = uniqueMachineReqTree->queryPropTree(xpath);
  2229. if (!uniqueFolderReqTree)
  2230. {
  2231. Owned<IPropertyTree> folderReq = createPTree("Folder");
  2232. folderReq->addProp("@name", folder.queryProp("@name"));
  2233. folderReq->addProp("@path", aDiskPath);
  2234. uniqueMachineReqTree->addPropTree(folderReq->queryName(), LINK(folderReq));
  2235. }
  2236. }
  2237. }
  2238. }
  2239. }
  2240. IArrayOf<IConstComponent>& Cws_machineEx::listComponentsByType(IPropertyTree* envRoot,
  2241. const char* componentType, IArrayOf<IConstComponent>& componentList)
  2242. {
  2243. VStringBuffer xpath("Software/%s", componentType);
  2244. Owned<IPropertyTreeIterator> components= envRoot->getElements(xpath);
  2245. ForEach(*components)
  2246. {
  2247. Owned<IEspComponent> component = createComponent();
  2248. component->setName(components->query().queryProp("@name"));
  2249. component->setType(componentType);
  2250. componentList.append(*component.getClear());
  2251. }
  2252. return componentList;
  2253. }
  2254. IArrayOf<IConstComponent>& Cws_machineEx::listComponentsForCheckingUsage(IConstEnvironment* constEnv,
  2255. IArrayOf<IConstComponent>& componentList)
  2256. {
  2257. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2258. listComponentsByType(envRoot, eqThorCluster, componentList);
  2259. listComponentsByType(envRoot, eqRoxieCluster, componentList);
  2260. listComponentsByType(envRoot, eqDali, componentList);
  2261. listComponentsByType(envRoot, eqEclAgent, componentList);
  2262. listComponentsByType(envRoot, eqSashaServer, componentList);
  2263. listComponentsByType(envRoot, eqDropZone, componentList);
  2264. listComponentsByType(envRoot, eqDfu, componentList);
  2265. listComponentsByType(envRoot, eqEclCCServer, componentList);
  2266. listComponentsByType(envRoot, eqEclServer, componentList);
  2267. listComponentsByType(envRoot, eqEclScheduler, componentList);
  2268. listComponentsByType(envRoot, eqEsp, componentList);
  2269. return componentList;
  2270. }
  2271. IPropertyTree* Cws_machineEx::getComponentUsageReq(IEspGetComponentUsageRequest& req, IConstEnvironment* constEnv)
  2272. {
  2273. IArrayOf<IConstComponent>& componentList = req.getComponents();
  2274. if (!componentList.length())
  2275. listComponentsForCheckingUsage(constEnv, componentList);
  2276. Owned<IPropertyTree> usageReq = createPTree("Req");
  2277. ForEachItemIn(i, componentList)
  2278. {
  2279. IConstComponent& component = componentList.item(i);
  2280. const char* type = component.getType();
  2281. if (isEmptyString(type))
  2282. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component Type");
  2283. if (strieq(type, eqThorCluster))
  2284. readThorUsageReq(component.getName(), constEnv, usageReq);
  2285. else if (strieq(type, eqRoxieCluster))
  2286. readRoxieUsageReq(component.getName(), constEnv, usageReq);
  2287. else if (strieq(type, eqDropZone))
  2288. readDropZoneUsageReq(component.getName(), constEnv, usageReq);
  2289. else
  2290. readOtherComponentUsageReq(component.getName(), type, constEnv, usageReq);
  2291. }
  2292. return usageReq.getClear();
  2293. }
  2294. void Cws_machineEx::getMachineUsages(IEspContext& context, IPropertyTree* uniqueUsages)
  2295. {
  2296. UnsignedArray threadHandles;
  2297. Owned<IPropertyTreeIterator> requests= uniqueUsages->getElements("Machine");
  2298. ForEach(*requests)
  2299. {
  2300. Owned<CGetMachineUsageThreadParam> threadParam = new CGetMachineUsageThreadParam(this, context, &requests->query());
  2301. PooledThreadHandle handle = m_threadPool->start(threadParam.getClear());
  2302. threadHandles.append(handle);
  2303. }
  2304. ForEachItemIn(i, threadHandles)
  2305. m_threadPool->join(threadHandles.item(i));
  2306. }
  2307. void Cws_machineEx::getMachineUsage(IEspContext& context, CGetMachineUsageThreadParam* param)
  2308. {
  2309. VStringBuffer command("/%s/sbin/usage -d=", environmentConfData.m_executionPath.str());
  2310. unsigned pathCount = 0;
  2311. Owned<IPropertyTreeIterator> diskPathList = param->request->getElements("Folder");
  2312. ForEach(*diskPathList)
  2313. {
  2314. IPropertyTree& t = diskPathList->query();
  2315. if (pathCount > 0)
  2316. command.append(",");
  2317. command.appendf("%s", t.queryProp("@path"));
  2318. pathCount++;
  2319. }
  2320. ESPLOG(LogMax, "command(%s)", command.str());
  2321. StringBuffer response;
  2322. int error = runCommand(context, param->request->queryProp("@netAddress"), nullptr,
  2323. (EnvMachineOS) param->request->getPropInt("@OS", MachineOsLinux), command.str(), nullptr, nullptr, response);
  2324. if (error != 0 || isEmptyString(response))
  2325. {
  2326. if (isEmptyString(response))
  2327. param->request->addProp("@error", "Failed in getting component usage.");
  2328. else
  2329. param->request->addProp("@error", response);
  2330. return;
  2331. }
  2332. ESPLOG(LogMax, "response(%s)", response.str());
  2333. ForEach(*diskPathList)
  2334. {
  2335. IPropertyTree& diskPathTree = diskPathList->query();
  2336. StringBuffer aDiskPathResp;
  2337. VStringBuffer diskPath("%s:", diskPathTree.queryProp("@path"));
  2338. readALineFromResult(response, diskPath, aDiskPathResp, true);
  2339. CStorageData sData(false, true, false);
  2340. if (!sData.read(aDiskPathResp))
  2341. {
  2342. DBGLOG("Failed to read disc space on %s: %s", param->request->queryProp("@netAddress"), aDiskPathResp.str());
  2343. diskPathTree.addProp("@error", "Failed to read disc space.");
  2344. continue;
  2345. }
  2346. diskPathTree.addPropInt64("@used", sData.getDiskSpaceUsed());
  2347. diskPathTree.addPropInt64("@available", sData.getDiskSpaceAvailable());
  2348. diskPathTree.addPropInt("@percentAvail", sData.getDiskSpacePercentAvail());
  2349. diskPathTree.addPropInt64("@size", sData.getDiskSpaceActualSize());
  2350. const char* pathUsed = sData.getDiskSpacePath();
  2351. if (!isEmptyString(pathUsed))
  2352. diskPathTree.addProp("@pathUsed", pathUsed);
  2353. }
  2354. }
  2355. void Cws_machineEx::readComponentUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2356. const IPropertyTree* uniqueUsages, IArrayOf<IEspComponentUsage>& componentUsages)
  2357. {
  2358. double version = context.getClientVersion();
  2359. Owned<IPropertyTreeIterator> components= usageReq->getElements("Component");
  2360. ForEach(*components)
  2361. {
  2362. IPropertyTree& component = components->query();
  2363. Owned<IEspComponentUsage> componentUsage = createComponentUsage();
  2364. componentUsage->setName(component.queryProp("@name"));
  2365. componentUsage->setType(component.queryProp("@type"));
  2366. IArrayOf<IEspMachineUsage> machineUsages;
  2367. Owned<IPropertyTreeIterator> machines= component.getElements("Machine");
  2368. ForEach(*machines)
  2369. {
  2370. IPropertyTree& machine = machines->query();
  2371. const char* netAddress = machine.queryProp("@netAddress");
  2372. Owned<IEspMachineUsage> machineUsage = createMachineUsage();
  2373. machineUsage->setName(machine.queryProp("@name"));
  2374. machineUsage->setNetAddress(netAddress);
  2375. VStringBuffer xpath("Machine[@netAddress='%s']", netAddress);
  2376. IPropertyTree* uniqueMachineReqTree = uniqueUsages->queryPropTree(xpath);
  2377. if (!uniqueMachineReqTree)
  2378. {
  2379. if (version < 1.17)
  2380. machineUsage->setDescription("No data returns.");
  2381. else
  2382. machineUsage->setException("No data returns.");
  2383. machineUsages.append(*machineUsage.getClear());
  2384. continue;
  2385. }
  2386. const char* error = uniqueMachineReqTree->queryProp("@error");
  2387. if (!isEmptyString(error))
  2388. {
  2389. if (version < 1.17)
  2390. machineUsage->setDescription(error);
  2391. else
  2392. machineUsage->setException(error);
  2393. machineUsages.append(*machineUsage.getClear());
  2394. continue;
  2395. }
  2396. IArrayOf<IEspDiskUsage> diskUsages;
  2397. Owned<IPropertyTreeIterator> folders = machine.getElements("Folder");
  2398. ForEach(*folders)
  2399. {
  2400. IPropertyTree& folder = folders->query();
  2401. const char* aDiskPath = folder.queryProp("@path");
  2402. Owned<IEspDiskUsage> diskUsage = createDiskUsage();
  2403. diskUsage->setName(folder.queryProp("@name"));
  2404. diskUsage->setPath(aDiskPath);
  2405. xpath.setf("Folder[@path='%s']", aDiskPath);
  2406. IPropertyTree* folderTree = uniqueMachineReqTree->queryPropTree(xpath);
  2407. if (!folderTree)
  2408. {
  2409. if (version < 1.17)
  2410. diskUsage->setDescription("No data returns.");
  2411. else
  2412. diskUsage->setException("No data returns.");
  2413. }
  2414. else
  2415. {
  2416. const char* error = folderTree->queryProp("@error");
  2417. if (!isEmptyString(error))
  2418. {
  2419. if (version < 1.17)
  2420. diskUsage->setDescription(error);
  2421. else
  2422. diskUsage->setException(error);
  2423. }
  2424. else
  2425. {
  2426. diskUsage->setAvailable(folderTree->getPropInt64("@available"));
  2427. diskUsage->setInUse(folderTree->getPropInt64("@used"));
  2428. diskUsage->setPercentAvailable(folderTree->getPropInt("@percentAvail"));
  2429. const char* pathUsed = folderTree->queryProp("@pathUsed");
  2430. if (!isEmptyString(pathUsed))
  2431. {
  2432. VStringBuffer desc("%s not found. Read disk usage from %s", aDiskPath, pathUsed);
  2433. diskUsage->setDescription(desc);
  2434. }
  2435. if ((version >= 1.18) && folderTree->hasProp("@size"))
  2436. diskUsage->setActualSize(folderTree->getPropInt64("@size"));
  2437. }
  2438. }
  2439. diskUsages.append(*diskUsage.getClear());
  2440. }
  2441. machineUsage->setDiskUsages(diskUsages);
  2442. machineUsages.append(*machineUsage.getClear());
  2443. }
  2444. componentUsage->setMachineUsages(machineUsages);
  2445. componentUsages.append(*componentUsage.getClear());
  2446. }
  2447. }
  2448. StringBuffer& Cws_machineEx::setUsageTimeStr(CUsageCache* usageCache, StringBuffer& timeStr)
  2449. {
  2450. if (usageCache)
  2451. usageCache->queryTimeCached(timeStr);
  2452. else
  2453. {
  2454. CDateTime timeNow;
  2455. timeNow.setNow();
  2456. timeNow.getString(timeStr, true);
  2457. }
  2458. return timeStr;
  2459. }
  2460. bool Cws_machineEx::onGetComponentUsage(IEspContext& context, IEspGetComponentUsageRequest& req,
  2461. IEspGetComponentUsageResponse& resp)
  2462. {
  2463. try
  2464. {
  2465. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2466. double version = context.getClientVersion();
  2467. StringBuffer timeStr;
  2468. IArrayOf<IEspComponentUsage> componentUsages;
  2469. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2470. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2471. Owned<IPropertyTree> usageReq = getComponentUsageReq(req, constEnv);
  2472. Owned<CUsageCache> usage;
  2473. Owned<const IPropertyTree> uniqueUsages;
  2474. if (req.getBypassCachedResult())
  2475. {
  2476. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2477. //Add unique machines from the usageReq to uniqueUsages.
  2478. setUniqueMachineUsageReq(usageReq, tmpUniqueUsages);
  2479. getMachineUsages(context, tmpUniqueUsages);
  2480. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2481. }
  2482. else
  2483. {
  2484. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2485. if (!usage)
  2486. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2487. ESPLOG(LogMax, "GetComponentUsage: found UsageCache.");
  2488. uniqueUsages.set(usage->queryUsages());
  2489. }
  2490. readComponentUsageResult(context, usageReq, uniqueUsages, componentUsages);
  2491. if (version >= 1.17)
  2492. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2493. resp.setComponentUsages(componentUsages);
  2494. }
  2495. catch(IException* e)
  2496. {
  2497. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2498. }
  2499. return true;
  2500. }
  2501. StringArray& Cws_machineEx::listTargetClusterNames(IConstEnvironment* constEnv, StringArray& targetClusters)
  2502. {
  2503. #ifdef _CONTAINERIZED
  2504. Owned<IStringIterator> targets = getContainerTargetClusters(nullptr, nullptr);
  2505. #else
  2506. Owned<IStringIterator> targets = getTargetClusters(nullptr, nullptr);
  2507. #endif
  2508. ForEach(*targets)
  2509. {
  2510. SCMStringBuffer target;
  2511. targetClusters.append(targets->str(target).str());
  2512. }
  2513. return targetClusters;
  2514. }
  2515. IPropertyTree* Cws_machineEx::getTargetClusterUsageReq(IEspGetTargetClusterUsageRequest& req, IConstEnvironment* constEnv)
  2516. {
  2517. StringArray& targetClusters = req.getTargetClusters();
  2518. if (targetClusters.empty())
  2519. listTargetClusterNames(constEnv, targetClusters);
  2520. Owned<IPropertyTree> usageReq = createPTree("Req");
  2521. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2522. ForEachItemIn(i, targetClusters)
  2523. {
  2524. const char* targetClusterName = targetClusters.item(i);
  2525. if (isEmptyString(targetClusterName))
  2526. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Target Cluster specified.");
  2527. Owned<IConstWUClusterInfo> targetClusterInfo = getTargetClusterInfo(targetClusterName);
  2528. if (!targetClusterInfo)
  2529. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Could not find information about target cluster %s ", targetClusterName);
  2530. Owned<IPropertyTree> targetClusterTree = createPTree("TargetCluster");
  2531. targetClusterTree->addProp("@name", targetClusterName);
  2532. const StringArray& thors = targetClusterInfo->getThorProcesses();
  2533. ForEachItemIn(i, thors)
  2534. {
  2535. const char* thor = thors.item(i);
  2536. if (!isEmptyString(thor))
  2537. readThorUsageReq(thor, constEnv, targetClusterTree);
  2538. }
  2539. SCMStringBuffer roxie;
  2540. targetClusterInfo->getRoxieProcess(roxie);
  2541. if (roxie.length())
  2542. readRoxieUsageReq(roxie.str(), constEnv, targetClusterTree);
  2543. SCMStringBuffer eclAgent, eclScheduler;
  2544. targetClusterInfo->getAgentName(eclAgent);
  2545. if (eclAgent.length())
  2546. readOtherComponentUsageReq(eclAgent.str(), eqEclAgent, constEnv, targetClusterTree);
  2547. targetClusterInfo->getECLSchedulerName(eclScheduler);
  2548. if (eclScheduler.length())
  2549. readOtherComponentUsageReq(eclScheduler.str(), eqEclScheduler, constEnv, targetClusterTree);
  2550. const StringArray& eclServers = targetClusterInfo->getECLServerNames();
  2551. ForEachItemIn(j, eclServers)
  2552. readOtherComponentUsageReq(eclServers.item(j), targetClusterInfo->isLegacyEclServer() ? eqEclServer : eqEclCCServer, constEnv, targetClusterTree);
  2553. usageReq->addPropTree(targetClusterTree->queryName(), LINK(targetClusterTree));
  2554. }
  2555. return usageReq.getClear();
  2556. }
  2557. void Cws_machineEx::readTargetClusterUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2558. const IPropertyTree* uniqueUsages, IArrayOf<IEspTargetClusterUsage>& targetClusterUsages)
  2559. {
  2560. Owned<IPropertyTreeIterator> targetClusters= usageReq->getElements("TargetCluster");
  2561. ForEach(*targetClusters)
  2562. {
  2563. IPropertyTree& targetCluster = targetClusters->query();
  2564. Owned<IEspTargetClusterUsage> targetClusterUsage = createTargetClusterUsage();
  2565. targetClusterUsage->setName(targetCluster.queryProp("@name"));
  2566. IArrayOf<IEspComponentUsage> componentUsages;
  2567. readComponentUsageResult(context, &targetCluster, uniqueUsages, componentUsages);
  2568. targetClusterUsage->setComponentUsages(componentUsages);
  2569. targetClusterUsages.append(*targetClusterUsage.getClear());
  2570. }
  2571. }
  2572. bool Cws_machineEx::onGetTargetClusterUsage(IEspContext& context, IEspGetTargetClusterUsageRequest& req,
  2573. IEspGetTargetClusterUsageResponse& resp)
  2574. {
  2575. try
  2576. {
  2577. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2578. double version = context.getClientVersion();
  2579. StringBuffer timeStr;
  2580. IArrayOf<IEspTargetClusterUsage> targetClusterUsages;
  2581. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2582. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2583. Owned<IPropertyTree> usageReq = getTargetClusterUsageReq(req, constEnv);
  2584. Owned<CUsageCache> usage;
  2585. Owned<const IPropertyTree> uniqueUsages;
  2586. if (req.getBypassCachedResult())
  2587. {
  2588. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2589. Owned<IPropertyTreeIterator> targetClusterItr= usageReq->getElements("TargetCluster");
  2590. ForEach(*targetClusterItr)
  2591. {
  2592. IPropertyTree& targetCluster = targetClusterItr->query();
  2593. setUniqueMachineUsageReq(&targetCluster, tmpUniqueUsages);
  2594. }
  2595. getMachineUsages(context, tmpUniqueUsages);
  2596. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2597. }
  2598. else
  2599. {
  2600. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2601. if (!usage)
  2602. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2603. ESPLOG(LogMax, "GetTargetClusterUsage: found UsageCache.");
  2604. uniqueUsages.set(usage->queryUsages());
  2605. }
  2606. readTargetClusterUsageResult(context, usageReq, uniqueUsages, targetClusterUsages);
  2607. if (version >= 1.17)
  2608. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2609. resp.setTargetClusterUsages(targetClusterUsages);
  2610. }
  2611. catch(IException* e)
  2612. {
  2613. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2614. }
  2615. return true;
  2616. }
  2617. bool Cws_machineEx::getEclAgentNameFromNodeGroupName(const char* nodeGroupName, StringBuffer& agentName)
  2618. {
  2619. //Node group name for an eclagent should be: 'hthor__' + ECLAgentName[ + '_' + a number]
  2620. if ((strlen(nodeGroupName) <= 7) || strnicmp(nodeGroupName, "hthor__", 7))
  2621. return false;
  2622. agentName.set(nodeGroupName + 7);
  2623. const char* ptr = strrchr(agentName.str(), '_');
  2624. if (isEmptyString(ptr) || isEmptyString(++ptr))
  2625. return true;
  2626. const char* ptrSuffix = ptr - 1;
  2627. do
  2628. {
  2629. if (!isdigit(ptr[0]))
  2630. return true;
  2631. ptr++;
  2632. } while(!isEmptyString(ptr));
  2633. agentName.setLength(agentName.length() - (ptr - ptrSuffix));
  2634. return true;
  2635. }
  2636. void Cws_machineEx::getThorClusterNamesByGroupName(IPropertyTree* envRoot, const char* group, StringArray& thorClusterNames)
  2637. {
  2638. Owned<IPropertyTreeIterator> thorClusters= envRoot->getElements("Software/ThorCluster");
  2639. ForEach(*thorClusters)
  2640. {
  2641. IPropertyTree& thorCluster = thorClusters->query();
  2642. const char *nodeGroupName = thorCluster.queryProp("@nodeGroup");
  2643. if (!isEmptyString(nodeGroupName) && !strieq(nodeGroupName, group))
  2644. continue;
  2645. if (!isEmptyString(nodeGroupName))
  2646. thorClusterNames.append(nodeGroupName);
  2647. else
  2648. {
  2649. const char *name = thorCluster.queryProp("@name");
  2650. if (strieq(name, group))
  2651. thorClusterNames.append(name);
  2652. }
  2653. }
  2654. }
  2655. StringArray& Cws_machineEx::listThorHThorNodeGroups(IConstEnvironment* constEnv, StringArray& nodeGroups)
  2656. {
  2657. BoolHash uniqueThorClusterGroupNames;
  2658. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2659. Owned<IPropertyTreeIterator> it =envRoot->getElements("Software/ThorCluster");
  2660. ForEach(*it)
  2661. {
  2662. IPropertyTree& cluster = it->query();
  2663. StringBuffer thorClusterGroupName;
  2664. getClusterGroupName(cluster, thorClusterGroupName);
  2665. if (!thorClusterGroupName.length())
  2666. continue;
  2667. bool* found = uniqueThorClusterGroupNames.getValue(thorClusterGroupName);
  2668. if (found && *found)
  2669. continue;
  2670. nodeGroups.append(thorClusterGroupName);
  2671. uniqueThorClusterGroupNames.setValue(thorClusterGroupName, true);
  2672. }
  2673. it.setown(envRoot->getElements("Software/EclAgentProcess"));
  2674. ForEach(*it)
  2675. {
  2676. IPropertyTree &cluster = it->query();
  2677. const char* name = cluster.queryProp("@name");
  2678. if (!name||!*name)
  2679. continue;
  2680. unsigned ins = 0;
  2681. Owned<IPropertyTreeIterator> insts = cluster.getElements("Instance");
  2682. ForEach(*insts)
  2683. {
  2684. ins++;
  2685. StringBuffer gname("hthor__");
  2686. gname.append(name);
  2687. if (ins>1)
  2688. gname.append('_').append(ins);
  2689. nodeGroups.append(gname);
  2690. }
  2691. }
  2692. return nodeGroups;
  2693. }
  2694. IPropertyTree* Cws_machineEx::getNodeGroupUsageReq(IEspGetNodeGroupUsageRequest& req, IConstEnvironment* constEnv)
  2695. {
  2696. StringArray& nodeGroups = req.getNodeGroups();
  2697. if (nodeGroups.empty())
  2698. listThorHThorNodeGroups(constEnv, nodeGroups);
  2699. if (nodeGroups.empty())
  2700. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No node group found.");
  2701. Owned<IPropertyTree> usageReq = createPTree("Req");
  2702. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2703. ForEachItemIn(i, nodeGroups)
  2704. {
  2705. const char* nodeGroupName = nodeGroups.item(i);
  2706. if (isEmptyString(nodeGroupName))
  2707. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty node group specified.");
  2708. Owned<IPropertyTree> nodeGroupTree = createPTree("NodeGroup");
  2709. nodeGroupTree->addProp("@name", nodeGroupName);
  2710. StringBuffer agentName;
  2711. if (getEclAgentNameFromNodeGroupName(nodeGroupName, agentName))
  2712. readOtherComponentUsageReq(agentName.str(), eqEclAgent, constEnv, nodeGroupTree);
  2713. else
  2714. {
  2715. StringArray thorNames;
  2716. getThorClusterNamesByGroupName(envRoot, nodeGroupName, thorNames);
  2717. if (thorNames.length() == 0)
  2718. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No thor/hthor can be found for node group name %s.", nodeGroupName);
  2719. ForEachItemIn(ii, thorNames)
  2720. readThorUsageReq(thorNames.item(ii), constEnv, nodeGroupTree);
  2721. }
  2722. usageReq->addPropTree(nodeGroupTree->queryName(), LINK(nodeGroupTree));
  2723. }
  2724. return usageReq.getClear();
  2725. }
  2726. void Cws_machineEx::readNodeGroupUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2727. const IPropertyTree* uniqueUsages, IArrayOf<IEspNodeGroupUsage>& nodeGroupUsages)
  2728. {
  2729. Owned<IPropertyTreeIterator> nodeGroups= usageReq->getElements("NodeGroup");
  2730. ForEach(*nodeGroups)
  2731. {
  2732. IPropertyTree& nodeGroup = nodeGroups->query();
  2733. Owned<IEspNodeGroupUsage> nodeGroupUsage = createNodeGroupUsage();
  2734. nodeGroupUsage->setName(nodeGroup.queryProp("@name"));
  2735. IArrayOf<IEspComponentUsage> componentUsages;
  2736. readComponentUsageResult(context, &nodeGroup, uniqueUsages, componentUsages);
  2737. nodeGroupUsage->setComponentUsages(componentUsages);
  2738. nodeGroupUsages.append(*nodeGroupUsage.getClear());
  2739. }
  2740. }
  2741. bool Cws_machineEx::onGetNodeGroupUsage(IEspContext& context, IEspGetNodeGroupUsageRequest& req,
  2742. IEspGetNodeGroupUsageResponse& resp)
  2743. {
  2744. try
  2745. {
  2746. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2747. double version = context.getClientVersion();
  2748. StringBuffer timeStr;
  2749. IArrayOf<IEspNodeGroupUsage> nodeGroupUsages;
  2750. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2751. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2752. Owned<IPropertyTree> usageReq = getNodeGroupUsageReq(req, constEnv);
  2753. Owned<CUsageCache> usage;
  2754. Owned<const IPropertyTree> uniqueUsages;
  2755. if (req.getBypassCachedResult())
  2756. {
  2757. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2758. Owned<IPropertyTreeIterator> nodeGroupItr= usageReq->getElements("NodeGroup");
  2759. ForEach(*nodeGroupItr)
  2760. {
  2761. IPropertyTree& nodeGroup = nodeGroupItr->query();
  2762. setUniqueMachineUsageReq(&nodeGroup, tmpUniqueUsages);
  2763. }
  2764. getMachineUsages(context, tmpUniqueUsages);
  2765. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2766. }
  2767. else
  2768. {
  2769. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2770. if (!usage)
  2771. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2772. ESPLOG(LogMax, "GetNodeGroupUsage: found UsageCache.");
  2773. uniqueUsages.set(usage->queryUsages());
  2774. }
  2775. readNodeGroupUsageResult(context, usageReq, uniqueUsages, nodeGroupUsages);
  2776. if (version >= 1.17)
  2777. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2778. resp.setNodeGroupUsages(nodeGroupUsages);
  2779. }
  2780. catch(IException* e)
  2781. {
  2782. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2783. }
  2784. return true;
  2785. }
  2786. bool Cws_machineEx::onGetComponentStatus(IEspContext &context, IEspGetComponentStatusRequest &req, IEspGetComponentStatusResponse &resp)
  2787. {
  2788. try
  2789. {
  2790. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Component Status. Permission denied.");
  2791. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  2792. Owned<IESPComponentStatusInfo> status = factory->getComponentStatus();
  2793. if (!status) //Should never happen
  2794. return false;
  2795. int statusID = status->getComponentStatusID();
  2796. if (statusID < 0)
  2797. {
  2798. resp.setStatus("Not reported");
  2799. }
  2800. else
  2801. {
  2802. resp.setComponentType(status->getComponentType());
  2803. resp.setEndPoint(status->getEndPoint());
  2804. resp.setReporter(status->getReporter());
  2805. resp.setComponentStatus(status->getComponentStatus());
  2806. resp.setTimeReportedStr(status->getTimeReportedStr());
  2807. IConstStatusReport* componentStatus = status->getStatusReport();
  2808. if (componentStatus)
  2809. resp.setStatusReport(*componentStatus);
  2810. resp.setComponentStatusList(status->getComponentStatusList());
  2811. }
  2812. resp.setComponentStatusID(statusID);
  2813. resp.setStatusCode(0);
  2814. }
  2815. catch(IException* e)
  2816. {
  2817. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2818. }
  2819. return true;
  2820. }
  2821. bool Cws_machineEx::onUpdateComponentStatus(IEspContext &context, IEspUpdateComponentStatusRequest &req, IEspUpdateComponentStatusResponse &resp)
  2822. {
  2823. try
  2824. {
  2825. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Update Component Status. Permission denied.");
  2826. const char* reporter = req.getReporter();
  2827. if (!reporter || !*reporter)
  2828. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Report not specified.");
  2829. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  2830. factory->updateComponentStatus(reporter, req.getComponentStatusList());
  2831. resp.setStatusCode(0);
  2832. }
  2833. catch(IException* e)
  2834. {
  2835. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2836. }
  2837. return true;
  2838. }
  2839. CInfoCache* CUsageCacheReader::read()
  2840. {
  2841. Owned<IPropertyTree> uniqueUsages = getUsageReqAllMachines();
  2842. //Send usage command to each machine
  2843. Owned<IEspContext> espContext = createEspContext();
  2844. servicePtr->getMachineUsages(*espContext, uniqueUsages);
  2845. Owned<CUsageCache> usageCache = new CUsageCache();
  2846. usageCache->setUsages(uniqueUsages.getClear());
  2847. return usageCache.getClear();
  2848. }
  2849. IPropertyTree* CUsageCacheReader::getUsageReqAllMachines()
  2850. {
  2851. //Collect network addresses and HPCC folders for all HPCC machines.
  2852. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2853. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2854. IArrayOf<IConstComponent> componentList;
  2855. servicePtr->listComponentsForCheckingUsage(constEnv, componentList);
  2856. //Create a PTree which will be used to store the usages of all HPCC machines.
  2857. Owned<IPropertyTree> uniqueUsages = createPTree("Usage");
  2858. //Store the network addresses and HPCC folders into the PTree.
  2859. //Their usages may be added by calling servicePtr->getMachineUsages().
  2860. ForEachItemIn(i, componentList)
  2861. {
  2862. IConstComponent& component = componentList.item(i);
  2863. const char* type = component.getType();
  2864. if (isEmptyString(type))
  2865. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component Type");
  2866. if (strieq(type, eqThorCluster))
  2867. addClusterUsageReq(constEnv, component.getName(), true, uniqueUsages);
  2868. else if (strieq(type, eqRoxieCluster))
  2869. addClusterUsageReq(constEnv, component.getName(), false, uniqueUsages);
  2870. else if (strieq(type, eqDropZone))
  2871. addDropZoneUsageReq(constEnv, component.getName(), uniqueUsages);
  2872. else
  2873. addOtherComponentUsageReq(constEnv, component.getName(), type, uniqueUsages);
  2874. }
  2875. return uniqueUsages.getClear();
  2876. }
  2877. void CUsageCacheReader::addClusterUsageReq(IConstEnvironment* constEnv, const char* name, bool thorCluster, IPropertyTree* usageReq)
  2878. {
  2879. if (isEmptyString(name))
  2880. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty cluster name");
  2881. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2882. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  2883. Owned<IPropertyTree> logFolderReq = servicePtr->createDiskUsageReq(envDirectories, "log", thorCluster ? "thor" : "roxie", name);
  2884. Owned<IPropertyTree> dataFolderReq = servicePtr->createDiskUsageReq(envDirectories, "data", thorCluster ? "thor" : "roxie", name);
  2885. Owned<IPropertyTree> repFolderReq;
  2886. if (thorCluster)
  2887. repFolderReq.setown(servicePtr->createDiskUsageReq(envDirectories, "mirror", "thor", name));
  2888. StringBuffer xpath;
  2889. if (thorCluster)
  2890. xpath.setf("Software/ThorCluster[@name='%s']/ThorSlaveProcess", name);
  2891. else
  2892. xpath.setf("Software/RoxieCluster[@name='%s']/RoxieServerProcess", name);
  2893. Owned<IPropertyTreeIterator> processes= envRoot->getElements(xpath);
  2894. ForEach(*processes)
  2895. {
  2896. IPropertyTree& process = processes->query();
  2897. const char* computer = process.queryProp("@computer");
  2898. if (isEmptyString(computer))
  2899. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  2900. checkAndAddMachineUsageReq(constEnv, computer, logFolderReq, dataFolderReq, repFolderReq, usageReq);
  2901. }
  2902. if (!thorCluster)
  2903. return;
  2904. //Read ThorMasterProcess in case it is on a different machine
  2905. xpath.setf("Software/ThorCluster[@name='%s']/ThorMasterProcess/@computer", name);
  2906. const char* computer = envRoot->queryProp(xpath);
  2907. if (isEmptyString(computer))
  2908. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get %s", xpath.str());
  2909. checkAndAddMachineUsageReq(constEnv, computer, logFolderReq, dataFolderReq, repFolderReq, usageReq);
  2910. }
  2911. void CUsageCacheReader::checkAndAddMachineUsageReq(IConstEnvironment* constEnv, const char* computer, IPropertyTree* logFolderReq,
  2912. IPropertyTree* dataFolderReq, IPropertyTree* repFolderReq, IPropertyTree* usageReq)
  2913. {
  2914. Owned<IPropertyTree> machineReq = servicePtr->createMachineUsageReq(constEnv, computer);
  2915. VStringBuffer xpath("Machine[@netAddress='%s']", machineReq->queryProp("@netAddress"));
  2916. IPropertyTree* foundMachineReqTree = usageReq->queryPropTree(xpath);
  2917. if (!foundMachineReqTree)
  2918. {
  2919. //Not sure we need those folders here. Add them just in case.
  2920. if (logFolderReq)
  2921. machineReq->addPropTree(logFolderReq->queryName(), LINK(logFolderReq));
  2922. if (dataFolderReq)
  2923. machineReq->addPropTree(dataFolderReq->queryName(), LINK(dataFolderReq));
  2924. if (repFolderReq)
  2925. machineReq->addPropTree(repFolderReq->queryName(), LINK(repFolderReq));
  2926. usageReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2927. return;
  2928. }
  2929. //Add unique disk folders
  2930. checkAndAddFolderReq(logFolderReq, foundMachineReqTree);
  2931. checkAndAddFolderReq(dataFolderReq, foundMachineReqTree);
  2932. checkAndAddFolderReq(repFolderReq, foundMachineReqTree);
  2933. }
  2934. void CUsageCacheReader::checkAndAddFolderReq(IPropertyTree* folderReq, IPropertyTree* machineReqTree)
  2935. {
  2936. if (!folderReq)
  2937. return;
  2938. //Add unique disk folders
  2939. VStringBuffer xpath("Folder[@path='%s']", folderReq->queryProp("@path"));
  2940. if (!machineReqTree->queryPropTree(xpath))
  2941. machineReqTree->addPropTree(folderReq->queryName(), LINK(folderReq));
  2942. }
  2943. void CUsageCacheReader::addDropZoneUsageReq(IConstEnvironment* constEnv, const char* name, IPropertyTree* usageReq)
  2944. {
  2945. if (isEmptyString(name))
  2946. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty DropZone name");
  2947. Owned<IConstDropZoneInfo> envDropZone = constEnv->getDropZone(name);
  2948. if (!envDropZone)
  2949. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dropzone %s not found", name);
  2950. if (!envDropZone->isECLWatchVisible())
  2951. return;
  2952. SCMStringBuffer directory;
  2953. envDropZone->getDirectory(directory);
  2954. if (directory.length() == 0)
  2955. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get directory for DropZone %s", name);
  2956. Owned<IPropertyTree> dataFolder = createPTree("Folder");
  2957. dataFolder->addProp("@name", "data");
  2958. dataFolder->addProp("@path", directory.str());
  2959. SCMStringBuffer computerName;
  2960. envDropZone->getComputerName(computerName);
  2961. if (computerName.length() == 0)
  2962. {
  2963. OS_TYPE os = (getPathSepChar(directory.str()) == '/') ? OS_LINUX : OS_WINDOWS;
  2964. Owned<IConstDropZoneServerInfoIterator> servers = envDropZone->getServers();
  2965. ForEach(*servers)
  2966. {
  2967. IConstDropZoneServerInfo& server = servers->query();
  2968. StringBuffer serverNetAddress;
  2969. server.getServer(serverNetAddress.clear());
  2970. VStringBuffer xpath("Machine[@netAddress='%s']", serverNetAddress.str());
  2971. IPropertyTree* foundMachineReqTree = usageReq->queryPropTree(xpath);
  2972. if (foundMachineReqTree)
  2973. {
  2974. checkAndAddFolderReq(dataFolder, foundMachineReqTree);
  2975. continue;
  2976. }
  2977. Owned<IPropertyTree> machineReq = createPTree("Machine");
  2978. machineReq->addProp("@name", serverNetAddress.str());
  2979. machineReq->addProp("@netAddress", serverNetAddress.str());
  2980. machineReq->addPropInt("@OS", os);
  2981. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2982. usageReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2983. }
  2984. }
  2985. else
  2986. { //legacy dropzone settings
  2987. checkAndAddMachineUsageReq(constEnv, computerName.str(), nullptr, dataFolder, nullptr, usageReq);
  2988. }
  2989. }
  2990. void CUsageCacheReader::addOtherComponentUsageReq(IConstEnvironment* constEnv, const char* name, const char* type, IPropertyTree* usageReq)
  2991. {
  2992. if (isEmptyString(name))
  2993. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component name");
  2994. const char* componentType = findComponentTypeFromProcessType(type);
  2995. if (!componentType)
  2996. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Component usage function is not supported for %s", type);
  2997. //Find disk folders for log, data, etc.
  2998. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2999. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  3000. Owned<IPropertyTree> dataFolder = servicePtr->createDiskUsageReq(envDirectories, "data", componentType, name);
  3001. Owned<IPropertyTree> logFolder = servicePtr->createDiskUsageReq(envDirectories, "log", componentType, name);
  3002. Owned<IPropertyTree> repFolder;
  3003. if (strieq(type, eqDali))
  3004. repFolder.setown(servicePtr->createDiskUsageReq(envDirectories, "mirror", "dali", name));
  3005. VStringBuffer xpath("Software/%s[@name='%s']/Instance", type, name);
  3006. Owned<IPropertyTreeIterator> it = envRoot->getElements(xpath);
  3007. ForEach(*it)
  3008. {
  3009. IPropertyTree& instance = it->query();
  3010. const char* computer = instance.queryProp("@computer");
  3011. if (isEmptyString(computer))
  3012. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  3013. checkAndAddMachineUsageReq(constEnv, computer, logFolder, dataFolder, repFolder, usageReq);
  3014. }
  3015. }