www.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. #include "www.h"
  2. #include "concat_strings.h"
  3. #include "html_output.h"
  4. #include <library/cpp/messagebus/remote_connection_status.h>
  5. #include <library/cpp/monlib/deprecated/json/writer.h>
  6. #include <library/cpp/http/fetch/httpfsm.h>
  7. #include <library/cpp/http/fetch/httpheader.h>
  8. #include <library/cpp/http/server/http.h>
  9. #include <library/cpp/json/writer/json.h>
  10. #include <library/cpp/resource/resource.h>
  11. #include <library/cpp/uri/http_url.h>
  12. #include <util/string/cast.h>
  13. #include <util/string/printf.h>
  14. #include <util/system/mutex.h>
  15. #include <utility>
  16. using namespace NBus;
  17. using namespace NBus::NPrivate;
  18. using namespace NActor;
  19. using namespace NActor::NPrivate;
  20. static const char HTTP_OK_JS[] = "HTTP/1.1 200 Ok\r\nContent-Type: text/javascript\r\nConnection: Close\r\n\r\n";
  21. static const char HTTP_OK_JSON[] = "HTTP/1.1 200 Ok\r\nContent-Type: application/json; charset=utf-8\r\nConnection: Close\r\n\r\n";
  22. static const char HTTP_OK_PNG[] = "HTTP/1.1 200 Ok\r\nContent-Type: image/png\r\nConnection: Close\r\n\r\n";
  23. static const char HTTP_OK_BIN[] = "HTTP/1.1 200 Ok\r\nContent-Type: application/octet-stream\r\nConnection: Close\r\n\r\n";
  24. static const char HTTP_OK_HTML[] = "HTTP/1.1 200 Ok\r\nContent-Type: text/html; charset=utf-8\r\nConnection: Close\r\n\r\n";
  25. namespace {
  26. typedef TIntrusivePtr<TBusModuleInternal> TBusModuleInternalPtr;
  27. template <typename TValuePtr>
  28. struct TNamedValues {
  29. TVector<std::pair<TString, TValuePtr>> Entries;
  30. TValuePtr FindByName(TStringBuf name) {
  31. Y_ABORT_UNLESS(!!name);
  32. for (unsigned i = 0; i < Entries.size(); ++i) {
  33. if (Entries[i].first == name) {
  34. return Entries[i].second;
  35. }
  36. }
  37. return TValuePtr();
  38. }
  39. TString FindNameByPtr(TValuePtr value) {
  40. Y_ABORT_UNLESS(!!value);
  41. for (unsigned i = 0; i < Entries.size(); ++i) {
  42. if (Entries[i].second.Get() == value.Get()) {
  43. return Entries[i].first;
  44. }
  45. }
  46. Y_ABORT("unregistered");
  47. }
  48. void Add(TValuePtr p) {
  49. Y_ABORT_UNLESS(!!p);
  50. // Do not add twice
  51. for (unsigned i = 0; i < Entries.size(); ++i) {
  52. if (Entries[i].second.Get() == p.Get()) {
  53. return;
  54. }
  55. }
  56. if (!!p->GetNameInternal()) {
  57. TValuePtr current = FindByName(p->GetNameInternal());
  58. if (!current) {
  59. Entries.emplace_back(p->GetNameInternal(), p);
  60. return;
  61. }
  62. }
  63. for (unsigned i = 1;; ++i) {
  64. TString prefix = p->GetNameInternal();
  65. if (!prefix) {
  66. prefix = "unnamed";
  67. }
  68. TString name = ConcatStrings(prefix, "-", i);
  69. TValuePtr current = FindByName(name);
  70. if (!current) {
  71. Entries.emplace_back(name, p);
  72. return;
  73. }
  74. }
  75. }
  76. size_t size() const {
  77. return Entries.size();
  78. }
  79. bool operator!() const {
  80. return size() == 0;
  81. }
  82. };
  83. template <typename TSessionPtr>
  84. struct TSessionValues: public TNamedValues<TSessionPtr> {
  85. typedef TNamedValues<TSessionPtr> TBase;
  86. TVector<TString> GetNamesForQueue(TBusMessageQueue* queue) {
  87. TVector<TString> r;
  88. for (unsigned i = 0; i < TBase::size(); ++i) {
  89. if (TBase::Entries[i].second->GetQueue() == queue) {
  90. r.push_back(TBase::Entries[i].first);
  91. }
  92. }
  93. return r;
  94. }
  95. };
  96. }
  97. namespace {
  98. TString RootHref() {
  99. return ConcatStrings("?");
  100. }
  101. TString QueueHref(TStringBuf name) {
  102. return ConcatStrings("?q=", name);
  103. }
  104. TString ServerSessionHref(TStringBuf name) {
  105. return ConcatStrings("?ss=", name);
  106. }
  107. TString ClientSessionHref(TStringBuf name) {
  108. return ConcatStrings("?cs=", name);
  109. }
  110. TString OldModuleHref(TStringBuf name) {
  111. return ConcatStrings("?om=", name);
  112. }
  113. /*
  114. static void RootLink() {
  115. A(RootHref(), "root");
  116. }
  117. */
  118. void QueueLink(TStringBuf name) {
  119. A(QueueHref(name), name);
  120. }
  121. void ServerSessionLink(TStringBuf name) {
  122. A(ServerSessionHref(name), name);
  123. }
  124. void ClientSessionLink(TStringBuf name) {
  125. A(ClientSessionHref(name), name);
  126. }
  127. void OldModuleLink(TStringBuf name) {
  128. A(OldModuleHref(name), name);
  129. }
  130. }
  131. struct TBusWww::TImpl {
  132. // TODO: use weak pointers
  133. TNamedValues<TBusMessageQueuePtr> Queues;
  134. TSessionValues<TIntrusivePtr<TBusClientSession>> ClientSessions;
  135. TSessionValues<TIntrusivePtr<TBusServerSession>> ServerSessions;
  136. TSessionValues<TBusModuleInternalPtr> Modules;
  137. TMutex Mutex;
  138. void RegisterClientSession(TBusClientSessionPtr s) {
  139. Y_ABORT_UNLESS(!!s);
  140. TGuard<TMutex> g(Mutex);
  141. ClientSessions.Add(s.Get());
  142. Queues.Add(s->GetQueue());
  143. }
  144. void RegisterServerSession(TBusServerSessionPtr s) {
  145. Y_ABORT_UNLESS(!!s);
  146. TGuard<TMutex> g(Mutex);
  147. ServerSessions.Add(s.Get());
  148. Queues.Add(s->GetQueue());
  149. }
  150. void RegisterQueue(TBusMessageQueuePtr q) {
  151. Y_ABORT_UNLESS(!!q);
  152. TGuard<TMutex> g(Mutex);
  153. Queues.Add(q);
  154. }
  155. void RegisterModule(TBusModule* module) {
  156. Y_ABORT_UNLESS(!!module);
  157. TGuard<TMutex> g(Mutex);
  158. {
  159. TVector<TBusClientSessionPtr> clientSessions = module->GetInternal()->GetClientSessionsInternal();
  160. for (unsigned i = 0; i < clientSessions.size(); ++i) {
  161. RegisterClientSession(clientSessions[i]);
  162. }
  163. }
  164. {
  165. TVector<TBusServerSessionPtr> serverSessions = module->GetInternal()->GetServerSessionsInternal();
  166. for (unsigned i = 0; i < serverSessions.size(); ++i) {
  167. RegisterServerSession(serverSessions[i]);
  168. }
  169. }
  170. Queues.Add(module->GetInternal()->GetQueue());
  171. Modules.Add(module->GetInternal());
  172. }
  173. TString FindQueueNameBySessionName(TStringBuf sessionName, bool client) {
  174. TIntrusivePtr<TBusClientSession> clientSession;
  175. TIntrusivePtr<TBusServerSession> serverSession;
  176. TBusSession* session;
  177. if (client) {
  178. clientSession = ClientSessions.FindByName(sessionName);
  179. session = clientSession.Get();
  180. } else {
  181. serverSession = ServerSessions.FindByName(sessionName);
  182. session = serverSession.Get();
  183. }
  184. Y_ABORT_UNLESS(!!session);
  185. return Queues.FindNameByPtr(session->GetQueue());
  186. }
  187. struct TRequest {
  188. TImpl* const Outer;
  189. IOutputStream& Os;
  190. const TCgiParameters& CgiParams;
  191. const TOptionalParams& Params;
  192. TRequest(TImpl* outer, IOutputStream& os, const TCgiParameters& cgiParams, const TOptionalParams& params)
  193. : Outer(outer)
  194. , Os(os)
  195. , CgiParams(cgiParams)
  196. , Params(params)
  197. {
  198. }
  199. void CrumbsParentLinks() {
  200. for (unsigned i = 0; i < Params.ParentLinks.size(); ++i) {
  201. const TLink& link = Params.ParentLinks[i];
  202. TTagGuard li("li");
  203. A(link.Href, link.Title);
  204. }
  205. }
  206. void Crumb(TStringBuf name, TStringBuf href = "") {
  207. if (!!href) {
  208. TTagGuard li("li");
  209. A(href, name);
  210. } else {
  211. LiWithClass("active", name);
  212. }
  213. }
  214. void BreadcrumbRoot() {
  215. TTagGuard ol("ol", "breadcrumb");
  216. CrumbsParentLinks();
  217. Crumb("MessageBus");
  218. }
  219. void BreadcrumbQueue(TStringBuf queueName) {
  220. TTagGuard ol("ol", "breadcrumb");
  221. CrumbsParentLinks();
  222. Crumb("MessageBus", RootHref());
  223. Crumb(ConcatStrings("queue ", queueName));
  224. }
  225. void BreadcrumbSession(TStringBuf sessionName, bool client) {
  226. TString queueName = Outer->FindQueueNameBySessionName(sessionName, client);
  227. TStringBuf whatSession = client ? "client session" : "server session";
  228. TTagGuard ol("ol", "breadcrumb");
  229. CrumbsParentLinks();
  230. Crumb("MessageBus", RootHref());
  231. Crumb(ConcatStrings("queue ", queueName), QueueHref(queueName));
  232. Crumb(ConcatStrings(whatSession, " ", sessionName));
  233. }
  234. void ServeSessionsOfQueue(TBusMessageQueuePtr queue, bool includeQueue) {
  235. TVector<TString> clientNames = Outer->ClientSessions.GetNamesForQueue(queue.Get());
  236. TVector<TString> serverNames = Outer->ServerSessions.GetNamesForQueue(queue.Get());
  237. TVector<TString> moduleNames = Outer->Modules.GetNamesForQueue(queue.Get());
  238. TTagGuard table("table", "table table-condensed table-bordered");
  239. {
  240. TTagGuard colgroup("colgroup");
  241. TagWithClass("col", "col-md-2");
  242. TagWithClass("col", "col-md-2");
  243. TagWithClass("col", "col-md-8");
  244. }
  245. {
  246. TTagGuard tr("tr");
  247. Th("What", "span2");
  248. Th("Name", "span2");
  249. Th("Status", "span6");
  250. }
  251. if (includeQueue) {
  252. TTagGuard tr1("tr");
  253. Td("queue");
  254. {
  255. TTagGuard td("td");
  256. QueueLink(Outer->Queues.FindNameByPtr(queue));
  257. }
  258. {
  259. TTagGuard tr2("td");
  260. Pre(queue->GetStatusSingleLine());
  261. }
  262. }
  263. for (unsigned j = 0; j < clientNames.size(); ++j) {
  264. TTagGuard tr("tr");
  265. Td("client session");
  266. {
  267. TTagGuard td("td");
  268. ClientSessionLink(clientNames[j]);
  269. }
  270. {
  271. TTagGuard td("td");
  272. Pre(Outer->ClientSessions.FindByName(clientNames[j])->GetStatusSingleLine());
  273. }
  274. }
  275. for (unsigned j = 0; j < serverNames.size(); ++j) {
  276. TTagGuard tr("tr");
  277. Td("server session");
  278. {
  279. TTagGuard td("td");
  280. ServerSessionLink(serverNames[j]);
  281. }
  282. {
  283. TTagGuard td("td");
  284. Pre(Outer->ServerSessions.FindByName(serverNames[j])->GetStatusSingleLine());
  285. }
  286. }
  287. for (unsigned j = 0; j < moduleNames.size(); ++j) {
  288. TTagGuard tr("tr");
  289. Td("module");
  290. {
  291. TTagGuard td("td");
  292. if (false) {
  293. OldModuleLink(moduleNames[j]);
  294. } else {
  295. // TODO
  296. Text(moduleNames[j]);
  297. }
  298. }
  299. {
  300. TTagGuard td("td");
  301. Pre(Outer->Modules.FindByName(moduleNames[j])->GetStatusSingleLine());
  302. }
  303. }
  304. }
  305. void ServeQueue(const TString& name) {
  306. TBusMessageQueuePtr queue = Outer->Queues.FindByName(name);
  307. if (!queue) {
  308. BootstrapError(ConcatStrings("queue not found by name: ", name));
  309. return;
  310. }
  311. BreadcrumbQueue(name);
  312. TDivGuard container("container");
  313. H1(ConcatStrings("MessageBus queue ", '"', name, '"'));
  314. TBusMessageQueueStatus status = queue->GetStatusRecordInternal();
  315. Pre(status.PrintToString());
  316. ServeSessionsOfQueue(queue, false);
  317. HnWithSmall(3, "Peak queue size", "(stored for an hour)");
  318. {
  319. TDivGuard div;
  320. TDivGuard div2(TAttr("id", "queue-size-graph"), TAttr("style", "height: 300px"));
  321. }
  322. {
  323. TScriptFunctionGuard script;
  324. NJsonWriter::TBuf data(NJsonWriter::HEM_ESCAPE_HTML);
  325. NJsonWriter::TBuf ticks(NJsonWriter::HEM_ESCAPE_HTML);
  326. const TExecutorHistory& history = status.ExecutorStatus.History;
  327. data.BeginList();
  328. ticks.BeginList();
  329. for (unsigned i = 0; i < history.HistoryRecords.size(); ++i) {
  330. ui64 secondOfMinute = (history.FirstHistoryRecordSecond() + i) % 60;
  331. ui64 minuteOfHour = (history.FirstHistoryRecordSecond() + i) / 60 % 60;
  332. unsigned printEach;
  333. if (history.HistoryRecords.size() <= 500) {
  334. printEach = 1;
  335. } else if (history.HistoryRecords.size() <= 1000) {
  336. printEach = 2;
  337. } else if (history.HistoryRecords.size() <= 3000) {
  338. printEach = 6;
  339. } else {
  340. printEach = 12;
  341. }
  342. if (secondOfMinute % printEach != 0) {
  343. continue;
  344. }
  345. ui32 max = 0;
  346. for (unsigned j = 0; j < printEach; ++j) {
  347. if (i < j) {
  348. continue;
  349. }
  350. max = Max<ui32>(max, history.HistoryRecords[i - j].MaxQueueSize);
  351. }
  352. data.BeginList();
  353. data.WriteString(ToString(i));
  354. data.WriteInt(max);
  355. data.EndList();
  356. // TODO: can be done with flot time plugin
  357. if (history.HistoryRecords.size() <= 20) {
  358. ticks.BeginList();
  359. ticks.WriteInt(i);
  360. ticks.WriteString(ToString(secondOfMinute));
  361. ticks.EndList();
  362. } else if (history.HistoryRecords.size() <= 60) {
  363. if (secondOfMinute % 5 == 0) {
  364. ticks.BeginList();
  365. ticks.WriteInt(i);
  366. ticks.WriteString(ToString(secondOfMinute));
  367. ticks.EndList();
  368. }
  369. } else {
  370. bool needTick;
  371. if (history.HistoryRecords.size() <= 3 * 60) {
  372. needTick = secondOfMinute % 15 == 0;
  373. } else if (history.HistoryRecords.size() <= 7 * 60) {
  374. needTick = secondOfMinute % 30 == 0;
  375. } else if (history.HistoryRecords.size() <= 20 * 60) {
  376. needTick = secondOfMinute == 0;
  377. } else {
  378. needTick = secondOfMinute == 0 && minuteOfHour % 5 == 0;
  379. }
  380. if (needTick) {
  381. ticks.BeginList();
  382. ticks.WriteInt(i);
  383. ticks.WriteString(Sprintf(":%02u:%02u", (unsigned)minuteOfHour, (unsigned)secondOfMinute));
  384. ticks.EndList();
  385. }
  386. }
  387. }
  388. ticks.EndList();
  389. data.EndList();
  390. HtmlOutputStream() << " var data = " << data.Str() << ";\n";
  391. HtmlOutputStream() << " var ticks = " << ticks.Str() << ";\n";
  392. HtmlOutputStream() << " plotQueueSize('#queue-size-graph', data, ticks);\n";
  393. }
  394. }
  395. void ServeSession(TStringBuf name, bool client) {
  396. TIntrusivePtr<TBusClientSession> clientSession;
  397. TIntrusivePtr<TBusServerSession> serverSession;
  398. TBusSession* session;
  399. TStringBuf whatSession;
  400. if (client) {
  401. whatSession = "client session";
  402. clientSession = Outer->ClientSessions.FindByName(name);
  403. session = clientSession.Get();
  404. } else {
  405. whatSession = "server session";
  406. serverSession = Outer->ServerSessions.FindByName(name);
  407. session = serverSession.Get();
  408. }
  409. if (!session) {
  410. BootstrapError(ConcatStrings(whatSession, " not found by name: ", name));
  411. return;
  412. }
  413. TSessionDumpStatus dumpStatus = session->GetStatusRecordInternal();
  414. TBusMessageQueuePtr queue = session->GetQueue();
  415. TString queueName = Outer->Queues.FindNameByPtr(session->GetQueue());
  416. BreadcrumbSession(name, client);
  417. TDivGuard container("container");
  418. H1(ConcatStrings("MessageBus ", whatSession, " ", '"', name, '"'));
  419. TBusMessageQueueStatus queueStatus = queue->GetStatusRecordInternal();
  420. {
  421. H3(ConcatStrings("queue ", queueName));
  422. Pre(queueStatus.PrintToString());
  423. }
  424. TSessionDumpStatus status = session->GetStatusRecordInternal();
  425. if (status.Shutdown) {
  426. BootstrapError("Session shut down");
  427. return;
  428. }
  429. H3("Basic");
  430. Pre(status.Head);
  431. if (status.ConnectionStatusSummary.Server) {
  432. H3("Acceptors");
  433. Pre(status.Acceptors);
  434. }
  435. H3("Connections");
  436. Pre(status.ConnectionsSummary);
  437. {
  438. TDivGuard div;
  439. TTagGuard button("button",
  440. TAttr("type", "button"),
  441. TAttr("class", "btn"),
  442. TAttr("data-toggle", "collapse"),
  443. TAttr("data-target", "#connections"));
  444. Text("Show connection details");
  445. }
  446. {
  447. TDivGuard div(TAttr("id", "connections"), TAttr("class", "collapse"));
  448. Pre(status.Connections);
  449. }
  450. H3("TBusSessionConfig");
  451. Pre(status.Config.PrintToString());
  452. if (!client) {
  453. H3("Message process time histogram");
  454. const TDurationHistogram& h =
  455. dumpStatus.ConnectionStatusSummary.WriterStatus.Incremental.ProcessDurationHistogram;
  456. {
  457. TDivGuard div;
  458. TDivGuard div2(TAttr("id", "h"), TAttr("style", "height: 300px"));
  459. }
  460. {
  461. TScriptFunctionGuard script;
  462. NJsonWriter::TBuf buf(NJsonWriter::HEM_ESCAPE_HTML);
  463. buf.BeginList();
  464. for (unsigned i = 0; i < h.Times.size(); ++i) {
  465. TString label = TDurationHistogram::LabelBefore(i);
  466. buf.BeginList();
  467. buf.WriteString(label);
  468. buf.WriteLongLong(h.Times[i]);
  469. buf.EndList();
  470. }
  471. buf.EndList();
  472. HtmlOutputStream() << " var hist = " << buf.Str() << ";\n";
  473. HtmlOutputStream() << " plotHist('#h', hist);\n";
  474. }
  475. }
  476. }
  477. void ServeDefault() {
  478. if (!Outer->Queues) {
  479. BootstrapError("no queues");
  480. return;
  481. }
  482. BreadcrumbRoot();
  483. TDivGuard container("container");
  484. H1("MessageBus queues");
  485. for (unsigned i = 0; i < Outer->Queues.size(); ++i) {
  486. TString queueName = Outer->Queues.Entries[i].first;
  487. TBusMessageQueuePtr queue = Outer->Queues.Entries[i].second;
  488. HnWithSmall(3, queueName, "(queue)");
  489. ServeSessionsOfQueue(queue, true);
  490. }
  491. }
  492. void WriteQueueSensors(NMonitoring::TDeprecatedJsonWriter& sj, TStringBuf queueName, TBusMessageQueue* queue) {
  493. auto status = queue->GetStatusRecordInternal();
  494. sj.OpenMetric();
  495. sj.WriteLabels("mb_queue", queueName, "sensor", "WorkQueueSize");
  496. sj.WriteValue(status.ExecutorStatus.WorkQueueSize);
  497. sj.CloseMetric();
  498. }
  499. void WriteMessageCounterSensors(NMonitoring::TDeprecatedJsonWriter& sj,
  500. TStringBuf labelName, TStringBuf sessionName, bool read, const TMessageCounter& counter) {
  501. TStringBuf readOrWrite = read ? "read" : "write";
  502. sj.OpenMetric();
  503. sj.WriteLabels(labelName, sessionName, "mb_dir", readOrWrite, "sensor", "MessageBytes");
  504. sj.WriteValue(counter.BytesData);
  505. sj.WriteModeDeriv();
  506. sj.CloseMetric();
  507. sj.OpenMetric();
  508. sj.WriteLabels(labelName, sessionName, "mb_dir", readOrWrite, "sensor", "MessageCount");
  509. sj.WriteValue(counter.Count);
  510. sj.WriteModeDeriv();
  511. sj.CloseMetric();
  512. }
  513. void WriteSessionStatus(NMonitoring::TDeprecatedJsonWriter& sj, TStringBuf sessionName, bool client,
  514. TBusSession* session) {
  515. TStringBuf labelName = client ? "mb_client_session" : "mb_server_session";
  516. auto status = session->GetStatusRecordInternal();
  517. sj.OpenMetric();
  518. sj.WriteLabels(labelName, sessionName, "sensor", "InFlightCount");
  519. sj.WriteValue(status.Status.InFlightCount);
  520. sj.CloseMetric();
  521. sj.OpenMetric();
  522. sj.WriteLabels(labelName, sessionName, "sensor", "InFlightSize");
  523. sj.WriteValue(status.Status.InFlightSize);
  524. sj.CloseMetric();
  525. sj.OpenMetric();
  526. sj.WriteLabels(labelName, sessionName, "sensor", "SendQueueSize");
  527. sj.WriteValue(status.ConnectionStatusSummary.WriterStatus.SendQueueSize);
  528. sj.CloseMetric();
  529. if (client) {
  530. sj.OpenMetric();
  531. sj.WriteLabels(labelName, sessionName, "sensor", "AckMessagesSize");
  532. sj.WriteValue(status.ConnectionStatusSummary.WriterStatus.AckMessagesSize);
  533. sj.CloseMetric();
  534. }
  535. WriteMessageCounterSensors(sj, labelName, sessionName, false,
  536. status.ConnectionStatusSummary.WriterStatus.Incremental.MessageCounter);
  537. WriteMessageCounterSensors(sj, labelName, sessionName, true,
  538. status.ConnectionStatusSummary.ReaderStatus.Incremental.MessageCounter);
  539. }
  540. void ServeSolomonJson(const TString& q, const TString& cs, const TString& ss) {
  541. Y_UNUSED(q);
  542. Y_UNUSED(cs);
  543. Y_UNUSED(ss);
  544. bool all = q == "" && cs == "" && ss == "";
  545. NMonitoring::TDeprecatedJsonWriter sj(&Os);
  546. sj.OpenDocument();
  547. sj.OpenMetrics();
  548. for (unsigned i = 0; i < Outer->Queues.size(); ++i) {
  549. TString queueName = Outer->Queues.Entries[i].first;
  550. TBusMessageQueuePtr queue = Outer->Queues.Entries[i].second;
  551. if (all || q == queueName) {
  552. WriteQueueSensors(sj, queueName, &*queue);
  553. }
  554. TVector<TString> clientNames = Outer->ClientSessions.GetNamesForQueue(queue.Get());
  555. TVector<TString> serverNames = Outer->ServerSessions.GetNamesForQueue(queue.Get());
  556. TVector<TString> moduleNames = Outer->Modules.GetNamesForQueue(queue.Get());
  557. for (auto& sessionName : clientNames) {
  558. if (all || cs == sessionName) {
  559. auto session = Outer->ClientSessions.FindByName(sessionName);
  560. WriteSessionStatus(sj, sessionName, true, &*session);
  561. }
  562. }
  563. for (auto& sessionName : serverNames) {
  564. if (all || ss == sessionName) {
  565. auto session = Outer->ServerSessions.FindByName(sessionName);
  566. WriteSessionStatus(sj, sessionName, false, &*session);
  567. }
  568. }
  569. }
  570. sj.CloseMetrics();
  571. sj.CloseDocument();
  572. }
  573. void ServeStatic(IOutputStream& os, TStringBuf path) {
  574. if (path.EndsWith(".js")) {
  575. os << HTTP_OK_JS;
  576. } else if (path.EndsWith(".png")) {
  577. os << HTTP_OK_PNG;
  578. } else {
  579. os << HTTP_OK_BIN;
  580. }
  581. auto blob = NResource::Find(TString("/") + TString(path));
  582. os.Write(blob.Data(), blob.Size());
  583. }
  584. void HeaderJsCss() {
  585. LinkStylesheet("//yandex.st/bootstrap/3.0.2/css/bootstrap.css");
  586. LinkFavicon("?file=bus-ico.png");
  587. ScriptHref("//yandex.st/jquery/2.0.3/jquery.js");
  588. ScriptHref("//yandex.st/bootstrap/3.0.2/js/bootstrap.js");
  589. ScriptHref("//cdnjs.cloudflare.com/ajax/libs/flot/0.8.1/jquery.flot.min.js");
  590. ScriptHref("//cdnjs.cloudflare.com/ajax/libs/flot/0.8.1/jquery.flot.categories.min.js");
  591. ScriptHref("?file=messagebus.js");
  592. }
  593. void Serve() {
  594. THtmlOutputStreamPushPop pp(&Os);
  595. TCgiParameters::const_iterator file = CgiParams.Find("file");
  596. if (file != CgiParams.end()) {
  597. ServeStatic(Os, file->second);
  598. return;
  599. }
  600. bool solomonJson = false;
  601. TCgiParameters::const_iterator fmt = CgiParams.Find("fmt");
  602. if (fmt != CgiParams.end()) {
  603. if (fmt->second == "solomon-json") {
  604. solomonJson = true;
  605. }
  606. }
  607. TCgiParameters::const_iterator cs = CgiParams.Find("cs");
  608. TCgiParameters::const_iterator ss = CgiParams.Find("ss");
  609. TCgiParameters::const_iterator q = CgiParams.Find("q");
  610. if (solomonJson) {
  611. Os << HTTP_OK_JSON;
  612. TString qp = q != CgiParams.end() ? q->first : "";
  613. TString csp = cs != CgiParams.end() ? cs->first : "";
  614. TString ssp = ss != CgiParams.end() ? ss->first : "";
  615. ServeSolomonJson(qp, csp, ssp);
  616. } else {
  617. Os << HTTP_OK_HTML;
  618. Doctype();
  619. TTagGuard html("html");
  620. {
  621. TTagGuard head("head");
  622. HeaderJsCss();
  623. // &#x2709; &#x1f68c;
  624. Title(TChars("MessageBus", false));
  625. }
  626. TTagGuard body("body");
  627. if (cs != CgiParams.end()) {
  628. ServeSession(cs->second, true);
  629. } else if (ss != CgiParams.end()) {
  630. ServeSession(ss->second, false);
  631. } else if (q != CgiParams.end()) {
  632. ServeQueue(q->second);
  633. } else {
  634. ServeDefault();
  635. }
  636. }
  637. }
  638. };
  639. void ServeHttp(IOutputStream& os, const TCgiParameters& queryArgs, const TBusWww::TOptionalParams& params) {
  640. TGuard<TMutex> g(Mutex);
  641. TRequest request(this, os, queryArgs, params);
  642. request.Serve();
  643. }
  644. };
  645. NBus::TBusWww::TBusWww()
  646. : Impl(new TImpl)
  647. {
  648. }
  649. NBus::TBusWww::~TBusWww() {
  650. }
  651. void NBus::TBusWww::RegisterClientSession(TBusClientSessionPtr s) {
  652. Impl->RegisterClientSession(s);
  653. }
  654. void TBusWww::RegisterServerSession(TBusServerSessionPtr s) {
  655. Impl->RegisterServerSession(s);
  656. }
  657. void TBusWww::RegisterQueue(TBusMessageQueuePtr q) {
  658. Impl->RegisterQueue(q);
  659. }
  660. void TBusWww::RegisterModule(TBusModule* module) {
  661. Impl->RegisterModule(module);
  662. }
  663. void TBusWww::ServeHttp(IOutputStream& httpOutputStream,
  664. const TCgiParameters& queryArgs,
  665. const TBusWww::TOptionalParams& params) {
  666. Impl->ServeHttp(httpOutputStream, queryArgs, params);
  667. }
  668. struct TBusWwwHttpServer::TImpl: public THttpServer::ICallBack {
  669. TIntrusivePtr<TBusWww> Www;
  670. THttpServer HttpServer;
  671. static THttpServer::TOptions MakeHttpServerOptions(unsigned port) {
  672. Y_ABORT_UNLESS(port > 0);
  673. THttpServer::TOptions r;
  674. r.Port = port;
  675. return r;
  676. }
  677. TImpl(TIntrusivePtr<TBusWww> www, unsigned port)
  678. : Www(www)
  679. , HttpServer(this, MakeHttpServerOptions(port))
  680. {
  681. HttpServer.Start();
  682. }
  683. struct TClientRequestImpl: public TClientRequest {
  684. TBusWwwHttpServer::TImpl* const Outer;
  685. TClientRequestImpl(TBusWwwHttpServer::TImpl* outer)
  686. : Outer(outer)
  687. {
  688. }
  689. bool Reply(void*) override {
  690. Outer->ServeRequest(Input(), Output());
  691. return true;
  692. }
  693. };
  694. TString MakeSimpleResponse(unsigned code, TString text, TString content = "") {
  695. if (!content) {
  696. TStringStream contentSs;
  697. contentSs << code << " " << text;
  698. content = contentSs.Str();
  699. }
  700. TStringStream ss;
  701. ss << "HTTP/1.1 "
  702. << code << " " << text << "\r\nConnection: Close\r\n\r\n"
  703. << content;
  704. return ss.Str();
  705. }
  706. void ServeRequest(THttpInput& input, THttpOutput& output) {
  707. TCgiParameters cgiParams;
  708. try {
  709. THttpRequestHeader header;
  710. THttpHeaderParser parser;
  711. parser.Init(&header);
  712. if (parser.Execute(input.FirstLine()) < 0) {
  713. HtmlOutputStream() << MakeSimpleResponse(400, "Bad request");
  714. return;
  715. }
  716. THttpURL url;
  717. if (url.Parse(header.GetUrl()) != THttpURL::ParsedOK) {
  718. HtmlOutputStream() << MakeSimpleResponse(400, "Invalid url");
  719. return;
  720. }
  721. cgiParams.Scan(url.Get(THttpURL::FieldQuery));
  722. TBusWww::TOptionalParams params;
  723. //params.ParentLinks.emplace_back();
  724. //params.ParentLinks.back().Title = "temp";
  725. //params.ParentLinks.back().Href = "http://wiki.yandex-team.ru/";
  726. Www->ServeHttp(output, cgiParams, params);
  727. } catch (...) {
  728. output << MakeSimpleResponse(500, "Exception",
  729. TString() + "Exception: " + CurrentExceptionMessage());
  730. }
  731. }
  732. TClientRequest* CreateClient() override {
  733. return new TClientRequestImpl(this);
  734. }
  735. ~TImpl() override {
  736. HttpServer.Stop();
  737. }
  738. };
  739. NBus::TBusWwwHttpServer::TBusWwwHttpServer(TIntrusivePtr<TBusWww> www, unsigned port)
  740. : Impl(new TImpl(www, port))
  741. {
  742. }
  743. NBus::TBusWwwHttpServer::~TBusWwwHttpServer() {
  744. }