1
0

StatsManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Diagnostics;
  31. using System.Linq;
  32. using System.Text;
  33. using OpenSim.Framework;
  34. using OpenMetaverse.StructuredData;
  35. namespace OpenSim.Framework.Monitoring
  36. {
  37. /// <summary>
  38. /// Static class used to register/deregister/fetch statistics
  39. /// </summary>
  40. public static class StatsManager
  41. {
  42. // Subcommand used to list other stats.
  43. public const string AllSubCommand = "all";
  44. // Subcommand used to list other stats.
  45. public const string ListSubCommand = "list";
  46. public static string StatsPassword { get; set; }
  47. // All subcommands
  48. public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand };
  49. /// <summary>
  50. /// Registered stats categorized by category/container/shortname
  51. /// </summary>
  52. /// <remarks>
  53. /// Do not add or remove directly from this dictionary.
  54. /// </remarks>
  55. public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats
  56. = new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>();
  57. // private static AssetStatsCollector assetStats;
  58. // private static UserStatsCollector userStats;
  59. // private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector();
  60. // public static AssetStatsCollector AssetStats { get { return assetStats; } }
  61. // public static UserStatsCollector UserStats { get { return userStats; } }
  62. public static SimExtraStatsCollector SimExtraStats { get; set; }
  63. public static void RegisterConsoleCommands(ICommandConsole console)
  64. {
  65. console.Commands.AddCommand(
  66. "General",
  67. false,
  68. "stats show",
  69. "stats show [list|all|(<category>[.<container>])+",
  70. "Show statistical information for this server",
  71. "If no final argument is specified then legacy statistics information is currently shown.\n"
  72. + "'list' argument will show statistic categories.\n"
  73. + "'all' will show all statistics.\n"
  74. + "A <category> name will show statistics from that category.\n"
  75. + "A <category>.<container> name will show statistics from that category in that container.\n"
  76. + "More than one name can be given separated by spaces.\n",
  77. HandleShowStatsCommand);
  78. console.Commands.AddCommand(
  79. "General",
  80. false,
  81. "show stats",
  82. "show stats [list|all|(<category>[.<container>])+",
  83. "Alias for 'stats show' command",
  84. HandleShowStatsCommand);
  85. StatsLogger.RegisterConsoleCommands(console);
  86. }
  87. public static void HandleShowStatsCommand(string module, string[] cmd)
  88. {
  89. ICommandConsole con = MainConsole.Instance;
  90. if (cmd.Length > 2)
  91. {
  92. foreach (string name in cmd.Skip(2))
  93. {
  94. string[] components = name.Split('.');
  95. string categoryName = components[0];
  96. string containerName = components.Length > 1 ? components[1] : null;
  97. string statName = components.Length > 2 ? components[2] : null;
  98. if (categoryName == AllSubCommand)
  99. {
  100. OutputAllStatsToConsole(con);
  101. }
  102. else if (categoryName == ListSubCommand)
  103. {
  104. con.Output("Statistic categories available are:");
  105. foreach (string category in RegisteredStats.Keys)
  106. con.Output(" {0}", category);
  107. }
  108. else
  109. {
  110. SortedDictionary<string, SortedDictionary<string, Stat>> category;
  111. if (!RegisteredStats.TryGetValue(categoryName, out category))
  112. {
  113. con.Output("No such category as {0}", categoryName);
  114. }
  115. else
  116. {
  117. if (String.IsNullOrEmpty(containerName))
  118. {
  119. OutputCategoryStatsToConsole(con, category);
  120. }
  121. else
  122. {
  123. SortedDictionary<string, Stat> container;
  124. if (category.TryGetValue(containerName, out container))
  125. {
  126. if (String.IsNullOrEmpty(statName))
  127. {
  128. OutputContainerStatsToConsole(con, container);
  129. }
  130. else
  131. {
  132. Stat stat;
  133. if (container.TryGetValue(statName, out stat))
  134. {
  135. OutputStatToConsole(con, stat);
  136. }
  137. else
  138. {
  139. con.Output(
  140. "No such stat {0} in {1}.{2}", statName, categoryName, containerName);
  141. }
  142. }
  143. }
  144. else
  145. {
  146. con.Output("No such container {0} in category {1}", containerName, categoryName);
  147. }
  148. }
  149. }
  150. }
  151. }
  152. }
  153. else
  154. {
  155. // Legacy
  156. if (SimExtraStats != null)
  157. con.Output(SimExtraStats.Report(con.ConsoleScene));
  158. else
  159. OutputAllStatsToConsole(con);
  160. }
  161. }
  162. public static List<string> GetAllStatsReports()
  163. {
  164. List<string> reports = new List<string>();
  165. foreach (var category in RegisteredStats.Values)
  166. reports.AddRange(GetCategoryStatsReports(category));
  167. return reports;
  168. }
  169. private static void OutputAllStatsToConsole(ICommandConsole con)
  170. {
  171. foreach (string report in GetAllStatsReports())
  172. con.Output(report);
  173. con.Output(MemoryReport());
  174. }
  175. private static string MemoryReport()
  176. {
  177. StringBuilder sb = new StringBuilder(Environment.NewLine);
  178. sb.AppendFormat(
  179. "Heap allocated: {0}MB \t allocation rate (last/avg): {1}/{2}MB/s\n",
  180. Math.Round(GC.GetTotalMemory(false) / 1024.0 / 1024.0),
  181. Math.Round((MemoryWatchdog.LastHeapAllocationRate * 1000) / 1048576.0, 3),
  182. Math.Round((MemoryWatchdog.AverageHeapAllocationRate * 1000) / 1048576.0, 3));
  183. GCMemoryInfo gcmem = GC.GetGCMemoryInfo();
  184. sb.AppendFormat(
  185. "GCTotalCommited: {0}MB \t GCTotalAvaiable {1}MB \t GCHMthreshold {2}MB\n",
  186. Math.Round(gcmem.TotalCommittedBytes / 1024.0 / 1024.0),
  187. Math.Round(gcmem.TotalAvailableMemoryBytes / 1024.0 / 1024.0),
  188. Math.Round(gcmem.HighMemoryLoadThresholdBytes / 1024.0 / 1024.0));
  189. try
  190. {
  191. using (Process myprocess = Process.GetCurrentProcess())
  192. {
  193. sb.AppendFormat(
  194. "Process memory: Physical {0}MB \t Paged {1}MB\n",
  195. Math.Round(myprocess.WorkingSet64 / 1024.0 / 1024.0),
  196. Math.Round(myprocess.PagedMemorySize64 / 1024.0 / 1024.0));
  197. sb.AppendFormat(
  198. "Peak process memory: Physical {0}MB \t Paged {1}MB \t\n",
  199. Math.Round(myprocess.PeakWorkingSet64 / 1024.0 / 1024.0),
  200. Math.Round(myprocess.PeakPagedMemorySize64 / 1024.0 / 1024.0));
  201. sb.AppendFormat("\nTotal process Threads {0}\n", myprocess.Threads.Count);
  202. }
  203. }
  204. catch
  205. { }
  206. return sb.ToString();
  207. }
  208. private static List<string> GetCategoryStatsReports(
  209. SortedDictionary<string, SortedDictionary<string, Stat>> category)
  210. {
  211. List<string> reports = new List<string>();
  212. foreach (var container in category.Values)
  213. reports.AddRange(GetContainerStatsReports(container));
  214. return reports;
  215. }
  216. private static void OutputCategoryStatsToConsole(
  217. ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category)
  218. {
  219. foreach (string report in GetCategoryStatsReports(category))
  220. con.Output(report);
  221. }
  222. private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container)
  223. {
  224. List<string> reports = new List<string>();
  225. foreach (Stat stat in container.Values)
  226. reports.Add(stat.ToConsoleString());
  227. return reports;
  228. }
  229. private static void OutputContainerStatsToConsole(
  230. ICommandConsole con, SortedDictionary<string, Stat> container)
  231. {
  232. foreach (string report in GetContainerStatsReports(container))
  233. con.Output(report);
  234. }
  235. private static void OutputStatToConsole(ICommandConsole con, Stat stat)
  236. {
  237. con.Output(stat.ToConsoleString());
  238. }
  239. // Creates an OSDMap of the format:
  240. // { categoryName: {
  241. // containerName: {
  242. // statName: {
  243. // "Name": name,
  244. // "ShortName": shortName,
  245. // ...
  246. // },
  247. // statName: {
  248. // "Name": name,
  249. // "ShortName": shortName,
  250. // ...
  251. // },
  252. // ...
  253. // },
  254. // containerName: {
  255. // ...
  256. // },
  257. // ...
  258. // },
  259. // categoryName: {
  260. // ...
  261. // },
  262. // ...
  263. // }
  264. // The passed in parameters will filter the categories, containers and stats returned. If any of the
  265. // parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned.
  266. // Case matters.
  267. public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName)
  268. {
  269. OSDMap map = new OSDMap();
  270. lock (RegisteredStats)
  271. {
  272. foreach (string catName in RegisteredStats.Keys)
  273. {
  274. // Do this category if null spec, "all" subcommand or category name matches passed parameter.
  275. // Skip category if none of the above.
  276. if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName))
  277. continue;
  278. OSDMap contMap = new OSDMap();
  279. foreach (string contName in RegisteredStats[catName].Keys)
  280. {
  281. if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName))
  282. continue;
  283. OSDMap statMap = new OSDMap();
  284. SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName];
  285. foreach (string statName in theStats.Keys)
  286. {
  287. if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName))
  288. continue;
  289. statMap.Add(statName, theStats[statName].ToBriefOSDMap());
  290. }
  291. contMap.Add(contName, statMap);
  292. }
  293. map.Add(catName, contMap);
  294. }
  295. }
  296. return map;
  297. }
  298. public static Hashtable HandleStatsRequest(Hashtable request)
  299. {
  300. Hashtable responsedata = new Hashtable();
  301. // string regpath = request["uri"].ToString();
  302. int response_code = 200;
  303. string contenttype = "text/json";
  304. if (StatsPassword != String.Empty && (!request.ContainsKey("pass") || request["pass"].ToString() != StatsPassword))
  305. {
  306. responsedata["int_response_code"] = response_code;
  307. responsedata["content_type"] = "text/plain";
  308. responsedata["keepalive"] = false;
  309. responsedata["str_response_string"] = "Access denied";
  310. responsedata["access_control_allow_origin"] = "*";
  311. return responsedata;
  312. }
  313. string pCategoryName = StatsManager.AllSubCommand;
  314. string pContainerName = StatsManager.AllSubCommand;
  315. string pStatName = StatsManager.AllSubCommand;
  316. if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString();
  317. if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString();
  318. if (request.ContainsKey("stat")) pStatName = request["stat"].ToString();
  319. string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString();
  320. // If requestor wants it as a callback function, build response as a function rather than just the JSON string.
  321. if (request.ContainsKey("callback"))
  322. {
  323. strOut = request["callback"].ToString() + "(" + strOut + ");";
  324. }
  325. // m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}",
  326. // LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut);
  327. responsedata["int_response_code"] = response_code;
  328. responsedata["content_type"] = contenttype;
  329. responsedata["keepalive"] = false;
  330. responsedata["str_response_string"] = strOut;
  331. responsedata["access_control_allow_origin"] = "*";
  332. return responsedata;
  333. }
  334. // /// <summary>
  335. // /// Start collecting statistics related to assets.
  336. // /// Should only be called once.
  337. // /// </summary>
  338. // public static AssetStatsCollector StartCollectingAssetStats()
  339. // {
  340. // assetStats = new AssetStatsCollector();
  341. //
  342. // return assetStats;
  343. // }
  344. //
  345. // /// <summary>
  346. // /// Start collecting statistics related to users.
  347. // /// Should only be called once.
  348. // /// </summary>
  349. // public static UserStatsCollector StartCollectingUserStats()
  350. // {
  351. // userStats = new UserStatsCollector();
  352. //
  353. // return userStats;
  354. // }
  355. /// <summary>
  356. /// Register a statistic.
  357. /// </summary>
  358. /// <param name='stat'></param>
  359. /// <returns></returns>
  360. public static bool RegisterStat(Stat stat)
  361. {
  362. SortedDictionary<string, SortedDictionary<string, Stat>> category = null;
  363. SortedDictionary<string, Stat> container = null;
  364. lock (RegisteredStats)
  365. {
  366. // Stat name is not unique across category/container/shortname key.
  367. // XXX: For now just return false. This is to avoid problems in regression tests where all tests
  368. // in a class are run in the same instance of the VM.
  369. if (TryGetStatParents(stat, out category, out container))
  370. return false;
  371. if (container == null)
  372. container = new SortedDictionary<string, Stat>();
  373. if (category == null)
  374. category = new SortedDictionary<string, SortedDictionary<string, Stat>>();
  375. container[stat.ShortName] = stat;
  376. category[stat.Container] = container;
  377. RegisteredStats[stat.Category] = category;
  378. }
  379. return true;
  380. }
  381. /// <summary>
  382. /// Deregister a statistic
  383. /// </summary>>
  384. /// <param name='stat'></param>
  385. /// <returns></returns>
  386. public static bool DeregisterStat(Stat stat)
  387. {
  388. SortedDictionary<string, SortedDictionary<string, Stat>> category = null;
  389. SortedDictionary<string, Stat> container = null;
  390. lock (RegisteredStats)
  391. {
  392. if (!TryGetStatParents(stat, out category, out container))
  393. return false;
  394. if(container != null)
  395. {
  396. container.Remove(stat.ShortName);
  397. if(category != null && container.Count == 0)
  398. {
  399. category.Remove(stat.Container);
  400. if(category.Count == 0)
  401. RegisteredStats.Remove(stat.Category);
  402. }
  403. }
  404. stat.Dispose();
  405. return true;
  406. }
  407. }
  408. public static bool TryGetStat(string category, string container, string statShortName, out Stat stat)
  409. {
  410. stat = null;
  411. SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
  412. lock (RegisteredStats)
  413. {
  414. if (!TryGetStatsForCategory(category, out categoryStats))
  415. return false;
  416. SortedDictionary<string, Stat> containerStats;
  417. if (!categoryStats.TryGetValue(container, out containerStats))
  418. return false;
  419. return containerStats.TryGetValue(statShortName, out stat);
  420. }
  421. }
  422. public static bool TryGetStatsForCategory(
  423. string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats)
  424. {
  425. lock (RegisteredStats)
  426. return RegisteredStats.TryGetValue(category, out stats);
  427. }
  428. /// <summary>
  429. /// Get the same stat for each container in a given category.
  430. /// </summary>
  431. /// <returns>
  432. /// The stats if there were any to fetch. Otherwise null.
  433. /// </returns>
  434. /// <param name='category'></param>
  435. /// <param name='statShortName'></param>
  436. public static List<Stat> GetStatsFromEachContainer(string category, string statShortName)
  437. {
  438. SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats;
  439. lock (RegisteredStats)
  440. {
  441. if (!RegisteredStats.TryGetValue(category, out categoryStats))
  442. return null;
  443. List<Stat> stats = null;
  444. foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values)
  445. {
  446. if (containerStats.ContainsKey(statShortName))
  447. {
  448. if (stats == null)
  449. stats = new List<Stat>();
  450. stats.Add(containerStats[statShortName]);
  451. }
  452. }
  453. return stats;
  454. }
  455. }
  456. public static bool TryGetStatParents(
  457. Stat stat,
  458. out SortedDictionary<string, SortedDictionary<string, Stat>> category,
  459. out SortedDictionary<string, Stat> container)
  460. {
  461. category = null;
  462. container = null;
  463. lock (RegisteredStats)
  464. {
  465. if (RegisteredStats.TryGetValue(stat.Category, out category))
  466. {
  467. if (category.TryGetValue(stat.Container, out container))
  468. {
  469. if (container.ContainsKey(stat.ShortName))
  470. return true;
  471. }
  472. }
  473. }
  474. return false;
  475. }
  476. public static void RecordStats()
  477. {
  478. lock (RegisteredStats)
  479. {
  480. foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values)
  481. {
  482. foreach (SortedDictionary<string, Stat> container in category.Values)
  483. {
  484. foreach (Stat stat in container.Values)
  485. {
  486. if (stat.MeasuresOfInterest != MeasuresOfInterest.None)
  487. stat.RecordValue();
  488. }
  489. }
  490. }
  491. }
  492. }
  493. }
  494. /// <summary>
  495. /// Stat type.
  496. /// </summary>
  497. /// <remarks>
  498. /// A push stat is one which is continually updated and so it's value can simply by read.
  499. /// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated.
  500. /// </remarks>
  501. public enum StatType
  502. {
  503. Push,
  504. Pull
  505. }
  506. /// <summary>
  507. /// Measures of interest for this stat.
  508. /// </summary>
  509. [Flags]
  510. public enum MeasuresOfInterest
  511. {
  512. None,
  513. AverageChangeOverTime
  514. }
  515. /// <summary>
  516. /// Verbosity of stat.
  517. /// </summary>
  518. /// <remarks>
  519. /// Info will always be displayed.
  520. /// </remarks>
  521. public enum StatVerbosity
  522. {
  523. Debug,
  524. Info
  525. }
  526. }