ws_machineService.cpp 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522
  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. static const int THREAD_POOL_SIZE = 40;
  24. static const int THREAD_POOL_STACK_SIZE = 64000;
  25. static const char* FEATURE_URL = "MachineInfoAccess";
  26. const unsigned ROXIECONTROLSTATETIMEOUT = 5000; //5 second
  27. class CMachineInfoThreadParam : public CWsMachineThreadParam
  28. {
  29. public:
  30. IMPLEMENT_IINTERFACE;
  31. IEspContext& m_context;
  32. CGetMachineInfoUserOptions& m_options; //From request
  33. CMachineData& m_machineData; //From request
  34. IArrayOf<IEspMachineInfoEx>& m_machineInfoTable; //For response
  35. StringArray& m_machineInfoColumns; //For response
  36. MapStringTo<int>& channelsMap; //For response
  37. CMachineInfoThreadParam(Cws_machineEx* pService, IEspContext& context, CGetMachineInfoUserOptions& options,
  38. CMachineData& machineData, IArrayOf<IEspMachineInfoEx>& machineInfoTable, StringArray& machineInfoColumns,
  39. MapStringTo<int>& _channelsMap)
  40. : CWsMachineThreadParam(NULL, NULL, NULL, pService),
  41. m_context(context),
  42. m_options(options),
  43. m_machineData(machineData),
  44. m_machineInfoTable(machineInfoTable),
  45. m_machineInfoColumns(machineInfoColumns),
  46. channelsMap(_channelsMap)
  47. {
  48. }
  49. virtual void doWork()
  50. {
  51. m_pService->doGetMachineInfo(m_context, this);
  52. }
  53. void addColumn(const char* columnName)
  54. {
  55. synchronized block(s_mutex);
  56. if (m_machineInfoColumns.find(columnName) == NotFound)
  57. m_machineInfoColumns.append(columnName);
  58. }
  59. int* getChannels(const char* key) { return channelsMap.getValue(key); };
  60. private:
  61. static Mutex s_mutex;
  62. };
  63. Mutex CMachineInfoThreadParam::s_mutex;
  64. class CRoxieStateInfoThreadParam : public CWsMachineThreadParam
  65. {
  66. public:
  67. StringAttr clusterName;
  68. IArrayOf<IEspMachineInfoEx>& machineInfoTable; //For response
  69. MapStringTo<int>& channelsMap; //For response
  70. CRoxieStateInfoThreadParam(Cws_machineEx* pService, const char* _clusterName,
  71. IArrayOf<IEspMachineInfoEx>& _machineInfoTable, MapStringTo<int>& _channelsMap)
  72. : CWsMachineThreadParam(pService), clusterName(_clusterName), machineInfoTable(_machineInfoTable),
  73. channelsMap(_channelsMap)
  74. {
  75. }
  76. virtual void doWork()
  77. {
  78. m_pService->getRoxieStateInfo(this);
  79. }
  80. int* getChannels(const char* key) { return channelsMap.getValue(key); };
  81. };
  82. class CGetMachineUsageThreadParam : public CWsMachineThreadParam
  83. {
  84. public:
  85. IEspContext& espContext;
  86. IPropertyTree* request;
  87. CGetMachineUsageThreadParam(Cws_machineEx* pService, IEspContext& _espContext, IPropertyTree* _request)
  88. : CWsMachineThreadParam(pService), espContext(_espContext), request(_request) {}
  89. virtual void doWork()
  90. {
  91. m_pService->getMachineUsage(espContext, this);
  92. }
  93. };
  94. const char* findComponentTypeFromProcessType(const char* ProcessType)
  95. {
  96. if (strieq(ProcessType, eqDali))
  97. return "dali";
  98. if (strieq(ProcessType, eqEclAgent))
  99. return "eclagent";
  100. if (strieq(ProcessType, eqDfu))
  101. return "dfuserver";
  102. if (strieq(ProcessType, eqEsp))
  103. return "esp";
  104. if (strieq(ProcessType, eqEclCCServer) || strieq(ProcessType, eqEclServer))
  105. return "eclserver";
  106. if (strieq(ProcessType, eqEclScheduler))
  107. return "eclscheduler";
  108. if (strieq(ProcessType, eqSashaServer))
  109. return "sasha";
  110. return nullptr;
  111. }
  112. void Cws_machineEx::init(IPropertyTree *cfg, const char *process, const char *service)
  113. {
  114. //Read settings from esp.xml
  115. StringBuffer xpath;
  116. xpath.appendf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]", process, service);
  117. Owned<IPropertyTree> pServiceNode = cfg->getPropTree(xpath.str());
  118. m_bMonitorDaliFileServer = pServiceNode->getPropBool("@monitorDaliFileServer", false);
  119. m_processFilters.setown( pServiceNode->getPropTree("ProcessFilters") );
  120. const char* pchExcludePartitions = pServiceNode->queryProp("@excludePartitions");
  121. if (pchExcludePartitions && *pchExcludePartitions)
  122. {
  123. StringArray sPartitions;
  124. sPartitions.appendList(pchExcludePartitions, ", ;");
  125. unsigned int numOfPartitions = sPartitions.ordinality();
  126. for (unsigned int i=0; i<numOfPartitions; i++)
  127. {
  128. const char* partition = sPartitions.item(i);
  129. if (!partition || !*partition)
  130. continue;
  131. if (strchr(partition, '*'))
  132. m_excludePartitionPatterns.insert( partition );
  133. else
  134. m_excludePartitions.insert( partition );
  135. }
  136. }
  137. m_useDefaultHPCCInit = pServiceNode->getPropBool("UseDefaultHPCCInit", true);//Still used by Rexec for now
  138. m_SSHConnectTimeoutSeconds = pServiceNode->getPropInt("SSHConnectTimeoutSeconds", 5);
  139. const char* machineInfoScript = pServiceNode->queryProp("MachineInfoFile");
  140. if (machineInfoScript && *machineInfoScript)
  141. m_machineInfoFile.append(machineInfoScript);
  142. else
  143. m_machineInfoFile.append("preflight");
  144. //Read settings from environment.xml
  145. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  146. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  147. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  148. Owned<IPropertyTree> pEnvSettings = pEnvironmentRoot->getPropTree("EnvSettings");
  149. if (pEnvSettings)
  150. {
  151. pEnvSettings->getProp("configs", environmentConfData.m_configsPath.clear());
  152. pEnvSettings->getProp("path", environmentConfData.m_executionPath.clear());
  153. pEnvSettings->getProp("runtime", environmentConfData.m_runtimePath.clear());
  154. pEnvSettings->getProp("lock", environmentConfData.m_lockPath.clear());
  155. pEnvSettings->getProp("pid", environmentConfData.m_pidPath.clear());
  156. pEnvSettings->getProp("user", environmentConfData.m_user.clear());
  157. }
  158. m_threadPoolSize = pServiceNode->getPropInt("ThreadPoolSize", THREAD_POOL_SIZE);
  159. m_threadPoolStackSize = pServiceNode->getPropInt("ThreadPoolStackSize", THREAD_POOL_STACK_SIZE);
  160. //Start thread pool
  161. Owned<IThreadFactory> pThreadFactory = new CWsMachineThreadFactory();
  162. m_threadPool.setown(createThreadPool("WsMachine Thread Pool", pThreadFactory,
  163. NULL, m_threadPoolSize, 10000, m_threadPoolStackSize)); //10 sec timeout for available thread; use stack size of 2MB
  164. setupLegacyFilters();
  165. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  166. factory->init(pServiceNode);
  167. unsigned machineUsageCacheForceRebuildMinutes = pServiceNode->getPropInt("MachineUsageCacheMinutes", machineUsageCacheMinutes);
  168. unsigned machineUsageCacheAutoRebuildMinutes = pServiceNode->getPropInt("MachineUsageCacheAutoRebuildMinutes", defaultMachineUsageCacheAutoBuildMinutes);
  169. usageCacheReader.setown(new CUsageCacheReader(this, "Usage Reader", machineUsageCacheAutoRebuildMinutes*60, machineUsageCacheForceRebuildMinutes*60));
  170. }
  171. StringBuffer& Cws_machineEx::getAcceptLanguage(IEspContext& context, StringBuffer& acceptLanguage)
  172. {
  173. context.getAcceptLanguage(acceptLanguage);
  174. if (!acceptLanguage.length())
  175. {
  176. acceptLanguage.set("en");
  177. return acceptLanguage;
  178. }
  179. acceptLanguage.setLength(2);
  180. VStringBuffer languageFile("%ssmc_xslt/nls/%s/hpcc.xml", getCFD(), acceptLanguage.str());
  181. if (!checkFileExists(languageFile.str()))
  182. acceptLanguage.set("en");
  183. return acceptLanguage;
  184. }
  185. bool Cws_machineEx::onGetMachineInfo(IEspContext &context, IEspGetMachineInfoRequest & req,
  186. IEspGetMachineInfoResponse & resp)
  187. {
  188. try
  189. {
  190. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  191. StringArray& addresses = req.getAddresses();
  192. if (addresses.empty())
  193. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  194. CGetMachineInfoData machineInfoData;
  195. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  196. req.getApplyProcessFilter(), addresses, req.getAddProcessesToFilter(), machineInfoData);
  197. getMachineInfo(context, machineInfoData);
  198. setMachineInfoResponse(context, req, machineInfoData, resp);
  199. }
  200. catch(IException* e)
  201. {
  202. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  203. }
  204. return true;
  205. }
  206. bool Cws_machineEx::onGetMachineInfoEx(IEspContext &context, IEspGetMachineInfoRequestEx & req, IEspGetMachineInfoResponseEx & resp)
  207. {
  208. try
  209. {
  210. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  211. StringArray& addresses = req.getAddresses();
  212. if (addresses.empty())
  213. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No network address specified.");
  214. double version = context.getClientVersion();
  215. CGetMachineInfoData machineInfoData;
  216. readMachineInfoRequest(context, true, true, true, true, true, addresses, NULL, machineInfoData);
  217. getMachineInfo(context, machineInfoData);
  218. if (machineInfoData.getMachineInfoTable().ordinality())
  219. resp.setMachines(machineInfoData.getMachineInfoTable());
  220. if (version >= 1.12)
  221. {
  222. StringBuffer acceptLanguage;
  223. resp.setAcceptLanguage(getAcceptLanguage(context, acceptLanguage).str());
  224. }
  225. }
  226. catch(IException* e)
  227. {
  228. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  229. }
  230. return true;
  231. }
  232. bool Cws_machineEx::onGetTargetClusterInfo(IEspContext &context, IEspGetTargetClusterInfoRequest & req,
  233. IEspGetTargetClusterInfoResponse & resp)
  234. {
  235. try
  236. {
  237. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Target Cluster Information. Permission denied.");
  238. StringArray& targetClusters = req.getTargetClusters();
  239. if (targetClusters.empty())
  240. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "No target cluster specified.");
  241. CGetMachineInfoData machineInfoData;
  242. Owned<IPropertyTree> targetClustersOut = createPTreeFromXMLString("<Root/>");
  243. readMachineInfoRequest(context, req.getGetProcessorInfo(), req.getGetStorageInfo(), req.getLocalFileSystemsOnly(), req.getGetSoftwareInfo(),
  244. req.getApplyProcessFilter(), req.getAddProcessesToFilter(), targetClusters, machineInfoData, targetClustersOut);
  245. getMachineInfo(context, machineInfoData);
  246. setTargetClusterInfoResponse(context, req, machineInfoData, targetClustersOut, resp);
  247. }
  248. catch(IException* e)
  249. {
  250. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  251. }
  252. return true;
  253. }
  254. void Cws_machineEx::addChannels(CGetMachineInfoData& machineInfoData, IPropertyTree* envRoot,
  255. const char* componentType, const char* componentName)
  256. {
  257. VStringBuffer key("%s|%s", componentType, componentName);
  258. int* channels = machineInfoData.getChannels(key);
  259. if (channels)
  260. return;
  261. StringBuffer path("Software/");
  262. if (strieq(componentType, eqThorSlaveProcess))
  263. path.append(eqThorCluster);
  264. else if (strieq(componentType, eqRoxieServerProcess))
  265. path.append(eqRoxieCluster);
  266. else
  267. throw MakeStringException(ECLWATCH_INVALID_COMPONENT_TYPE, "Invalid %s in Cws_machineEx::addChannels().", componentType);
  268. path.appendf("[@name=\"%s\"]", componentName);
  269. Owned<IPropertyTree> component;
  270. if (envRoot)
  271. {
  272. component.setown(envRoot->getPropTree(path));
  273. }
  274. else
  275. {
  276. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  277. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  278. Owned<IPropertyTree> root = &constEnv->getPTree();
  279. component.setown(root->getPropTree(path));
  280. }
  281. if (!component)
  282. throw MakeStringException(ECLWATCH_INVALID_IP_OR_COMPONENT, "%s not found.", componentName);
  283. StringAttr attr;
  284. if (strieq(componentType, eqThorSlaveProcess))
  285. attr.set("@channelsPerSlave");
  286. else
  287. attr.set("@channelsPerNode");
  288. if (component->hasProp(attr.get()))
  289. machineInfoData.addToChannelsMap(key, component->getPropInt(attr.get()));
  290. }
  291. ////////////////////////////////////////////////////////////////////////////////////////
  292. // Read Machine Infomation request and collect related settings from environment.xml //
  293. ////////////////////////////////////////////////////////////////////////////////////////
  294. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  295. StringArray& processes, const char* addProcessesToFilters, CGetMachineInfoData& machineInfoData)
  296. {
  297. double version = context.getClientVersion();
  298. StringBuffer userID, password;
  299. context.getUserID(userID);
  300. context.getPassword(password);
  301. machineInfoData.getOptions().setUserName(userID.str());
  302. machineInfoData.getOptions().setPassword(password.str());
  303. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  304. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  305. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  306. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  307. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  308. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  309. BoolHash uniqueProcesses;
  310. for (unsigned i=0; i<processes.ordinality(); i++)
  311. {
  312. StringArray address;
  313. address.appendList(processes.item(i), ":");
  314. StringBuffer address1, address2, processType, compName, path;
  315. unsigned processNumber = 0;
  316. if (!machineInfoData.getOptions().getGetSoftwareInfo())
  317. {
  318. parseAddresses(address.item(0), address1, address2);
  319. }
  320. else
  321. {
  322. if (address.ordinality() < 5)
  323. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Invalid address format in '%s'.", processes.item(i));
  324. parseProcessString(address, address1, address2, processType, compName, path, processNumber);
  325. }
  326. setProcessRequest(machineInfoData, uniqueProcesses, address1.str(), address2.str(), processType.str(), compName.str(), path.str(), processNumber);
  327. if (strieq(processType.str(), eqRoxieServerProcess))
  328. machineInfoData.appendRoxieClusters(compName.str());
  329. if ((version >= 1.16) && (strieq(processType, eqThorSlaveProcess) || strieq(processType, eqRoxieServerProcess)))
  330. addChannels(machineInfoData, nullptr, processType, compName);
  331. }
  332. }
  333. void Cws_machineEx::readMachineInfoRequest(IEspContext& context, bool getProcessorInfo, bool getStorageInfo, bool localFileSystemsOnly, bool getSoftwareInfo, bool applyProcessFilter,
  334. const char* addProcessesToFilters, StringArray& targetClustersIn, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClusterTreeOut)
  335. {
  336. StringBuffer userID, password;
  337. context.getUserID(userID);
  338. context.getPassword(password);
  339. machineInfoData.getOptions().setUserName(userID.str());
  340. machineInfoData.getOptions().setPassword(password.str());
  341. machineInfoData.getOptions().setGetProcessorInfo(getProcessorInfo);
  342. machineInfoData.getOptions().setGetStorageInfo(getStorageInfo);
  343. machineInfoData.getOptions().setLocalFileSystemsOnly(localFileSystemsOnly);
  344. machineInfoData.getOptions().setGetSoftwareInfo(getSoftwareInfo);
  345. machineInfoData.getOptions().setApplyProcessFilter(applyProcessFilter);
  346. machineInfoData.getOptions().getAdditionalProcessFilters().appendList(addProcessesToFilters, " ,\t");
  347. readSettingsForTargetClusters(context, targetClustersIn, machineInfoData, targetClusterTreeOut);
  348. }
  349. //Parses address request from machine information request in the form "192.168.1.4-6|."
  350. //The second address is the address retrieved from environment setting (could be a '.').
  351. void Cws_machineEx::parseAddresses(const char *address, StringBuffer& address1, StringBuffer& address2)
  352. {
  353. address1 = address;
  354. address2.clear();
  355. const char* props1 = strchr(address, '|');
  356. if (props1)
  357. {
  358. address2 = props1+1;
  359. address1.setLength(props1 - address);
  360. }
  361. address1.trim();
  362. address2.trim();
  363. }
  364. //Parses machine information request for each process in the form "192.168.1.4-6|.:ThorSlaveProcess:thor1:2:/var/lib/..."
  365. void Cws_machineEx::parseProcessString(StringArray& process, StringBuffer& address1, StringBuffer& address2,
  366. StringBuffer& processType, StringBuffer& compName, StringBuffer& path, unsigned& processNumber)
  367. {
  368. parseAddresses(process.item(0), address1, address2);
  369. processType.clear().append( process.item(1) ).trim();
  370. compName.clear().append( process.item(2) ).trim();
  371. EnvMachineOS os = (EnvMachineOS) atoi( process.item(3) );
  372. path.clear().append( process.item(4) ).trim();
  373. if (path.length())
  374. {
  375. char pat1, pat2;
  376. char rep1, rep2;
  377. if (os == MachineOsLinux)
  378. {
  379. pat1 = ':'; rep1 = '$';
  380. pat2 = '\\';rep2 = '/';
  381. }
  382. else
  383. {
  384. pat1 = '$'; rep1 = ':';
  385. pat2 = '/';rep2 = '\\';
  386. }
  387. path.replace( pat1, rep1 );
  388. path.replace( pat2, rep2 );
  389. if ((os == MachineOsLinux) && (path.charAt(0) != '/'))
  390. path.insert(0, '/');
  391. }
  392. if (process.ordinality() < 6)
  393. return;
  394. processNumber = atoi( process.item(5) );
  395. }
  396. void Cws_machineEx::setProcessRequest(CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses, const char* address1, const char* address2,
  397. const char* processType, const char* compName, const char* path, unsigned processNumber)
  398. {
  399. IpAddress ipAddr;
  400. unsigned numIps = ipAddr.ipsetrange(address1);
  401. //address is like 192.168.1.4-6
  402. //so process each address in the range
  403. if (!ipAddr.isIp4())
  404. IPV6_NOT_IMPLEMENTED();
  405. //Always use "EclAgentProcess" to retrieve machine info for "AgentExecProcess"
  406. StringBuffer processTypeStr;
  407. if (processType && *processType)
  408. {
  409. if (strieq(processType, eqAgentExec))
  410. processTypeStr.append(eqEclAgent);
  411. else
  412. processTypeStr = processType;
  413. }
  414. while (numIps--)
  415. {
  416. unsigned numAddr;
  417. if (ipAddr.getNetAddress(sizeof(numAddr),&numAddr)!=sizeof(numAddr))
  418. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid network address.");
  419. ipAddr.ipincrement(1);
  420. //Clean possible duplication
  421. StringBuffer valuesToBeChecked;
  422. valuesToBeChecked.append(numAddr);
  423. if (machineInfoData.getOptions().getGetSoftwareInfo())
  424. valuesToBeChecked.appendf(":%s:%s:%d", processTypeStr.str(), compName, processNumber);
  425. bool* found = uniqueProcesses.getValue(valuesToBeChecked.str());
  426. if (found && *found)
  427. continue;
  428. uniqueProcesses.setValue(valuesToBeChecked.str(), true);
  429. addProcessRequestToMachineInfoData(machineInfoData, address1, address2, processTypeStr.str(), compName, path, processNumber);
  430. }
  431. }
  432. void Cws_machineEx::addProcessRequestToMachineInfoData(CGetMachineInfoData& machineInfoData, const char* address1, const char* address2,
  433. const char* processType, const char* compName, const char* path, unsigned processNumber)
  434. {
  435. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  436. ForEachItemIn(idx, machines)
  437. {
  438. CMachineData& machine = machines.item(idx);
  439. if (streq(address1, machine.getNetworkAddress()))
  440. {
  441. addProcessData(&machine, processType, compName, path, processNumber);
  442. return;
  443. }
  444. }
  445. char pathSep;
  446. EnvMachineOS os;
  447. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  448. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(address1);
  449. if (pMachineInfo.get())
  450. os = pMachineInfo->getOS();
  451. else
  452. os = MachineOsUnknown;
  453. if (os == MachineOsW2K)
  454. pathSep = '\\';
  455. else
  456. pathSep = '/';
  457. Owned<CMachineData> machineNew = new CMachineData(address1, address2, os, pathSep);
  458. //Read possible dependencies for all processes
  459. set<string>& dependenciesForAllProcesses = machineNew->getDependencies();
  460. StringBuffer xPath;
  461. xPath.appendf("Platform[@name='%s']/ProcessFilter[@name='any']/Process", machineNew->getOS() == MachineOsW2K ? "Windows" : "Linux");
  462. Owned<IPropertyTreeIterator> processes = m_processFilters->getElements(xPath.str());
  463. ForEach (*processes)
  464. {
  465. StringBuffer processName;
  466. processes->query().getProp("@name", processName);
  467. processName.toLowerCase().replaceString(".exe", "");
  468. if ((processName.length() > 0) && (!streq(processName.str(), "hoagentd"))) //hoagentd is not needed anymore
  469. dependenciesForAllProcesses.insert(processName.str());
  470. }
  471. if (m_bMonitorDaliFileServer && (dependenciesForAllProcesses.find("dafilesrv") == dependenciesForAllProcesses.end()))
  472. dependenciesForAllProcesses.insert("dafilesrv");
  473. addProcessData(machineNew, processType, compName, path, processNumber);
  474. machines.append(*machineNew.getClear());
  475. }
  476. //Create a CProcessData object and add it to CMachineData
  477. void Cws_machineEx::addProcessData(CMachineData* machine, const char* processType, const char* compName,
  478. const char* path, unsigned processNumber)
  479. {
  480. if (!machine)
  481. return;
  482. StringBuffer pathStr(path);
  483. if (pathStr.length() > 0)
  484. {
  485. char pathSep = machine->getPathSep();
  486. if (pathStr.charAt(pathStr.length() - 1) != pathSep)
  487. pathStr.append(pathSep);
  488. }
  489. Owned<CProcessData> process = new CProcessData(compName, processType, pathStr.str(), processNumber);
  490. //Copy dependencies for all processes
  491. set<string>& dependenciesForThisProcess = process->getDependencies();
  492. set<string>& dependenciesForAllProcesses = machine->getDependencies();
  493. set<string>::const_iterator it = dependenciesForAllProcesses.begin();
  494. set<string>::const_iterator iEnd = dependenciesForAllProcesses.end();
  495. for (; it != iEnd; it++) //add in sorted order simply by traversing the map
  496. dependenciesForThisProcess.insert((*it).c_str());
  497. //now collect "process-specific" dependencies
  498. StringBuffer xPath;
  499. xPath.appendf("Platform[@name='%s']/ProcessFilter[@name='%s']", machine->getOS() == MachineOsW2K ? "Windows" : "Linux", processType);
  500. IPropertyTree* processFilterNode = m_processFilters->queryPropTree( xPath.str() );
  501. if (!processFilterNode)
  502. {
  503. machine->getProcesses().append(*process.getClear());
  504. return;
  505. }
  506. Owned<IPropertyTreeIterator> processes = processFilterNode->getElements("Process");
  507. ForEach (*processes)
  508. {
  509. IPropertyTree* pProcess = &processes->query();
  510. const char* name = pProcess->queryProp("@name");
  511. if (!name || streq(name, "."))
  512. continue;
  513. StringBuffer processName(name);
  514. processName.toLowerCase().replaceString(".exe", "");
  515. if (processName.length() < 1)
  516. continue;
  517. //Environment.xml may contain old filter settings.
  518. if (isLegacyFilter(processType, processName.str()))
  519. continue;
  520. if (pProcess->getPropBool("@remove", false))
  521. dependenciesForThisProcess.erase(processName.str());
  522. else
  523. dependenciesForThisProcess.insert(processName.str());
  524. }
  525. process->setMultipleInstances(machine->getOS() == MachineOsLinux && processFilterNode->getPropBool("@multipleInstances", false));
  526. machine->getProcesses().append(*process.getClear());
  527. }
  528. //Collect process settings for the requested target clusters
  529. void Cws_machineEx::readSettingsForTargetClusters(IEspContext& context, StringArray& targetClusters, CGetMachineInfoData& machineInfoData, IPropertyTree* targetClustersOut)
  530. {
  531. unsigned ordinality= targetClusters.ordinality();
  532. if (ordinality < 1)
  533. return;
  534. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  535. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  536. if (!pEnvironmentRoot)
  537. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  538. BoolHash uniqueProcesses;
  539. for (unsigned index=0; index<ordinality; index++)
  540. {
  541. StringBuffer clusterType;
  542. const char* clusterName = targetClusters.item(index);
  543. const char* pClusterName = strchr(clusterName, ':');
  544. if (pClusterName)
  545. {
  546. clusterType.append(clusterName, 0, pClusterName - clusterName);
  547. pClusterName++;
  548. }
  549. if (!pClusterName || !*pClusterName)
  550. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster name not specified.");
  551. if (clusterType.length() < 1)
  552. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster type not specified.");
  553. StringBuffer path;
  554. path.appendf("Software/Topology/Cluster[@name='%s']", pClusterName);
  555. IPropertyTree* pCluster = pEnvironmentRoot->queryPropTree(path.str());
  556. if (!pCluster)
  557. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", pClusterName);
  558. Owned<IPropertyTreeIterator> clusterProcesses;
  559. if (strieq(clusterType.str(), eqThorCluster) || strieq(clusterType.str(), eqRoxieCluster))
  560. {
  561. clusterProcesses.setown(pCluster->getElements(clusterType.str()));
  562. if (!clusterProcesses->first())
  563. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Cluster %s not found in environment setting.", clusterType.str());
  564. }
  565. Owned<IPropertyTreeIterator> eclCCServerProcesses= pCluster->getElements(eqEclCCServer);
  566. Owned<IPropertyTreeIterator> eclServerProcesses= pCluster->getElements(eqEclServer);
  567. Owned<IPropertyTreeIterator> eclAgentProcesses= pCluster->getElements(eqEclAgent);
  568. Owned<IPropertyTreeIterator> eclSchedulerProcesses= pCluster->getElements(eqEclScheduler);
  569. IPropertyTree *targetClusterOut = targetClustersOut->addPropTree("TargetCluster", createPTree("TargetCluster"));
  570. targetClusterOut->setProp("@Name", pClusterName);
  571. targetClusterOut->setProp("@Type", clusterType.str());
  572. //Read Cluster processes
  573. if (clusterProcesses && clusterProcesses->first())
  574. ForEach(*clusterProcesses)
  575. readTargetClusterProcesses(context, clusterProcesses->query(), clusterType.str(), uniqueProcesses, machineInfoData, targetClusterOut);
  576. //Read eclCCServer process
  577. if (eclCCServerProcesses->first())
  578. readTargetClusterProcesses(context, eclCCServerProcesses->query(), eqEclCCServer, uniqueProcesses, machineInfoData, targetClusterOut);
  579. //Read eclServer process
  580. if (eclServerProcesses->first())
  581. readTargetClusterProcesses(context, eclServerProcesses->query(), eqEclServer, uniqueProcesses, machineInfoData, targetClusterOut);
  582. //Read eclAgent process
  583. if (eclAgentProcesses->first())
  584. readTargetClusterProcesses(context, eclAgentProcesses->query(), eqEclAgent, uniqueProcesses, machineInfoData, targetClusterOut);
  585. //Read eclScheduler process
  586. if (eclSchedulerProcesses->first())
  587. readTargetClusterProcesses(context, eclSchedulerProcesses->query(), eqEclScheduler, uniqueProcesses, machineInfoData, targetClusterOut);
  588. }
  589. }
  590. //Collect settings for one group of target cluster processes
  591. void Cws_machineEx::readTargetClusterProcesses(IEspContext& context, IPropertyTree &processNode, const char* nodeType, BoolHash& uniqueProcesses, CGetMachineInfoData& machineInfoData,
  592. IPropertyTree* targetClustersOut)
  593. {
  594. const char* process = processNode.queryProp("@process");
  595. if (!process || !*process)
  596. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process attribute not set for ECLCCServer in environment setting.");
  597. Owned<IConstEnvironment> constEnv = getConstEnvironment();
  598. Owned<IPropertyTree> pEnvironmentRoot = &constEnv->getPTree();
  599. if (!pEnvironmentRoot)
  600. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  601. IPropertyTree* pEnvironmentSoftware = pEnvironmentRoot->queryPropTree("Software");
  602. if (!pEnvironmentSoftware)
  603. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get environment information.");
  604. double version = context.getClientVersion();
  605. IPropertyTree* pClusterProcess = NULL;
  606. if (strieq(nodeType, eqThorCluster) || strieq(nodeType, eqRoxieCluster))
  607. {
  608. StringBuffer path;
  609. path.appendf("Software/%s[@name='%s']", nodeType, process);
  610. pClusterProcess = pEnvironmentRoot->queryPropTree(path.str());
  611. if (!pClusterProcess)
  612. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Process not set for %s in environment setting.", path.str());
  613. if (strieq(nodeType, eqRoxieCluster))
  614. machineInfoData.appendRoxieClusters(process);
  615. }
  616. IPropertyTree *pInfo = targetClustersOut->addPropTree("Process", createPTree("Process"));
  617. pInfo->setProp("@Name", process);
  618. pInfo->setProp("@Type", nodeType);
  619. StringBuffer dirStr;
  620. IPropertyTree* pEnvironmentDirectories = pEnvironmentSoftware->queryPropTree("Directories");
  621. if (!pClusterProcess)
  622. {
  623. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  624. dirStr.clear().append(processNode.queryProp("@directory"));
  625. getProcesses(constEnv, pEnvironmentSoftware, process, nodeType, dirStr.str(), machineInfoData, false, uniqueProcesses);
  626. return;
  627. }
  628. if (!pEnvironmentDirectories || !getConfigurationDirectory(pEnvironmentDirectories, "run", nodeType, process, dirStr))
  629. dirStr.clear().append(pClusterProcess->queryProp("@directory"));
  630. if (strieq(nodeType, eqThorCluster))
  631. {
  632. getProcesses(constEnv, pClusterProcess, process, eqThorMasterProcess, dirStr.str(), machineInfoData, true, uniqueProcesses);
  633. getThorProcesses(constEnv, pClusterProcess, process, eqThorSlaveProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  634. getThorProcesses(constEnv, pClusterProcess, process, eqThorSpareProcess, dirStr.str(), machineInfoData, uniqueProcesses);
  635. if (version >= 1.16)
  636. addChannels(machineInfoData, pEnvironmentRoot, eqThorSlaveProcess, process);
  637. }
  638. else if (strieq(nodeType, eqRoxieCluster))
  639. {
  640. BoolHash uniqueRoxieProcesses;
  641. getProcesses(constEnv, pClusterProcess, process, eqRoxieServerProcess, dirStr.str(), machineInfoData, true, uniqueProcesses, &uniqueRoxieProcesses);
  642. if (version >= 1.16)
  643. addChannels(machineInfoData, pEnvironmentRoot, eqRoxieServerProcess, process);
  644. }
  645. }
  646. void Cws_machineEx::getThorProcesses(IConstEnvironment* constEnv, IPropertyTree* cluster, const char* processName,
  647. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData, BoolHash& uniqueProcesses)
  648. {
  649. if (!constEnv || !cluster)
  650. return;
  651. Owned<IGroup> nodeGroup;
  652. StringBuffer groupName;
  653. if (strieq(processType, eqThorSlaveProcess))
  654. {
  655. getClusterGroupName(*cluster, groupName);
  656. if (groupName.length() < 1)
  657. {
  658. OWARNLOG("Cannot find group name for %s", processName);
  659. return;
  660. }
  661. nodeGroup.setown(getClusterProcessNodeGroup(processName, eqThorCluster));
  662. }
  663. else
  664. {
  665. getClusterSpareGroupName(*cluster, groupName);
  666. if (groupName.length() < 1)
  667. {
  668. OWARNLOG("Cannot find group name for %s", processName);
  669. return;
  670. }
  671. nodeGroup.setown(queryNamedGroupStore().lookup(groupName.str()));
  672. }
  673. if (!nodeGroup || (nodeGroup->ordinality() == 0))
  674. {
  675. OWARNLOG("Cannot find node group for %s", processName);
  676. return;
  677. }
  678. int slavesPerNode = cluster->getPropInt("@slavesPerNode");
  679. Owned<INodeIterator> gi = nodeGroup->getIterator();
  680. ForEach(*gi)
  681. {
  682. StringBuffer addressRead;
  683. gi->query().endpoint().getIpText(addressRead);
  684. if (addressRead.length() == 0)
  685. {
  686. OWARNLOG("Network address not found for a node in node group %s", groupName.str());
  687. continue;
  688. }
  689. StringBuffer netAddress;
  690. const char* ip = addressRead.str();
  691. if (!streq(ip, "."))
  692. {
  693. netAddress.append(ip);
  694. }
  695. else
  696. {
  697. IpAddress ipaddr = queryHostIP();
  698. ipaddr.getIpText(netAddress);
  699. }
  700. if (netAddress.length() == 0)
  701. {
  702. OWARNLOG("Network address not found for a node in node group %s", groupName.str());
  703. continue;
  704. }
  705. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachineByAddress(addressRead.str());
  706. if (!pMachineInfo.get())
  707. {
  708. OWARNLOG("Machine not found at network address %s", addressRead.str());
  709. continue;
  710. }
  711. //Each thor slave is a process. The i is used to check whether the process is running or not.
  712. for (unsigned i = 1; i <= slavesPerNode; i++)
  713. setProcessRequest(machineInfoData, uniqueProcesses, netAddress.str(), addressRead.str(),
  714. processType, processName, directory, i);
  715. }
  716. return;
  717. }
  718. void Cws_machineEx::getProcesses(IConstEnvironment* constEnv, IPropertyTree* environment, const char* processName,
  719. const char* processType, const char* directory, CGetMachineInfoData& machineInfoData,
  720. bool isThorOrRoxieProcess, BoolHash& uniqueProcesses, BoolHash* uniqueRoxieProcesses)
  721. {
  722. Owned<IPropertyTreeIterator> processes= environment->getElements(processType);
  723. ForEach(*processes)
  724. {
  725. StringArray processInstances, directories;
  726. IPropertyTree &process = processes->query();
  727. //Thor master and roxie server has been checked before this call.
  728. if (!isThorOrRoxieProcess)
  729. {
  730. const char* name = process.queryProp("@name");
  731. if (!name || !*name || !streq(name, processName))
  732. continue;
  733. }
  734. const char* computerName = process.queryProp("@computer");
  735. if (computerName && *computerName)
  736. appendProcessInstance(computerName, directory, NULL, processInstances, directories);
  737. else
  738. {
  739. Owned<IPropertyTreeIterator> instances= process.getElements("Instance");
  740. ForEach(*instances)
  741. {
  742. IPropertyTree &instance = instances->query();
  743. appendProcessInstance(instance.queryProp("@computer"), directory, instance.queryProp("@directory"), processInstances, directories);
  744. }
  745. }
  746. if (processInstances.length() < 1)
  747. continue;
  748. for (unsigned i = 0; i < processInstances.length(); i++)
  749. {
  750. const char* name0 = processInstances.item(i);
  751. const char* directory0 = directories.item(i);
  752. if (uniqueRoxieProcesses)//to avoid duplicate entries for roxie (one machine has only one roxie process).
  753. {
  754. bool* found = uniqueRoxieProcesses->getValue(name0);
  755. if (found && *found)
  756. continue;
  757. uniqueRoxieProcesses->setValue(name0, true);
  758. }
  759. Owned<IConstMachineInfo> pMachineInfo = constEnv->getMachine(name0);
  760. if (!pMachineInfo.get())
  761. {
  762. OWARNLOG("Machine %s not found in environment setting", name0);
  763. continue;
  764. }
  765. SCMStringBuffer ep;
  766. pMachineInfo->getNetAddress(ep);
  767. const char* ip = ep.str();
  768. if (!ip)
  769. {
  770. OWARNLOG("Network address not found for machine %s", name0);
  771. continue;
  772. }
  773. StringBuffer netAddress;
  774. StringBuffer configNetAddress(ip);
  775. if (!streq(ip, "."))
  776. {
  777. netAddress.set(ip);
  778. }
  779. else
  780. {
  781. IpAddress ipaddr = queryHostIP();
  782. ipaddr.getIpText(netAddress);
  783. }
  784. setProcessRequest(machineInfoData, uniqueProcesses, netAddress.str(), configNetAddress.str(), processType, processName, directory0);
  785. }
  786. }
  787. return;
  788. }
  789. void Cws_machineEx::setupLegacyFilters()
  790. {
  791. unsigned idx = 0;
  792. while (legacyFilterStrings[idx])
  793. {
  794. m_legacyFilters.setValue(legacyFilterStrings[idx], true);
  795. idx++;
  796. }
  797. return;
  798. }
  799. bool Cws_machineEx::isLegacyFilter(const char* processType, const char* dependency)
  800. {
  801. if (!processType || !*processType || !dependency || !*dependency)
  802. return false;
  803. StringBuffer filterString;
  804. filterString.appendf("%s:%s", processType, dependency);
  805. bool* found = m_legacyFilters.getValue(filterString.str());
  806. if (found && *found)
  807. return true;
  808. return false;
  809. }
  810. //The stateHashes stores different state hashes in one roxie cluster.
  811. //It also stores how many roxie nodes have the same state hashes.
  812. unsigned Cws_machineEx::addRoxieStateHash(const char* hash, StateHashes& stateHashes, unsigned& totalUniqueHashes)
  813. {
  814. if (!hash || !*hash)
  815. return -1;
  816. unsigned hashID = 0;
  817. IStateHash* stateHash = stateHashes.getValue(hash);
  818. if (stateHash)
  819. {
  820. //if the stateHashes already has the same 'hash', increases the count for the 'stateHash'.
  821. //The 'StateHash' with the highest count will be the 'Major StateHash'.
  822. //If a roxie node does not contain the 'Major StateHash', it has a 'mismatch' state hash.
  823. hashID = stateHash->queryID();
  824. stateHash->incrementCount();
  825. }
  826. else
  827. {
  828. //Add a new 'StateHash'. Set its hashID to totalUniqueHashes and set its count to 1.
  829. hashID = totalUniqueHashes;
  830. Owned<IStateHash> newStateHash = new CStateHash(hashID, 1);
  831. stateHashes.setValue(hash, newStateHash);
  832. totalUniqueHashes++;
  833. }
  834. return hashID;
  835. }
  836. void Cws_machineEx::updateMajorRoxieStateHash(StateHashes& stateHashes, CIArrayOf<CRoxieStateData>& roxieStates)
  837. {
  838. //Find out which state hash is for the most of the roxie nodes inside this roxie cluster.
  839. unsigned majorHashID = 0;
  840. unsigned majorHashCount = 0;
  841. HashIterator hashes(stateHashes);
  842. ForEach(hashes)
  843. {
  844. IStateHash *hash = stateHashes.mapToValue(&hashes.query());
  845. unsigned hashCount = hash->queryCount();
  846. if (majorHashCount >= hashCount)
  847. continue;
  848. majorHashCount = hashCount;
  849. majorHashID = hash->queryID();
  850. }
  851. //Set the MajorHash to false if the roxie node's HashID() != majorHashID.
  852. ForEachItemIn(ii, roxieStates)
  853. {
  854. CRoxieStateData& roxieState = roxieStates.item(ii);
  855. if (roxieState.getHashID() != majorHashID)
  856. roxieState.setMajorHash(false);
  857. }
  858. }
  859. void Cws_machineEx::readRoxieStatus(const Owned<IPropertyTree> controlResp, CIArrayOf<CRoxieStateData>& roxieStates)
  860. {
  861. StateHashes stateHashes;
  862. unsigned totalUniqueHashes = 0;
  863. Owned<IPropertyTreeIterator> roxieEndpoints = controlResp->getElements("Endpoint");
  864. ForEach(*roxieEndpoints)
  865. {
  866. IPropertyTree& roxieEndpoint = roxieEndpoints->query();
  867. const char *ep = roxieEndpoint.queryProp("@ep");
  868. if (!ep || !*ep)
  869. continue;
  870. bool ok = false, attached = false, detached = false;
  871. const char *status = roxieEndpoint.queryProp("Status");
  872. if (status && strieq(status, "ok"))
  873. ok = true;
  874. const char *stateHash = roxieEndpoint.queryProp("State/@hash");
  875. if (roxieEndpoint.hasProp("Dali/@connected"))
  876. {
  877. if (roxieEndpoint.getPropBool("Dali/@connected"))
  878. attached = true;
  879. else
  880. detached = true;
  881. }
  882. StringArray locations;
  883. locations.appendListUniq(ep, ":");
  884. Owned<CRoxieStateData> roxieState = new CRoxieStateData(locations.item(0), addRoxieStateHash(stateHash, stateHashes, totalUniqueHashes));
  885. roxieState->setState(ok, attached, detached, stateHash);
  886. roxieStates.append(*roxieState.getClear());
  887. }
  888. if (totalUniqueHashes > 1)
  889. updateMajorRoxieStateHash(stateHashes, roxieStates);
  890. }
  891. void Cws_machineEx::getRoxieStateInfo(CRoxieStateInfoThreadParam* param)
  892. {
  893. const char* clusterName = param->clusterName.get();
  894. if (!clusterName || !*clusterName)
  895. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Roxie cluster not specified.");
  896. SocketEndpointArray servers;
  897. getRoxieProcessServers(clusterName, servers);
  898. if (!servers.length())
  899. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Roxie Process server not found.");
  900. Owned<IRoxieCommunicationClient> roxieClient = createRoxieCommunicationClient(servers.item(0), ROXIECONTROLSTATETIMEOUT);
  901. Owned<IPropertyTree> controlResp = roxieClient->sendRoxieControlAllNodes("<control:state/>", true);
  902. if (!controlResp)
  903. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get control response from roxie %s.", clusterName);
  904. CIArrayOf<CRoxieStateData> roxieStates;
  905. readRoxieStatus(controlResp, roxieStates);
  906. ForEachItemIn(i, param->machineInfoTable)
  907. {
  908. IEspMachineInfoEx& machineInfo = param->machineInfoTable.item(i);
  909. if (!streq(machineInfo.getProcessType(), eqRoxieServerProcess) || !streq(machineInfo.getComponentName(), clusterName))
  910. continue;
  911. //This method is thread safe because each machineInfo (for one roxie node) belongs to only one Roxie cluster.
  912. //It is impossible for different threads to update the same machineInfo.
  913. bool foundRoxieState = false;
  914. ForEachItemIn(ii, roxieStates)
  915. {
  916. CRoxieStateData& roxieState = roxieStates.item(ii);
  917. if (!roxieState.matchIPAddress(machineInfo.getAddress()))
  918. continue;
  919. StringBuffer state, stateDetails;
  920. roxieState.reportState(state, stateDetails);
  921. machineInfo.setRoxieState(state.str());
  922. machineInfo.setRoxieStateDetails(stateDetails.str());
  923. foundRoxieState = true;
  924. }
  925. if (!foundRoxieState)
  926. {
  927. machineInfo.setRoxieState("??");
  928. machineInfo.setRoxieStateDetails("Roxie state not found");
  929. }
  930. }
  931. }
  932. void Cws_machineEx::getMachineInfo(IEspContext& context, bool getRoxieState, CGetMachineInfoData& machineInfoData)
  933. {
  934. UnsignedArray threadHandles;
  935. if (!getRoxieState)
  936. {
  937. CIArrayOf<CMachineData>& machines = machineInfoData.getMachineData();
  938. ForEachItemIn(idx, machines)
  939. {
  940. Owned<CMachineInfoThreadParam> pThreadReq = new CMachineInfoThreadParam(this, context, machineInfoData.getOptions(),
  941. machines.item(idx), machineInfoData.getMachineInfoTable(), machineInfoData.getMachineInfoColumns(),
  942. machineInfoData.getChannelsMap());
  943. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  944. threadHandles.append(handle);
  945. }
  946. }
  947. else
  948. {
  949. StringArray& roxieClusters = machineInfoData.getRoxieClusters();
  950. ForEachItemIn(i, roxieClusters)
  951. {
  952. Owned<CRoxieStateInfoThreadParam> pThreadReq = new CRoxieStateInfoThreadParam(this, roxieClusters.item(i),
  953. machineInfoData.getMachineInfoTable(), machineInfoData.getChannelsMap());
  954. PooledThreadHandle handle = m_threadPool->start( pThreadReq.getClear());
  955. threadHandles.append(handle);
  956. }
  957. machineInfoData.getMachineInfoColumns().append("Roxie State");
  958. }
  959. //Block for worker threads to finish, if necessary and then collect results
  960. //Not use joinAll() because multiple threads may call this method. Each call uses the pool to create
  961. //its own threads of checking query state. Each call should only join the ones created by that call.
  962. ForEachItemIn(i, threadHandles)
  963. m_threadPool->join(threadHandles.item(i));
  964. }
  965. ////////////////////////////////////////////////////////////////////
  966. // Get Machine Information based on Machine Information request //
  967. ////////////////////////////////////////////////////////////////////
  968. void Cws_machineEx::getMachineInfo(IEspContext& context, CGetMachineInfoData& machineInfoData)
  969. {
  970. double version = context.getClientVersion();
  971. getMachineInfo(context, false, machineInfoData);
  972. if ((version >= 1.13) && !machineInfoData.getRoxieClusters().empty())
  973. getMachineInfo(context, true, machineInfoData);
  974. }
  975. // the following method is invoked on worker threads of CMachineInfoThreadParam
  976. void Cws_machineEx::doGetMachineInfo(IEspContext& context, CMachineInfoThreadParam* pParam)
  977. {
  978. #ifdef DETECT_WS_MC_MEM_LEAKS
  979. static bool firstTime = true;
  980. if (firstTime)
  981. {
  982. firstTime = false;
  983. unsigned t = setAllocHook(true);
  984. }
  985. #endif //DETECT_WS_MC_MEM_LEAKS
  986. int error = 0;
  987. StringBuffer preflightCommand, response;
  988. buildPreflightCommand(context, pParam, preflightCommand);
  989. if (preflightCommand.length() < 1)
  990. {
  991. response.append("Failed in creating Machine Information command.\n");
  992. error = -1;
  993. }
  994. else
  995. {
  996. 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);
  997. if ((error == 0) && (response.length() > 0))
  998. readPreflightResponse(context, pParam, response.str(), error);
  999. }
  1000. //Set IArrayOf<IEspMachineInfoEx> based on Preflight Response
  1001. setMachineInfo(context, pParam, response.str(), error);
  1002. #ifdef DETECT_WS_MC_MEM_LEAKS
  1003. DBGLOG("Allocated=%d", setAllocHook(false));
  1004. #endif //DETECT_WS_MC_MEM_LEAKS
  1005. }
  1006. void Cws_machineEx::buildPreflightCommand(IEspContext& context, CMachineInfoThreadParam* pParam, StringBuffer& preflightCommand)
  1007. {
  1008. preflightCommand.clear().appendf("/%s/sbin/%s -p=%s", environmentConfData.m_executionPath.str(),
  1009. m_machineInfoFile.str(), environmentConfData.m_pidPath.str());
  1010. if (preflightCommand.charAt(preflightCommand.length() - 1) == pParam->m_machineData.getPathSep())
  1011. preflightCommand.remove(preflightCommand.length()-1, 1);
  1012. bool checkDependency = false;
  1013. CIArrayOf<CProcessData>& processes = pParam->m_machineData.getProcesses();
  1014. ForEachItemIn(idx, processes)
  1015. {
  1016. CProcessData& process = processes.item(idx);
  1017. if (!process.getName() || !*process.getName())
  1018. continue;
  1019. StringBuffer procName;
  1020. if (streq(process.getType(), eqThorSlaveProcess))
  1021. procName.appendf("thorslave_%s_%d,%s_slave_%d", process.getName(), process.getProcessNumber(), process.getName(), process.getProcessNumber());
  1022. else if (streq(process.getType(), eqThorMasterProcess))
  1023. procName.appendf("%s,%s_master", process.getName(), process.getName());
  1024. else
  1025. procName.append(process.getName());
  1026. if (idx < 1)
  1027. preflightCommand.appendf(" -n=%s", procName.str());
  1028. else
  1029. preflightCommand.appendf(",%s", procName.str());
  1030. if (!process.getDependencies().empty())
  1031. checkDependency = true;
  1032. }
  1033. if (checkDependency || !pParam->m_options.getApplyProcessFilter())
  1034. preflightCommand.append(" -d=ALL");
  1035. if (pParam->m_options.getGetStorageInfo() && !pParam->m_options.getLocalFileSystemsOnly())
  1036. preflightCommand.append(" -m=YES");
  1037. }
  1038. int Cws_machineEx::runCommand(IEspContext& context, const char* sAddress, const char* sConfigAddress, EnvMachineOS os,
  1039. const char* sCommand, const char* sUserId, const char* sPassword, StringBuffer& response)
  1040. {
  1041. int exitCode = -1;
  1042. try
  1043. {
  1044. StringBuffer command(sCommand);
  1045. StringBuffer userId;
  1046. StringBuffer password;
  1047. bool bLinux;
  1048. if (sConfigAddress && *sConfigAddress)
  1049. getAccountAndPlatformInfo(sConfigAddress, userId, password, bLinux);
  1050. else
  1051. getAccountAndPlatformInfo(sAddress, userId, password, bLinux);
  1052. if (!sUserId || !*sUserId || !sPassword ||!*sPassword)
  1053. {
  1054. //BUG: 9825 - remote execution on linux needs to use individual accounts
  1055. //use userid/password in ESP context for remote execution...
  1056. if (bLinux)
  1057. {
  1058. userId.clear();
  1059. password.clear();
  1060. context.getUserID(userId);
  1061. context.getPassword(password);
  1062. }
  1063. }
  1064. else
  1065. {
  1066. userId.clear().append(sUserId);
  1067. password.clear().append(sPassword);
  1068. }
  1069. // make sure there actually is something in command before we run a remote connection
  1070. if (command.length() < 1)
  1071. return exitCode;
  1072. Owned<IFRunSSH> connection = createFRunSSH();
  1073. connection->init(command.str(),NULL,NULL,NULL,m_SSHConnectTimeoutSeconds,0);
  1074. // executed as single connection
  1075. connection->exec(IpAddress(sAddress),NULL,false);
  1076. response.append(connection->getReplyText()[0]);
  1077. exitCode = connection->getReply()[0];
  1078. int len = response.length();
  1079. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1080. response.setLength(len);
  1081. if (response.length() && !exitCode)
  1082. response.insert(0, "Response: ");
  1083. else if (!exitCode)
  1084. response.insert(0, "No response recieved.\n");
  1085. }
  1086. // CFRunSSH uses a MakeStringExceptionDirect throw to pass code and result string
  1087. catch(IException* e)
  1088. {
  1089. exitCode = e->errorCode();
  1090. // errorCode == -1 on successful CFRunSSH execution
  1091. if(exitCode == -1)
  1092. exitCode = 0;
  1093. StringBuffer buf;
  1094. e->errorMessage(buf);
  1095. response.append(buf.str());
  1096. int len = response.length();
  1097. if (len > 0 && response.charAt(--len) == '\n') // strip newline
  1098. response.setLength(len);
  1099. // on successful connection
  1100. if (response.length() && !exitCode)
  1101. response.insert(0,"Response: ");
  1102. else if (!exitCode)
  1103. response.insert(0, "No response recieved.\n");
  1104. e->Release();
  1105. }
  1106. #ifndef NO_CATCHALL
  1107. catch(...)
  1108. {
  1109. response.append("An unknown exception occurred!");
  1110. exitCode = -1;
  1111. }
  1112. #endif
  1113. return exitCode;
  1114. }
  1115. int Cws_machineEx::invokeProgram(const char *command_line, StringBuffer& response)
  1116. {
  1117. char buffer[128];
  1118. FILE *fp;
  1119. // Run the command so that it writes its output to a pipe. Open this
  1120. // pipe with read text attribute so that we can read it
  1121. // like a text file.
  1122. if (getEspLogLevel()>LogNormal)
  1123. {
  1124. DBGLOG("command_line=<%s>", command_line);
  1125. }
  1126. #ifndef NO_CONNECTION_DEBUG
  1127. if( (fp = popen( command_line, "r" )) == NULL )
  1128. return -1;
  1129. #else
  1130. if( (fp = fopen( "c:\\temp\\preflight_result.txt", "r" )) == NULL )
  1131. return -1;
  1132. #endif
  1133. // Read pipe until end of file. End of file indicates that
  1134. //the stream closed its standard out (probably meaning it
  1135. //terminated).
  1136. while ( !feof(fp) )
  1137. if ( fgets( buffer, 128, fp) )
  1138. response.append( buffer );
  1139. if (getEspLogLevel()>LogNormal)
  1140. {
  1141. DBGLOG("response=<%s>", response.str());
  1142. }
  1143. // Close pipe and print return value of CHKDSK.
  1144. #ifndef NO_CONNECTION_DEBUG
  1145. return pclose( fp );
  1146. #else
  1147. return fclose( fp );
  1148. #endif
  1149. }
  1150. void Cws_machineEx::readPreflightResponse(IEspContext& context, CMachineInfoThreadParam* pParam, const char* response, int error)
  1151. {
  1152. if (!response || !*response)
  1153. return;
  1154. StringBuffer computerUpTime;
  1155. readALineFromResult(response, "ComputerUpTime:", computerUpTime, true);
  1156. if (computerUpTime.length() < 1)
  1157. computerUpTime.append("-");
  1158. else
  1159. {
  1160. const char* pStr = strchr(computerUpTime.str(), ' ');
  1161. if (pStr)
  1162. {
  1163. pStr++;
  1164. pStr = strchr(pStr, ' ');
  1165. if (pStr)
  1166. {
  1167. pStr++;
  1168. if (pStr)
  1169. pParam->m_machineData.setComputerUpTime(pStr);
  1170. }
  1171. }
  1172. if (!pStr)
  1173. pParam->m_machineData.setComputerUpTime(computerUpTime);
  1174. }
  1175. if (pParam->m_options.getGetProcessorInfo())
  1176. {
  1177. StringBuffer CPUIdle;
  1178. readALineFromResult(response, "CPU-Idle:", CPUIdle, true);
  1179. if (CPUIdle.length() < 1)
  1180. pParam->m_machineData.setCPULoad(0);
  1181. else
  1182. {
  1183. if (CPUIdle.charAt(CPUIdle.length() - 1) == '%')
  1184. CPUIdle.setLength(CPUIdle.length() - 1);
  1185. pParam->m_machineData.setCPULoad(100-atoi(CPUIdle.str()));
  1186. }
  1187. }
  1188. if (pParam->m_options.getGetStorageInfo())
  1189. readStorageData(response, pParam);
  1190. if (pParam->m_options.getGetSoftwareInfo())
  1191. readProcessData(response, pParam);
  1192. }
  1193. void Cws_machineEx::readALineFromResult(const char *result, const char *start, StringBuffer& value, bool trim)
  1194. {
  1195. if (!result || !*result)
  1196. return;
  1197. const char* pStr = strstr(result, start);
  1198. if (!pStr)
  1199. return;
  1200. pStr += strlen(start);
  1201. if (!pStr)
  1202. return;
  1203. const char* pStr1 = strchr(pStr, 0x0a);
  1204. if (pStr1)
  1205. value.append(pStr, 0, pStr1 - pStr);
  1206. else
  1207. value.append(pStr);
  1208. if (trim)
  1209. value.trim();
  1210. }
  1211. void Cws_machineEx::readStorageData(const char* response, CMachineInfoThreadParam* pParam)
  1212. {
  1213. if (!response || !*response)
  1214. return;
  1215. const char* pStr = strstr(response, "---SpaceUsedAndFree---");
  1216. if (!pStr)
  1217. DBGLOG("Storage information not found on %s", pParam->m_machineData.getNetworkAddress());
  1218. bool isTitleLine = true;
  1219. CIArrayOf<CStorageData>& storage = pParam->m_machineData.getStorage();
  1220. while (pStr)
  1221. {
  1222. StringBuffer buf;
  1223. const char* pStr1 = strchr(pStr, 0x0a);
  1224. if (pStr1)
  1225. {
  1226. buf.append(pStr, 0, pStr1 - pStr);
  1227. pStr = pStr1+1;
  1228. }
  1229. else
  1230. {
  1231. buf.append(pStr);
  1232. pStr = NULL;
  1233. }
  1234. if (isTitleLine)
  1235. {
  1236. isTitleLine = false;
  1237. continue;
  1238. }
  1239. if (buf.length() > 0)
  1240. {
  1241. StringBuffer diskSpaceTitle;
  1242. int diskSpacePercentAvail = 0;
  1243. __int64 diskSpaceAvailable = 0, diskSpaceTotal = 0;
  1244. if (!readStorageSpace(buf.str(), diskSpaceTitle, diskSpaceAvailable, diskSpaceTotal, diskSpacePercentAvail))
  1245. DBGLOG("Invalid storage information on %s: %s", pParam->m_machineData.getNetworkAddress(), buf.str());
  1246. else if ((diskSpaceTitle.length() > 0) && !excludePartition(diskSpaceTitle.str()))
  1247. {
  1248. Owned<CStorageData> diskData = new CStorageData(diskSpaceTitle, diskSpaceAvailable, diskSpaceTotal, diskSpacePercentAvail);
  1249. storage.append(*diskData.getClear());
  1250. }
  1251. }
  1252. if (!pStr || (strnicmp(pStr, "---ProcessList1---", 18)==0))
  1253. break;
  1254. }
  1255. }
  1256. bool Cws_machineEx::readStorageSpace(const char *line, StringBuffer& title, __int64& free, __int64& total, int& percentAvail)
  1257. {
  1258. if (!line || !*line)
  1259. return false;
  1260. StringBuffer freeStr, usedStr;
  1261. const char* pStr = line;
  1262. const char* pStr1 = strchr(pStr, ':');
  1263. if (!pStr1)
  1264. return false;
  1265. title.clear().append(pStr, 0, pStr1 - pStr);
  1266. pStr = pStr1 + 2;
  1267. pStr1 = (char*) strchr(pStr, ' ');
  1268. if (!pStr1)
  1269. return false;
  1270. usedStr.append(pStr, 0, pStr1 - pStr);
  1271. pStr = pStr1 + 1;
  1272. if (!pStr)
  1273. return false;
  1274. freeStr.append(pStr);
  1275. __int64 factor1 = 1;
  1276. if (freeStr.length() > 9)
  1277. {
  1278. freeStr.setLength(freeStr.length()-6);
  1279. factor1 = 1000000;
  1280. }
  1281. free = atol(freeStr.str())*factor1;
  1282. __int64 factor2 = 1;
  1283. if (usedStr.length() > 9)
  1284. {
  1285. usedStr.setLength(usedStr.length()-6);
  1286. factor2 = 1000000;
  1287. }
  1288. __int64 used = atol(usedStr.str())*factor2;
  1289. total = free + used;
  1290. if (total > 0)
  1291. percentAvail = (int) ((free*100)/total);
  1292. free = (__int64) free /1000; //MByte
  1293. total = (__int64) total /1000; //MByte
  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->queryPropTree(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. bool Cws_machineEx::readDiskSpaceResponse(const char* response, __int64& free, __int64& used, int& percentAvail, StringBuffer& pathUsed)
  2308. {
  2309. if (isEmptyString(response))
  2310. return false;
  2311. StringArray data;
  2312. data.appendList(response, " ");
  2313. if (data.length() < 2)
  2314. return false;
  2315. used = atol(data.item(0));
  2316. free = atol(data.item(1));
  2317. __int64 total = free + used;
  2318. if (total > 0)
  2319. percentAvail = (int) ((free*100)/total);
  2320. //The given path (ex. /var/lib/HPCCSystems/hpcc-mirror/thor) in the usage request does not exist.
  2321. //The data.item(2) is the path (ex. /var/lib/HPCCSystems/hpcc-mirror/) the usage script is used
  2322. //to read the DiskSpace.
  2323. if (data.length() > 2)
  2324. pathUsed.set(data.item(2));
  2325. return true;
  2326. }
  2327. void Cws_machineEx::getMachineUsage(IEspContext& context, CGetMachineUsageThreadParam* param)
  2328. {
  2329. VStringBuffer command("/%s/sbin/usage -d=", environmentConfData.m_executionPath.str());
  2330. unsigned pathCount = 0;
  2331. Owned<IPropertyTreeIterator> diskPathList = param->request->getElements("Folder");
  2332. ForEach(*diskPathList)
  2333. {
  2334. IPropertyTree& t = diskPathList->query();
  2335. if (pathCount > 0)
  2336. command.append(",");
  2337. command.appendf("%s", t.queryProp("@path"));
  2338. pathCount++;
  2339. }
  2340. ESPLOG(LogMax, "command(%s)", command.str());
  2341. StringBuffer response;
  2342. int error = runCommand(context, param->request->queryProp("@netAddress"), nullptr,
  2343. (EnvMachineOS) param->request->getPropInt("@OS", MachineOsLinux), command.str(), nullptr, nullptr, response);
  2344. if (error != 0 || isEmptyString(response))
  2345. {
  2346. if (isEmptyString(response))
  2347. param->request->addProp("@error", "Failed in getting component usage.");
  2348. else
  2349. param->request->addProp("@error", response);
  2350. return;
  2351. }
  2352. ESPLOG(LogMax, "response(%s)", response.str());
  2353. ForEach(*diskPathList)
  2354. {
  2355. IPropertyTree& diskPathTree = diskPathList->query();
  2356. StringBuffer aDiskPathResp, pathUsed;
  2357. VStringBuffer diskPath("%s:", diskPathTree.queryProp("@path"));
  2358. readALineFromResult(response, diskPath, aDiskPathResp, true);
  2359. int percentAvail = 0;
  2360. __int64 diskSpaceAvailable = 0, diskSpaceUsed = 0;
  2361. if (!readDiskSpaceResponse(aDiskPathResp.str(), diskSpaceAvailable, diskSpaceUsed, percentAvail, pathUsed))
  2362. {
  2363. DBGLOG("Failed to read disc space on %s: %s", param->request->queryProp("@netAddress"), aDiskPathResp.str());
  2364. diskPathTree.addProp("@error", "Failed to read disc space.");
  2365. continue;
  2366. }
  2367. diskPathTree.addPropInt64("@used", diskSpaceUsed);
  2368. diskPathTree.addPropInt64("@available", diskSpaceAvailable);
  2369. diskPathTree.addPropInt("@percentAvail", percentAvail);
  2370. if (!pathUsed.isEmpty())
  2371. diskPathTree.addProp("@pathUsed", pathUsed);
  2372. }
  2373. }
  2374. void Cws_machineEx::readComponentUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2375. const IPropertyTree* uniqueUsages, IArrayOf<IEspComponentUsage>& componentUsages)
  2376. {
  2377. double version = context.getClientVersion();
  2378. Owned<IPropertyTreeIterator> components= usageReq->getElements("Component");
  2379. ForEach(*components)
  2380. {
  2381. IPropertyTree& component = components->query();
  2382. Owned<IEspComponentUsage> componentUsage = createComponentUsage();
  2383. componentUsage->setName(component.queryProp("@name"));
  2384. componentUsage->setType(component.queryProp("@type"));
  2385. IArrayOf<IEspMachineUsage> machineUsages;
  2386. Owned<IPropertyTreeIterator> machines= component.getElements("Machine");
  2387. ForEach(*machines)
  2388. {
  2389. IPropertyTree& machine = machines->query();
  2390. const char* netAddress = machine.queryProp("@netAddress");
  2391. Owned<IEspMachineUsage> machineUsage = createMachineUsage();
  2392. machineUsage->setName(machine.queryProp("@name"));
  2393. machineUsage->setNetAddress(netAddress);
  2394. VStringBuffer xpath("Machine[@netAddress='%s']", netAddress);
  2395. IPropertyTree* uniqueMachineReqTree = uniqueUsages->queryPropTree(xpath);
  2396. if (!uniqueMachineReqTree)
  2397. {
  2398. if (version < 1.17)
  2399. machineUsage->setDescription("No data returns.");
  2400. else
  2401. machineUsage->setException("No data returns.");
  2402. machineUsages.append(*machineUsage.getClear());
  2403. continue;
  2404. }
  2405. const char* error = uniqueMachineReqTree->queryProp("@error");
  2406. if (!isEmptyString(error))
  2407. {
  2408. if (version < 1.17)
  2409. machineUsage->setDescription(error);
  2410. else
  2411. machineUsage->setException(error);
  2412. machineUsages.append(*machineUsage.getClear());
  2413. continue;
  2414. }
  2415. IArrayOf<IEspDiskUsage> diskUsages;
  2416. Owned<IPropertyTreeIterator> folders = machine.getElements("Folder");
  2417. ForEach(*folders)
  2418. {
  2419. IPropertyTree& folder = folders->query();
  2420. const char* aDiskPath = folder.queryProp("@path");
  2421. Owned<IEspDiskUsage> diskUsage = createDiskUsage();
  2422. diskUsage->setName(folder.queryProp("@name"));
  2423. diskUsage->setPath(aDiskPath);
  2424. xpath.setf("Folder[@path='%s']", aDiskPath);
  2425. IPropertyTree* folderTree = uniqueMachineReqTree->queryPropTree(xpath);
  2426. if (!folderTree)
  2427. {
  2428. if (version < 1.17)
  2429. diskUsage->setDescription("No data returns.");
  2430. else
  2431. diskUsage->setException("No data returns.");
  2432. }
  2433. else
  2434. {
  2435. const char* error = folderTree->queryProp("@error");
  2436. if (!isEmptyString(error))
  2437. {
  2438. if (version < 1.17)
  2439. diskUsage->setDescription(error);
  2440. else
  2441. diskUsage->setException(error);
  2442. }
  2443. else
  2444. {
  2445. diskUsage->setAvailable(folderTree->getPropInt64("@available"));
  2446. diskUsage->setInUse(folderTree->getPropInt64("@used"));
  2447. diskUsage->setPercentAvailable(folderTree->getPropInt("@percentAvail"));
  2448. const char* pathUsed = folderTree->queryProp("@pathUsed");
  2449. if (!isEmptyString(pathUsed))
  2450. {
  2451. VStringBuffer desc("%s not found. Read disk usage from %s", aDiskPath, pathUsed);
  2452. diskUsage->setDescription(desc);
  2453. }
  2454. }
  2455. }
  2456. diskUsages.append(*diskUsage.getClear());
  2457. }
  2458. machineUsage->setDiskUsages(diskUsages);
  2459. machineUsages.append(*machineUsage.getClear());
  2460. }
  2461. componentUsage->setMachineUsages(machineUsages);
  2462. componentUsages.append(*componentUsage.getClear());
  2463. }
  2464. }
  2465. StringBuffer& Cws_machineEx::setUsageTimeStr(CUsageCache* usageCache, StringBuffer& timeStr)
  2466. {
  2467. if (usageCache)
  2468. usageCache->queryTimeCached(timeStr);
  2469. else
  2470. {
  2471. CDateTime timeNow;
  2472. timeNow.setNow();
  2473. timeNow.getString(timeStr, true);
  2474. }
  2475. return timeStr;
  2476. }
  2477. bool Cws_machineEx::onGetComponentUsage(IEspContext& context, IEspGetComponentUsageRequest& req,
  2478. IEspGetComponentUsageResponse& resp)
  2479. {
  2480. try
  2481. {
  2482. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2483. double version = context.getClientVersion();
  2484. StringBuffer timeStr;
  2485. IArrayOf<IEspComponentUsage> componentUsages;
  2486. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2487. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2488. Owned<IPropertyTree> usageReq = getComponentUsageReq(req, constEnv);
  2489. Owned<CUsageCache> usage;
  2490. Owned<const IPropertyTree> uniqueUsages;
  2491. if (req.getBypassCachedResult())
  2492. {
  2493. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2494. //Add unique machines from the usageReq to uniqueUsages.
  2495. setUniqueMachineUsageReq(usageReq, tmpUniqueUsages);
  2496. getMachineUsages(context, tmpUniqueUsages);
  2497. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2498. }
  2499. else
  2500. {
  2501. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2502. if (!usage)
  2503. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2504. ESPLOG(LogMax, "GetComponentUsage: found UsageCache.");
  2505. uniqueUsages.set(usage->queryUsages());
  2506. }
  2507. readComponentUsageResult(context, usageReq, uniqueUsages, componentUsages);
  2508. if (version >= 1.17)
  2509. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2510. resp.setComponentUsages(componentUsages);
  2511. }
  2512. catch(IException* e)
  2513. {
  2514. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2515. }
  2516. return true;
  2517. }
  2518. StringArray& Cws_machineEx::listTargetClusterNames(IConstEnvironment* constEnv, StringArray& targetClusters)
  2519. {
  2520. Owned<IStringIterator> targets = getTargetClusters(nullptr, nullptr);
  2521. ForEach(*targets)
  2522. {
  2523. SCMStringBuffer target;
  2524. targetClusters.append(targets->str(target).str());
  2525. }
  2526. return targetClusters;
  2527. }
  2528. IPropertyTree* Cws_machineEx::getTargetClusterUsageReq(IEspGetTargetClusterUsageRequest& req, IConstEnvironment* constEnv)
  2529. {
  2530. StringArray& targetClusters = req.getTargetClusters();
  2531. if (targetClusters.empty())
  2532. listTargetClusterNames(constEnv, targetClusters);
  2533. Owned<IPropertyTree> usageReq = createPTree("Req");
  2534. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2535. ForEachItemIn(i, targetClusters)
  2536. {
  2537. const char* targetClusterName = targetClusters.item(i);
  2538. if (isEmptyString(targetClusterName))
  2539. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Target Cluster specified.");
  2540. Owned<IConstWUClusterInfo> targetClusterInfo = getTargetClusterInfo(targetClusterName);
  2541. if (!targetClusterInfo)
  2542. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Could not find information about target cluster %s ", targetClusterName);
  2543. Owned<IPropertyTree> targetClusterTree = createPTree("TargetCluster");
  2544. targetClusterTree->addProp("@name", targetClusterName);
  2545. const StringArray& thors = targetClusterInfo->getThorProcesses();
  2546. ForEachItemIn(i, thors)
  2547. {
  2548. const char* thor = thors.item(i);
  2549. if (!isEmptyString(thor))
  2550. readThorUsageReq(thor, constEnv, targetClusterTree);
  2551. }
  2552. SCMStringBuffer roxie;
  2553. targetClusterInfo->getRoxieProcess(roxie);
  2554. if (roxie.length())
  2555. readRoxieUsageReq(roxie.str(), constEnv, targetClusterTree);
  2556. SCMStringBuffer eclAgent, eclServer, eclScheduler;
  2557. targetClusterInfo->getAgentName(eclAgent);
  2558. if (eclAgent.length())
  2559. readOtherComponentUsageReq(eclAgent.str(), eqEclAgent, constEnv, targetClusterTree);
  2560. targetClusterInfo->getECLServerName(eclServer);
  2561. if (eclServer.length())
  2562. readOtherComponentUsageReq(eclServer.str(), targetClusterInfo->isLegacyEclServer() ? eqEclServer : eqEclCCServer, constEnv, targetClusterTree);
  2563. targetClusterInfo->getECLSchedulerName(eclScheduler);
  2564. if (eclScheduler.length())
  2565. readOtherComponentUsageReq(eclScheduler.str(), eqEclScheduler, constEnv, targetClusterTree);
  2566. usageReq->addPropTree(targetClusterTree->queryName(), LINK(targetClusterTree));
  2567. }
  2568. return usageReq.getClear();
  2569. }
  2570. void Cws_machineEx::readTargetClusterUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2571. const IPropertyTree* uniqueUsages, IArrayOf<IEspTargetClusterUsage>& targetClusterUsages)
  2572. {
  2573. Owned<IPropertyTreeIterator> targetClusters= usageReq->getElements("TargetCluster");
  2574. ForEach(*targetClusters)
  2575. {
  2576. IPropertyTree& targetCluster = targetClusters->query();
  2577. Owned<IEspTargetClusterUsage> targetClusterUsage = createTargetClusterUsage();
  2578. targetClusterUsage->setName(targetCluster.queryProp("@name"));
  2579. IArrayOf<IEspComponentUsage> componentUsages;
  2580. readComponentUsageResult(context, &targetCluster, uniqueUsages, componentUsages);
  2581. targetClusterUsage->setComponentUsages(componentUsages);
  2582. targetClusterUsages.append(*targetClusterUsage.getClear());
  2583. }
  2584. }
  2585. bool Cws_machineEx::onGetTargetClusterUsage(IEspContext& context, IEspGetTargetClusterUsageRequest& req,
  2586. IEspGetTargetClusterUsageResponse& resp)
  2587. {
  2588. try
  2589. {
  2590. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2591. double version = context.getClientVersion();
  2592. StringBuffer timeStr;
  2593. IArrayOf<IEspTargetClusterUsage> targetClusterUsages;
  2594. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2595. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2596. Owned<IPropertyTree> usageReq = getTargetClusterUsageReq(req, constEnv);
  2597. Owned<CUsageCache> usage;
  2598. Owned<const IPropertyTree> uniqueUsages;
  2599. if (req.getBypassCachedResult())
  2600. {
  2601. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2602. Owned<IPropertyTreeIterator> targetClusterItr= usageReq->getElements("TargetCluster");
  2603. ForEach(*targetClusterItr)
  2604. {
  2605. IPropertyTree& targetCluster = targetClusterItr->query();
  2606. setUniqueMachineUsageReq(&targetCluster, tmpUniqueUsages);
  2607. }
  2608. getMachineUsages(context, tmpUniqueUsages);
  2609. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2610. }
  2611. else
  2612. {
  2613. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2614. if (!usage)
  2615. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2616. ESPLOG(LogMax, "GetTargetClusterUsage: found UsageCache.");
  2617. uniqueUsages.set(usage->queryUsages());
  2618. }
  2619. readTargetClusterUsageResult(context, usageReq, uniqueUsages, targetClusterUsages);
  2620. if (version >= 1.17)
  2621. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2622. resp.setTargetClusterUsages(targetClusterUsages);
  2623. }
  2624. catch(IException* e)
  2625. {
  2626. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2627. }
  2628. return true;
  2629. }
  2630. bool Cws_machineEx::getEclAgentNameFromNodeGroupName(const char* nodeGroupName, StringBuffer& agentName)
  2631. {
  2632. //Node group name for an eclagent should be: 'hthor__' + ECLAgentName[ + '_' + a number]
  2633. if ((strlen(nodeGroupName) <= 7) || strnicmp(nodeGroupName, "hthor__", 7))
  2634. return false;
  2635. agentName.set(nodeGroupName + 7);
  2636. const char* ptr = strrchr(agentName.str(), '_');
  2637. if (isEmptyString(ptr) || isEmptyString(++ptr))
  2638. return true;
  2639. const char* ptrSuffix = ptr - 1;
  2640. do
  2641. {
  2642. if (!isdigit(ptr[0]))
  2643. return true;
  2644. ptr++;
  2645. } while(!isEmptyString(ptr));
  2646. agentName.setLength(agentName.length() - (ptr - ptrSuffix));
  2647. return true;
  2648. }
  2649. void Cws_machineEx::getThorClusterNamesByGroupName(IPropertyTree* envRoot, const char* group, StringArray& thorClusterNames)
  2650. {
  2651. Owned<IPropertyTreeIterator> thorClusters= envRoot->getElements("Software/ThorCluster");
  2652. ForEach(*thorClusters)
  2653. {
  2654. IPropertyTree& thorCluster = thorClusters->query();
  2655. const char *nodeGroupName = thorCluster.queryProp("@nodeGroup");
  2656. if (!isEmptyString(nodeGroupName) && !strieq(nodeGroupName, group))
  2657. continue;
  2658. if (!isEmptyString(nodeGroupName))
  2659. thorClusterNames.append(nodeGroupName);
  2660. else
  2661. {
  2662. const char *name = thorCluster.queryProp("@name");
  2663. if (strieq(name, group))
  2664. thorClusterNames.append(name);
  2665. }
  2666. }
  2667. }
  2668. StringArray& Cws_machineEx::listThorHThorNodeGroups(IConstEnvironment* constEnv, StringArray& nodeGroups)
  2669. {
  2670. BoolHash uniqueThorClusterGroupNames;
  2671. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2672. Owned<IPropertyTreeIterator> it =envRoot->getElements("Software/ThorCluster");
  2673. ForEach(*it)
  2674. {
  2675. IPropertyTree& cluster = it->query();
  2676. StringBuffer thorClusterGroupName;
  2677. getClusterGroupName(cluster, thorClusterGroupName);
  2678. if (!thorClusterGroupName.length())
  2679. continue;
  2680. bool* found = uniqueThorClusterGroupNames.getValue(thorClusterGroupName);
  2681. if (found && *found)
  2682. continue;
  2683. nodeGroups.append(thorClusterGroupName);
  2684. uniqueThorClusterGroupNames.setValue(thorClusterGroupName, true);
  2685. }
  2686. it.setown(envRoot->getElements("Software/EclAgentProcess"));
  2687. ForEach(*it)
  2688. {
  2689. IPropertyTree &cluster = it->query();
  2690. const char* name = cluster.queryProp("@name");
  2691. if (!name||!*name)
  2692. continue;
  2693. unsigned ins = 0;
  2694. Owned<IPropertyTreeIterator> insts = cluster.getElements("Instance");
  2695. ForEach(*insts)
  2696. {
  2697. ins++;
  2698. StringBuffer gname("hthor__");
  2699. gname.append(name);
  2700. if (ins>1)
  2701. gname.append('_').append(ins);
  2702. nodeGroups.append(gname);
  2703. }
  2704. }
  2705. return nodeGroups;
  2706. }
  2707. IPropertyTree* Cws_machineEx::getNodeGroupUsageReq(IEspGetNodeGroupUsageRequest& req, IConstEnvironment* constEnv)
  2708. {
  2709. StringArray& nodeGroups = req.getNodeGroups();
  2710. if (nodeGroups.empty())
  2711. listThorHThorNodeGroups(constEnv, nodeGroups);
  2712. if (nodeGroups.empty())
  2713. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No node group found.");
  2714. Owned<IPropertyTree> usageReq = createPTree("Req");
  2715. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2716. ForEachItemIn(i, nodeGroups)
  2717. {
  2718. const char* nodeGroupName = nodeGroups.item(i);
  2719. if (isEmptyString(nodeGroupName))
  2720. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty node group specified.");
  2721. Owned<IPropertyTree> nodeGroupTree = createPTree("NodeGroup");
  2722. nodeGroupTree->addProp("@name", nodeGroupName);
  2723. StringBuffer agentName;
  2724. if (getEclAgentNameFromNodeGroupName(nodeGroupName, agentName))
  2725. readOtherComponentUsageReq(agentName.str(), eqEclAgent, constEnv, nodeGroupTree);
  2726. else
  2727. {
  2728. StringArray thorNames;
  2729. getThorClusterNamesByGroupName(envRoot, nodeGroupName, thorNames);
  2730. if (thorNames.length() == 0)
  2731. throw MakeStringException(ECLWATCH_INVALID_INPUT, "No thor/hthor can be found for node group name %s.", nodeGroupName);
  2732. ForEachItemIn(ii, thorNames)
  2733. readThorUsageReq(thorNames.item(ii), constEnv, nodeGroupTree);
  2734. }
  2735. usageReq->addPropTree(nodeGroupTree->queryName(), LINK(nodeGroupTree));
  2736. }
  2737. return usageReq.getClear();
  2738. }
  2739. void Cws_machineEx::readNodeGroupUsageResult(IEspContext& context, IPropertyTree* usageReq,
  2740. const IPropertyTree* uniqueUsages, IArrayOf<IEspNodeGroupUsage>& nodeGroupUsages)
  2741. {
  2742. Owned<IPropertyTreeIterator> nodeGroups= usageReq->getElements("NodeGroup");
  2743. ForEach(*nodeGroups)
  2744. {
  2745. IPropertyTree& nodeGroup = nodeGroups->query();
  2746. Owned<IEspNodeGroupUsage> nodeGroupUsage = createNodeGroupUsage();
  2747. nodeGroupUsage->setName(nodeGroup.queryProp("@name"));
  2748. IArrayOf<IEspComponentUsage> componentUsages;
  2749. readComponentUsageResult(context, &nodeGroup, uniqueUsages, componentUsages);
  2750. nodeGroupUsage->setComponentUsages(componentUsages);
  2751. nodeGroupUsages.append(*nodeGroupUsage.getClear());
  2752. }
  2753. }
  2754. bool Cws_machineEx::onGetNodeGroupUsage(IEspContext& context, IEspGetNodeGroupUsageRequest& req,
  2755. IEspGetNodeGroupUsageResponse& resp)
  2756. {
  2757. try
  2758. {
  2759. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Machine Information. Permission denied.");
  2760. double version = context.getClientVersion();
  2761. StringBuffer timeStr;
  2762. IArrayOf<IEspNodeGroupUsage> nodeGroupUsages;
  2763. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2764. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2765. Owned<IPropertyTree> usageReq = getNodeGroupUsageReq(req, constEnv);
  2766. Owned<CUsageCache> usage;
  2767. Owned<const IPropertyTree> uniqueUsages;
  2768. if (req.getBypassCachedResult())
  2769. {
  2770. Owned<IPropertyTree> tmpUniqueUsages = createPTree("Usage");
  2771. Owned<IPropertyTreeIterator> nodeGroupItr= usageReq->getElements("NodeGroup");
  2772. ForEach(*nodeGroupItr)
  2773. {
  2774. IPropertyTree& nodeGroup = nodeGroupItr->query();
  2775. setUniqueMachineUsageReq(&nodeGroup, tmpUniqueUsages);
  2776. }
  2777. getMachineUsages(context, tmpUniqueUsages);
  2778. uniqueUsages.setown(tmpUniqueUsages.getClear());
  2779. }
  2780. else
  2781. {
  2782. usage.setown((CUsageCache*) usageCacheReader->getCachedInfo());
  2783. if (!usage)
  2784. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get usage. Please try later.");
  2785. ESPLOG(LogMax, "GetNodeGroupUsage: found UsageCache.");
  2786. uniqueUsages.set(usage->queryUsages());
  2787. }
  2788. readNodeGroupUsageResult(context, usageReq, uniqueUsages, nodeGroupUsages);
  2789. if (version >= 1.17)
  2790. resp.setUsageTime(setUsageTimeStr(usage, timeStr));
  2791. resp.setNodeGroupUsages(nodeGroupUsages);
  2792. }
  2793. catch(IException* e)
  2794. {
  2795. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2796. }
  2797. return true;
  2798. }
  2799. bool Cws_machineEx::onGetComponentStatus(IEspContext &context, IEspGetComponentStatusRequest &req, IEspGetComponentStatusResponse &resp)
  2800. {
  2801. try
  2802. {
  2803. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Get Component Status. Permission denied.");
  2804. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  2805. Owned<IESPComponentStatusInfo> status = factory->getComponentStatus();
  2806. if (!status) //Should never happen
  2807. return false;
  2808. int statusID = status->getComponentStatusID();
  2809. if (statusID < 0)
  2810. {
  2811. resp.setStatus("Not reported");
  2812. }
  2813. else
  2814. {
  2815. resp.setComponentType(status->getComponentType());
  2816. resp.setEndPoint(status->getEndPoint());
  2817. resp.setReporter(status->getReporter());
  2818. resp.setComponentStatus(status->getComponentStatus());
  2819. resp.setTimeReportedStr(status->getTimeReportedStr());
  2820. IConstStatusReport* componentStatus = status->getStatusReport();
  2821. if (componentStatus)
  2822. resp.setStatusReport(*componentStatus);
  2823. resp.setComponentStatusList(status->getComponentStatusList());
  2824. }
  2825. resp.setComponentStatusID(statusID);
  2826. resp.setStatusCode(0);
  2827. }
  2828. catch(IException* e)
  2829. {
  2830. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2831. }
  2832. return true;
  2833. }
  2834. bool Cws_machineEx::onUpdateComponentStatus(IEspContext &context, IEspUpdateComponentStatusRequest &req, IEspUpdateComponentStatusResponse &resp)
  2835. {
  2836. try
  2837. {
  2838. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Write, ECLWATCH_MACHINE_INFO_ACCESS_DENIED, "Failed to Update Component Status. Permission denied.");
  2839. const char* reporter = req.getReporter();
  2840. if (!reporter || !*reporter)
  2841. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Report not specified.");
  2842. Owned<IComponentStatusFactory> factory = getComponentStatusFactory();
  2843. factory->updateComponentStatus(reporter, req.getComponentStatusList());
  2844. resp.setStatusCode(0);
  2845. }
  2846. catch(IException* e)
  2847. {
  2848. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2849. }
  2850. return true;
  2851. }
  2852. CInfoCache* CUsageCacheReader::read()
  2853. {
  2854. Owned<IPropertyTree> uniqueUsages = getUsageReqAllMachines();
  2855. //Send usage command to each machine
  2856. Owned<IEspContext> espContext = createEspContext();
  2857. servicePtr->getMachineUsages(*espContext, uniqueUsages);
  2858. Owned<CUsageCache> usageCache = new CUsageCache();
  2859. usageCache->setUsages(uniqueUsages.getClear());
  2860. return usageCache.getClear();
  2861. }
  2862. IPropertyTree* CUsageCacheReader::getUsageReqAllMachines()
  2863. {
  2864. //Collect network addresses and HPCC folders for all HPCC machines.
  2865. Owned<IEnvironmentFactory> envFactory = getEnvironmentFactory(true);
  2866. Owned<IConstEnvironment> constEnv = envFactory->openEnvironment();
  2867. IArrayOf<IConstComponent> componentList;
  2868. servicePtr->listComponentsForCheckingUsage(constEnv, componentList);
  2869. //Create a PTree which will be used to store the usages of all HPCC machines.
  2870. Owned<IPropertyTree> uniqueUsages = createPTree("Usage");
  2871. //Store the network addresses and HPCC folders into the PTree.
  2872. //Their usages may be added by calling servicePtr->getMachineUsages().
  2873. ForEachItemIn(i, componentList)
  2874. {
  2875. IConstComponent& component = componentList.item(i);
  2876. const char* type = component.getType();
  2877. if (isEmptyString(type))
  2878. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component Type");
  2879. if (strieq(type, eqThorCluster))
  2880. addClusterUsageReq(constEnv, component.getName(), true, uniqueUsages);
  2881. else if (strieq(type, eqRoxieCluster))
  2882. addClusterUsageReq(constEnv, component.getName(), false, uniqueUsages);
  2883. else if (strieq(type, eqDropZone))
  2884. addDropZoneUsageReq(constEnv, component.getName(), uniqueUsages);
  2885. else
  2886. addOtherComponentUsageReq(constEnv, component.getName(), type, uniqueUsages);
  2887. }
  2888. return uniqueUsages.getClear();
  2889. }
  2890. void CUsageCacheReader::addClusterUsageReq(IConstEnvironment* constEnv, const char* name, bool thorCluster, IPropertyTree* usageReq)
  2891. {
  2892. if (isEmptyString(name))
  2893. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty cluster name");
  2894. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  2895. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  2896. Owned<IPropertyTree> logFolderReq = servicePtr->createDiskUsageReq(envDirectories, "log", thorCluster ? "thor" : "roxie", name);
  2897. Owned<IPropertyTree> dataFolderReq = servicePtr->createDiskUsageReq(envDirectories, "data", thorCluster ? "thor" : "roxie", name);
  2898. Owned<IPropertyTree> repFolderReq;
  2899. if (thorCluster)
  2900. repFolderReq.setown(servicePtr->createDiskUsageReq(envDirectories, "mirror", "thor", name));
  2901. StringBuffer xpath;
  2902. if (thorCluster)
  2903. xpath.setf("Software/ThorCluster[@name='%s']/ThorSlaveProcess", name);
  2904. else
  2905. xpath.setf("Software/RoxieCluster[@name='%s']/RoxieServerProcess", name);
  2906. Owned<IPropertyTreeIterator> processes= envRoot->getElements(xpath);
  2907. ForEach(*processes)
  2908. {
  2909. IPropertyTree& process = processes->query();
  2910. const char* computer = process.queryProp("@computer");
  2911. if (isEmptyString(computer))
  2912. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  2913. checkAndAddMachineUsageReq(constEnv, computer, logFolderReq, dataFolderReq, repFolderReq, usageReq);
  2914. }
  2915. if (!thorCluster)
  2916. return;
  2917. //Read ThorMasterProcess in case it is on a different machine
  2918. xpath.setf("Software/ThorCluster[@name='%s']/ThorMasterProcess/@computer", name);
  2919. const char* computer = envRoot->queryProp(xpath);
  2920. if (isEmptyString(computer))
  2921. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get %s", xpath.str());
  2922. checkAndAddMachineUsageReq(constEnv, computer, logFolderReq, dataFolderReq, repFolderReq, usageReq);
  2923. }
  2924. void CUsageCacheReader::checkAndAddMachineUsageReq(IConstEnvironment* constEnv, const char* computer, IPropertyTree* logFolderReq,
  2925. IPropertyTree* dataFolderReq, IPropertyTree* repFolderReq, IPropertyTree* usageReq)
  2926. {
  2927. Owned<IPropertyTree> machineReq = servicePtr->createMachineUsageReq(constEnv, computer);
  2928. VStringBuffer xpath("Machine[@netAddress='%s']", machineReq->queryProp("@netAddress"));
  2929. IPropertyTree* foundMachineReqTree = usageReq->queryPropTree(xpath);
  2930. if (!foundMachineReqTree)
  2931. {
  2932. //Not sure we need those folders here. Add them just in case.
  2933. if (logFolderReq)
  2934. machineReq->addPropTree(logFolderReq->queryName(), LINK(logFolderReq));
  2935. if (dataFolderReq)
  2936. machineReq->addPropTree(dataFolderReq->queryName(), LINK(dataFolderReq));
  2937. if (repFolderReq)
  2938. machineReq->addPropTree(repFolderReq->queryName(), LINK(repFolderReq));
  2939. usageReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2940. return;
  2941. }
  2942. //Add unique disk folders
  2943. checkAndAddFolderReq(logFolderReq, foundMachineReqTree);
  2944. checkAndAddFolderReq(dataFolderReq, foundMachineReqTree);
  2945. checkAndAddFolderReq(repFolderReq, foundMachineReqTree);
  2946. }
  2947. void CUsageCacheReader::checkAndAddFolderReq(IPropertyTree* folderReq, IPropertyTree* machineReqTree)
  2948. {
  2949. if (!folderReq)
  2950. return;
  2951. //Add unique disk folders
  2952. VStringBuffer xpath("Folder[@path='%s']", folderReq->queryProp("@path"));
  2953. if (!machineReqTree->queryPropTree(xpath))
  2954. machineReqTree->addPropTree(folderReq->queryName(), LINK(folderReq));
  2955. }
  2956. void CUsageCacheReader::addDropZoneUsageReq(IConstEnvironment* constEnv, const char* name, IPropertyTree* usageReq)
  2957. {
  2958. if (isEmptyString(name))
  2959. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty DropZone name");
  2960. Owned<IConstDropZoneInfo> envDropZone = constEnv->getDropZone(name);
  2961. if (!envDropZone || !envDropZone->isECLWatchVisible())
  2962. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Dropzone %s not found", name);
  2963. SCMStringBuffer directory;
  2964. envDropZone->getDirectory(directory);
  2965. if (directory.length() == 0)
  2966. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get directory for DropZone %s", name);
  2967. Owned<IPropertyTree> dataFolder = createPTree("Folder");
  2968. dataFolder->addProp("@name", "data");
  2969. dataFolder->addProp("@path", directory.str());
  2970. SCMStringBuffer computerName;
  2971. envDropZone->getComputerName(computerName);
  2972. if (computerName.length() == 0)
  2973. {
  2974. OS_TYPE os = (getPathSepChar(directory.str()) == '/') ? OS_LINUX : OS_WINDOWS;
  2975. Owned<IConstDropZoneServerInfoIterator> servers = envDropZone->getServers();
  2976. ForEach(*servers)
  2977. {
  2978. IConstDropZoneServerInfo& server = servers->query();
  2979. StringBuffer serverNetAddress;
  2980. server.getServer(serverNetAddress.clear());
  2981. VStringBuffer xpath("Machine[@netAddress='%s']", serverNetAddress.str());
  2982. IPropertyTree* foundMachineReqTree = usageReq->queryPropTree(xpath);
  2983. if (foundMachineReqTree)
  2984. {
  2985. checkAndAddFolderReq(dataFolder, foundMachineReqTree);
  2986. continue;
  2987. }
  2988. Owned<IPropertyTree> machineReq = createPTree("Machine");
  2989. machineReq->addProp("@name", serverNetAddress.str());
  2990. machineReq->addProp("@netAddress", serverNetAddress.str());
  2991. machineReq->addPropInt("@OS", os);
  2992. machineReq->addPropTree(dataFolder->queryName(), LINK(dataFolder));
  2993. usageReq->addPropTree(machineReq->queryName(), LINK(machineReq));
  2994. }
  2995. }
  2996. else
  2997. { //legacy dropzone settings
  2998. checkAndAddMachineUsageReq(constEnv, computerName.str(), nullptr, dataFolder, nullptr, usageReq);
  2999. }
  3000. }
  3001. void CUsageCacheReader::addOtherComponentUsageReq(IConstEnvironment* constEnv, const char* name, const char* type, IPropertyTree* usageReq)
  3002. {
  3003. if (isEmptyString(name))
  3004. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Empty Component name");
  3005. const char* componentType = findComponentTypeFromProcessType(type);
  3006. if (!componentType)
  3007. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Component usage function is not supported for %s", type);
  3008. //Find disk folders for log, data, etc.
  3009. Owned<IPropertyTree> envRoot = &constEnv->getPTree();
  3010. IPropertyTree* envDirectories = envRoot->queryPropTree("Software/Directories");
  3011. Owned<IPropertyTree> dataFolder = servicePtr->createDiskUsageReq(envDirectories, "data", componentType, name);
  3012. Owned<IPropertyTree> logFolder = servicePtr->createDiskUsageReq(envDirectories, "log", componentType, name);
  3013. Owned<IPropertyTree> repFolder;
  3014. if (strieq(type, eqDali))
  3015. repFolder.setown(servicePtr->createDiskUsageReq(envDirectories, "mirror", "dali", name));
  3016. VStringBuffer xpath("Software/%s[@name='%s']/Instance", type, name);
  3017. Owned<IPropertyTreeIterator> it = envRoot->getElements(xpath);
  3018. ForEach(*it)
  3019. {
  3020. IPropertyTree& instance = it->query();
  3021. const char* computer = instance.queryProp("@computer");
  3022. if (isEmptyString(computer))
  3023. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Failed to get @computer for %s", xpath.str());
  3024. checkAndAddMachineUsageReq(constEnv, computer, logFolder, dataFolder, repFolder, usageReq);
  3025. }
  3026. }