aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs
diff options
context:
space:
mode:
authorDiva Canto2013-02-25 10:25:56 -0800
committerDiva Canto2013-02-25 10:25:56 -0800
commit66c5934d90061da2db7137c98951fc42bf407475 (patch)
treef3f44bbaf0a64c72004d16ded3447c4600fe8d81 /OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs
parentMissing var in [LoginService] for HG Robust. (diff)
parentAdd StatsManager registration for region specific stats as collected (diff)
downloadopensim-SC-66c5934d90061da2db7137c98951fc42bf407475.zip
opensim-SC-66c5934d90061da2db7137c98951fc42bf407475.tar.gz
opensim-SC-66c5934d90061da2db7137c98951fc42bf407475.tar.bz2
opensim-SC-66c5934d90061da2db7137c98951fc42bf407475.tar.xz
Merge branch 'master' of ssh://opensimulator.org/var/git/opensim
Diffstat (limited to 'OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs')
-rw-r--r--OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs328
1 files changed, 328 insertions, 0 deletions
diff --git a/OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs b/OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs
new file mode 100644
index 0000000..a3d2436
--- /dev/null
+++ b/OpenSim/Region/OptionalModules/Framework/Monitoring/ServerStats.cs
@@ -0,0 +1,328 @@
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
28using System;
29using System.Collections.Generic;
30using System.Diagnostics;
31using System.Linq;
32using System.Net.NetworkInformation;
33using System.Text;
34using System.Threading;
35
36using log4net;
37using Mono.Addins;
38using Nini.Config;
39
40using OpenSim.Framework;
41using OpenSim.Framework.Console;
42using OpenSim.Framework.Monitoring;
43using OpenSim.Region.Framework.Interfaces;
44using OpenSim.Region.Framework.Scenes;
45
46using OpenMetaverse.StructuredData;
47
48namespace OpenSim.Region.OptionalModules.Framework.Monitoring
49{
50[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ServerStatistics")]
51public class ServerStats : ISharedRegionModule
52{
53 private readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
54 private readonly string LogHeader = "[SERVER STATS]";
55
56 public bool Enabled = false;
57 private static Dictionary<string, Stat> RegisteredStats = new Dictionary<string, Stat>();
58
59 public readonly string CategoryServer = "server";
60
61 public readonly string ContainerProcessor = "processor";
62 public readonly string ContainerMemory = "memory";
63 public readonly string ContainerNetwork = "network";
64 public readonly string ContainerProcess = "process";
65
66 public string NetworkInterfaceTypes = "Ethernet";
67
68 readonly int performanceCounterSampleInterval = 500;
69 int lastperformanceCounterSampleTime = 0;
70
71 private class PerfCounterControl
72 {
73 public PerformanceCounter perfCounter;
74 public int lastFetch;
75 public string name;
76 public PerfCounterControl(PerformanceCounter pPc)
77 : this(pPc, String.Empty)
78 {
79 }
80 public PerfCounterControl(PerformanceCounter pPc, string pName)
81 {
82 perfCounter = pPc;
83 lastFetch = 0;
84 name = pName;
85 }
86 }
87
88 PerfCounterControl processorPercentPerfCounter = null;
89
90 #region ISharedRegionModule
91 // IRegionModuleBase.Name
92 public string Name { get { return "Server Stats"; } }
93 // IRegionModuleBase.ReplaceableInterface
94 public Type ReplaceableInterface { get { return null; } }
95 // IRegionModuleBase.Initialize
96 public void Initialise(IConfigSource source)
97 {
98 IConfig cfg = source.Configs["Monitoring"];
99
100 if (cfg != null)
101 Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
102
103 if (Enabled)
104 {
105 NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
106 }
107 }
108 // IRegionModuleBase.Close
109 public void Close()
110 {
111 if (RegisteredStats.Count > 0)
112 {
113 foreach (Stat stat in RegisteredStats.Values)
114 {
115 StatsManager.DeregisterStat(stat);
116 stat.Dispose();
117 }
118 RegisteredStats.Clear();
119 }
120 }
121 // IRegionModuleBase.AddRegion
122 public void AddRegion(Scene scene)
123 {
124 }
125 // IRegionModuleBase.RemoveRegion
126 public void RemoveRegion(Scene scene)
127 {
128 }
129 // IRegionModuleBase.RegionLoaded
130 public void RegionLoaded(Scene scene)
131 {
132 }
133 // ISharedRegionModule.PostInitialize
134 public void PostInitialise()
135 {
136 if (RegisteredStats.Count == 0)
137 {
138 RegisterServerStats();
139 }
140 }
141 #endregion ISharedRegionModule
142
143 private void MakeStat(string pName, string pUnit, string pContainer, Action<Stat> act)
144 {
145 Stat stat = new Stat(pName, pName, "", pUnit, CategoryServer, pContainer, StatType.Pull, act, StatVerbosity.Info);
146 StatsManager.RegisterStat(stat);
147 RegisteredStats.Add(pName, stat);
148 }
149
150 public void RegisterServerStats()
151 {
152 lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
153 PerformanceCounter tempPC;
154 Stat tempStat;
155 string tempName;
156
157 try
158 {
159 tempName = "CPUPercent";
160 tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
161 processorPercentPerfCounter = new PerfCounterControl(tempPC);
162 // A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
163 tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
164 StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter, Util.IsWindows() ? 1 : -1); },
165 StatVerbosity.Info);
166 StatsManager.RegisterStat(tempStat);
167 RegisteredStats.Add(tempName, tempStat);
168
169 MakeStat("TotalProcessorTime", "sec", ContainerProcessor,
170 (s) => { s.Value = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; });
171
172 MakeStat("UserProcessorTime", "sec", ContainerProcessor,
173 (s) => { s.Value = Process.GetCurrentProcess().UserProcessorTime.TotalSeconds; });
174
175 MakeStat("PrivilegedProcessorTime", "sec", ContainerProcessor,
176 (s) => { s.Value = Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds; });
177
178 MakeStat("Threads", "threads", ContainerProcessor,
179 (s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
180 }
181 catch (Exception e)
182 {
183 m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
184 }
185
186 try
187 {
188 List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
189
190 IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
191 foreach (NetworkInterface nic in nics)
192 {
193 if (nic.OperationalStatus != OperationalStatus.Up)
194 continue;
195
196 string nicInterfaceType = nic.NetworkInterfaceType.ToString();
197 if (!okInterfaceTypes.Contains(nicInterfaceType))
198 {
199 m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'. To include, add to [Monitoring]NetworkInterfaceTypes='Ethernet,Loopback'",
200 LogHeader, nic.Name, nicInterfaceType);
201 continue;
202 }
203
204 if (nic.Supports(NetworkInterfaceComponent.IPv4))
205 {
206 IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
207 if (nicStats != null)
208 {
209 MakeStat("BytesRcvd/" + nic.Name, "KB", ContainerNetwork,
210 (s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
211 MakeStat("BytesSent/" + nic.Name, "KB", ContainerNetwork,
212 (s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
213 MakeStat("TotalBytes/" + nic.Name, "KB", ContainerNetwork,
214 (s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
215 }
216 }
217 }
218 }
219 catch (Exception e)
220 {
221 m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
222 }
223
224 MakeStat("ProcessMemory", "MB", ContainerMemory,
225 (s) => { s.Value = Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d; });
226 MakeStat("ObjectMemory", "MB", ContainerMemory,
227 (s) => { s.Value = GC.GetTotalMemory(false) / 1024d / 1024d; });
228 MakeStat("LastMemoryChurn", "MB/sec", ContainerMemory,
229 (s) => { s.Value = Math.Round(MemoryWatchdog.LastMemoryChurn * 1000d / 1024d / 1024d, 3); });
230 MakeStat("AverageMemoryChurn", "MB/sec", ContainerMemory,
231 (s) => { s.Value = Math.Round(MemoryWatchdog.AverageMemoryChurn * 1000d / 1024d / 1024d, 3); });
232 }
233
234 // Notes on performance counters:
235 // "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
236 // "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
237 // "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
238 private delegate double PerfCounterNextValue();
239 private void GetNextValue(Stat stat, PerfCounterControl perfControl)
240 {
241 GetNextValue(stat, perfControl, 1.0);
242 }
243 private void GetNextValue(Stat stat, PerfCounterControl perfControl, double factor)
244 {
245 if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
246 {
247 if (perfControl != null && perfControl.perfCounter != null)
248 {
249 try
250 {
251 // Kludge for factor to run double duty. If -1, subtract the value from one
252 if (factor == -1)
253 stat.Value = 1 - perfControl.perfCounter.NextValue();
254 else
255 stat.Value = perfControl.perfCounter.NextValue() / factor;
256 }
257 catch (Exception e)
258 {
259 m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
260 }
261 perfControl.lastFetch = Util.EnvironmentTickCount();
262 }
263 }
264 }
265
266 private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
267 private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
268 {
269 // Get the one nic that has the name of this stat
270 IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
271 (network) => network.Name == stat.Description);
272 try
273 {
274 foreach (NetworkInterface nic in nics)
275 {
276 IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
277 if (intrStats != null)
278 stat.Value = Math.Round(getter(intrStats) / factor, 3);
279 break;
280 }
281 }
282 catch
283 {
284 // There are times interfaces go away so we just won't update the stat for this
285 m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
286 }
287 }
288}
289
290public class ServerStatsAggregator : Stat
291{
292 public ServerStatsAggregator(
293 string shortName,
294 string name,
295 string description,
296 string unitName,
297 string category,
298 string container
299 )
300 : base(
301 shortName,
302 name,
303 description,
304 unitName,
305 category,
306 container,
307 StatType.Push,
308 MeasuresOfInterest.None,
309 null,
310 StatVerbosity.Info)
311 {
312 }
313 public override string ToConsoleString()
314 {
315 StringBuilder sb = new StringBuilder();
316
317 return sb.ToString();
318 }
319
320 public override OSDMap ToOSDMap()
321 {
322 OSDMap ret = new OSDMap();
323
324 return ret;
325 }
326}
327
328}