ServerStatsCollector.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  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. MakeStat("ProcessResident", null, "MB", ContainerProcess,
  221. (s) =>
  222. {
  223. Process myprocess = Process.GetCurrentProcess();
  224. myprocess.Refresh();
  225. s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0);
  226. });
  227. MakeStat("ProcessPaged", null, "MB", ContainerProcess,
  228. (s) =>
  229. {
  230. Process myprocess = Process.GetCurrentProcess();
  231. myprocess.Refresh();
  232. s.Value = Math.Round(Process.GetCurrentProcess().PagedMemorySize64 / 1024.0 / 1024.0);
  233. });
  234. MakeStat("ProcessVirtual", null, "MB", ContainerProcess,
  235. (s) =>
  236. {
  237. Process myprocess = Process.GetCurrentProcess();
  238. myprocess.Refresh();
  239. s.Value = Math.Round(Process.GetCurrentProcess().VirtualMemorySize64 / 1024.0 / 1024.0);
  240. });
  241. MakeStat("PeakProcessResident", null, "MB", ContainerProcess,
  242. (s) =>
  243. {
  244. Process myprocess = Process.GetCurrentProcess();
  245. myprocess.Refresh();
  246. s.Value = Math.Round(Process.GetCurrentProcess().PeakWorkingSet64 / 1024.0 / 1024.0);
  247. });
  248. MakeStat("PeakProcessPaged", null, "MB", ContainerProcess,
  249. (s) =>
  250. {
  251. Process myprocess = Process.GetCurrentProcess();
  252. myprocess.Refresh();
  253. s.Value = Math.Round(Process.GetCurrentProcess().PeakPagedMemorySize64 / 1024.0 / 1024.0);
  254. });
  255. MakeStat("PeakProcessVirtual", null, "MB", ContainerProcess,
  256. (s) =>
  257. {
  258. Process myprocess = Process.GetCurrentProcess();
  259. myprocess.Refresh();
  260. s.Value = Math.Round(Process.GetCurrentProcess().PeakVirtualMemorySize64 / 1024.0 / 1024.0);
  261. });
  262. }
  263. // Notes on performance counters:
  264. // "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
  265. // "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
  266. // "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
  267. private delegate double PerfCounterNextValue();
  268. private void GetNextValue(Stat stat, PerfCounterControl perfControl)
  269. {
  270. if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
  271. {
  272. if (perfControl != null && perfControl.perfCounter != null)
  273. {
  274. try
  275. {
  276. stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
  277. }
  278. catch (Exception e)
  279. {
  280. m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
  281. }
  282. perfControl.lastFetch = Util.EnvironmentTickCount();
  283. }
  284. }
  285. }
  286. // Lookup the nic that goes with this stat and set the value by using a fetch action.
  287. // Not sure about closure with delegates inside delegates.
  288. private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
  289. private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
  290. {
  291. // Get the one nic that has the name of this stat
  292. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
  293. (network) => network.Name == stat.Description);
  294. try
  295. {
  296. foreach (NetworkInterface nic in nics)
  297. {
  298. IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
  299. if (intrStats != null)
  300. {
  301. double newVal = Math.Round(getter(intrStats) / factor, 3);
  302. stat.Value = newVal;
  303. }
  304. break;
  305. }
  306. }
  307. catch
  308. {
  309. // There are times interfaces go away so we just won't update the stat for this
  310. m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
  311. }
  312. }
  313. }
  314. public class ServerStatsAggregator : Stat
  315. {
  316. public ServerStatsAggregator(
  317. string shortName,
  318. string name,
  319. string description,
  320. string unitName,
  321. string category,
  322. string container
  323. )
  324. : base(
  325. shortName,
  326. name,
  327. description,
  328. unitName,
  329. category,
  330. container,
  331. StatType.Push,
  332. MeasuresOfInterest.None,
  333. null,
  334. StatVerbosity.Info)
  335. {
  336. }
  337. public override string ToConsoleString()
  338. {
  339. StringBuilder sb = new StringBuilder();
  340. return sb.ToString();
  341. }
  342. public override OSDMap ToOSDMap()
  343. {
  344. OSDMap ret = new OSDMap();
  345. return ret;
  346. }
  347. }
  348. }