ServerStatsCollector.cs 18 KB

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