1
0

OutgoingQueueRefillEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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.Concurrent;
  29. using System.Reflection;
  30. using System.Threading;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Monitoring;
  34. using OpenSim.Region.Framework.Scenes;
  35. namespace OpenSim.Region.ClientStack.LindenUDP
  36. {
  37. public struct RefillRequest
  38. {
  39. public LLUDPClient Client;
  40. public ThrottleOutPacketTypeFlags Categories;
  41. public RefillRequest(LLUDPClient client, ThrottleOutPacketTypeFlags categories)
  42. {
  43. Client = client;
  44. Categories = categories;
  45. }
  46. }
  47. public class OutgoingQueueRefillEngine
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. public bool IsRunning { get; private set; }
  51. /// <summary>
  52. /// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
  53. /// </summary>
  54. public int RequestProcessTimeoutOnStop { get; set; }
  55. /// <summary>
  56. /// Controls whether we need to warn in the log about exceeding the max queue size.
  57. /// </summary>
  58. /// <remarks>
  59. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  60. /// order to avoid spamming the log with lots of warnings.
  61. /// </remarks>
  62. private bool m_warnOverMaxQueue = true;
  63. private BlockingCollection<RefillRequest> m_requestQueue;
  64. private CancellationTokenSource m_cancelSource = new CancellationTokenSource();
  65. private LLUDPServer m_udpServer;
  66. private Stat m_oqreRequestsWaitingStat;
  67. /// <summary>
  68. /// Used to signal that we are ready to complete stop.
  69. /// </summary>
  70. private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
  71. public OutgoingQueueRefillEngine(LLUDPServer server)
  72. {
  73. RequestProcessTimeoutOnStop = 5000;
  74. m_udpServer = server;
  75. MainConsole.Instance.Commands.AddCommand(
  76. "Debug",
  77. false,
  78. "debug lludp oqre",
  79. "debug lludp oqre <start|stop|status>",
  80. "Start, stop or get status of OutgoingQueueRefillEngine.",
  81. "If stopped then refill requests are processed directly via the threadpool.",
  82. HandleOqreCommand);
  83. }
  84. public void Start()
  85. {
  86. lock (this)
  87. {
  88. if (IsRunning)
  89. return;
  90. IsRunning = true;
  91. m_finishedProcessingAfterStop.Reset();
  92. m_requestQueue = new BlockingCollection<RefillRequest>(new ConcurrentQueue<RefillRequest>(), 5000);
  93. m_oqreRequestsWaitingStat =
  94. new Stat(
  95. "OQRERequestsWaiting",
  96. "Number of outgong queue refill requests waiting for processing.",
  97. "",
  98. "",
  99. "clientstack",
  100. m_udpServer.Scene.Name,
  101. StatType.Pull,
  102. MeasuresOfInterest.None,
  103. stat => stat.Value = m_requestQueue.Count,
  104. StatVerbosity.Debug);
  105. StatsManager.RegisterStat(m_oqreRequestsWaitingStat);
  106. WorkManager.StartThread(
  107. ProcessRequests,
  108. String.Format("OutgoingQueueRefillEngineThread ({0})", m_udpServer.Scene.Name),
  109. ThreadPriority.Normal,
  110. false,
  111. true,
  112. null,
  113. int.MaxValue);
  114. }
  115. }
  116. public void Stop()
  117. {
  118. lock (this)
  119. {
  120. try
  121. {
  122. if (!IsRunning)
  123. return;
  124. IsRunning = false;
  125. int requestsLeft = m_requestQueue.Count;
  126. if (requestsLeft <= 0)
  127. {
  128. m_cancelSource.Cancel();
  129. }
  130. else
  131. {
  132. m_log.InfoFormat("[OUTGOING QUEUE REFILL ENGINE]: Waiting to write {0} events after stop.", requestsLeft);
  133. while (requestsLeft > 0)
  134. {
  135. if (!m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
  136. {
  137. // After timeout no events have been written
  138. if (requestsLeft == m_requestQueue.Count)
  139. {
  140. m_log.WarnFormat(
  141. "[OUTGOING QUEUE REFILL ENGINE]: No requests processed after {0} ms wait. Discarding remaining {1} requests",
  142. RequestProcessTimeoutOnStop, requestsLeft);
  143. break;
  144. }
  145. }
  146. requestsLeft = m_requestQueue.Count;
  147. }
  148. }
  149. }
  150. finally
  151. {
  152. m_cancelSource.Dispose();
  153. StatsManager.DeregisterStat(m_oqreRequestsWaitingStat);
  154. m_oqreRequestsWaitingStat = null;
  155. m_requestQueue = null;
  156. }
  157. }
  158. }
  159. public bool QueueRequest(LLUDPClient client, ThrottleOutPacketTypeFlags categories)
  160. {
  161. if (m_requestQueue.Count < m_requestQueue.BoundedCapacity)
  162. {
  163. // m_log.DebugFormat(
  164. // "[OUTGOING QUEUE REFILL ENGINE]: Adding request for categories {0} for {1} in {2}",
  165. // categories, client.AgentID, m_udpServer.Scene.Name);
  166. m_requestQueue.Add(new RefillRequest(client, categories));
  167. if (!m_warnOverMaxQueue)
  168. m_warnOverMaxQueue = true;
  169. return true;
  170. }
  171. else
  172. {
  173. if (m_warnOverMaxQueue)
  174. {
  175. m_log.WarnFormat(
  176. "[OUTGOING QUEUE REFILL ENGINE]: Request queue at maximum capacity, not recording request from {0} in {1}",
  177. client.AgentID, m_udpServer.Scene.Name);
  178. m_warnOverMaxQueue = false;
  179. }
  180. return false;
  181. }
  182. }
  183. private void ProcessRequests()
  184. {
  185. Thread.CurrentThread.Priority = ThreadPriority.Highest;
  186. try
  187. {
  188. while (IsRunning || m_requestQueue.Count > 0)
  189. {
  190. RefillRequest req = m_requestQueue.Take(m_cancelSource.Token);
  191. // QueueEmpty callback = req.Client.OnQueueEmpty;
  192. //
  193. // if (callback != null)
  194. // {
  195. // try
  196. // {
  197. // callback(req.Categories);
  198. // }
  199. // catch (Exception e)
  200. // {
  201. // m_log.Error("[OUTGOING QUEUE REFILL ENGINE]: ProcessRequests(" + req.Categories + ") threw an exception: " + e.Message, e);
  202. // }
  203. // }
  204. req.Client.FireQueueEmpty(req.Categories);
  205. }
  206. }
  207. catch (OperationCanceledException)
  208. {
  209. }
  210. m_finishedProcessingAfterStop.Set();
  211. }
  212. private void HandleOqreCommand(string module, string[] args)
  213. {
  214. if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
  215. return;
  216. if (args.Length != 4)
  217. {
  218. MainConsole.Instance.Output("Usage: debug lludp oqre <stop|start|status>");
  219. return;
  220. }
  221. string subCommand = args[3];
  222. if (subCommand == "stop")
  223. {
  224. Stop();
  225. MainConsole.Instance.OutputFormat("Stopped OQRE for {0}", m_udpServer.Scene.Name);
  226. }
  227. else if (subCommand == "start")
  228. {
  229. Start();
  230. MainConsole.Instance.OutputFormat("Started OQRE for {0}", m_udpServer.Scene.Name);
  231. }
  232. else if (subCommand == "status")
  233. {
  234. MainConsole.Instance.OutputFormat("OQRE in {0}", m_udpServer.Scene.Name);
  235. MainConsole.Instance.OutputFormat("Running: {0}", IsRunning);
  236. MainConsole.Instance.OutputFormat(
  237. "Requests waiting: {0}", IsRunning ? m_requestQueue.Count.ToString() : "n/a");
  238. }
  239. else
  240. {
  241. MainConsole.Instance.OutputFormat("Unrecognized OQRE subcommand {0}", subCommand);
  242. }
  243. }
  244. }
  245. }