Stat.cs 12 KB

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