ServerStatsCollector.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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.Diagnostics;
  30. using System.Linq;
  31. using System.Net.NetworkInformation;
  32. using System.Text;
  33. using System.Threading;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. namespace OpenSim.Framework.Monitoring
  39. {
  40. public class ServerStatsCollector
  41. {
  42. private readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  43. private readonly string LogHeader = "[SERVER STATS]";
  44. public bool Enabled = false;
  45. private static Dictionary<string, Stat> RegisteredStats = new Dictionary<string, Stat>();
  46. public readonly string CategoryServer = "server";
  47. public readonly string ContainerThreadpool = "threadpool";
  48. public readonly string ContainerProcessor = "processor";
  49. public readonly string ContainerMemory = "memory";
  50. public readonly string ContainerNetwork = "network";
  51. public readonly string ContainerProcess = "process";
  52. public string NetworkInterfaceTypes = "Ethernet";
  53. readonly int performanceCounterSampleInterval = 500;
  54. // int lastperformanceCounterSampleTime = 0;
  55. private class PerfCounterControl
  56. {
  57. public PerformanceCounter perfCounter;
  58. public int lastFetch;
  59. public string name;
  60. public PerfCounterControl(PerformanceCounter pPc)
  61. : this(pPc, String.Empty)
  62. {
  63. }
  64. public PerfCounterControl(PerformanceCounter pPc, string pName)
  65. {
  66. perfCounter = pPc;
  67. lastFetch = 0;
  68. name = pName;
  69. }
  70. }
  71. PerfCounterControl processorPercentPerfCounter = null;
  72. // IRegionModuleBase.Initialize
  73. public void Initialise(IConfigSource source)
  74. {
  75. if (source == null)
  76. return;
  77. IConfig cfg = source.Configs["Monitoring"];
  78. if (cfg != null)
  79. Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
  80. if (Enabled)
  81. {
  82. NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
  83. }
  84. }
  85. public void Start()
  86. {
  87. if (RegisteredStats.Count == 0)
  88. RegisterServerStats();
  89. }
  90. public void Close()
  91. {
  92. if (RegisteredStats.Count > 0)
  93. {
  94. foreach (Stat stat in RegisteredStats.Values)
  95. {
  96. StatsManager.DeregisterStat(stat);
  97. stat.Dispose();
  98. }
  99. RegisteredStats.Clear();
  100. }
  101. }
  102. private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act)
  103. {
  104. MakeStat(pName, pDesc, pUnit, pContainer, act, MeasuresOfInterest.None);
  105. }
  106. private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act, MeasuresOfInterest moi)
  107. {
  108. string desc = pDesc;
  109. if (desc == null)
  110. desc = pName;
  111. Stat stat = new Stat(pName, pName, desc, pUnit, CategoryServer, pContainer, StatType.Pull, moi, act, StatVerbosity.Debug);
  112. StatsManager.RegisterStat(stat);
  113. RegisteredStats.Add(pName, stat);
  114. }
  115. public void RegisterServerStats()
  116. {
  117. // lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
  118. PerformanceCounter tempPC;
  119. Stat tempStat;
  120. string tempName;
  121. try
  122. {
  123. tempName = "CPUPercent";
  124. tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  125. processorPercentPerfCounter = new PerfCounterControl(tempPC);
  126. // A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
  127. tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
  128. StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
  129. StatVerbosity.Info);
  130. StatsManager.RegisterStat(tempStat);
  131. RegisteredStats.Add(tempName, tempStat);
  132. MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
  133. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
  134. MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
  135. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); });
  136. MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
  137. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); });
  138. MakeStat("Threads", null, "threads", ContainerProcessor,
  139. (s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
  140. }
  141. catch (Exception e)
  142. {
  143. m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
  144. }
  145. MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool,
  146. s =>
  147. {
  148. int workerThreads, iocpThreads;
  149. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  150. s.Value = workerThreads;
  151. });
  152. MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool,
  153. s =>
  154. {
  155. int workerThreads, iocpThreads;
  156. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  157. s.Value = iocpThreads;
  158. });
  159. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null)
  160. {
  161. MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads);
  162. MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads);
  163. MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems);
  164. MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads);
  165. MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads);
  166. MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks);
  167. }
  168. MakeStat(
  169. "HTTPRequestsMade",
  170. "Number of outbound HTTP requests made",
  171. "requests",
  172. ContainerNetwork,
  173. s => s.Value = WebUtil.RequestNumber,
  174. MeasuresOfInterest.AverageChangeOverTime);
  175. try
  176. {
  177. List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
  178. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
  179. foreach (NetworkInterface nic in nics)
  180. {
  181. if (nic.OperationalStatus != OperationalStatus.Up)
  182. continue;
  183. string nicInterfaceType = nic.NetworkInterfaceType.ToString();
  184. if (!okInterfaceTypes.Contains(nicInterfaceType))
  185. {
  186. m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.",
  187. LogHeader, nic.Name, nicInterfaceType);
  188. m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}",
  189. LogHeader, NetworkInterfaceTypes);
  190. continue;
  191. }
  192. if (nic.Supports(NetworkInterfaceComponent.IPv4))
  193. {
  194. IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
  195. if (nicStats != null)
  196. {
  197. MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  198. (s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
  199. MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  200. (s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
  201. MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  202. (s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
  203. }
  204. }
  205. // TODO: add IPv6 (it may actually happen someday)
  206. }
  207. }
  208. catch (Exception e)
  209. {
  210. m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
  211. }
  212. MakeStat("ProcessMemory", null, "MB", ContainerMemory,
  213. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); });
  214. MakeStat("HeapMemory", null, "MB", ContainerMemory,
  215. (s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); });
  216. MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory,
  217. (s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
  218. MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory,
  219. (s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
  220. }
  221. // Notes on performance counters:
  222. // "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
  223. // "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
  224. // "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
  225. private delegate double PerfCounterNextValue();
  226. private void GetNextValue(Stat stat, PerfCounterControl perfControl)
  227. {
  228. if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
  229. {
  230. if (perfControl != null && perfControl.perfCounter != null)
  231. {
  232. try
  233. {
  234. stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
  235. }
  236. catch (Exception e)
  237. {
  238. m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
  239. }
  240. perfControl.lastFetch = Util.EnvironmentTickCount();
  241. }
  242. }
  243. }
  244. // Lookup the nic that goes with this stat and set the value by using a fetch action.
  245. // Not sure about closure with delegates inside delegates.
  246. private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
  247. private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
  248. {
  249. // Get the one nic that has the name of this stat
  250. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
  251. (network) => network.Name == stat.Description);
  252. try
  253. {
  254. foreach (NetworkInterface nic in nics)
  255. {
  256. IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
  257. if (intrStats != null)
  258. {
  259. double newVal = Math.Round(getter(intrStats) / factor, 3);
  260. stat.Value = newVal;
  261. }
  262. break;
  263. }
  264. }
  265. catch
  266. {
  267. // There are times interfaces go away so we just won't update the stat for this
  268. m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
  269. }
  270. }
  271. }
  272. public class ServerStatsAggregator : Stat
  273. {
  274. public ServerStatsAggregator(
  275. string shortName,
  276. string name,
  277. string description,
  278. string unitName,
  279. string category,
  280. string container
  281. )
  282. : base(
  283. shortName,
  284. name,
  285. description,
  286. unitName,
  287. category,
  288. container,
  289. StatType.Push,
  290. MeasuresOfInterest.None,
  291. null,
  292. StatVerbosity.Info)
  293. {
  294. }
  295. public override string ToConsoleString()
  296. {
  297. StringBuilder sb = new StringBuilder();
  298. return sb.ToString();
  299. }
  300. public override OSDMap ToOSDMap()
  301. {
  302. OSDMap ret = new OSDMap();
  303. return ret;
  304. }
  305. }
  306. }