ServerStatsCollector.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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", false);
  80. if (Enabled)
  81. {
  82. NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
  83. }
  84. }
  85. public void Start()
  86. {
  87. if(!Enabled)
  88. return;
  89. if (RegisteredStats.Count == 0)
  90. RegisterServerStats();
  91. }
  92. public void Close()
  93. {
  94. if(!Enabled)
  95. return;
  96. if (RegisteredStats.Count > 0)
  97. {
  98. foreach (Stat stat in RegisteredStats.Values)
  99. {
  100. StatsManager.DeregisterStat(stat);
  101. stat.Dispose();
  102. }
  103. RegisteredStats.Clear();
  104. }
  105. }
  106. private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act)
  107. {
  108. MakeStat(pName, pDesc, pUnit, pContainer, act, MeasuresOfInterest.None);
  109. }
  110. private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act, MeasuresOfInterest moi)
  111. {
  112. string desc = pDesc;
  113. if (desc == null)
  114. desc = pName;
  115. Stat stat = new Stat(pName, pName, desc, pUnit, CategoryServer, pContainer, StatType.Pull, moi, act, StatVerbosity.Debug);
  116. StatsManager.RegisterStat(stat);
  117. RegisteredStats.Add(pName, stat);
  118. }
  119. public void RegisterServerStats()
  120. {
  121. // lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
  122. PerformanceCounter tempPC;
  123. Stat tempStat;
  124. string tempName;
  125. try
  126. {
  127. tempName = "CPUPercent";
  128. tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
  129. processorPercentPerfCounter = new PerfCounterControl(tempPC);
  130. // A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
  131. tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
  132. StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
  133. StatVerbosity.Info);
  134. StatsManager.RegisterStat(tempStat);
  135. RegisteredStats.Add(tempName, tempStat);
  136. MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
  137. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
  138. MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
  139. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); });
  140. MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
  141. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); });
  142. MakeStat("Threads", null, "threads", ContainerProcessor,
  143. (s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
  144. }
  145. catch (Exception e)
  146. {
  147. m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
  148. }
  149. MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool,
  150. s =>
  151. {
  152. int workerThreads, iocpThreads;
  153. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  154. s.Value = workerThreads;
  155. });
  156. MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool,
  157. s =>
  158. {
  159. int workerThreads, iocpThreads;
  160. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  161. s.Value = iocpThreads;
  162. });
  163. if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null)
  164. {
  165. MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads);
  166. MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads);
  167. MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems);
  168. MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads);
  169. MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads);
  170. MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks);
  171. }
  172. MakeStat(
  173. "HTTPRequestsMade",
  174. "Number of outbound HTTP requests made",
  175. "requests",
  176. ContainerNetwork,
  177. s => s.Value = WebUtil.RequestNumber,
  178. MeasuresOfInterest.AverageChangeOverTime);
  179. try
  180. {
  181. List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
  182. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
  183. foreach (NetworkInterface nic in nics)
  184. {
  185. if (nic.OperationalStatus != OperationalStatus.Up)
  186. continue;
  187. string nicInterfaceType = nic.NetworkInterfaceType.ToString();
  188. if (!okInterfaceTypes.Contains(nicInterfaceType))
  189. {
  190. m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.",
  191. LogHeader, nic.Name, nicInterfaceType);
  192. m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}",
  193. LogHeader, NetworkInterfaceTypes);
  194. continue;
  195. }
  196. if (nic.Supports(NetworkInterfaceComponent.IPv4))
  197. {
  198. IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
  199. if (nicStats != null)
  200. {
  201. MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  202. (s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
  203. MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  204. (s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
  205. MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork,
  206. (s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
  207. }
  208. }
  209. // TODO: add IPv6 (it may actually happen someday)
  210. }
  211. }
  212. catch (Exception e)
  213. {
  214. m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
  215. }
  216. MakeStat("ProcessMemory", null, "MB", ContainerMemory,
  217. (s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); });
  218. MakeStat("HeapMemory", null, "MB", ContainerMemory,
  219. (s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); });
  220. MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory,
  221. (s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
  222. MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory,
  223. (s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
  224. MakeStat("ProcessResident", null, "MB", ContainerProcess,
  225. (s) =>
  226. {
  227. Process myprocess = Process.GetCurrentProcess();
  228. myprocess.Refresh();
  229. s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0);
  230. });
  231. MakeStat("ProcessPaged", null, "MB", ContainerProcess,
  232. (s) =>
  233. {
  234. Process myprocess = Process.GetCurrentProcess();
  235. myprocess.Refresh();
  236. s.Value = Math.Round(Process.GetCurrentProcess().PagedMemorySize64 / 1024.0 / 1024.0);
  237. });
  238. MakeStat("ProcessVirtual", null, "MB", ContainerProcess,
  239. (s) =>
  240. {
  241. Process myprocess = Process.GetCurrentProcess();
  242. myprocess.Refresh();
  243. s.Value = Math.Round(Process.GetCurrentProcess().VirtualMemorySize64 / 1024.0 / 1024.0);
  244. });
  245. MakeStat("PeakProcessResident", null, "MB", ContainerProcess,
  246. (s) =>
  247. {
  248. Process myprocess = Process.GetCurrentProcess();
  249. myprocess.Refresh();
  250. s.Value = Math.Round(Process.GetCurrentProcess().PeakWorkingSet64 / 1024.0 / 1024.0);
  251. });
  252. MakeStat("PeakProcessPaged", null, "MB", ContainerProcess,
  253. (s) =>
  254. {
  255. Process myprocess = Process.GetCurrentProcess();
  256. myprocess.Refresh();
  257. s.Value = Math.Round(Process.GetCurrentProcess().PeakPagedMemorySize64 / 1024.0 / 1024.0);
  258. });
  259. MakeStat("PeakProcessVirtual", null, "MB", ContainerProcess,
  260. (s) =>
  261. {
  262. Process myprocess = Process.GetCurrentProcess();
  263. myprocess.Refresh();
  264. s.Value = Math.Round(Process.GetCurrentProcess().PeakVirtualMemorySize64 / 1024.0 / 1024.0);
  265. });
  266. }
  267. // Notes on performance counters:
  268. // "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
  269. // "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
  270. // "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
  271. private delegate double PerfCounterNextValue();
  272. private void GetNextValue(Stat stat, PerfCounterControl perfControl)
  273. {
  274. if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
  275. {
  276. if (perfControl != null && perfControl.perfCounter != null)
  277. {
  278. try
  279. {
  280. stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
  281. }
  282. catch (Exception e)
  283. {
  284. m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
  285. }
  286. perfControl.lastFetch = Util.EnvironmentTickCount();
  287. }
  288. }
  289. }
  290. // Lookup the nic that goes with this stat and set the value by using a fetch action.
  291. // Not sure about closure with delegates inside delegates.
  292. private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
  293. private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
  294. {
  295. // Get the one nic that has the name of this stat
  296. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
  297. (network) => network.Name == stat.Description);
  298. try
  299. {
  300. foreach (NetworkInterface nic in nics)
  301. {
  302. IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
  303. if (intrStats != null)
  304. {
  305. double newVal = Math.Round(getter(intrStats) / factor, 3);
  306. stat.Value = newVal;
  307. }
  308. break;
  309. }
  310. }
  311. catch
  312. {
  313. // There are times interfaces go away so we just won't update the stat for this
  314. m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
  315. }
  316. }
  317. }
  318. public class ServerStatsAggregator : Stat
  319. {
  320. public ServerStatsAggregator(
  321. string shortName,
  322. string name,
  323. string description,
  324. string unitName,
  325. string category,
  326. string container
  327. )
  328. : base(
  329. shortName,
  330. name,
  331. description,
  332. unitName,
  333. category,
  334. container,
  335. StatType.Push,
  336. MeasuresOfInterest.None,
  337. null,
  338. StatVerbosity.Info)
  339. {
  340. }
  341. public override string ToConsoleString()
  342. {
  343. StringBuilder sb = new StringBuilder();
  344. return sb.ToString();
  345. }
  346. public override OSDMap ToOSDMap()
  347. {
  348. OSDMap ret = new OSDMap();
  349. return ret;
  350. }
  351. }
  352. }