Stat.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. shortName = shortName.Replace(c, '#');
  157. // throw new Exception(string.Format("Stat name {0} cannot contain character {1}", shortName, c));
  158. }
  159. ShortName = shortName;
  160. Name = name;
  161. Description = description;
  162. UnitName = unitName;
  163. Category = category;
  164. Container = container;
  165. StatType = type;
  166. if (StatType == StatType.Push && pullAction != null)
  167. throw new Exception("A push stat cannot have a pull action");
  168. else
  169. PullAction = pullAction;
  170. MeasuresOfInterest = moi;
  171. if ((moi & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
  172. m_samples = new Queue<double>(m_maxSamples);
  173. Verbosity = verbosity;
  174. }
  175. // IDisposable.Dispose()
  176. public virtual void Dispose()
  177. {
  178. return;
  179. }
  180. /// <summary>
  181. /// Record a value in the sample set.
  182. /// </summary>
  183. /// <remarks>
  184. /// Do not call this if MeasuresOfInterest.None
  185. /// </remarks>
  186. public void RecordValue()
  187. {
  188. double newValue = Value;
  189. lock (m_samples)
  190. {
  191. if (m_samples.Count >= m_maxSamples)
  192. m_samples.Dequeue();
  193. // m_log.DebugFormat("[STAT]: Recording value {0} for {1}", newValue, Name);
  194. m_samples.Enqueue(newValue);
  195. }
  196. }
  197. public virtual string ToConsoleString()
  198. {
  199. StringBuilder sb = new StringBuilder();
  200. sb.AppendFormat(
  201. "{0}.{1}.{2} : {3}{4}",
  202. Category,
  203. Container,
  204. ShortName,
  205. Value,
  206. string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName));
  207. AppendMeasuresOfInterest(sb);
  208. return sb.ToString();
  209. }
  210. public virtual OSDMap ToOSDMap()
  211. {
  212. OSDMap ret = new OSDMap();
  213. ret.Add("StatType", "Stat"); // used by overloading classes to denote type of stat
  214. ret.Add("Category", OSD.FromString(Category));
  215. ret.Add("Container", OSD.FromString(Container));
  216. ret.Add("ShortName", OSD.FromString(ShortName));
  217. ret.Add("Name", OSD.FromString(Name));
  218. ret.Add("Description", OSD.FromString(Description));
  219. ret.Add("UnitName", OSD.FromString(UnitName));
  220. ret.Add("Value", OSD.FromReal(Value));
  221. double lastChangeOverTime, averageChangeOverTime;
  222. if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
  223. {
  224. ret.Add("LastChangeOverTime", OSD.FromReal(lastChangeOverTime));
  225. ret.Add("AverageChangeOverTime", OSD.FromReal(averageChangeOverTime));
  226. }
  227. return ret;
  228. }
  229. // Compute the averages over time and return same.
  230. // Return 'true' if averages were actually computed. 'false' if no average info.
  231. public bool ComputeMeasuresOfInterest(out double lastChangeOverTime, out double averageChangeOverTime)
  232. {
  233. bool ret = false;
  234. lastChangeOverTime = 0;
  235. averageChangeOverTime = 0;
  236. if ((MeasuresOfInterest & MeasuresOfInterest.AverageChangeOverTime) == MeasuresOfInterest.AverageChangeOverTime)
  237. {
  238. double totalChange = 0;
  239. double? penultimateSample = null;
  240. double? lastSample = null;
  241. lock (m_samples)
  242. {
  243. // m_log.DebugFormat(
  244. // "[STAT]: Samples for {0} are {1}",
  245. // Name, string.Join(",", m_samples.Select(s => s.ToString()).ToArray()));
  246. foreach (double s in m_samples)
  247. {
  248. if (lastSample != null)
  249. totalChange += s - (double)lastSample;
  250. penultimateSample = lastSample;
  251. lastSample = s;
  252. }
  253. }
  254. if (lastSample != null && penultimateSample != null)
  255. {
  256. lastChangeOverTime
  257. = ((double)lastSample - (double)penultimateSample) / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
  258. }
  259. int divisor = m_samples.Count <= 1 ? 1 : m_samples.Count - 1;
  260. averageChangeOverTime = totalChange / divisor / (Watchdog.WATCHDOG_INTERVAL_MS / 1000);
  261. ret = true;
  262. }
  263. return ret;
  264. }
  265. protected void AppendMeasuresOfInterest(StringBuilder sb)
  266. {
  267. double lastChangeOverTime = 0;
  268. double averageChangeOverTime = 0;
  269. if (ComputeMeasuresOfInterest(out lastChangeOverTime, out averageChangeOverTime))
  270. {
  271. sb.AppendFormat(
  272. ", {0:0.##}{1}/s, {2:0.##}{3}/s",
  273. lastChangeOverTime,
  274. string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName),
  275. averageChangeOverTime,
  276. string.IsNullOrEmpty(UnitName) ? "" : string.Format(" {0}", UnitName));
  277. }
  278. }
  279. }
  280. }