SimStatsReporter.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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.Timers;
  30. using OpenMetaverse.Packets;
  31. using OpenSim.Framework;
  32. using OpenSim.Framework.Monitoring;
  33. using OpenSim.Region.Framework.Interfaces;
  34. namespace OpenSim.Region.Framework.Scenes
  35. {
  36. /// <summary>
  37. /// Collect statistics from the scene to send to the client and for access by other monitoring tools.
  38. /// </summary>
  39. /// <remarks>
  40. /// FIXME: This should be a monitoring region module
  41. /// </remarks>
  42. public class SimStatsReporter
  43. {
  44. private static readonly log4net.ILog m_log
  45. = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  46. public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates";
  47. public delegate void SendStatResult(SimStats stats);
  48. public delegate void YourStatsAreWrong();
  49. public event SendStatResult OnSendStatsResult;
  50. public event YourStatsAreWrong OnStatsIncorrect;
  51. private SendStatResult handlerSendStatResult;
  52. private YourStatsAreWrong handlerStatsIncorrect;
  53. /// <summary>
  54. /// These are the IDs of stats sent in the StatsPacket to the viewer.
  55. /// </summary>
  56. /// <remarks>
  57. /// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators
  58. /// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky).
  59. /// </remarks>
  60. public enum Stats : uint
  61. {
  62. TimeDilation = 0,
  63. SimFPS = 1,
  64. PhysicsFPS = 2,
  65. AgentUpdates = 3,
  66. FrameMS = 4,
  67. NetMS = 5,
  68. OtherMS = 6,
  69. PhysicsMS = 7,
  70. AgentMS = 8,
  71. ImageMS = 9,
  72. ScriptMS = 10,
  73. TotalPrim = 11,
  74. ActivePrim = 12,
  75. Agents = 13,
  76. ChildAgents = 14,
  77. ActiveScripts = 15,
  78. ScriptLinesPerSecond = 16,
  79. InPacketsPerSecond = 17,
  80. OutPacketsPerSecond = 18,
  81. PendingDownloads = 19,
  82. PendingUploads = 20,
  83. VirtualSizeKb = 21,
  84. ResidentSizeKb = 22,
  85. PendingLocalUploads = 23,
  86. UnAckedBytes = 24,
  87. PhysicsPinnedTasks = 25,
  88. PhysicsLodTasks = 26,
  89. SimPhysicsStepMs = 27,
  90. SimPhysicsShapeMs = 28,
  91. SimPhysicsOtherMs = 29,
  92. SimPhysicsMemory = 30,
  93. ScriptEps = 31,
  94. SimSpareMs = 32,
  95. SimSleepMs = 33,
  96. SimIoPumpTime = 34
  97. }
  98. /// <summary>
  99. /// This is for llGetRegionFPS
  100. /// </summary>
  101. public float LastReportedSimFPS
  102. {
  103. get { return lastReportedSimFPS; }
  104. }
  105. /// <summary>
  106. /// Number of object updates performed in the last stats cycle
  107. /// </summary>
  108. /// <remarks>
  109. /// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a
  110. /// large number of object updates.
  111. /// </remarks>
  112. public float LastReportedObjectUpdates { get; private set; }
  113. public float[] LastReportedSimStats
  114. {
  115. get { return lastReportedSimStats; }
  116. }
  117. /// <summary>
  118. /// Extra sim statistics that are used by monitors but not sent to the client.
  119. /// </summary>
  120. /// <value>
  121. /// The keys are the stat names.
  122. /// </value>
  123. private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>();
  124. // Sending a stats update every 3 seconds-
  125. private int m_statsUpdatesEveryMS = 3000;
  126. private float m_statsUpdateFactor;
  127. private float m_timeDilation;
  128. private int m_fps;
  129. /// <summary>
  130. /// Number of the last frame on which we processed a stats udpate.
  131. /// </summary>
  132. private uint m_lastUpdateFrame;
  133. /// <summary>
  134. /// Our nominal fps target, as expected in fps stats when a sim is running normally.
  135. /// </summary>
  136. private float m_nominalReportedFps = 55;
  137. /// <summary>
  138. /// Parameter to adjust reported scene fps
  139. /// </summary>
  140. /// <remarks>
  141. /// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently.
  142. /// However, we will still report an FPS that's closer to what people are used to seeing. A lower FPS might
  143. /// affect clients and monitoring scripts/software.
  144. /// </remarks>
  145. private float m_reportedFpsCorrectionFactor = 5;
  146. // saved last reported value so there is something available for llGetRegionFPS
  147. private float lastReportedSimFPS;
  148. private float[] lastReportedSimStats = new float[22];
  149. private float m_pfps;
  150. /// <summary>
  151. /// Number of agent updates requested in this stats cycle
  152. /// </summary>
  153. private int m_agentUpdates;
  154. /// <summary>
  155. /// Number of object updates requested in this stats cycle
  156. /// </summary>
  157. private int m_objectUpdates;
  158. private int m_frameMS;
  159. private int m_spareMS;
  160. private int m_netMS;
  161. private int m_agentMS;
  162. private int m_physicsMS;
  163. private int m_imageMS;
  164. private int m_otherMS;
  165. //Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed.
  166. //Ckrinke private int m_scriptMS = 0;
  167. private int m_rootAgents;
  168. private int m_childAgents;
  169. private int m_numPrim;
  170. private int m_inPacketsPerSecond;
  171. private int m_outPacketsPerSecond;
  172. private int m_activePrim;
  173. private int m_unAckedBytes;
  174. private int m_pendingDownloads;
  175. private int m_pendingUploads = 0; // FIXME: Not currently filled in
  176. private int m_activeScripts;
  177. private int m_scriptLinesPerSecond;
  178. private int m_objectCapacity = 45000;
  179. private Scene m_scene;
  180. private RegionInfo ReportingRegion;
  181. private Timer m_report = new Timer();
  182. private IEstateModule estateModule;
  183. public SimStatsReporter(Scene scene)
  184. {
  185. m_scene = scene;
  186. m_reportedFpsCorrectionFactor = scene.MinFrameTime * m_nominalReportedFps;
  187. m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
  188. ReportingRegion = scene.RegionInfo;
  189. m_objectCapacity = scene.RegionInfo.ObjectCapacity;
  190. m_report.AutoReset = true;
  191. m_report.Interval = m_statsUpdatesEveryMS;
  192. m_report.Elapsed += TriggerStatsHeartbeat;
  193. m_report.Enabled = true;
  194. if (StatsManager.SimExtraStats != null)
  195. OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket;
  196. }
  197. public void Close()
  198. {
  199. m_report.Elapsed -= TriggerStatsHeartbeat;
  200. m_report.Close();
  201. }
  202. /// <summary>
  203. /// Sets the number of milliseconds between stat updates.
  204. /// </summary>
  205. /// <param name='ms'></param>
  206. public void SetUpdateMS(int ms)
  207. {
  208. m_statsUpdatesEveryMS = ms;
  209. m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000);
  210. m_report.Interval = m_statsUpdatesEveryMS;
  211. }
  212. private void TriggerStatsHeartbeat(object sender, EventArgs args)
  213. {
  214. try
  215. {
  216. statsHeartBeat(sender, args);
  217. }
  218. catch (Exception e)
  219. {
  220. m_log.Warn(string.Format(
  221. "[SIM STATS REPORTER] Update for {0} failed with exception ",
  222. m_scene.RegionInfo.RegionName), e);
  223. }
  224. }
  225. private void statsHeartBeat(object sender, EventArgs e)
  226. {
  227. SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[22];
  228. SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock();
  229. // Know what's not thread safe in Mono... modifying timers.
  230. // m_log.Debug("Firing Stats Heart Beat");
  231. lock (m_report)
  232. {
  233. uint regionFlags = 0;
  234. try
  235. {
  236. if (estateModule == null)
  237. estateModule = m_scene.RequestModuleInterface<IEstateModule>();
  238. regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0;
  239. }
  240. catch (Exception)
  241. {
  242. // leave region flags at 0
  243. }
  244. #region various statistic googly moogly
  245. // We're going to lie about the FPS because we've been lying since 2008. The actual FPS is currently
  246. // locked at a maximum of 11. Maybe at some point this can change so that we're not lying.
  247. int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor);
  248. // save the reported value so there is something available for llGetRegionFPS
  249. lastReportedSimFPS = reportedFPS / m_statsUpdateFactor;
  250. float physfps = ((m_pfps / 1000));
  251. //if (physfps > 600)
  252. //physfps = physfps - (physfps - 600);
  253. if (physfps < 0)
  254. physfps = 0;
  255. #endregion
  256. m_rootAgents = m_scene.SceneGraph.GetRootAgentCount();
  257. m_childAgents = m_scene.SceneGraph.GetChildAgentCount();
  258. m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount();
  259. m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount();
  260. m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount();
  261. // FIXME: Checking for stat sanity is a complex approach. What we really need to do is fix the code
  262. // so that stat numbers are always consistent.
  263. CheckStatSanity();
  264. //Our time dilation is 0.91 when we're running a full speed,
  265. // therefore to make sure we get an appropriate range,
  266. // we have to factor in our error. (0.10f * statsUpdateFactor)
  267. // multiplies the fix for the error times the amount of times it'll occur a second
  268. // / 10 divides the value by the number of times the sim heartbeat runs (10fps)
  269. // Then we divide the whole amount by the amount of seconds pass in between stats updates.
  270. // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change
  271. // values to X-per-second values.
  272. uint thisFrame = m_scene.Frame;
  273. float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor;
  274. m_lastUpdateFrame = thisFrame;
  275. // Avoid div-by-zero if somehow we've not updated any frames.
  276. if (framesUpdated == 0)
  277. framesUpdated = 1;
  278. for (int i = 0; i < 22; i++)
  279. {
  280. sb[i] = new SimStatsPacket.StatBlock();
  281. }
  282. sb[0].StatID = (uint) Stats.TimeDilation;
  283. sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor));
  284. sb[1].StatID = (uint) Stats.SimFPS;
  285. sb[1].StatValue = reportedFPS / m_statsUpdateFactor;
  286. sb[2].StatID = (uint) Stats.PhysicsFPS;
  287. sb[2].StatValue = physfps / m_statsUpdateFactor;
  288. sb[3].StatID = (uint) Stats.AgentUpdates;
  289. sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor);
  290. sb[4].StatID = (uint) Stats.Agents;
  291. sb[4].StatValue = m_rootAgents;
  292. sb[5].StatID = (uint) Stats.ChildAgents;
  293. sb[5].StatValue = m_childAgents;
  294. sb[6].StatID = (uint) Stats.TotalPrim;
  295. sb[6].StatValue = m_numPrim;
  296. sb[7].StatID = (uint) Stats.ActivePrim;
  297. sb[7].StatValue = m_activePrim;
  298. sb[8].StatID = (uint)Stats.FrameMS;
  299. sb[8].StatValue = m_frameMS / framesUpdated;
  300. sb[9].StatID = (uint)Stats.NetMS;
  301. sb[9].StatValue = m_netMS / framesUpdated;
  302. sb[10].StatID = (uint)Stats.PhysicsMS;
  303. sb[10].StatValue = m_physicsMS / framesUpdated;
  304. sb[11].StatID = (uint)Stats.ImageMS ;
  305. sb[11].StatValue = m_imageMS / framesUpdated;
  306. sb[12].StatID = (uint)Stats.OtherMS;
  307. sb[12].StatValue = m_otherMS / framesUpdated;
  308. sb[13].StatID = (uint)Stats.InPacketsPerSecond;
  309. sb[13].StatValue = (m_inPacketsPerSecond / m_statsUpdateFactor);
  310. sb[14].StatID = (uint)Stats.OutPacketsPerSecond;
  311. sb[14].StatValue = (m_outPacketsPerSecond / m_statsUpdateFactor);
  312. sb[15].StatID = (uint)Stats.UnAckedBytes;
  313. sb[15].StatValue = m_unAckedBytes;
  314. sb[16].StatID = (uint)Stats.AgentMS;
  315. sb[16].StatValue = m_agentMS / framesUpdated;
  316. sb[17].StatID = (uint)Stats.PendingDownloads;
  317. sb[17].StatValue = m_pendingDownloads;
  318. sb[18].StatID = (uint)Stats.PendingUploads;
  319. sb[18].StatValue = m_pendingUploads;
  320. sb[19].StatID = (uint)Stats.ActiveScripts;
  321. sb[19].StatValue = m_activeScripts;
  322. sb[20].StatID = (uint)Stats.ScriptLinesPerSecond;
  323. sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor;
  324. sb[21].StatID = (uint)Stats.SimSpareMs;
  325. sb[21].StatValue = m_spareMS / framesUpdated;
  326. for (int i = 0; i < 22; i++)
  327. {
  328. lastReportedSimStats[i] = sb[i].StatValue;
  329. }
  330. SimStats simStats
  331. = new SimStats(
  332. ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity,
  333. rb, sb, m_scene.RegionInfo.originRegionID);
  334. handlerSendStatResult = OnSendStatsResult;
  335. if (handlerSendStatResult != null)
  336. {
  337. handlerSendStatResult(simStats);
  338. }
  339. // Extra statistics that aren't currently sent to clients
  340. lock (m_lastReportedExtraSimStats)
  341. {
  342. m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor;
  343. Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats();
  344. if (physicsStats != null)
  345. {
  346. foreach (KeyValuePair<string, float> tuple in physicsStats)
  347. {
  348. // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second
  349. // Need to change things so that stats source can indicate whether they are per second or
  350. // per frame.
  351. if (tuple.Key.EndsWith("MS"))
  352. m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated;
  353. else
  354. m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor;
  355. }
  356. }
  357. }
  358. ResetValues();
  359. }
  360. }
  361. private void ResetValues()
  362. {
  363. m_timeDilation = 0;
  364. m_fps = 0;
  365. m_pfps = 0;
  366. m_agentUpdates = 0;
  367. m_objectUpdates = 0;
  368. //m_inPacketsPerSecond = 0;
  369. //m_outPacketsPerSecond = 0;
  370. m_unAckedBytes = 0;
  371. m_scriptLinesPerSecond = 0;
  372. m_frameMS = 0;
  373. m_agentMS = 0;
  374. m_netMS = 0;
  375. m_physicsMS = 0;
  376. m_imageMS = 0;
  377. m_otherMS = 0;
  378. m_spareMS = 0;
  379. //Ckrinke This variable is not used, so comment to remove compiler warning until it is used.
  380. //Ckrinke m_scriptMS = 0;
  381. }
  382. # region methods called from Scene
  383. // The majority of these functions are additive
  384. // so that you can easily change the amount of
  385. // seconds in between sim stats updates
  386. public void AddTimeDilation(float td)
  387. {
  388. //float tdsetting = td;
  389. //if (tdsetting > 1.0f)
  390. //tdsetting = (tdsetting - (tdsetting - 0.91f));
  391. //if (tdsetting < 0)
  392. //tdsetting = 0.0f;
  393. m_timeDilation = td;
  394. }
  395. internal void CheckStatSanity()
  396. {
  397. if (m_rootAgents < 0 || m_childAgents < 0)
  398. {
  399. handlerStatsIncorrect = OnStatsIncorrect;
  400. if (handlerStatsIncorrect != null)
  401. {
  402. handlerStatsIncorrect();
  403. }
  404. }
  405. if (m_rootAgents == 0 && m_childAgents == 0)
  406. {
  407. m_unAckedBytes = 0;
  408. }
  409. }
  410. public void AddFPS(int frames)
  411. {
  412. m_fps += frames;
  413. }
  414. public void AddPhysicsFPS(float frames)
  415. {
  416. m_pfps += frames;
  417. }
  418. public void AddObjectUpdates(int numUpdates)
  419. {
  420. m_objectUpdates += numUpdates;
  421. }
  422. public void AddAgentUpdates(int numUpdates)
  423. {
  424. m_agentUpdates += numUpdates;
  425. }
  426. public void AddInPackets(int numPackets)
  427. {
  428. m_inPacketsPerSecond = numPackets;
  429. }
  430. public void AddOutPackets(int numPackets)
  431. {
  432. m_outPacketsPerSecond = numPackets;
  433. }
  434. public void AddunAckedBytes(int numBytes)
  435. {
  436. m_unAckedBytes += numBytes;
  437. if (m_unAckedBytes < 0) m_unAckedBytes = 0;
  438. }
  439. public void addFrameMS(int ms)
  440. {
  441. m_frameMS += ms;
  442. }
  443. public void AddSpareMS(int ms)
  444. {
  445. m_spareMS += ms;
  446. }
  447. public void addNetMS(int ms)
  448. {
  449. m_netMS += ms;
  450. }
  451. public void addAgentMS(int ms)
  452. {
  453. m_agentMS += ms;
  454. }
  455. public void addPhysicsMS(int ms)
  456. {
  457. m_physicsMS += ms;
  458. }
  459. public void addImageMS(int ms)
  460. {
  461. m_imageMS += ms;
  462. }
  463. public void addOtherMS(int ms)
  464. {
  465. m_otherMS += ms;
  466. }
  467. public void AddPendingDownloads(int count)
  468. {
  469. m_pendingDownloads += count;
  470. if (m_pendingDownloads < 0)
  471. m_pendingDownloads = 0;
  472. //m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads);
  473. }
  474. public void addScriptLines(int count)
  475. {
  476. m_scriptLinesPerSecond += count;
  477. }
  478. public void AddPacketsStats(int inPackets, int outPackets, int unAckedBytes)
  479. {
  480. AddInPackets(inPackets);
  481. AddOutPackets(outPackets);
  482. AddunAckedBytes(unAckedBytes);
  483. }
  484. #endregion
  485. public Dictionary<string, float> GetExtraSimStats()
  486. {
  487. lock (m_lastReportedExtraSimStats)
  488. return new Dictionary<string, float>(m_lastReportedExtraSimStats);
  489. }
  490. }
  491. }