Stat.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.Generic;
  29. using System.Text;
  30. using OpenMetaverse.StructuredData;
  31. namespace OpenSim.Framework.Monitoring
  32. {
  33. /// <summary>
  34. /// Holds individual statistic details
  35. /// </summary>
  36. public class Stat: IDisposable
  37. {
  38. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. public static readonly char[] DisallowedShortNameCharacters = { '.' };
  40. /// <summary>
  41. /// Category of this stat (e.g. cache, scene, etc).
  42. /// </summary>
  43. public string Category { get; private set; }
  44. /// <summary>
  45. /// Containing name for this stat.
  46. /// FIXME: In the case of a scene, this is currently the scene name (though this leaves
  47. /// us with a to-be-resolved problem of non-unique region names).
  48. /// </summary>
  49. /// <value>
  50. /// The container.
  51. /// </value>
  52. public string Container { get; private set; }
  53. public StatType StatType { get; private set; }
  54. public MeasuresOfInterest MeasuresOfInterest { get; private set; }
  55. /// <summary>
  56. /// Action used to update this stat when the value is requested if it's a pull type.
  57. /// </summary>
  58. public Action<Stat> PullAction { get; private set; }
  59. public StatVerbosity Verbosity { get; private set; }
  60. public string ShortName { get; private set; }
  61. public string Name { get; private set; }
  62. public string Description { get; private set; }
  63. public virtual string UnitName { get; private set; }
  64. public virtual double Value
  65. {
  66. get
  67. {
  68. // Asking for an update here means that the updater cannot access this value without infinite recursion.
  69. // XXX: A slightly messy but simple solution may be to flick a flag so we can tell if this is being
  70. // called by the pull action and just return the value.
  71. try
  72. {
  73. if (StatType == StatType.Pull)
  74. PullAction(this);
  75. return m_value;
  76. }
  77. catch
  78. {
  79. return 0;
  80. }
  81. }
  82. set
  83. {
  84. m_value = value;
  85. }
  86. }
  87. private double m_value;
  88. /// <summary>
  89. /// Historical samples for calculating measures of interest average.
  90. /// </summary>
  91. /// <remarks>
  92. /// Will be null if no measures of interest require samples.
  93. /// </remarks>
  94. private Queue<double> m_samples;
  95. /// <summary>
  96. /// Maximum number of statistical samples.
  97. /// </summary>
  98. /// <remarks>
  99. /// At the moment this corresponds to 1 minute since the sampling rate is every 2.5 seconds as triggered from
  100. /// the main Watchdog.
  101. /// </remarks>
  102. private static int m_maxSamples = 24;
  103. public Stat(
  104. string shortName,
  105. string name,
  106. string description,
  107. string unitName,
  108. string category,
  109. string container,
  110. StatType type,
  111. Action<Stat> pullAction,
  112. StatVerbosity verbosity)
  113. : this(
  114. shortName,
  115. name,
  116. description,
  117. unitName,
  118. category,
  119. container,
  120. type,
  121. MeasuresOfInterest.None,
  122. pullAction,
  123. verbosity)
  124. {
  125. }
  126. /// <summary>
  127. /// Constructor
  128. /// </summary>
  129. /// <param name='shortName'>Short name for the stat. Must not contain spaces. e.g. "LongFrames"</param>
  130. /// <param name='name'>Human readable name for the stat. e.g. "Long frames"</param>
  131. /// <param name='description'>Description of stat</param>
  132. /// <param name='unitName'>
  133. /// Unit name for the stat. Should be preceeded by a space if the unit name isn't normally appeneded immediately to the value.
  134. /// e.g. " frames"
  135. /// </param>
  136. /// <param name='category'>Category under which this stat should appear, e.g. "scene". Do not capitalize.</param>
  137. /// <param name='container'>Entity to which this stat relates. e.g. scene name if this is a per scene stat.</param>
  138. /// <param name='type'>Push or pull</param>
  139. /// <param name='pullAction'>Pull stats need an action to update the stat on request. Push stats should set null here.</param>
  140. /// <param name='moi'>Measures of interest</param>
  141. /// <param name='verbosity'>Verbosity of stat. Controls whether it will appear in short stat display or only full display.</param>
  142. public Stat(
  143. string shortName,
  144. string name,
  145. string description,
  146. string unitName,
  147. string category,
  148. string container,
  149. StatType type,
  150. MeasuresOfInterest moi,
  151. Action<Stat> pullAction,
  152. StatVerbosity verbosity)
  153. {
  154. if (StatsManager.SubCommands.Contains(category))
  155. throw new Exception(
  156. string.Format("Stat cannot be in category '{0}' since this is reserved for a subcommand", category));
  157. foreach (char c in DisallowedShortNameCharacters)
  158. {
  159. if (shortName.IndexOf(c) != -1)
  160. shortName = shortName.Replace(c, '#');
  161. // throw new Exception(string.Format("Stat name {0} cannot contain character {1}", shortName, c));
  162. }
  163. ShortName = shortName;
  164. Name = name;
  165. Description = description;
  166. UnitName = unitName;
  167. Category = category;
  168. Container = container;
  169. StatType = type;
  170. if (StatType == StatType.Push && pullAction != null)
  171. throw new Exception("A push stat cannot have a pull action");
  172. else
  173. PullAction = pullAction;
  174. MeasuresOfInterest = moi;
  175. if ((moi & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
  176. m_samples = new Queue<double>(m_maxSamples);
  177. Verbosity = verbosity;
  178. }
  179. ~Stat()
  180. {
  181. Dispose(false);
  182. }
  183. public void Dispose()
  184. {
  185. Dispose(true);
  186. GC.SuppressFinalize(this);
  187. }
  188. private void Dispose(bool disposing)
  189. {
  190. PullAction = null;
  191. return;
  192. }
  193. /// <summary>
  194. /// Record a value in the sample set.
  195. /// </summary>
  196. /// <remarks>
  197. /// Do not call this if MeasuresOfInterest.None
  198. /// </remarks>
  199. public void RecordValue()
  200. {
  201. double newValue = Value;
  202. lock (m_samples)
  203. {
  204. if (m_samples.Count >= m_maxSamples)
  205. m_samples.Dequeue();
  206. // m_log.DebugFormat("[STAT]: Recording value {0} for {1}", newValue, Name);
  207. m_samples.Enqueue(newValue);
  208. }
  209. }
  210. public virtual string ToConsoleString()
  211. {
  212. StringBuilder sb = new StringBuilder();
  213. if(string.IsNullOrEmpty(UnitName))
  214. {
  215. sb.AppendFormat(
  216. "{0}.{1}.{2} : {3:0.###}",
  217. Category,
  218. Container,
  219. ShortName,
  220. Value);
  221. }
  222. else
  223. {
  224. sb.AppendFormat(
  225. "{0}.{1}.{2} : {3:0.###} {4}",
  226. Category,
  227. Container,
  228. ShortName,
  229. Value,
  230. UnitName);
  231. }
  232. AppendMeasuresOfInterest(sb);
  233. return sb.ToString();
  234. }
  235. public virtual OSDMap ToBriefOSDMap()
  236. {
  237. OSDMap ret = new OSDMap();
  238. ret.Add("Value", OSD.FromReal(Value));
  239. return ret;
  240. }
  241. public virtual OSDMap ToOSDMap()
  242. {
  243. OSDMap ret = new OSDMap();
  244. ret.Add("StatType", "Stat"); // used by overloading classes to denote type of stat
  245. ret.Add("Category", OSD.FromString(Category));
  246. ret.Add("Container", OSD.FromString(Container));
  247. ret.Add("ShortName", OSD.FromString(ShortName));
  248. ret.Add("Name", OSD.FromString(Name));
  249. ret.Add("Description", OSD.FromString(Description));
  250. ret.Add("UnitName", OSD.FromString(UnitName));
  251. ret.Add("Value", OSD.FromReal(Value));
  252. double lastChangeOverTime, averageChangeOverTime;
  253. if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
  254. {
  255. ret.Add("LastChangeOverTime", OSD.FromReal(lastChangeOverTime));
  256. ret.Add("AverageChangeOverTime", OSD.FromReal(averageChangeOverTime));
  257. }
  258. return ret;
  259. }
  260. // Compute the averages over time and return same.
  261. // Return 'true' if averages were actually computed. 'false' if no average info.
  262. public bool ComputeMeasuresOfInterest(out double lastChangeOverTime, out double averageChangeOverTime)
  263. {
  264. bool ret = false;
  265. lastChangeOverTime = 0;
  266. averageChangeOverTime = 0;
  267. if ((MeasuresOfInterest & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
  268. {
  269. double totalChange = 0;
  270. double? penultimateSample = null;
  271. double? lastSample = null;
  272. lock (m_samples)
  273. {
  274. //m_log.DebugFormat(
  275. // "[STAT]: Samples for {0} are {1}",
  276. // Name, string.Join(",", m_samples.Select(s => s.ToString()).ToArray()));
  277. foreach (double s in m_samples)
  278. {
  279. if (lastSample != null)
  280. totalChange += s - (double)lastSample;
  281. penultimateSample = lastSample;
  282. lastSample = s;
  283. }
  284. }
  285. if (lastSample != null && penultimateSample != null)
  286. {
  287. lastChangeOverTime = ((double)lastSample - (double)penultimateSample) / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
  288. }
  289. int divisor = m_samples.Count <= 1 ? 1 : m_samples.Count - 1;
  290. averageChangeOverTime = totalChange / divisor / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
  291. ret = true;
  292. }
  293. return ret;
  294. }
  295. protected void AppendMeasuresOfInterest(StringBuilder sb)
  296. {
  297. double lastChangeOverTime = 0;
  298. double averageChangeOverTime = 0;
  299. if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
  300. {
  301. if(string.IsNullOrEmpty(UnitName))
  302. {
  303. sb.AppendFormat(
  304. ", {0:0.###}/s, {1:0.###}/s",
  305. lastChangeOverTime,
  306. averageChangeOverTime);
  307. }
  308. else
  309. {
  310. sb.AppendFormat(
  311. ", {0:0.###} {1}/s, {2:0.###} {3}/s",
  312. lastChangeOverTime, UnitName,
  313. averageChangeOverTime, UnitName);
  314. }
  315. }
  316. }
  317. }
  318. }