ws_smcService.cpp 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664
  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. #pragma warning (disable : 4786)
  14. #include "build-config.h"
  15. #ifdef _USE_OPENLDAP
  16. #include "ldapsecurity.ipp"
  17. #endif
  18. #include "ws_smcService.hpp"
  19. #include "wshelpers.hpp"
  20. #include "dasds.hpp"
  21. #include "daqueue.hpp"
  22. #include "WUWrapper.hpp"
  23. #include "dfuwu.hpp"
  24. #include "exception_util.hpp"
  25. #include "roxiecontrol.hpp"
  26. #include "workunit.hpp"
  27. #define STATUS_SERVER_THOR "ThorMaster"
  28. #define STATUS_SERVER_HTHOR "HThorServer"
  29. #define STATUS_SERVER_ROXIE "RoxieServer"
  30. #define STATUS_SERVER_DFUSERVER "DFUserver"
  31. #define STATUS_SERVER_ECLSERVER "ECLserver"
  32. #define STATUS_SERVER_ECLCCSERVER "ECLCCserver"
  33. #define STATUS_SERVER_ECLAGENT "ECLagent"
  34. #define CLUSTER_TYPE_THOR "Thor"
  35. #define CLUSTER_TYPE_HTHOR "HThor"
  36. #define CLUSTER_TYPE_ROXIE "Roxie"
  37. static const char* FEATURE_URL = "SmcAccess";
  38. const char* THORQUEUE_FEATURE = "ThorQueueAccess";
  39. static const char* ROXIE_CONTROL_URL = "RoxieControlAccess";
  40. static const char* OWN_WU_ACCESS = "OwnWorkunitsAccess";
  41. static const char* OTHERS_WU_ACCESS = "OthersWorkunitsAccess";
  42. static const char* SMC_ACCESS_DENIED = "Access Denied";
  43. static const char* QUEUE_ACCESS_DENIED = "Failed to access the queue functions. Permission denied.";
  44. const char* PERMISSIONS_FILENAME = "espsmc_permissions.xml";
  45. void AccessSuccess(IEspContext& context, char const * msg,...) __attribute__((format(printf, 2, 3)));
  46. void AccessSuccess(IEspContext& context, char const * msg,...)
  47. {
  48. StringBuffer buf;
  49. buf.appendf("User %s: ",context.queryUserId());
  50. va_list args;
  51. va_start(args, msg);
  52. buf.valist_appendf(msg, args);
  53. va_end(args);
  54. AUDIT(AUDIT_TYPE_ACCESS_SUCCESS,buf.str());
  55. }
  56. void AccessFailure(IEspContext& context, char const * msg,...) __attribute__((format(printf, 2, 3)));
  57. void AccessFailure(IEspContext& context, char const * msg,...)
  58. {
  59. StringBuffer buf;
  60. buf.appendf("User %s: ",context.queryUserId());
  61. va_list args;
  62. va_start(args, msg);
  63. buf.valist_appendf(msg, args);
  64. va_end(args);
  65. AUDIT(AUDIT_TYPE_ACCESS_FAILURE,buf.str());
  66. }
  67. struct QueueLock
  68. {
  69. QueueLock(IJobQueue* q): queue(q) { queue->lock(); }
  70. ~QueueLock()
  71. {
  72. queue->unlock();
  73. }
  74. Linked<IJobQueue> queue;
  75. };
  76. static int sortTargetClustersByNameDescending(IInterface * const *L, IInterface * const *R)
  77. {
  78. IEspTargetCluster *left = (IEspTargetCluster *) *L;
  79. IEspTargetCluster *right = (IEspTargetCluster *) *R;
  80. return strcmp(right->getClusterName(), left->getClusterName());
  81. }
  82. static int sortTargetClustersByNameAscending(IInterface * const *L, IInterface * const *R)
  83. {
  84. IEspTargetCluster *left = (IEspTargetCluster *) *L;
  85. IEspTargetCluster *right = (IEspTargetCluster *) *R;
  86. return strcmp(left->getClusterName(), right->getClusterName());
  87. }
  88. static int sortTargetClustersBySizeDescending(IInterface * const *L, IInterface * const *R)
  89. {
  90. IEspTargetCluster *left = (IEspTargetCluster *) *L;
  91. IEspTargetCluster *right = (IEspTargetCluster *) *R;
  92. return right->getClusterSize() - left->getClusterSize();
  93. }
  94. static int sortTargetClustersBySizeAscending(IInterface * const *L, IInterface * const *R)
  95. {
  96. IEspTargetCluster *left = (IEspTargetCluster *) *L;
  97. IEspTargetCluster *right = (IEspTargetCluster *) *R;
  98. return left->getClusterSize() - right->getClusterSize();
  99. }
  100. void CWsSMCEx::init(IPropertyTree *cfg, const char *process, const char *service)
  101. {
  102. if (!daliClientActive())
  103. {
  104. OERRLOG("No Dali Connection Active.");
  105. throw MakeStringException(-1, "No Dali Connection Active. Please Specify a Dali to connect to in you configuration file");
  106. }
  107. m_BannerAction = 0;
  108. m_EnableChatURL = false;
  109. m_BannerSize = "4";
  110. m_BannerColor = "red";
  111. m_BannerScroll = "2";
  112. StringBuffer xpath;
  113. xpath.appendf("Software/EspProcess[@name='%s']/@portalurl", process);
  114. const char* portalURL = cfg->queryProp(xpath.str());
  115. if (portalURL && *portalURL)
  116. m_PortalURL.append(portalURL);
  117. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ActivityInfoCacheSeconds", process, service);
  118. unsigned activityInfoCacheSeconds = cfg->getPropInt(xpath.str(), DEFAULTACTIVITYINFOCACHEFORCEBUILDSECOND);
  119. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/LogDaliConnection", process, service);
  120. if (cfg->getPropBool(xpath.str()))
  121. querySDS().setConfigOpt("Client/@LogConnection", "true");
  122. xpath.setf("Software/EspProcess[@name=\"%s\"]/EspService[@name=\"%s\"]/ActivityInfoCacheAutoRebuildSeconds", process, service);
  123. unsigned activityInfoCacheAutoRebuildSeconds = cfg->getPropInt(xpath.str(), DEFAULTACTIVITYINFOCACHEAUTOREBUILDSECOND);
  124. activityInfoReader.setown(new CActivityInfoReader(activityInfoCacheAutoRebuildSeconds, activityInfoCacheSeconds));
  125. }
  126. struct CActiveWorkunitWrapper: public CActiveWorkunit
  127. {
  128. CActiveWorkunitWrapper(IEspContext &context, const char* wuid,const char* location = NULL,unsigned index=0): CActiveWorkunit("","")
  129. {
  130. CWUWrapper wu(wuid, context);
  131. setActiveWorkunit(wu, wuid, location, index, context.getClientVersion(), false);
  132. }
  133. CActiveWorkunitWrapper(const char* wuid, const char* location = NULL, unsigned index=0): CActiveWorkunit("","")
  134. {
  135. CWUWrapper wu(wuid);
  136. setActiveWorkunit(wu, wuid, location, index, 0.0, true);
  137. }
  138. CActiveWorkunitWrapper(const char* wuid,const char* owner, const char* jobname, const char* state, const char* priority): CActiveWorkunit("","")
  139. {
  140. setWuid(wuid);
  141. setState(state);
  142. setOwner(owner);
  143. setJobname(jobname);
  144. setPriority(priority);
  145. }
  146. void setActiveWorkunit(CWUWrapper& wu, const char* wuid, const char* location, unsigned index, double version, bool notCheckVersion)
  147. {
  148. SCMStringBuffer stateEx;
  149. setWuid(wuid);
  150. const char *state = wu->queryStateDesc();
  151. setStateID(wu->getState());
  152. if (wu->getState() == WUStateBlocked)
  153. {
  154. wu->getStateEx(stateEx);
  155. if (notCheckVersion || (version > 1.00))
  156. setExtra(stateEx.str());
  157. }
  158. buildAndSetState(state, stateEx.str(), location, index);
  159. if ((notCheckVersion || (version > 1.09)) && (wu->getState() == WUStateFailed))
  160. setWarning("The job will ultimately not complete. Please check ECLAgent.");
  161. setOwner(wu->queryUser());
  162. setJobname(wu->queryJobName());
  163. setPriorityStr(wu->getPriority());
  164. if ((notCheckVersion || (version > 1.08)) && wu->isPausing())
  165. {
  166. setIsPausing(true);
  167. }
  168. if (notCheckVersion || (version > 1.14))
  169. {
  170. setClusterName(wu->queryClusterName());
  171. }
  172. }
  173. void buildAndSetState(const char* state, const char* stateEx, const char* location, unsigned index)
  174. {
  175. if (!state || !*state)
  176. return;
  177. StringBuffer stateStr;
  178. if(index && location && *location)
  179. stateStr.setf("queued(%d) [%s on %s]", index, state, location);
  180. else if(index)
  181. stateStr.setf("queued(%d) [%s]", index, state);
  182. else if(location && *location)
  183. stateStr.setf("%s [%s]", state, location);
  184. else
  185. stateStr.set(state);
  186. if (stateEx && *stateEx)
  187. stateStr.appendf(" %s", stateEx);
  188. setState(stateStr.str());
  189. }
  190. void setPriorityStr(unsigned priorityType)
  191. {
  192. switch(priorityType)
  193. {
  194. case PriorityClassHigh: setPriority("high"); break;
  195. default:
  196. case PriorityClassNormal: setPriority("normal"); break;
  197. case PriorityClassLow: setPriority("low"); break;
  198. }
  199. return;
  200. }
  201. };
  202. bool CActivityInfo::isCachedActivityInfoValid(unsigned timeOutSeconds)
  203. {
  204. CDateTime timeNow;
  205. timeNow.setNow();
  206. return timeNow.getSimple() <= timeCached.getSimple() + timeOutSeconds;;
  207. }
  208. void CActivityInfo::createActivityInfo(IEspContext& context)
  209. {
  210. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  211. Owned<IConstEnvironment> env = factory->openEnvironment();
  212. CConstWUClusterInfoArray clusters;
  213. Owned<IPropertyTree> envRoot= &env->getPTree();
  214. getEnvironmentClusterInfo(envRoot, clusters);
  215. try
  216. {
  217. jobQueueSnapshot.setown(createJQSnapshot());
  218. }
  219. catch(IException* e)
  220. {
  221. EXCLOG(e, "CActivityInfo::createActivityInfo");
  222. e->Release();
  223. }
  224. Owned<IRemoteConnection> connStatusServers = querySDS().connect("/Status/Servers",myProcessSession(),RTM_LOCK_READ,30000);
  225. if (!connStatusServers)
  226. throw MakeStringException(ECLWATCH_CANNOT_GET_STATUS_INFO, "Failed to get status server information.");
  227. IPropertyTree* serverStatusRoot = connStatusServers->queryRoot();
  228. readTargetClusterInfo(clusters, serverStatusRoot);
  229. readActiveWUsAndQueuedWUs(context, envRoot, serverStatusRoot);
  230. timeCached.setNow();
  231. }
  232. void CActivityInfo::readTargetClusterInfo(CConstWUClusterInfoArray& clusters, IPropertyTree* serverStatusRoot)
  233. {
  234. ForEachItemIn(c, clusters)
  235. {
  236. IConstWUClusterInfo &cluster = clusters.item(c);
  237. Owned<CWsSMCTargetCluster> targetCluster = new CWsSMCTargetCluster();
  238. readTargetClusterInfo(cluster, serverStatusRoot, targetCluster);
  239. if (cluster.getPlatform() == ThorLCRCluster)
  240. thorTargetClusters.append(*targetCluster.getClear());
  241. else if (cluster.getPlatform() == RoxieCluster)
  242. roxieTargetClusters.append(*targetCluster.getClear());
  243. else
  244. hthorTargetClusters.append(*targetCluster.getClear());
  245. }
  246. }
  247. void CActivityInfo::readTargetClusterInfo(IConstWUClusterInfo& cluster, IPropertyTree* serverStatusRoot, CWsSMCTargetCluster* targetCluster)
  248. {
  249. SCMStringBuffer clusterName;
  250. cluster.getName(clusterName);
  251. targetCluster->clusterName.set(clusterName.str());
  252. targetCluster->clusterType = cluster.getPlatform();
  253. targetCluster->clusterSize = cluster.getSize();
  254. cluster.getServerQueue(targetCluster->serverQueue.queueName);
  255. cluster.getAgentQueue(targetCluster->agentQueue.queueName);
  256. StringBuffer statusServerName;
  257. CWsSMCQueue* smcQueue = NULL;
  258. if (targetCluster->clusterType == ThorLCRCluster)
  259. {
  260. statusServerName.set(getStatusServerTypeName(WsSMCSSTThorLCRCluster));
  261. smcQueue = &targetCluster->clusterQueue;
  262. cluster.getThorQueue(smcQueue->queueName);
  263. }
  264. else if (targetCluster->clusterType == RoxieCluster)
  265. {
  266. statusServerName.set(getStatusServerTypeName(WsSMCSSTRoxieCluster));
  267. smcQueue = &targetCluster->agentQueue;
  268. }
  269. else
  270. {
  271. statusServerName.set(getStatusServerTypeName(WsSMCSSTHThorCluster));
  272. smcQueue = &targetCluster->agentQueue;
  273. }
  274. targetCluster->statusServerName.set(statusServerName.str());
  275. targetCluster->queueName.set(smcQueue->queueName.str());
  276. bool validQueue = readJobQueue(smcQueue->queueName.str(), targetCluster->queuedWUIDs, smcQueue->queueState, smcQueue->queueStateDetails);
  277. if (!validQueue)
  278. smcQueue->notFoundInJobQueues = true;
  279. if (validQueue && smcQueue->queueState.length())
  280. targetCluster->queueStatus.set(smcQueue->queueState.str());
  281. if (serverStatusRoot)
  282. {
  283. smcQueue->foundQueueInStatusServer = findQueueInStatusServer(serverStatusRoot, statusServerName.str(), targetCluster->queueName.get());
  284. if (!smcQueue->foundQueueInStatusServer)
  285. targetCluster->clusterStatusDetails.appendf("Cluster %s not listening for workunits; ", clusterName.str());
  286. }
  287. targetCluster->serverQueue.notFoundInJobQueues = !readJobQueue(targetCluster->serverQueue.queueName.str(), targetCluster->wuidsOnServerQueue, targetCluster->serverQueue.queueState, targetCluster->serverQueue.queueStateDetails);
  288. }
  289. bool CActivityInfo::readJobQueue(const char* queueName, StringArray& wuids, StringBuffer& state, StringBuffer& stateDetails)
  290. {
  291. if (!queueName || !*queueName)
  292. {
  293. state.set("Unknown");
  294. stateDetails.set("Empty queue name");
  295. return false;
  296. }
  297. if (!jobQueueSnapshot)
  298. {
  299. state.set("Unknown");
  300. stateDetails.set("jobQueueSnapshot not found");
  301. IWARNLOG("CActivityInfo::readJobQueue: jobQueueSnapshot not found.");
  302. return false;
  303. }
  304. Owned<IJobQueueConst> jobQueue;
  305. try
  306. {
  307. jobQueue.setown(jobQueueSnapshot->getJobQueue(queueName));
  308. if (!jobQueue)
  309. {
  310. IWARNLOG("CActivityInfo::readJobQueue: failed to get info for job queue %s", queueName);
  311. return false;
  312. }
  313. }
  314. catch(IException* e)
  315. {
  316. state.set("Unknown");
  317. e->errorMessage(stateDetails);
  318. e->Release();
  319. return false;
  320. }
  321. CJobQueueContents queuedJobs;
  322. jobQueue->copyItemsAndState(queuedJobs, state, stateDetails);
  323. Owned<IJobQueueIterator> iter = queuedJobs.getIterator();
  324. ForEach(*iter)
  325. {
  326. const char* wuid = iter->query().queryWUID();
  327. if (wuid && *wuid)
  328. wuids.append(wuid);
  329. }
  330. return true;
  331. }
  332. const char *CActivityInfo::getStatusServerTypeName(WsSMCStatusServerType type)
  333. {
  334. return (type < WsSMCSSTterm) ? WsSMCStatusServerTypeNames[type] : NULL;
  335. }
  336. bool CActivityInfo::findQueueInStatusServer(IPropertyTree* serverStatusRoot, const char* serverName, const char* queueName)
  337. {
  338. VStringBuffer path("Server[@name=\"%s\"]", serverName);
  339. Owned<IPropertyTreeIterator> it(serverStatusRoot->getElements(path.str()));
  340. ForEach(*it)
  341. {
  342. IPropertyTree& serverStatusNode = it->query();
  343. const char* queue = serverStatusNode.queryProp("@queue");
  344. if (!queue || !*queue)
  345. continue;
  346. StringArray qlist;
  347. qlist.appendListUniq(queue, ",");
  348. ForEachItemIn(q, qlist)
  349. {
  350. if (strieq(qlist.item(q), queueName))
  351. return true;
  352. }
  353. }
  354. return false;
  355. }
  356. void CActivityInfo::readActiveWUsAndQueuedWUs(IEspContext& context, IPropertyTree* envRoot, IPropertyTree* serverStatusRoot)
  357. {
  358. readRunningWUsOnStatusServer(context, serverStatusRoot, WsSMCSSTThorLCRCluster);
  359. readWUsInTargetClusterJobQueues(context, thorTargetClusters);
  360. readRunningWUsOnStatusServer(context, serverStatusRoot, WsSMCSSTRoxieCluster);
  361. readWUsInTargetClusterJobQueues(context, roxieTargetClusters);
  362. readRunningWUsOnStatusServer(context, serverStatusRoot, WsSMCSSTHThorCluster);
  363. readWUsInTargetClusterJobQueues(context, hthorTargetClusters);
  364. readRunningWUsOnStatusServer(context, serverStatusRoot, WsSMCSSTECLagent);
  365. readRunningWUsAndJobQueueforOtherStatusServers(context, serverStatusRoot);
  366. //TODO: add queued WUs for ECLCCServer/ECLServer here. Right now, they are under target clusters.
  367. getDFUServersAndWUs(context, envRoot, serverStatusRoot);
  368. getDFURecoveryJobs();
  369. }
  370. void CActivityInfo::readRunningWUsOnStatusServer(IEspContext& context, IPropertyTree* serverStatusRoot, WsSMCStatusServerType statusServerType)
  371. {
  372. const char* serverName = getStatusServerTypeName(statusServerType);
  373. if (!serverName || !*serverName)
  374. return;
  375. bool isECLAgent = (statusServerType == WsSMCSSTECLagent);
  376. VStringBuffer path("Server[@name=\"%s\"]", serverName);
  377. Owned<IPropertyTreeIterator> itrStatusServer(serverStatusRoot->getElements(path.str()));
  378. ForEach(*itrStatusServer)
  379. {
  380. IPropertyTree& serverStatusNode = itrStatusServer->query();
  381. StringBuffer serverInstance;
  382. if (statusServerType == WsSMCSSTThorLCRCluster)
  383. serverStatusNode.getProp("@thorname", serverInstance);
  384. else if (statusServerType == WsSMCSSTRoxieCluster)
  385. serverStatusNode.getProp("@cluster", serverInstance);
  386. else
  387. serverInstance.appendf("%s on %s", serverName, serverStatusNode.queryProp("@node"));
  388. Owned<IPropertyTreeIterator> wuids(serverStatusNode.getElements("WorkUnit"));
  389. ForEach(*wuids)
  390. {
  391. const char* wuid=wuids->query().queryProp(NULL);
  392. if (!wuid || !*wuid || checkSetUniqueECLWUID(wuid))
  393. continue;
  394. CWsSMCTargetCluster* targetCluster;
  395. if (statusServerType == WsSMCSSTRoxieCluster)
  396. targetCluster = findWUClusterInfo(wuid, isECLAgent, roxieTargetClusters, thorTargetClusters, hthorTargetClusters);
  397. else if (statusServerType == WsSMCSSTHThorCluster)
  398. targetCluster = findWUClusterInfo(wuid, isECLAgent, hthorTargetClusters, thorTargetClusters, roxieTargetClusters);
  399. else
  400. targetCluster = findWUClusterInfo(wuid, isECLAgent, thorTargetClusters, roxieTargetClusters, hthorTargetClusters);
  401. if (!targetCluster)
  402. continue;
  403. const char* targetClusterName = targetCluster->clusterName.get();
  404. CWsSMCQueue* jobQueue;
  405. if (statusServerType == WsSMCSSTThorLCRCluster)
  406. jobQueue = &targetCluster->clusterQueue;
  407. else
  408. jobQueue = &targetCluster->agentQueue;
  409. Owned<IEspActiveWorkunit> wu;
  410. if (!isECLAgent)
  411. {
  412. const char *cluster = serverStatusNode.queryProp("Cluster");
  413. StringBuffer queueName;
  414. if (cluster) // backward compat check.
  415. getClusterThorQueueName(queueName, cluster);
  416. else
  417. queueName.append(targetCluster->queueName.get());
  418. createActiveWorkUnit(context, wu, wuid, !strieq(targetClusterName, serverInstance.str()) ? serverInstance.str() : NULL, 0, serverName,
  419. queueName, serverInstance.str(), targetClusterName, false);
  420. if (wu->getStateID() == WUStateRunning) //'aborting' may be another possible status
  421. {
  422. int sgDuration = serverStatusNode.getPropInt("@sg_duration", -1);
  423. int subgraph = serverStatusNode.getPropInt("@subgraph", -1);
  424. if (subgraph > -1 && sgDuration > -1)
  425. {
  426. const char* graph = serverStatusNode.queryProp("@graph");
  427. VStringBuffer durationStr("%d min", sgDuration);
  428. VStringBuffer subgraphStr("%d", subgraph);
  429. wu->setGraphName(graph);
  430. wu->setDuration(durationStr.str());
  431. wu->setGID(subgraphStr.str());
  432. }
  433. if (serverStatusNode.getPropInt("@memoryBlocked ", 0) != 0)
  434. wu->setMemoryBlocked(1);
  435. }
  436. }
  437. else
  438. {
  439. createActiveWorkUnit(context, wu, wuid, serverInstance.str(), 0, serverName, serverName, serverInstance.str(), targetClusterName, false);
  440. if (targetCluster->clusterType == ThorLCRCluster)
  441. wu->setClusterType(CLUSTER_TYPE_THOR);
  442. else if (targetCluster->clusterType == RoxieCluster)
  443. wu->setClusterType(CLUSTER_TYPE_ROXIE);
  444. else
  445. wu->setClusterType(CLUSTER_TYPE_HTHOR);
  446. wu->setClusterQueueName(targetCluster->queueName.get());
  447. if (wu->getStateID() != WUStateRunning)
  448. {
  449. const char *extra = wu->getExtra();
  450. if (wu->getStateID() != WUStateBlocked || !extra || !*extra) // Blocked on persist treated as running here
  451. {
  452. aws.append(*wu.getClear());
  453. jobQueue->countQueuedJobs++;
  454. continue;
  455. }
  456. }
  457. //Should this be set only if wu->getStateID() == WUStateRunning?
  458. if (serverStatusNode.getPropInt("@memoryBlocked ", 0) != 0)
  459. wu->setMemoryBlocked(1);
  460. }
  461. aws.append(*wu.getClear());
  462. jobQueue->countRunningJobs++;
  463. }
  464. }
  465. }
  466. bool CActivityInfo::checkSetUniqueECLWUID(const char* wuid)
  467. {
  468. bool* idFound = uniqueECLWUIDs.getValue(wuid);
  469. if (!idFound || !*idFound)
  470. uniqueECLWUIDs.setValue(wuid, true);
  471. return idFound && *idFound;
  472. }
  473. CWsSMCTargetCluster* CActivityInfo::findWUClusterInfo(const char* wuid, bool isOnECLAgent, CIArrayOf<CWsSMCTargetCluster>& targetClusters,
  474. CIArrayOf<CWsSMCTargetCluster>& targetClusters1, CIArrayOf<CWsSMCTargetCluster>& targetClusters2)
  475. {
  476. StringAttr clusterName;
  477. try
  478. {
  479. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  480. Owned<IConstWorkUnit> cw = factory->openWorkUnit(wuid);
  481. if (!cw)
  482. return NULL;
  483. clusterName.set(cw->queryClusterName());
  484. if (!clusterName.length())
  485. return NULL;
  486. }
  487. catch (IException *e)
  488. {//Exception may be thrown when the openWorkUnit() is called inside the CWUWrapper
  489. StringBuffer msg;
  490. IWARNLOG("Failed to open workunit %s: %s", wuid, e->errorMessage(msg).str());
  491. e->Release();
  492. return NULL;
  493. }
  494. const char* cluster = clusterName.str();
  495. CWsSMCTargetCluster* targetCluster = findTargetCluster(cluster, targetClusters);
  496. if (targetCluster || !isOnECLAgent)
  497. return targetCluster;
  498. targetCluster = findTargetCluster(cluster, targetClusters1);
  499. if (targetCluster)
  500. return targetCluster;
  501. return findTargetCluster(cluster, targetClusters2);
  502. }
  503. CWsSMCTargetCluster* CActivityInfo::findTargetCluster(const char* clusterName, CIArrayOf<CWsSMCTargetCluster>& targetClusters)
  504. {
  505. ForEachItemIn(i, targetClusters)
  506. {
  507. CWsSMCTargetCluster& targetCluster = targetClusters.item(i);
  508. if (strieq(targetCluster.clusterName.get(), clusterName))
  509. return &targetCluster;
  510. }
  511. return NULL;
  512. }
  513. void CActivityInfo::createActiveWorkUnit(IEspContext& context, Owned<IEspActiveWorkunit>& ownedWU, const char* wuid, const char* location,
  514. unsigned index, const char* serverName, const char* queueName, const char* instanceName, const char* targetClusterName, bool useContext)
  515. {
  516. try
  517. {
  518. if (useContext)
  519. ownedWU.setown(new CActiveWorkunitWrapper(context, wuid, location, index));
  520. else
  521. ownedWU.setown(new CActiveWorkunitWrapper(wuid, location, index));
  522. }
  523. catch (IException *e)
  524. { //if the wu cannot be opened for some reason, the openWorkUnit() inside the CActiveWorkunitWrapper() may throw an exception.
  525. //We do not want the exception stops this process of retrieving/showing all active WUs. And that WU should still be displayed
  526. //with the exception.
  527. StringBuffer msg;
  528. ownedWU.setown(new CActiveWorkunitWrapper(wuid, "", "", e->errorMessage(msg).str(), "normal"));
  529. ownedWU->setStateID(WUStateUnknown);
  530. e->Release();
  531. }
  532. ownedWU->setServer(serverName);
  533. ownedWU->setQueueName(queueName);
  534. if (instanceName && *instanceName)
  535. ownedWU->setInstance(instanceName); // JCSMORE In thor case at least, if queued it is unknown which instance it will run on..
  536. if (targetClusterName && *targetClusterName)
  537. ownedWU->setTargetClusterName(targetClusterName);
  538. }
  539. void CActivityInfo::readWUsInTargetClusterJobQueues(IEspContext& context, CIArrayOf<CWsSMCTargetCluster>& targetClusters)
  540. {
  541. ForEachItemIn(i, targetClusters)
  542. {
  543. CWsSMCTargetCluster& targetCluster = targetClusters.item(i);
  544. if (targetCluster.clusterType == ThorLCRCluster)
  545. readWUsInTargetClusterJobQueue(context, targetCluster, targetCluster.clusterQueue, targetCluster.clusterName.get());
  546. if (targetCluster.agentQueue.queueName.length())
  547. readWUsInTargetClusterJobQueue(context, targetCluster, targetCluster.agentQueue, targetCluster.agentQueue.queueName.str());
  548. if (targetCluster.serverQueue.queueName.length()) //TODO: queued WUs for ECLCCServer/ECLServer should not be here.
  549. readWUsInTargetClusterJobQueue(context, targetCluster, targetCluster.serverQueue, targetCluster.serverQueue.queueName.str());
  550. }
  551. }
  552. void CActivityInfo::readWUsInTargetClusterJobQueue(IEspContext& context, CWsSMCTargetCluster& targetCluster, CWsSMCQueue& jobQueue, const char* queueName)
  553. {
  554. ForEachItemIn(i, targetCluster.queuedWUIDs)
  555. {
  556. const char* wuid = targetCluster.queuedWUIDs.item(i);
  557. if (!wuid || !*wuid || checkSetUniqueECLWUID(wuid))
  558. continue;
  559. Owned<IEspActiveWorkunit> wu;
  560. createActiveWorkUnit(context, wu, wuid, jobQueue.queueName.str(), ++jobQueue.countQueuedJobs, targetCluster.statusServerName.str(),
  561. queueName, NULL, targetCluster.clusterName.get(), false);
  562. aws.append(*wu.getClear());
  563. }
  564. }
  565. void CActivityInfo::addQueuedServerQueueJob(IEspContext& context, const char* serverName, const char* queueName, const char* instanceName, CIArrayOf<CWsSMCTargetCluster>& targetClusters)
  566. {
  567. ForEachItemIn(i, targetClusters)
  568. {
  569. CWsSMCTargetCluster& targetCluster = targetClusters.item(i);
  570. if (!targetCluster.wuidsOnServerQueue.length() || !strieq(queueName, targetCluster.serverQueue.queueName.str()))
  571. continue;
  572. ForEachItemIn(i1, targetCluster.wuidsOnServerQueue)
  573. {
  574. const char* wuid = targetCluster.wuidsOnServerQueue.item(i1);
  575. if (!wuid || !*wuid) //Multiple servers may monitor one queue. The WU may be shown under the multiple servers.
  576. continue;
  577. Owned<IEspActiveWorkunit> wu;
  578. createActiveWorkUnit(context, wu, wuid, NULL, 0, serverName, queueName, instanceName, NULL, false);
  579. aws.append(*wu.getClear());
  580. }
  581. }
  582. }
  583. void CActivityInfo::readRunningWUsAndJobQueueforOtherStatusServers(IEspContext& context, IPropertyTree* serverStatusRoot)
  584. {
  585. BoolHash uniqueServers;
  586. Owned<IPropertyTreeIterator> it(serverStatusRoot->getElements("Server"));
  587. ForEach(*it)
  588. {
  589. IPropertyTree& serverNode = it->query();
  590. const char* cluster = serverNode.queryProp("@cluster");
  591. const char* serverName = serverNode.queryProp("@name");
  592. const char* node = serverNode.queryProp("@node");
  593. const char* queueName = serverNode.queryProp("@queue");
  594. unsigned port = serverNode.getPropInt("@mpport", 0);
  595. if (!serverName || !*serverName || !node || !*node || strieq(serverName, STATUS_SERVER_DFUSERVER)
  596. || strieq(serverName, getStatusServerTypeName(WsSMCSSTThorLCRCluster)) || strieq(serverName, getStatusServerTypeName(WsSMCSSTRoxieCluster))
  597. || strieq(serverName, getStatusServerTypeName(WsSMCSSTHThorCluster)) || strieq(serverName, getStatusServerTypeName(WsSMCSSTECLagent)))
  598. continue; //target clusters, ECLAgent, DFUServer already handled separately
  599. StringBuffer instanceName;
  600. if (!isEmptyString(cluster))
  601. instanceName.set(cluster);
  602. else
  603. instanceName.setf("%s_on_%s:%d", serverName, node, port); //for legacy
  604. Owned<IPropertyTreeIterator> wuids(serverNode.getElements("WorkUnit"));
  605. ForEach(*wuids)
  606. {
  607. const char* wuid=wuids->query().queryProp(NULL);
  608. if (!wuid || !*wuid || checkSetUniqueECLWUID(wuid))
  609. continue;
  610. Owned<IEspActiveWorkunit> wu;
  611. createActiveWorkUnit(context, wu, wuid, NULL, 0, serverName, queueName, instanceName.str(), NULL, false);
  612. aws.append(*wu.getClear());
  613. }
  614. bool* found = uniqueServers.getValue(instanceName);
  615. if (!found || !*found)
  616. {
  617. uniqueServers.setValue(instanceName, true);
  618. getServerJobQueue(context, queueName, instanceName, serverName, node, port);
  619. //Now, we found a new server. we need to add queued jobs from the queues the server is monitoring.
  620. StringArray qList;
  621. qList.appendListUniq(queueName, ",");
  622. ForEachItemIn(q, qList)
  623. {
  624. addQueuedServerQueueJob(context, serverName, qList.item(q), instanceName.str(), thorTargetClusters);
  625. addQueuedServerQueueJob(context, serverName, qList.item(q), instanceName.str(), roxieTargetClusters);
  626. addQueuedServerQueueJob(context, serverName, qList.item(q), instanceName.str(), hthorTargetClusters);
  627. }
  628. }
  629. }
  630. return;
  631. }
  632. void CActivityInfo::getDFUServersAndWUs(IEspContext& context, IPropertyTree* envRoot, IPropertyTree* serverStatusRoot)
  633. {
  634. if (!envRoot)
  635. return;
  636. VStringBuffer path("Software/%s", eqDfu);
  637. Owned<IPropertyTreeIterator> services = envRoot->getElements(path);
  638. ForEach(*services)
  639. {
  640. IPropertyTree &serviceTree = services->query();
  641. const char *qname = serviceTree.queryProp("@queue");
  642. if (!qname || !*qname)
  643. continue;
  644. StringArray queues;
  645. queues.appendListUniq(qname, ",");
  646. const char *serverName = serviceTree.queryProp("@name");
  647. ForEachItemIn(q, queues)
  648. {
  649. StringArray wuidList;
  650. const char *queueName = queues.item(q);
  651. readDFUWUDetails(queueName, serverName, wuidList, readDFUWUIDs(serverStatusRoot, queueName, wuidList));
  652. getServerJobQueue(context, queueName, serverName, STATUS_SERVER_DFUSERVER, NULL, 0);
  653. }
  654. }
  655. }
  656. unsigned CActivityInfo::readDFUWUIDs(IPropertyTree* serverStatusRoot, const char* queueName, StringArray& wuidList)
  657. {
  658. if (!queueName || !*queueName)
  659. {
  660. IWARNLOG("CActivityInfo::readDFUWUIDs: queue name not specified");
  661. return 0;
  662. }
  663. unsigned runningWUCount = 0;
  664. VStringBuffer path("Server[@name=\"DFUserver\"]/Queue[@name=\"%s\"]",queueName);
  665. Owned<IPropertyTreeIterator> iter = serverStatusRoot->getElements(path.str());
  666. ForEach(*iter)
  667. {
  668. Owned<IPropertyTreeIterator> iterj = iter->query().getElements("Job");
  669. ForEach(*iterj)
  670. {
  671. const char *wuid = iterj->query().queryProp("@wuid");
  672. if (wuid && *wuid && (*wuid!='!')) // filter escapes -- see queuedJobs() in dfuwu.cpp
  673. {
  674. wuidList.append(wuid);
  675. runningWUCount++;
  676. }
  677. }
  678. }
  679. if (!jobQueueSnapshot)
  680. return runningWUCount;
  681. //Read queued jobs
  682. Owned<IJobQueueConst> jobQueue = jobQueueSnapshot->getJobQueue(queueName);
  683. if (!jobQueue)
  684. {
  685. IWARNLOG("CActivityInfo::readDFUWUIDs: failed to get info for job queue %s.", queueName);
  686. return runningWUCount;
  687. }
  688. CJobQueueContents jobList;
  689. jobQueue->copyItems(jobList);
  690. Owned<IJobQueueIterator> iterq = jobList.getIterator();
  691. ForEach(*iterq)
  692. {
  693. const char* wuid = iterq->query().queryWUID();
  694. if (wuid && *wuid)
  695. wuidList.append(wuid);
  696. }
  697. return runningWUCount;
  698. }
  699. void CActivityInfo::readDFUWUDetails(const char* queueName, const char* serverName, StringArray& wuidList, unsigned runningWUCount)
  700. {
  701. Owned<IDFUWorkUnitFactory> factory = getDFUWorkUnitFactory();
  702. ForEachItemIn(i, wuidList)
  703. {
  704. StringBuffer jname, uname, state, error;
  705. const char *wuid = wuidList.item(i);
  706. if (i<runningWUCount)
  707. state.set("running");
  708. else
  709. state.set("queued");
  710. try
  711. {
  712. Owned<IConstDFUWorkUnit> dfuwu = factory->openWorkUnit(wuid, false);
  713. dfuwu->getUser(uname);
  714. dfuwu->getJobName(jname);
  715. }
  716. catch (IException *e)
  717. {
  718. e->errorMessage(error);
  719. state.appendf(" (%s)", error.str());
  720. e->Release();
  721. }
  722. Owned<IEspActiveWorkunit> wu(new CActiveWorkunitWrapper(wuid, uname.str(), jname.str(), state.str(), "normal"));
  723. wu->setServer(STATUS_SERVER_DFUSERVER);
  724. wu->setInstance(serverName);
  725. wu->setQueueName(queueName);
  726. aws.append(*wu.getClear());
  727. }
  728. }
  729. void CActivityInfo::getDFURecoveryJobs()
  730. {
  731. Owned<IRemoteConnection> connDFURecovery = querySDS().connect("DFU/RECOVERY",myProcessSession(), RTM_LOCK_READ, 30000);
  732. if (!connDFURecovery)
  733. return;
  734. Owned<IPropertyTreeIterator> it(connDFURecovery->queryRoot()->getElements("job"));
  735. ForEach(*it)
  736. {
  737. IPropertyTree &jb=it->query();
  738. if (!jb.getPropBool("Running",false))
  739. continue;
  740. unsigned done = 0, total = 0;
  741. Owned<IPropertyTreeIterator> it = jb.getElements("DFT/progress");
  742. ForEach(*it)
  743. {
  744. IPropertyTree &p=it->query();
  745. if (p.getPropInt("@done",0))
  746. done++;
  747. total++;
  748. }
  749. StringBuffer cmd;
  750. cmd.append(jb.queryProp("@command")).append(" ").append(jb.queryProp("@command_parameters"));
  751. Owned<IEspDFUJob> job = new CDFUJob("","");
  752. job->setTimeStarted(jb.queryProp("@time_started"));
  753. job->setDone(done);
  754. job->setTotal(total);
  755. job->setCommand(cmd.str());
  756. DFURecoveryJobs.append(*job.getClear());
  757. }
  758. }
  759. void CActivityInfo::getServerJobQueue(IEspContext &context, const char* queueName, const char* serverName,
  760. const char* serverType, const char* networkAddress, unsigned port)
  761. {
  762. if (!queueName || !*queueName || !serverName || !*serverName || !serverType || !*serverType)
  763. return;
  764. double version = context.getClientVersion();
  765. Owned<IEspServerJobQueue> jobQueue = createServerJobQueue("", "");
  766. jobQueue->setServerName(serverName);
  767. jobQueue->setServerType(serverType);
  768. if (networkAddress && *networkAddress)
  769. {
  770. jobQueue->setNetworkAddress(networkAddress);
  771. jobQueue->setPort(port);
  772. }
  773. readServerJobQueueStatus(context, queueName, jobQueue);
  774. serverJobQueues.append(*jobQueue.getClear());
  775. }
  776. void CActivityInfo::readServerJobQueueStatus(IEspContext &context, const char* queueName, IEspServerJobQueue* jobQueue)
  777. {
  778. if (!jobQueueSnapshot)
  779. {
  780. IWARNLOG("CActivityInfo::readServerJobQueueStatus: jobQueueSnapshot not found.");
  781. return;
  782. }
  783. StringBuffer queueStateDetails;
  784. bool hasStopped = false, hasPaused = false;
  785. StringArray queueNames;
  786. queueNames.appendListUniq(queueName, ",");
  787. IArrayOf<IEspServerJobQueue> jobQueues;
  788. ForEachItemIn(i, queueNames)
  789. readServerJobQueueDetails(context, queueNames.item(i), hasStopped, hasPaused, queueStateDetails, jobQueues);
  790. double version = context.getClientVersion();
  791. if (version < 1.20)
  792. jobQueue->setQueueName(queueName);
  793. else if (version < 1.21)
  794. jobQueue->setQueueNames(queueNames);
  795. else
  796. jobQueue->setQueues(jobQueues);
  797. //The hasStopped, hasPaused, and queueStateDetails should be set inside readServerJobQueueDetails().
  798. if (hasStopped)
  799. jobQueue->setQueueStatus("stopped"); //Some of its job queues is stopped. So, return a warning here.
  800. else if (hasPaused)
  801. jobQueue->setQueueStatus("paused"); //Some of its job queues is paused. So, return a warning here.
  802. else
  803. jobQueue->setQueueStatus("running");
  804. jobQueue->setStatusDetails(queueStateDetails.str());
  805. }
  806. void CActivityInfo::readServerJobQueueDetails(IEspContext &context, const char* queueName, bool& hasStopped,
  807. bool& hasPaused, StringBuffer& queueStateDetails, IArrayOf<IEspServerJobQueue>& jobQueues)
  808. {
  809. double version = context.getClientVersion();
  810. StringBuffer status, details, stateDetailsString;
  811. Owned<IJobQueueConst> queue = jobQueueSnapshot->getJobQueue(queueName);
  812. if (queue)
  813. queue->getState(status, details);
  814. if (status.isEmpty())
  815. {
  816. if (version < 1.21)
  817. {
  818. if (!queue)
  819. queueStateDetails.appendf("%s not found in Status Server list; ", queueName);
  820. else
  821. queueStateDetails.appendf("No status set in Status Server list for %s; ", queueName);
  822. }
  823. else
  824. {
  825. Owned<IEspServerJobQueue> jobQueue = createServerJobQueue();
  826. jobQueue->setQueueName(queueName);
  827. if (!queue)
  828. stateDetailsString.setf("%s not found in Status Server list", queueName);
  829. else
  830. stateDetailsString.setf("No status set in Status Server list for %s", queueName);
  831. queueStateDetails.appendf("%s;", stateDetailsString.str());
  832. jobQueue->setStatusDetails(stateDetailsString.str());
  833. jobQueues.append(*jobQueue.getClear());
  834. }
  835. return;
  836. }
  837. if (version < 1.21)
  838. {
  839. if (strieq(status.str(), "paused"))
  840. hasPaused = true;
  841. else if (strieq(status.str(), "stopped"))
  842. hasStopped = true;
  843. if (details && *details)
  844. queueStateDetails.appendf("%s: queue %s; %s;", queueName, status.str(), details.str());
  845. else
  846. queueStateDetails.appendf("%s: queue %s;", queueName, status.str());
  847. }
  848. else
  849. {
  850. Owned<IEspServerJobQueue> jobQueue = createServerJobQueue();
  851. jobQueue->setQueueName(queueName);
  852. if (strieq(status.str(), "paused"))
  853. {
  854. hasPaused = true;
  855. jobQueue->setQueueStatus("paused");
  856. }
  857. else if (strieq(status.str(), "stopped"))
  858. {
  859. hasStopped = true;
  860. jobQueue->setQueueStatus("stopped");
  861. }
  862. else
  863. {
  864. jobQueue->setQueueStatus("running");
  865. }
  866. if (details && *details)
  867. {
  868. queueStateDetails.appendf("%s: queue %s; %s;", queueName, status.str(), details.str());
  869. stateDetailsString.setf("%s: queue %s; %s;", queueName, status.str(), details.str());
  870. }
  871. else
  872. {
  873. queueStateDetails.appendf("%s: queue %s;", queueName, status.str());
  874. stateDetailsString.setf("%s: queue %s;", queueName, status.str());
  875. }
  876. jobQueue->setStatusDetails(stateDetailsString.str());
  877. jobQueues.append(*jobQueue.getClear());
  878. }
  879. }
  880. bool CWsSMCEx::onIndex(IEspContext &context, IEspSMCIndexRequest &req, IEspSMCIndexResponse &resp)
  881. {
  882. resp.setRedirectUrl("/");
  883. return true;
  884. }
  885. void CWsSMCEx::readBannerAndChatRequest(IEspContext& context, IEspActivityRequest &req, IEspActivityResponse& resp)
  886. {
  887. StringBuffer chatURLStr, bannerStr;
  888. const char* chatURL = req.getChatURL();
  889. const char* banner = req.getBannerContent();
  890. //Filter out invalid chars
  891. if (chatURL && *chatURL)
  892. {
  893. const char* pStr = chatURL;
  894. unsigned len = strlen(chatURL);
  895. for (unsigned i = 0; i < len; i++)
  896. {
  897. if (isprint(*pStr))
  898. chatURLStr.append(*pStr);
  899. pStr++;
  900. }
  901. }
  902. if (banner && *banner)
  903. {
  904. const char* pStr = banner;
  905. unsigned len = strlen(banner);
  906. for (unsigned i = 0; i < len; i++)
  907. {
  908. bannerStr.append(isprint(*pStr) ? *pStr : '.');
  909. pStr++;
  910. }
  911. }
  912. chatURLStr.trim();
  913. bannerStr.trim();
  914. if (!req.getBannerAction_isNull() && req.getBannerAction() && (bannerStr.length() < 1))
  915. throw MakeStringException(ECLWATCH_MISSING_BANNER_CONTENT, "If a Banner is enabled, the Banner content must be specified.");
  916. if (!req.getEnableChatURL_isNull() && req.getEnableChatURL() && (chatURLStr.length() < 1))
  917. throw MakeStringException(ECLWATCH_MISSING_CHAT_URL, "If a Chat is enabled, the Chat URL must be specified.");
  918. //Now, store the strings since they are valid.
  919. m_ChatURL = chatURLStr;
  920. m_Banner = bannerStr;
  921. const char* bannerSize = req.getBannerSize();
  922. if (bannerSize && *bannerSize)
  923. m_BannerSize.set(bannerSize);
  924. const char* bannerColor = req.getBannerColor();
  925. if (bannerColor && *bannerColor)
  926. m_BannerColor.set(bannerColor);
  927. const char* bannerScroll = req.getBannerScroll();
  928. if (bannerScroll && *bannerScroll)
  929. m_BannerScroll.set(bannerScroll);
  930. m_BannerAction = req.getBannerAction();
  931. if(!req.getEnableChatURL_isNull())
  932. m_EnableChatURL = req.getEnableChatURL();
  933. }
  934. void CWsSMCEx::setBannerAndChatData(double version, IEspActivityResponse& resp)
  935. {
  936. resp.setShowBanner(m_BannerAction);
  937. resp.setShowChatURL(m_EnableChatURL);
  938. resp.setBannerContent(m_Banner.str());
  939. resp.setBannerSize(m_BannerSize.str());
  940. resp.setBannerColor(m_BannerColor.str());
  941. resp.setChatURL(m_ChatURL.str());
  942. if (version >= 1.08)
  943. resp.setBannerScroll(m_BannerScroll.str());
  944. }
  945. void CWsSMCEx::sortTargetClusters(IArrayOf<IEspTargetCluster>& clusters, const char* sortBy, bool descending)
  946. {
  947. if (!sortBy || !*sortBy || strieq(sortBy, "name"))
  948. clusters.sort(descending ? sortTargetClustersByNameDescending : sortTargetClustersByNameAscending);
  949. else
  950. clusters.sort(descending ? sortTargetClustersBySizeDescending : sortTargetClustersBySizeAscending);
  951. }
  952. void CWsSMCEx::getClusterQueueStatus(const CWsSMCTargetCluster& targetCluster, ClusterStatusType& queueStatusType, StringBuffer& queueStatusDetails)
  953. {
  954. const CWsSMCQueue* jobQueue = &targetCluster.clusterQueue;
  955. if (targetCluster.clusterType != ThorLCRCluster)
  956. jobQueue = &targetCluster.agentQueue;
  957. if (!jobQueue->queueName.length())
  958. return;
  959. bool queuePausedOrStopped = false;
  960. //get queueStatusDetails
  961. if (targetCluster.clusterStatusDetails.length())
  962. queueStatusDetails.set(targetCluster.clusterStatusDetails.str());
  963. if (jobQueue->queueState.length())
  964. {
  965. const char* queueState = jobQueue->queueState.str();
  966. queueStatusDetails.appendf("%s: queue %s; ", jobQueue->queueName.str(), queueState);
  967. if (jobQueue->queueStateDetails.length())
  968. queueStatusDetails.appendf(" %s;", jobQueue->queueStateDetails.str());
  969. if (strieq(queueState,"stopped") || strieq(queueState,"paused"))
  970. queuePausedOrStopped = true;
  971. }
  972. //get queueStatusType
  973. if (!jobQueue->foundQueueInStatusServer)
  974. {
  975. if (queuePausedOrStopped)
  976. queueStatusType = QueuePausedOrStoppedNotFound;
  977. else
  978. queueStatusType = QueueRunningNotFound;
  979. }
  980. else if (jobQueue->notFoundInJobQueues)
  981. queueStatusType = QueueNotFound;
  982. else if (!queuePausedOrStopped)
  983. queueStatusType = RunningNormal;
  984. else if (jobQueue->countRunningJobs > 0)
  985. queueStatusType = QueuePausedOrStoppedWithJobs;
  986. else
  987. queueStatusType = QueuePausedOrStoppedWithNoJob;
  988. return;
  989. }
  990. void CWsSMCEx::setClusterStatus(IEspContext& context, const CWsSMCTargetCluster& targetCluster, IEspTargetCluster* returnCluster)
  991. {
  992. ClusterStatusType queueStatusType = RunningNormal;
  993. StringBuffer queueStatusDetails;
  994. getClusterQueueStatus(targetCluster, queueStatusType, queueStatusDetails);
  995. returnCluster->setClusterStatus(queueStatusType);
  996. //Set 'Warning' which may be displayed beside cluster name
  997. if (queueStatusType == QueueRunningNotFound)
  998. returnCluster->setWarning("Cluster not listening for workunits");
  999. else if (queueStatusType == QueuePausedOrStoppedNotFound)
  1000. returnCluster->setWarning("Queue paused or stopped - Cluster not listening for workunits");
  1001. else if (queueStatusType == QueueNotFound)
  1002. returnCluster->setWarning("Queue not found");
  1003. else if (queueStatusType != RunningNormal)
  1004. returnCluster->setWarning("Queue paused or stopped");
  1005. //Set 'StatusDetails' which may be displayed when a mouse is moved over cluster icon
  1006. if (queueStatusDetails.length())
  1007. returnCluster->setStatusDetails(queueStatusDetails.str());
  1008. }
  1009. // This method reads job information from both /Status/Servers and IJobQueue.
  1010. //
  1011. // Each server component (a thor cluster, a dfuserver, or an eclagent) is one 'Server' branch under
  1012. // /Status/Servers. A 'Server' branch has a @queue which indicates the queue name of the server.
  1013. // A 'Server' branch also contains the information about running WUs on that 'Server'. This
  1014. // method reads the information. Those WUs are displays under that server (identified by its queue name)
  1015. // on Activity page.
  1016. //
  1017. // For the WUs list inside /Status/Servers/Server[@name=ECLagent] but not list under other 'Server', the
  1018. // existing code has to find out WUID and @clusterName of the WU. Then, uses @clusterName to find out the
  1019. // queue name in IConstWUClusterInfo. Those WUs list under that server (identified by its queue name) with
  1020. // a note 'on ECLagent'. TBD: the logic here will be simpler if the /Status/Servers/Server is named the
  1021. // instance and/or cluster.
  1022. //
  1023. // In order to get information about queued WUs, this method gets queue names from both IConstWUClusterInfo
  1024. // and other environment functions. Each of those queue names is linked to one IJobQueues. From the
  1025. // IJobQueues, this method reads queued jobs for each server component and list them under the server
  1026. // component (identified by its queue name).
  1027. bool CWsSMCEx::onActivity(IEspContext &context, IEspActivityRequest &req, IEspActivityResponse& resp)
  1028. {
  1029. try
  1030. {
  1031. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_SMC_ACCESS_DENIED, SMC_ACCESS_DENIED);
  1032. const char* build_ver = getBuildVersion();
  1033. resp.setBuild(build_ver);
  1034. double version = context.getClientVersion();
  1035. bool isSuperUser = true;
  1036. #ifdef _USE_OPENLDAP
  1037. CLdapSecManager* secmgr = dynamic_cast<CLdapSecManager*>(context.querySecManager());
  1038. if(secmgr && !secmgr->isSuperUser(context.queryUser()))
  1039. isSuperUser = false;
  1040. #endif
  1041. if(isSuperUser && req.getFromSubmitBtn())
  1042. readBannerAndChatRequest(context, req, resp);
  1043. if (version >= 1.12)
  1044. resp.setSuperUser(isSuperUser);
  1045. if (version >= 1.06)
  1046. setBannerAndChatData(version, resp);
  1047. Owned<CActivityInfo> activityInfo = activityInfoReader->getActivityInfo();
  1048. if (!activityInfo)
  1049. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get Activity Info. Please try later.");
  1050. setActivityResponse(context, activityInfo, req, resp);
  1051. }
  1052. catch(IException* e)
  1053. {
  1054. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1055. }
  1056. return true;
  1057. }
  1058. void CWsSMCEx::addWUsToResponse(IEspContext &context, const IArrayOf<IEspActiveWorkunit>& aws, IEspActivityResponse& resp)
  1059. {
  1060. const char* user = context.queryUserId();
  1061. IArrayOf<IEspActiveWorkunit> awsReturned;
  1062. ForEachItemIn(i, aws)
  1063. {
  1064. IEspActiveWorkunit& wu = aws.item(i);
  1065. const char* wuid = wu.getWuid();
  1066. if (wuid[0] == 'D')//DFU WU
  1067. {
  1068. awsReturned.append(*LINK(&wu));
  1069. continue;
  1070. }
  1071. try
  1072. {
  1073. //if no access, throw an exception and go to the 'catch' section.
  1074. const char* owner = wu.getOwner();
  1075. context.validateFeatureAccess((!owner || !*owner || (user && streq(user, owner))) ? OWN_WU_ACCESS : OTHERS_WU_ACCESS, SecAccess_Read, true);
  1076. awsReturned.append(*LINK(&wu));
  1077. continue;
  1078. }
  1079. catch (IException *e)
  1080. { //if the wu cannot be opened for some reason, the openWorkUnit() inside the CActiveWorkunitWrapper() may throw an exception.
  1081. //We do not want the exception stops this process of retrieving/showing all active WUs. And that WU should still be displayed
  1082. //with the exception.
  1083. StringBuffer msg;
  1084. Owned<IEspActiveWorkunit> cw = new CActiveWorkunitWrapper(wuid, "", "", e->errorMessage(msg).str(), "normal");
  1085. cw->setStateID(WUStateUnknown);
  1086. cw->setServer(wu.getServer());
  1087. cw->setQueueName(wu.getQueueName());
  1088. const char* instanceName = wu.getInstance();
  1089. const char* targetClusterName = wu.getTargetClusterName();
  1090. if (instanceName && *instanceName)
  1091. cw->setInstance(instanceName); // JCSMORE In thor case at least, if queued it is unknown which instance it will run on..
  1092. if (targetClusterName && *targetClusterName)
  1093. cw->setTargetClusterName(targetClusterName);
  1094. awsReturned.append(*cw.getClear());
  1095. e->Release();
  1096. }
  1097. }
  1098. resp.setRunning(awsReturned);
  1099. return;
  1100. }
  1101. void CWsSMCEx::setActivityResponse(IEspContext &context, CActivityInfo* activityInfo, IEspActivityRequest &req, IEspActivityResponse& resp)
  1102. {
  1103. double version = context.getClientVersion();
  1104. const char* sortBy = req.getSortBy();
  1105. bool descending = req.getDescending();
  1106. if (version >= 1.22)
  1107. {
  1108. StringBuffer s;
  1109. resp.setActivityTime(activityInfo->queryTimeCached(s));
  1110. resp.setDaliDetached(activityInfoReader->isDaliDetached());
  1111. }
  1112. if (version >= 1.16)
  1113. {
  1114. IArrayOf<IEspTargetCluster> thorClusters;
  1115. IArrayOf<IEspTargetCluster> hthorClusters;
  1116. IArrayOf<IEspTargetCluster> roxieClusters;
  1117. setESPTargetClusters(context, activityInfo->queryThorTargetClusters(), thorClusters);
  1118. setESPTargetClusters(context, activityInfo->queryRoxieTargetClusters(), roxieClusters);
  1119. setESPTargetClusters(context, activityInfo->queryHThorTargetClusters(), hthorClusters);
  1120. sortTargetClusters(thorClusters, sortBy, descending);
  1121. sortTargetClusters(roxieClusters, sortBy, descending);
  1122. SecAccessFlags access;
  1123. if (context.authorizeFeature(THORQUEUE_FEATURE, access) && access>=SecAccess_Full)
  1124. resp.setAccessRight("Access_Full");
  1125. resp.setSortBy(sortBy);
  1126. resp.setDescending(descending);
  1127. resp.setThorClusterList(thorClusters);
  1128. resp.setRoxieClusterList(roxieClusters);
  1129. resp.setHThorClusterList(hthorClusters);
  1130. resp.setServerJobQueues(activityInfo->queryServerJobQueues());
  1131. }
  1132. else
  1133. {//for backward compatible
  1134. IArrayOf<IEspThorCluster> thorClusters;
  1135. CIArrayOf<CWsSMCTargetCluster>& thorTargetClusters = activityInfo->queryThorTargetClusters();
  1136. ForEachItemIn(i, thorTargetClusters)
  1137. {
  1138. CWsSMCTargetCluster& targetCluster = thorTargetClusters.item(i);
  1139. Owned<IEspThorCluster> respThorCluster = new CThorCluster("", "");
  1140. respThorCluster->setClusterName(targetCluster.clusterName.get());
  1141. respThorCluster->setQueueStatus(targetCluster.queueStatus.get());
  1142. if (version >= 1.03)
  1143. respThorCluster->setQueueName(targetCluster.queueName.get());
  1144. if (version >= 1.11)
  1145. respThorCluster->setClusterSize(targetCluster.clusterSize);
  1146. thorClusters.append(*respThorCluster.getClear());
  1147. }
  1148. resp.setThorClusters(thorClusters);
  1149. if (version > 1.06)
  1150. {
  1151. IArrayOf<IEspRoxieCluster> roxieClusters;
  1152. CIArrayOf<CWsSMCTargetCluster>& roxieTargetClusters = activityInfo->queryRoxieTargetClusters();
  1153. ForEachItemIn(i, roxieTargetClusters)
  1154. {
  1155. CWsSMCTargetCluster& targetCluster = roxieTargetClusters.item(i);
  1156. Owned<IEspRoxieCluster> respRoxieCluster = new CRoxieCluster("", "");
  1157. respRoxieCluster->setClusterName(targetCluster.clusterName.get());
  1158. respRoxieCluster->setQueueStatus(targetCluster.queueStatus.get());
  1159. respRoxieCluster->setQueueName(targetCluster.queueName.get());
  1160. if (version >= 1.11)
  1161. respRoxieCluster->setClusterSize(targetCluster.clusterSize);
  1162. roxieClusters.append(*respRoxieCluster.getClear());
  1163. }
  1164. resp.setRoxieClusters(roxieClusters);
  1165. }
  1166. if (version > 1.10)
  1167. {
  1168. resp.setSortBy(sortBy);
  1169. resp.setDescending(req.getDescending());
  1170. }
  1171. if (version > 1.11)
  1172. {
  1173. IArrayOf<IEspHThorCluster> hThorClusters;
  1174. CIArrayOf<CWsSMCTargetCluster>& hthorTargetClusters = activityInfo->queryHThorTargetClusters();
  1175. ForEachItemIn(i, hthorTargetClusters)
  1176. {
  1177. CWsSMCTargetCluster& targetCluster = hthorTargetClusters.item(i);
  1178. Owned<IEspHThorCluster> respHThorCluster = new CHThorCluster("", "");
  1179. respHThorCluster->setClusterName(targetCluster.clusterName.get());
  1180. respHThorCluster->setQueueStatus(targetCluster.queueStatus.get());
  1181. respHThorCluster->setQueueName(targetCluster.queueName.get());
  1182. respHThorCluster->setClusterSize(targetCluster.clusterSize);
  1183. hThorClusters.append(*respHThorCluster.getClear());
  1184. }
  1185. resp.setHThorClusters(hThorClusters);
  1186. SecAccessFlags access;
  1187. if (context.authorizeFeature(THORQUEUE_FEATURE, access) && access>=SecAccess_Full)
  1188. resp.setAccessRight("Access_Full");
  1189. }
  1190. if (version > 1.03)
  1191. resp.setServerJobQueues(activityInfo->queryServerJobQueues());
  1192. }
  1193. resp.setDFUJobs(activityInfo->queryDFURecoveryJobs());
  1194. addWUsToResponse(context, activityInfo->queryActiveWUs(), resp);
  1195. return;
  1196. }
  1197. void CWsSMCEx::setESPTargetClusters(IEspContext& context, const CIArrayOf<CWsSMCTargetCluster>& targetClusters, IArrayOf<IEspTargetCluster>& respTargetClusters)
  1198. {
  1199. ForEachItemIn(i, targetClusters)
  1200. {
  1201. Owned<IEspTargetCluster> respTargetCluster = new CTargetCluster("", "");
  1202. setESPTargetCluster(context, targetClusters.item(i), respTargetCluster);
  1203. respTargetClusters.append(*respTargetCluster.getClear());
  1204. }
  1205. }
  1206. void CWsSMCEx::addCapabilities(IPropertyTree* pFeatureNode, const char* access,
  1207. IArrayOf<IEspCapability>& capabilities)
  1208. {
  1209. StringBuffer xpath(access);
  1210. xpath.append("/Capability");
  1211. Owned<IPropertyTreeIterator> it = pFeatureNode->getElements(xpath.str());
  1212. ForEach(*it)
  1213. {
  1214. IPropertyTree* pCapabilityNode = &it->query();
  1215. IEspCapability* pCapability = new CCapability("ws_smc");
  1216. pCapability->setName( pCapabilityNode->queryProp("@name") );
  1217. pCapability->setDescription( pCapabilityNode->queryProp("@description") );
  1218. capabilities.append(*pCapability);
  1219. }
  1220. }
  1221. bool CWsSMCEx::onMoveJobDown(IEspContext &context, IEspSMCJobRequest &req, IEspSMCJobResponse &resp)
  1222. {
  1223. try
  1224. {
  1225. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1226. {
  1227. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1228. QueueLock lock(queue);
  1229. unsigned index=queue->findRank(req.getWuid());
  1230. if(index<queue->ordinality())
  1231. {
  1232. Owned<IJobQueueItem> item0 = queue->getItem(index);
  1233. Owned<IJobQueueItem> item = queue->getItem(index+1);
  1234. if(item && item0 && (item0->getPriority() == item->getPriority()))
  1235. queue->moveAfter(req.getWuid(),item->queryWUID());
  1236. }
  1237. }
  1238. AccessSuccess(context, "Changed job priority %s",req.getWuid());
  1239. activityInfoReader->rebuild();
  1240. resp.setRedirectUrl("/WsSMC/");
  1241. }
  1242. catch(IException* e)
  1243. {
  1244. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1245. }
  1246. return true;
  1247. }
  1248. bool CWsSMCEx::onMoveJobUp(IEspContext &context, IEspSMCJobRequest &req, IEspSMCJobResponse &resp)
  1249. {
  1250. try
  1251. {
  1252. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1253. {
  1254. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1255. QueueLock lock(queue);
  1256. unsigned index=queue->findRank(req.getWuid());
  1257. if(index>0 && index<queue->ordinality())
  1258. {
  1259. Owned<IJobQueueItem> item0 = queue->getItem(index);
  1260. Owned<IJobQueueItem> item = queue->getItem(index-1);
  1261. if(item && item0 && (item0->getPriority() == item->getPriority()))
  1262. queue->moveBefore(req.getWuid(),item->queryWUID());
  1263. }
  1264. }
  1265. AccessSuccess(context, "Changed job priority %s",req.getWuid());
  1266. activityInfoReader->rebuild();
  1267. resp.setRedirectUrl("/WsSMC/");
  1268. }
  1269. catch(IException* e)
  1270. {
  1271. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1272. }
  1273. return true;
  1274. }
  1275. bool CWsSMCEx::onMoveJobBack(IEspContext &context, IEspSMCJobRequest &req, IEspSMCJobResponse &resp)
  1276. {
  1277. try
  1278. {
  1279. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1280. {
  1281. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1282. QueueLock lock(queue);
  1283. unsigned index=queue->findRank(req.getWuid());
  1284. if(index<queue->ordinality())
  1285. {
  1286. Owned<IJobQueueItem> item = queue->getItem(index);
  1287. int priority0 = item->getPriority();
  1288. unsigned biggestIndoxInSamePriority = index;
  1289. unsigned nextIndex = biggestIndoxInSamePriority + 1;
  1290. while (nextIndex<queue->ordinality())
  1291. {
  1292. item.setown(queue->getItem(nextIndex));
  1293. if (priority0 != item->getPriority())
  1294. {
  1295. break;
  1296. }
  1297. biggestIndoxInSamePriority = nextIndex;
  1298. nextIndex++;
  1299. }
  1300. if (biggestIndoxInSamePriority != index)
  1301. {
  1302. item.setown(queue->getItem(biggestIndoxInSamePriority));
  1303. queue->moveAfter(req.getWuid(), item->queryWUID());
  1304. }
  1305. }
  1306. }
  1307. AccessSuccess(context, "Changed job priority %s",req.getWuid());
  1308. activityInfoReader->rebuild();
  1309. resp.setRedirectUrl("/WsSMC/");
  1310. }
  1311. catch(IException* e)
  1312. {
  1313. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1314. }
  1315. return true;
  1316. }
  1317. bool CWsSMCEx::onMoveJobFront(IEspContext &context, IEspSMCJobRequest &req, IEspSMCJobResponse &resp)
  1318. {
  1319. try
  1320. {
  1321. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1322. {
  1323. Owned<IJobQueue> queue=createJobQueue(req.getQueueName());
  1324. QueueLock lock(queue);
  1325. unsigned index=queue->findRank(req.getWuid());
  1326. if (index>0 && index<queue->ordinality())
  1327. {
  1328. Owned<IJobQueueItem> item = queue->getItem(index);
  1329. int priority0 = item->getPriority();
  1330. unsigned smallestIndoxInSamePriority = index;
  1331. int nextIndex = smallestIndoxInSamePriority - 1;
  1332. while (nextIndex >= 0)
  1333. {
  1334. item.setown(queue->getItem(nextIndex));
  1335. if (priority0 != item->getPriority())
  1336. {
  1337. break;
  1338. }
  1339. smallestIndoxInSamePriority = nextIndex;
  1340. nextIndex--;
  1341. }
  1342. if (smallestIndoxInSamePriority != index)
  1343. {
  1344. item.setown(queue->getItem(smallestIndoxInSamePriority));
  1345. queue->moveBefore(req.getWuid(), item->queryWUID());
  1346. }
  1347. }
  1348. }
  1349. AccessSuccess(context, "Changed job priority %s",req.getWuid());
  1350. activityInfoReader->rebuild();
  1351. resp.setRedirectUrl("/WsSMC/");
  1352. }
  1353. catch(IException* e)
  1354. {
  1355. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1356. }
  1357. return true;
  1358. }
  1359. bool CWsSMCEx::onRemoveJob(IEspContext &context, IEspSMCJobRequest &req, IEspSMCJobResponse &resp)
  1360. {
  1361. try
  1362. {
  1363. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1364. abortWorkUnit(req.getWuid(), context.querySecManager(), context.queryUser());
  1365. {
  1366. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1367. QueueLock lock(queue);
  1368. unsigned index=queue->findRank(req.getWuid());
  1369. if(index<queue->ordinality())
  1370. {
  1371. if(!queue->cancelInitiateConversation(req.getWuid()))
  1372. throw MakeStringException(ECLWATCH_CANNOT_DELETE_WORKUNIT,"Failed to remove the workunit %s",req.getWuid());
  1373. }
  1374. }
  1375. AccessSuccess(context, "Removed job %s",req.getWuid());
  1376. activityInfoReader->rebuild();
  1377. resp.setRedirectUrl("/WsSMC/");
  1378. }
  1379. catch(IException* e)
  1380. {
  1381. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1382. }
  1383. return true;
  1384. }
  1385. bool CWsSMCEx::onStopQueue(IEspContext &context, IEspSMCQueueRequest &req, IEspSMCQueueResponse &resp)
  1386. {
  1387. try
  1388. {
  1389. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1390. {
  1391. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1392. StringBuffer info;
  1393. queue->stop(createQueueActionInfo(context, "stopped", req, info));
  1394. }
  1395. AccessSuccess(context, "Stopped queue %s", req.getCluster());
  1396. activityInfoReader->rebuild();
  1397. double version = context.getClientVersion();
  1398. if (version >= 1.19)
  1399. getStatusServerInfo(context, req.getServerType(), req.getCluster(), req.getNetworkAddress(), req.getPort(), resp.updateStatusServerInfo());
  1400. resp.setRedirectUrl("/WsSMC/");
  1401. }
  1402. catch(IException* e)
  1403. {
  1404. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1405. }
  1406. return true;
  1407. }
  1408. bool CWsSMCEx::onResumeQueue(IEspContext &context, IEspSMCQueueRequest &req, IEspSMCQueueResponse &resp)
  1409. {
  1410. try
  1411. {
  1412. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1413. {
  1414. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1415. StringBuffer info;
  1416. queue->resume(createQueueActionInfo(context, "resumed", req, info));
  1417. }
  1418. AccessSuccess(context, "Resumed queue %s", req.getCluster());
  1419. activityInfoReader->rebuild();
  1420. double version = context.getClientVersion();
  1421. if (version >= 1.19)
  1422. getStatusServerInfo(context, req.getServerType(), req.getCluster(), req.getNetworkAddress(), req.getPort(), resp.updateStatusServerInfo());
  1423. resp.setRedirectUrl("/WsSMC/");
  1424. }
  1425. catch(IException* e)
  1426. {
  1427. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1428. }
  1429. return true;
  1430. }
  1431. const char* CWsSMCEx::createQueueActionInfo(IEspContext &context, const char* state, IEspSMCQueueRequest &req, StringBuffer& info)
  1432. {
  1433. StringBuffer peer, currentTime;
  1434. context.getPeer(peer);
  1435. const char* userId = context.queryUserId();
  1436. if (!userId || !*userId)
  1437. userId = "Unknown user";
  1438. CDateTime now;
  1439. now.setNow();
  1440. now.getString(currentTime);
  1441. info.appendf("%s by <%s> at <%s> from <%s>", state, userId, currentTime.str(), peer.str());
  1442. const char* comment = req.getComment();
  1443. if (comment && *comment)
  1444. info.append(": ' ").append(comment).append("'");
  1445. return info.str();
  1446. }
  1447. bool CWsSMCEx::onPauseQueue(IEspContext &context, IEspSMCQueueRequest &req, IEspSMCQueueResponse &resp)
  1448. {
  1449. try
  1450. {
  1451. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1452. {
  1453. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1454. StringBuffer info;
  1455. queue->pause(createQueueActionInfo(context, "paused", req, info));
  1456. }
  1457. AccessSuccess(context, "Paused queue %s", req.getCluster());
  1458. activityInfoReader->rebuild();
  1459. double version = context.getClientVersion();
  1460. if (version >= 1.19)
  1461. getStatusServerInfo(context, req.getServerType(), req.getCluster(), req.getNetworkAddress(), req.getPort(), resp.updateStatusServerInfo());
  1462. resp.setRedirectUrl("/WsSMC/");
  1463. }
  1464. catch(IException* e)
  1465. {
  1466. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1467. }
  1468. return true;
  1469. }
  1470. bool CWsSMCEx::onClearQueue(IEspContext &context, IEspSMCQueueRequest &req, IEspSMCQueueResponse &resp)
  1471. {
  1472. try
  1473. {
  1474. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1475. {
  1476. Owned<IJobQueue> queue = createJobQueue(req.getQueueName());
  1477. QueueLock lock(queue);
  1478. for(unsigned i=0;i<queue->ordinality();i++)
  1479. {
  1480. Owned<IJobQueueItem> item = queue->getItem(i);
  1481. abortWorkUnit(item->queryWUID(), context.querySecManager(), context.queryUser());
  1482. }
  1483. queue->clear();
  1484. }
  1485. AccessSuccess(context, "Cleared queue %s",req.getCluster());
  1486. activityInfoReader->rebuild();
  1487. double version = context.getClientVersion();
  1488. if (version >= 1.19)
  1489. getStatusServerInfo(context, req.getServerType(), req.getCluster(), req.getNetworkAddress(), req.getPort(), resp.updateStatusServerInfo());
  1490. resp.setRedirectUrl("/WsSMC/");
  1491. }
  1492. catch(IException* e)
  1493. {
  1494. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1495. }
  1496. return true;
  1497. }
  1498. void CWsSMCEx::setJobPriority(IEspContext &context, IWorkUnitFactory* factory, const char* wuid, const char* queueName, WUPriorityClass& priority)
  1499. {
  1500. if (!wuid || !*wuid)
  1501. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Workunit ID not specified.");
  1502. if (!queueName || !*queueName)
  1503. throw MakeStringException(ECLWATCH_INVALID_INPUT, "queue not specified.");
  1504. Owned<IWorkUnit> lw = factory->updateWorkUnit(wuid, context.querySecManager(), context.queryUser());
  1505. if (!lw)
  1506. throw MakeStringException(ECLWATCH_CANNOT_UPDATE_WORKUNIT, "Cannot update Workunit %s", wuid);
  1507. lw->setPriority(priority);
  1508. // set job priority to queue
  1509. int priorityValue = lw->getPriorityValue();
  1510. {
  1511. CriticalBlock b(crit);
  1512. Owned<IJobQueue> queue = createJobQueue(queueName);
  1513. QueueLock lock(queue);
  1514. queue->changePriority(wuid,priorityValue);
  1515. }
  1516. return;
  1517. }
  1518. bool CWsSMCEx::onSetJobPriority(IEspContext &context, IEspSMCPriorityRequest &req, IEspSMCPriorityResponse &resp)
  1519. {
  1520. try
  1521. {
  1522. context.ensureFeatureAccess(THORQUEUE_FEATURE, SecAccess_Full, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1523. WUPriorityClass priority = PriorityClassNormal;
  1524. if(strieq(req.getPriority(),"high"))
  1525. priority = PriorityClassHigh;
  1526. else if(strieq(req.getPriority(),"low"))
  1527. priority = PriorityClassLow;
  1528. {
  1529. Owned<IWorkUnitFactory> factory = getWorkUnitFactory();
  1530. IArrayOf<IConstSMCJob>& jobs = req.getSMCJobs();
  1531. if (!jobs.length())
  1532. setJobPriority(context, factory, req.getWuid(), req.getQueueName(), priority);
  1533. else
  1534. {
  1535. ForEachItemIn(i, jobs)
  1536. {
  1537. IConstSMCJob &item = jobs.item(i);
  1538. const char *wuid = item.getWuid();
  1539. const char *queueName = item.getQueueName();
  1540. if (wuid && *wuid && queueName && *queueName)
  1541. setJobPriority(context, factory, wuid, queueName, priority);
  1542. }
  1543. }
  1544. }
  1545. activityInfoReader->rebuild();
  1546. resp.setRedirectUrl("/WsSMC/");
  1547. }
  1548. catch(IException* e)
  1549. {
  1550. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1551. }
  1552. return true;
  1553. }
  1554. bool CWsSMCEx::onGetThorQueueAvailability(IEspContext &context, IEspGetThorQueueAvailabilityRequest &req, IEspGetThorQueueAvailabilityResponse& resp)
  1555. {
  1556. try
  1557. {
  1558. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_THOR_QUEUE_ACCESS_DENIED, QUEUE_ACCESS_DENIED);
  1559. StringArray thorNames, groupNames, targetNames, queueNames;
  1560. getEnvironmentThorClusterNames(thorNames, groupNames, targetNames, queueNames);
  1561. IArrayOf<IEspThorCluster> ThorClusters;
  1562. ForEachItemIn(x, thorNames)
  1563. {
  1564. const char* targetName = targetNames.item(x);
  1565. const char* queueName = queueNames.item(x);
  1566. IEspThorCluster* returnCluster = new CThorCluster("","");
  1567. returnCluster->setClusterName(targetName);
  1568. returnCluster->setQueueName(queueName);
  1569. StringBuffer info;
  1570. Owned<IJobQueue> queue = createJobQueue(queueName);
  1571. if(queue->stopped(info))
  1572. returnCluster->setQueueStatus("stopped");
  1573. else if (queue->paused(info))
  1574. returnCluster->setQueueStatus("paused");
  1575. else
  1576. returnCluster->setQueueStatus("running");
  1577. unsigned enqueued=0;
  1578. unsigned connected=0;
  1579. unsigned waiting=0;
  1580. queue->getStats(connected,waiting,enqueued);
  1581. returnCluster->setQueueAvailable(waiting);
  1582. returnCluster->setJobsRunning(connected - waiting);
  1583. returnCluster->setJobsInQueue(enqueued);
  1584. ThorClusters.append(*returnCluster);
  1585. }
  1586. resp.setThorClusters(ThorClusters);
  1587. }
  1588. catch(IException* e)
  1589. {
  1590. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1591. }
  1592. return true;
  1593. }
  1594. bool CWsSMCEx::onSetBanner(IEspContext &context, IEspSetBannerRequest &req, IEspSetBannerResponse& resp)
  1595. {
  1596. try
  1597. {
  1598. #ifdef _USE_OPENLDAP
  1599. CLdapSecManager* secmgr = dynamic_cast<CLdapSecManager*>(context.querySecManager());
  1600. if(secmgr && !secmgr->isSuperUser(context.queryUser()))
  1601. {
  1602. context.setAuthStatus(AUTH_STATUS_NOACCESS);
  1603. throw MakeStringException(ECLWATCH_SUPER_USER_ACCESS_DENIED, "access denied, administrators only.");
  1604. }
  1605. #endif
  1606. StringBuffer chatURLStr, bannerStr;
  1607. const char* chatURL = req.getChatURL();
  1608. const char* banner = req.getBannerContent();
  1609. //Only display valid strings
  1610. if (chatURL)
  1611. {
  1612. const char* pStr = chatURL;
  1613. for (unsigned i = 0; i < strlen(chatURL); i++)
  1614. {
  1615. if ((pStr[0] > 31) && (pStr[0] < 127))
  1616. chatURLStr.append(pStr[0]);
  1617. pStr++;
  1618. }
  1619. }
  1620. if (banner)
  1621. {
  1622. const char* pStr = banner;
  1623. for (unsigned i = 0; i < strlen(banner); i++)
  1624. {
  1625. if ((pStr[0] > 31) && (pStr[0] < 127))
  1626. bannerStr.append(pStr[0]);
  1627. pStr++;
  1628. }
  1629. }
  1630. chatURLStr.trim();
  1631. bannerStr.trim();
  1632. if (!req.getBannerAction_isNull() && req.getBannerAction() && (bannerStr.length() < 1))
  1633. {
  1634. throw MakeStringException(ECLWATCH_MISSING_BANNER_CONTENT, "If a Banner is enabled, the Banner content must be specified.");
  1635. }
  1636. if (!req.getEnableChatURL_isNull() && req.getEnableChatURL() && (!req.getChatURL() || !*req.getChatURL()))
  1637. {
  1638. throw MakeStringException(ECLWATCH_MISSING_CHAT_URL, "If a Chat is enabled, the Chat URL must be specified.");
  1639. }
  1640. m_ChatURL = chatURLStr;
  1641. m_Banner = bannerStr;
  1642. const char* bannerSize = req.getBannerSize();
  1643. if (bannerSize && *bannerSize)
  1644. m_BannerSize.clear().append(bannerSize);
  1645. const char* bannerColor = req.getBannerColor();
  1646. if (bannerColor && *bannerColor)
  1647. m_BannerColor.clear().append(bannerColor);
  1648. const char* bannerScroll = req.getBannerScroll();
  1649. if (bannerScroll && *bannerScroll)
  1650. m_BannerScroll.clear().append(bannerScroll);
  1651. m_BannerAction = 0;
  1652. if(!req.getBannerAction_isNull())
  1653. m_BannerAction = req.getBannerAction();
  1654. m_EnableChatURL = 0;
  1655. if(!req.getEnableChatURL_isNull())
  1656. m_EnableChatURL = req.getEnableChatURL();
  1657. resp.setRedirectUrl("/WsSMC/Activity");
  1658. }
  1659. catch(IException* e)
  1660. {
  1661. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1662. }
  1663. return true;
  1664. }
  1665. bool CWsSMCEx::onNotInCommunityEdition(IEspContext &context, IEspNotInCommunityEditionRequest &req, IEspNotInCommunityEditionResponse &resp)
  1666. {
  1667. return true;
  1668. }
  1669. bool CWsSMCEx::onBrowseResources(IEspContext &context, IEspBrowseResourcesRequest & req, IEspBrowseResourcesResponse & resp)
  1670. {
  1671. try
  1672. {
  1673. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_SMC_ACCESS_DENIED, SMC_ACCESS_DENIED);
  1674. double version = context.getClientVersion();
  1675. Owned<IEnvironmentFactory> factory = getEnvironmentFactory(true);
  1676. Owned<IConstEnvironment> constEnv = factory->openEnvironment();
  1677. //The resource files will be downloaded from the same box of ESP (not dali)
  1678. StringBuffer ipStr;
  1679. IpAddress ipaddr = queryHostIP();
  1680. ipaddr.getIpText(ipStr);
  1681. if (ipStr.length() > 0)
  1682. {
  1683. resp.setNetAddress(ipStr.str());
  1684. Owned<IConstMachineInfo> machine = constEnv->getMachineByAddress(ipStr.str());
  1685. if (machine)
  1686. {
  1687. int os = machine->getOS();
  1688. resp.setOS(os);
  1689. }
  1690. }
  1691. if (m_PortalURL.length() > 0)
  1692. resp.setPortalURL(m_PortalURL.str());
  1693. #ifndef USE_RESOURCE
  1694. if (version > 1.12)
  1695. resp.setUseResource(false);
  1696. #else
  1697. if (version > 1.12)
  1698. resp.setUseResource(true);
  1699. //Now, get a list of resources stored inside the ESP box
  1700. IArrayOf<IEspHPCCResourceRepository> resourceRepositories;
  1701. Owned<IPropertyTree> pEnvRoot = &constEnv->getPTree();
  1702. const char* ossInstall = pEnvRoot->queryProp("EnvSettings/path");
  1703. if (!ossInstall || !*ossInstall)
  1704. {
  1705. OWARNLOG("Failed to get EnvSettings/Path in environment settings.");
  1706. return true;
  1707. }
  1708. StringBuffer path;
  1709. path.appendf("%s/componentfiles/files/downloads", ossInstall);
  1710. Owned<IFile> f = createIFile(path.str());
  1711. if(!f->exists() || !f->isDirectory())
  1712. {
  1713. OWARNLOG("Invalid resource folder");
  1714. return true;
  1715. }
  1716. Owned<IDirectoryIterator> di = f->directoryFiles(NULL, false, true);
  1717. if(di.get() == NULL)
  1718. {
  1719. OWARNLOG("Resource folder is empty.");
  1720. return true;
  1721. }
  1722. ForEach(*di)
  1723. {
  1724. if (!di->isDir())
  1725. continue;
  1726. StringBuffer folder, path0, tmpBuf;
  1727. di->getName(folder);
  1728. if (folder.length() == 0)
  1729. continue;
  1730. path0.appendf("%s/%s/description.xml", path.str(), folder.str());
  1731. Owned<IFile> f0 = createIFile(path0.str());
  1732. if(!f0->exists())
  1733. {
  1734. OWARNLOG("Description file not found for %s", folder.str());
  1735. continue;
  1736. }
  1737. OwnedIFileIO rIO = f0->openShared(IFOread,IFSHfull);
  1738. if(!rIO)
  1739. {
  1740. OWARNLOG("Failed to open the description file for %s", folder.str());
  1741. continue;
  1742. }
  1743. offset_t fileSize = f0->size();
  1744. tmpBuf.ensureCapacity((unsigned)fileSize);
  1745. tmpBuf.setLength((unsigned)fileSize);
  1746. size32_t nRead = rIO->read(0, (size32_t) fileSize, (char*)tmpBuf.str());
  1747. if (nRead != fileSize)
  1748. {
  1749. OWARNLOG("Failed to read the description file for %s", folder.str());
  1750. continue;
  1751. }
  1752. Owned<IPropertyTree> desc = createPTreeFromXMLString(tmpBuf.str());
  1753. if (!desc)
  1754. {
  1755. OWARNLOG("Invalid description file for %s", folder.str());
  1756. continue;
  1757. }
  1758. Owned<IPropertyTreeIterator> fileIterator = desc->getElements("file");
  1759. if (!fileIterator->first())
  1760. {
  1761. OWARNLOG("Invalid description file for %s", folder.str());
  1762. continue;
  1763. }
  1764. IArrayOf<IEspHPCCResource> resourcs;
  1765. do {
  1766. IPropertyTree &fileItem = fileIterator->query();
  1767. const char* filename = fileItem.queryProp("filename");
  1768. if (!filename || !*filename)
  1769. continue;
  1770. const char* name0 = fileItem.queryProp("name");
  1771. const char* description0 = fileItem.queryProp("description");
  1772. const char* version0 = fileItem.queryProp("version");
  1773. Owned<IEspHPCCResource> onefile = createHPCCResource();
  1774. onefile->setFileName(filename);
  1775. if (name0 && *name0)
  1776. onefile->setName(name0);
  1777. if (description0 && *description0)
  1778. onefile->setDescription(description0);
  1779. if (version0 && *version0)
  1780. onefile->setVersion(version0);
  1781. resourcs.append(*onefile.getLink());
  1782. } while (fileIterator->next());
  1783. if (resourcs.ordinality())
  1784. {
  1785. StringBuffer path1;
  1786. path1.appendf("%s/%s", path.str(), folder.str());
  1787. Owned<IEspHPCCResourceRepository> oneRepository = createHPCCResourceRepository();
  1788. oneRepository->setName(folder.str());
  1789. oneRepository->setPath(path1.str());
  1790. oneRepository->setHPCCResources(resourcs);
  1791. resourceRepositories.append(*oneRepository.getLink());
  1792. }
  1793. }
  1794. if (resourceRepositories.ordinality())
  1795. resp.setHPCCResourceRepositories(resourceRepositories);
  1796. #endif
  1797. }
  1798. catch(IException* e)
  1799. {
  1800. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1801. }
  1802. return true;
  1803. }
  1804. int CWsSMCSoapBindingEx::onHttpEcho(CHttpRequest* request, CHttpResponse* response)
  1805. {
  1806. StringBuffer xml;
  1807. xml.append(
  1808. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
  1809. "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
  1810. "<soap:Body>"
  1811. "<HttpEchoResponse xmlns='urn:hpccsystems:ws:httpecho'>");
  1812. appendXMLTag(xml, "Method", request->queryMethod());
  1813. appendXMLTag(xml, "UrlPath", request->queryPath());
  1814. appendXMLTag(xml, "UrlParameters", request->queryParamStr());
  1815. appendXMLOpenTag(xml, "Headers");
  1816. StringArray &headers = request->queryHeaders();
  1817. headers.sortAscii(false);
  1818. ForEachItemIn(i, headers)
  1819. {
  1820. const char *h = headers.item(i);
  1821. if (strnicmp(h, "Authorization", 13))
  1822. appendXMLTag(xml, "Header", h);
  1823. }
  1824. appendXMLCloseTag(xml, "Headers");
  1825. const char *content = request->queryContent();
  1826. if (content && *content)
  1827. appendXMLTag(xml, "Content", content);
  1828. xml.append("</HttpEchoResponse></soap:Body></soap:Envelope>");
  1829. response->setContent(xml);
  1830. response->setContentType("text/xml");
  1831. response->send();
  1832. return 0;
  1833. }
  1834. int CWsSMCSoapBindingEx::onGet(CHttpRequest* request, CHttpResponse* response)
  1835. {
  1836. const char *operation = request->queryServiceMethod();
  1837. if (!operation || !strieq(operation, "HttpEcho"))
  1838. return CWsSMCSoapBinding::onGet(request, response);
  1839. return onHttpEcho(request, response);
  1840. }
  1841. void CWsSMCSoapBindingEx::handleHttpPost(CHttpRequest *request, CHttpResponse *response)
  1842. {
  1843. sub_service sstype;
  1844. StringBuffer operation;
  1845. request->getEspPathInfo(sstype, NULL, NULL, &operation, false);
  1846. if (!operation || !strieq(operation, "HttpEcho"))
  1847. CWsSMCSoapBinding::handleHttpPost(request, response);
  1848. else
  1849. onHttpEcho(request, response);
  1850. }
  1851. int CWsSMCSoapBindingEx::onGetForm(IEspContext &context, CHttpRequest* request, CHttpResponse* response, const char *service, const char *method)
  1852. {
  1853. try
  1854. {
  1855. if(stricmp(method,"NotInCommunityEdition")==0)
  1856. {
  1857. StringBuffer page, url, link;
  1858. request->getParameter("EEPortal", url);
  1859. if (url.length() > 0)
  1860. link.appendf("Further information can be found at <a href=\"%s\" target=\"_blank\">%s</a>.", url.str(), url.str());
  1861. page.append(
  1862. "<html>"
  1863. "<head>"
  1864. "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
  1865. "<link rel=\"stylesheet\" type=\"text/css\" href=\"/esp/files/default.css\"/>"
  1866. "<link rel=\"stylesheet\" type=\"text/css\" href=\"/esp/files/yui/build/fonts/fonts-min.css\" />"
  1867. "<title>Advanced feature in Enterprise Edition</title>"
  1868. "</head>"
  1869. "<body>"
  1870. "<h3 style=\"text-align:centre;\">Advanced feature in the Enterprise Edition</h4>"
  1871. "<p style=\"text-align:centre;\">Support for this feature is coming soon. ");
  1872. if (link.length() > 0)
  1873. page.append(link.str());
  1874. page.append("</p></body>"
  1875. "</html>");
  1876. response->setContent(page.str());
  1877. response->setContentType("text/html");
  1878. response->send();
  1879. return 0;
  1880. }
  1881. else if(stricmp(method,"DisabledInThisVersion")==0)
  1882. {
  1883. StringBuffer page;
  1884. page.append(
  1885. "<html>"
  1886. "<head>"
  1887. "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
  1888. "<link rel=\"stylesheet\" type=\"text/css\" href=\"/esp/files/default.css\"/>"
  1889. "<link rel=\"stylesheet\" type=\"text/css\" href=\"/esp/files/yui/build/fonts/fonts-min.css\" />"
  1890. "<title>Disabled Feature in This Version</title>"
  1891. "</head>"
  1892. "<body>"
  1893. "<h3 style=\"text-align:centre;\">Disabled Feature in This Version</h4>"
  1894. "<p style=\"text-align:centre;\">This feature is disabled in this version. ");
  1895. page.append("</p></body>"
  1896. "</html>");
  1897. response->setContent(page.str());
  1898. response->setContentType("text/html");
  1899. response->send();
  1900. return 0;
  1901. }
  1902. }
  1903. catch(IException* e)
  1904. {
  1905. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  1906. }
  1907. return onGetForm(context, request, response, service, method);
  1908. }
  1909. inline const char *controlCmdMessage(int cmd)
  1910. {
  1911. switch (cmd)
  1912. {
  1913. case CRoxieControlCmdType_ATTACH:
  1914. return "<control:unlockDali/>";
  1915. case CRoxieControlCmdType_DETACH:
  1916. return "<control:lockDali/>";
  1917. case CRoxieControlCmdType_RELOAD:
  1918. return "<control:reload/>";
  1919. case CRoxieControlCmdType_RELOAD_RETRY:
  1920. return "<control:reload forceRetry='1' />";
  1921. case CRoxieControlCmdType_STATE:
  1922. return "<control:state/>";
  1923. default:
  1924. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Unknown Roxie Control Command.");
  1925. }
  1926. return NULL;
  1927. }
  1928. bool CWsSMCEx::onRoxieControlCmd(IEspContext &context, IEspRoxieControlCmdRequest &req, IEspRoxieControlCmdResponse &resp)
  1929. {
  1930. context.ensureFeatureAccess(ROXIE_CONTROL_URL, SecAccess_Full, ECLWATCH_SMC_ACCESS_DENIED, SMC_ACCESS_DENIED);
  1931. const char *process = req.getProcessCluster();
  1932. if (!process || !*process)
  1933. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Process cluster not specified.");
  1934. const char *controlReq = controlCmdMessage(req.getCommand());
  1935. SocketEndpointArray addrs;
  1936. getRoxieProcessServers(process, addrs);
  1937. if (!addrs.length())
  1938. throw MakeStringException(ECLWATCH_CANNOT_GET_ENV_INFO, "Process cluster not found.");
  1939. Owned<IPropertyTree> controlResp = sendRoxieControlAllNodes(addrs.item(0), controlReq, true, req.getWait());
  1940. if (!controlResp)
  1941. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get control response from roxie.");
  1942. IArrayOf<IEspRoxieControlEndpointInfo> respEndpoints;
  1943. Owned<IPropertyTreeIterator> roxieEndpoints = controlResp->getElements("Endpoint");
  1944. ForEach(*roxieEndpoints)
  1945. {
  1946. IPropertyTree &roxieEndpoint = roxieEndpoints->query();
  1947. Owned<IEspRoxieControlEndpointInfo> respEndpoint = createRoxieControlEndpointInfo();
  1948. respEndpoint->setAddress(roxieEndpoint.queryProp("@ep"));
  1949. respEndpoint->setStatus(roxieEndpoint.queryProp("Status"));
  1950. if (roxieEndpoint.hasProp("Dali/@connected"))
  1951. respEndpoint->setAttached(roxieEndpoint.getPropBool("Dali/@connected"));
  1952. if (roxieEndpoint.hasProp("State/@hash"))
  1953. respEndpoint->setStateHash(roxieEndpoint.queryProp("State/@hash"));
  1954. respEndpoints.append(*respEndpoint.getClear());
  1955. }
  1956. resp.setEndpoints(respEndpoints);
  1957. return true;
  1958. }
  1959. bool CWsSMCEx::onGetStatusServerInfo(IEspContext &context, IEspGetStatusServerInfoRequest &req, IEspGetStatusServerInfoResponse &resp)
  1960. {
  1961. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_SMC_ACCESS_DENIED, SMC_ACCESS_DENIED);
  1962. getStatusServerInfo(context, req.getServerType(), req.getServerName(), req.getNetworkAddress(), req.getPort(), resp.updateStatusServerInfo());
  1963. return true;
  1964. }
  1965. void CWsSMCEx::getStatusServerInfo(IEspContext &context, const char *serverType, const char *server, const char *networkAddress, unsigned port,
  1966. IEspStatusServerInfo& statusServerInfo)
  1967. {
  1968. if (!serverType || !*serverType)
  1969. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Server type not specified.");
  1970. Owned<CActivityInfo> activityInfo = activityInfoReader->getActivityInfo();
  1971. if (!activityInfo)
  1972. throw MakeStringException(ECLWATCH_INTERNAL_ERROR, "Failed to get Activity Info. Please try later.");
  1973. if (strieq(serverType,STATUS_SERVER_THOR))
  1974. {
  1975. setTargetClusterInfo(context, serverType, server, activityInfo->queryThorTargetClusters(), activityInfo->queryActiveWUs(), statusServerInfo);
  1976. }
  1977. else if (strieq(serverType,STATUS_SERVER_ROXIE))
  1978. {
  1979. setTargetClusterInfo(context, serverType, server, activityInfo->queryRoxieTargetClusters(), activityInfo->queryActiveWUs(), statusServerInfo);
  1980. }
  1981. else if (strieq(serverType,STATUS_SERVER_HTHOR))
  1982. {
  1983. setTargetClusterInfo(context, serverType, server, activityInfo->queryHThorTargetClusters(), activityInfo->queryActiveWUs(), statusServerInfo);
  1984. }
  1985. else if (strieq(serverType,STATUS_SERVER_DFUSERVER))
  1986. {
  1987. setServerQueueInfo(context, serverType, server, activityInfo->queryServerJobQueues(), activityInfo->queryActiveWUs(), statusServerInfo);
  1988. }
  1989. else
  1990. {
  1991. setServerQueueInfo(context, serverType, networkAddress, port, activityInfo->queryServerJobQueues(), activityInfo->queryActiveWUs(), statusServerInfo);
  1992. }
  1993. }
  1994. void CWsSMCEx::setTargetClusterInfo(IEspContext &context, const char *serverType, const char *clusterName, const CIArrayOf<CWsSMCTargetCluster>& targetClusters,
  1995. const IArrayOf<IEspActiveWorkunit>& aws, IEspStatusServerInfo& statusServerInfo)
  1996. {
  1997. if (!clusterName || !*clusterName)
  1998. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Cluster name not specified.");
  1999. IEspTargetCluster& clusterInfo = statusServerInfo.updateTargetClusterInfo();
  2000. ForEachItemIn(i, targetClusters)
  2001. {
  2002. CWsSMCTargetCluster& targetCluster = targetClusters.item(i);
  2003. const char* name = targetCluster.clusterName.get();
  2004. if (name && strieq(name, clusterName))
  2005. {
  2006. setESPTargetCluster(context, targetCluster, &clusterInfo);
  2007. break;
  2008. }
  2009. }
  2010. setActiveWUs(context, serverType, clusterName, clusterInfo.getQueueName(), aws, statusServerInfo);
  2011. }
  2012. void CWsSMCEx::setServerQueueInfo(IEspContext &context, const char *serverType, const char *serverName, const IArrayOf<IEspServerJobQueue>& serverJobQueues,
  2013. const IArrayOf<IEspActiveWorkunit>& aws, IEspStatusServerInfo& statusServerInfo)
  2014. {
  2015. if (!serverName || !*serverName)
  2016. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Server name not specified.");
  2017. ForEachItemIn(i, serverJobQueues)
  2018. {
  2019. IEspServerJobQueue& serverJobQueue = serverJobQueues.item(i);
  2020. const char* name = serverJobQueue.getServerName();
  2021. if (name && strieq(name, serverName))
  2022. {
  2023. IEspServerJobQueue& serverQueue = statusServerInfo.updateServerInfo();
  2024. serverQueue.copy(serverJobQueue);
  2025. break;
  2026. }
  2027. }
  2028. setActiveWUs(context, serverType, serverName, aws, statusServerInfo);
  2029. }
  2030. void CWsSMCEx::setServerQueueInfo(IEspContext &context, const char *serverType, const char *networkAddress, unsigned port, const IArrayOf<IEspServerJobQueue>& serverJobQueues,
  2031. const IArrayOf<IEspActiveWorkunit>& aws, IEspStatusServerInfo& statusServerInfo)
  2032. {
  2033. if (!networkAddress || !*networkAddress)
  2034. throw MakeStringException(ECLWATCH_MISSING_PARAMS, "Network address not specified.");
  2035. ForEachItemIn(i, serverJobQueues)
  2036. {
  2037. IEspServerJobQueue& serverJobQueue = serverJobQueues.item(i);
  2038. const char* ipAddress = serverJobQueue.getNetworkAddress();
  2039. unsigned thePort = serverJobQueue.getPort();
  2040. if (ipAddress && strieq(ipAddress, networkAddress) && (thePort == port))
  2041. {
  2042. IEspServerJobQueue& serverQueue = statusServerInfo.updateServerInfo();
  2043. serverQueue.copy(serverJobQueue);
  2044. break;
  2045. }
  2046. }
  2047. VStringBuffer instance("%s_on_%s:%d", serverType, networkAddress, port);
  2048. setActiveWUs(context, serverType, instance.str(), aws, statusServerInfo);
  2049. }
  2050. void CWsSMCEx::setESPTargetCluster(IEspContext &context, const CWsSMCTargetCluster& targetCluster, IEspTargetCluster* espTargetCluster)
  2051. {
  2052. espTargetCluster->setClusterName(targetCluster.clusterName.get());
  2053. espTargetCluster->setClusterSize(targetCluster.clusterSize);
  2054. espTargetCluster->setClusterType(targetCluster.clusterType);
  2055. espTargetCluster->setQueueName(targetCluster.queueName.get());
  2056. espTargetCluster->setQueueStatus(targetCluster.queueStatus.get());
  2057. setClusterStatus(context, targetCluster, espTargetCluster);
  2058. }
  2059. void CWsSMCEx::setActiveWUs(IEspContext &context, const char *serverType, const char *clusterName, const char *queueName, const IArrayOf<IEspActiveWorkunit>& aws, IEspStatusServerInfo& statusServerInfo)
  2060. {
  2061. const char* clusterType = CLUSTER_TYPE_THOR;
  2062. if (strieq(serverType,STATUS_SERVER_ROXIE))
  2063. clusterType = CLUSTER_TYPE_ROXIE;
  2064. else if (strieq(serverType,STATUS_SERVER_HTHOR))
  2065. clusterType = CLUSTER_TYPE_HTHOR;
  2066. IArrayOf<IEspActiveWorkunit> awsOnThisQueue;
  2067. ForEachItemIn(i, aws)
  2068. {
  2069. IEspActiveWorkunit& wu = aws.item(i);
  2070. const char* wuid = wu.getWuid();
  2071. if (!wuid || !*wuid)
  2072. continue;
  2073. const char* wuServerType = wu.getServer();
  2074. const char* wuClusterName = wu.getTargetClusterName();
  2075. if (!wuServerType || !wuClusterName || !strieq(serverType, wuServerType) || !strieq(clusterName, wuClusterName))
  2076. {
  2077. const char* wuClusterType = wu.getClusterType();
  2078. const char* wuClusterQueueName = wu.getClusterQueueName();
  2079. if (!wuClusterType || !wuClusterQueueName || !strieq(clusterType, wuClusterType) || !strieq(queueName, wuClusterQueueName))
  2080. continue;
  2081. }
  2082. Owned<IEspActiveWorkunit> wuOnThisQueue = new CActiveWorkunitWrapper(wuid, "", "", "", "");
  2083. setActiveWUs(context, wu, wuOnThisQueue);
  2084. awsOnThisQueue.append(*wuOnThisQueue.getClear());
  2085. }
  2086. statusServerInfo.setWorkunits(awsOnThisQueue);
  2087. }
  2088. void CWsSMCEx::setActiveWUs(IEspContext &context, const char *serverType, const char *instance, const IArrayOf<IEspActiveWorkunit>& aws, IEspStatusServerInfo& statusServerInfo)
  2089. {
  2090. IArrayOf<IEspActiveWorkunit> awsOnThisQueue;
  2091. ForEachItemIn(i, aws)
  2092. {
  2093. IEspActiveWorkunit& wu = aws.item(i);
  2094. const char* wuid = wu.getWuid();
  2095. if (!wuid || !*wuid)
  2096. continue;
  2097. const char* wuInstance = wu.getInstance();
  2098. if (!wuInstance || !strieq(wuInstance, instance))
  2099. continue;
  2100. Owned<IEspActiveWorkunit> wuOnThisQueue = new CActiveWorkunitWrapper(wuid, "", "", "", "");
  2101. setActiveWUs(context, wu, wuOnThisQueue);
  2102. awsOnThisQueue.append(*wuOnThisQueue.getClear());
  2103. }
  2104. statusServerInfo.setWorkunits(awsOnThisQueue);
  2105. }
  2106. void CWsSMCEx::setActiveWUs(IEspContext &context, IEspActiveWorkunit& wu, IEspActiveWorkunit* wuToSet)
  2107. {
  2108. try
  2109. {
  2110. const char* user = context.queryUserId();
  2111. const char* owner = wu.getOwner();
  2112. //if no access, throw an exception and go to the 'catch' section.
  2113. context.validateFeatureAccess((!owner || !*owner || (user && streq(user, owner))) ? OWN_WU_ACCESS : OTHERS_WU_ACCESS, SecAccess_Read, true);
  2114. wuToSet->copy(wu);
  2115. }
  2116. catch (IException *e)
  2117. { //if the wu cannot be opened for some reason, the openWorkUnit() inside the CActiveWorkunitWrapper() may throw an exception.
  2118. //We do not want the exception stops this process of retrieving/showing all active WUs. And that WU should still be displayed
  2119. //with the exception.
  2120. wuToSet->setStateID(WUStateUnknown);
  2121. wuToSet->setServer(wu.getServer());
  2122. wuToSet->setQueueName(wu.getQueueName());
  2123. const char* instanceName = wu.getInstance();
  2124. const char* targetClusterName = wu.getTargetClusterName();
  2125. if (instanceName && *instanceName)
  2126. wuToSet->setInstance(instanceName); // JCSMORE In thor case at least, if queued it is unknown which instance it will run on..
  2127. if (targetClusterName && *targetClusterName)
  2128. wuToSet->setTargetClusterName(targetClusterName);
  2129. e->Release();
  2130. }
  2131. }
  2132. static const char *LockModeNames[] = { "ALL", "READ", "WRITE", "HOLD", "SUB" };
  2133. void CWsSMCEx::addLockInfo(CLockMetaData& lD, const char* xPath, const char* lfn, unsigned msNow, time_t ttNow, IArrayOf<IEspLock>& locks)
  2134. {
  2135. Owned<IEspLock> lock = createLock();
  2136. if (xPath && *xPath)
  2137. lock->setXPath(xPath);
  2138. else if (lfn && *lfn)
  2139. lock->setLogicalFile(lfn);
  2140. else
  2141. return; //Should not happen
  2142. lock->setEPIP(lD.queryEp());
  2143. lock->setSessionID(lD.sessId);
  2144. unsigned duration = msNow-lD.timeLockObtained;
  2145. lock->setDurationMS(duration);
  2146. CDateTime timeLocked;
  2147. StringBuffer timeStr;
  2148. time_t ttLocked = ttNow - duration/1000;
  2149. timeLocked.set(ttLocked);
  2150. timeLocked.getString(timeStr);
  2151. lock->setTimeLocked(timeStr.str());
  2152. unsigned mode = lD.mode;
  2153. VStringBuffer modeStr("%x", mode);
  2154. lock->setModes(modeStr.str());
  2155. StringArray modes;
  2156. if (RTM_MODE(mode, RTM_LOCK_READ))
  2157. modes.append(LockModeNames[CLockModes_READ]);
  2158. if (RTM_MODE(mode, RTM_LOCK_WRITE))
  2159. modes.append(LockModeNames[CLockModes_WRITE]);
  2160. if (RTM_MODE(mode, RTM_LOCK_HOLD)) // long-term lock
  2161. modes.append(LockModeNames[CLockModes_HOLD]);
  2162. if (RTM_MODE(mode, RTM_LOCK_SUB)) // locks all descendants as well as self
  2163. modes.append(LockModeNames[CLockModes_SUB]);
  2164. lock->setModeNames(modes);
  2165. locks.append(*lock.getClear());
  2166. }
  2167. bool CWsSMCEx::onLockQuery(IEspContext &context, IEspLockQueryRequest &req, IEspLockQueryResponse &resp)
  2168. {
  2169. class CLockPostFilter
  2170. {
  2171. CLockModes mode;
  2172. time_t ttLTLow, ttLTHigh;
  2173. bool checkLTLow, checkLTHigh;
  2174. int durationLow, durationHigh;
  2175. bool checkMode(unsigned lockMode)
  2176. {
  2177. unsigned modeReq;
  2178. switch (mode)
  2179. {
  2180. case CLockModes_READ:
  2181. modeReq = RTM_LOCK_READ;
  2182. break;
  2183. case CLockModes_WRITE:
  2184. modeReq = RTM_LOCK_WRITE;
  2185. break;
  2186. case CLockModes_HOLD:
  2187. modeReq = RTM_LOCK_HOLD;
  2188. break;
  2189. case CLockModes_SUB:
  2190. modeReq = RTM_LOCK_SUB;
  2191. break;
  2192. default:
  2193. return true;
  2194. }
  2195. if (lockMode & modeReq)
  2196. return true;
  2197. return false;
  2198. }
  2199. public:
  2200. CLockPostFilter(IEspLockQueryRequest& req)
  2201. {
  2202. ttLTLow = 0;
  2203. ttLTHigh = 0;
  2204. mode = req.getMode();
  2205. if (mode == LockModes_Undefined)
  2206. throw MakeStringException(ECLWATCH_INVALID_INPUT, "Invalid Lock Mode");
  2207. if (req.getDurationMSLow_isNull())
  2208. durationLow = -1;
  2209. else
  2210. durationLow = req.getDurationMSLow();
  2211. if (req.getDurationMSHigh_isNull())
  2212. durationHigh = -1;
  2213. else
  2214. durationHigh = req.getDurationMSHigh();
  2215. const char* timeLow = req.getTimeLockedLow();
  2216. if (!timeLow || !*timeLow)
  2217. checkLTLow = false;
  2218. else
  2219. {
  2220. CDateTime dtLow;
  2221. dtLow.setString(timeLow, NULL, false);
  2222. ttLTLow = dtLow.getSimple();
  2223. checkLTLow = true;
  2224. }
  2225. const char* timeHigh = req.getTimeLockedHigh();
  2226. if (!timeHigh || !*timeHigh)
  2227. checkLTHigh = false;
  2228. else
  2229. {
  2230. CDateTime dtHigh;
  2231. dtHigh.setString(timeHigh, NULL, false);
  2232. ttLTHigh = dtHigh.getSimple();
  2233. checkLTHigh = true;
  2234. }
  2235. }
  2236. bool check(CLockMetaData& lD, unsigned msNow, time_t ttNow)
  2237. {
  2238. if (!checkMode(lD.mode))
  2239. return false;
  2240. int duration = msNow-lD.timeLockObtained;
  2241. if (durationLow > duration)
  2242. return false;
  2243. if ((durationHigh >= 0) && (durationHigh < duration))
  2244. return false;
  2245. if (checkLTLow && (ttNow - duration/1000 < ttLTLow))
  2246. return false;
  2247. if (checkLTHigh && (ttNow - duration/1000 > ttLTHigh))
  2248. return false;
  2249. return true;
  2250. }
  2251. };
  2252. try
  2253. {
  2254. context.ensureFeatureAccess(FEATURE_URL, SecAccess_Read, ECLWATCH_SMC_ACCESS_DENIED, SMC_ACCESS_DENIED);
  2255. CLockPostFilter postFilter(req);
  2256. StringBuffer xPath;
  2257. if (req.getAllFileLocks())
  2258. xPath.appendf("/%s/*", querySdsFilesRoot());
  2259. else
  2260. xPath = req.getXPath();
  2261. Owned<ILockInfoCollection> lockInfoCollection = querySDS().getLocks(req.getEPIP(), xPath.str());
  2262. IArrayOf<IEspLock> locks;
  2263. CDateTime time;
  2264. time.setNow();
  2265. time_t ttNow = time.getSimple();
  2266. unsigned msNow = msTick();
  2267. for (unsigned l=0; l<lockInfoCollection->queryLocks(); l++)
  2268. {
  2269. ILockInfo& lockInfo = lockInfoCollection->queryLock(l);
  2270. CDfsLogicalFileName dlfn;
  2271. const char* lfn = NULL;
  2272. const char* xPath = NULL;
  2273. if (dlfn.setFromXPath(lockInfo.queryXPath()))
  2274. lfn = dlfn.get();
  2275. else
  2276. xPath = lockInfo.queryXPath();
  2277. for (unsigned i=0; i<lockInfo.queryConnections(); i++)
  2278. {
  2279. CLockMetaData& lMD = lockInfo.queryLockData(i);
  2280. if (postFilter.check(lMD, msNow, ttNow))
  2281. addLockInfo(lMD, xPath, lfn, msNow, ttNow, locks);
  2282. }
  2283. }
  2284. unsigned numLocks = locks.length();
  2285. if (numLocks)
  2286. resp.setLocks(locks);
  2287. resp.setNumLocks(numLocks);
  2288. }
  2289. catch(IException* e)
  2290. {
  2291. FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR);
  2292. }
  2293. return true;
  2294. }
  2295. void CActivityInfoReader::threadmain()
  2296. {
  2297. #ifndef _CONTAINERIZED
  2298. PROGLOG("WsSMC CActivityInfoReader Thread started.");
  2299. unsigned int autoRebuildMillSeconds = 1000*autoRebuildSeconds;
  2300. while (!stopping)
  2301. {
  2302. if (!detached)
  2303. {
  2304. try
  2305. {
  2306. EspTimeSection timer("createActivityInfo");
  2307. Owned<IEspContext> espContext = createEspContext();
  2308. Owned<CActivityInfo> activityInfo = new CActivityInfo();
  2309. activityInfo->createActivityInfo(*espContext);
  2310. PROGLOG("WsSMC CActivityInfoReader: ActivityInfo collected.");
  2311. CriticalBlock b(crit);
  2312. activityInfoCache.setown(activityInfo.getClear());
  2313. // if 1st and getActivityInfo blocked, release it.
  2314. if (first)
  2315. {
  2316. first = false;
  2317. if (firstBlocked)
  2318. {
  2319. firstBlocked = false;
  2320. firstSem.signal();
  2321. }
  2322. }
  2323. }
  2324. catch(IException *e)
  2325. {
  2326. StringBuffer msg;
  2327. IERRLOG("Exception %d:%s in WsSMC CActivityInfoReader::run", e->errorCode(), e->errorMessage(msg).str());
  2328. e->Release();
  2329. }
  2330. catch(...)
  2331. {
  2332. IERRLOG("Unknown exception in WsSMC CActivityInfoReader::run");
  2333. }
  2334. }
  2335. waiting = true;
  2336. if (!sem.wait(autoRebuildMillSeconds))
  2337. {
  2338. bool expected = true;
  2339. waiting.compare_exchange_strong(expected, false);
  2340. }
  2341. }
  2342. #endif
  2343. }