ws_smcService.cpp 96 KB

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