IncomingPacketAsyncHandlingEngine.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 class Job
  38. {
  39. public string Name;
  40. public WaitCallback Callback;
  41. public object O;
  42. public Job(string name, WaitCallback callback, object o)
  43. {
  44. Name = name;
  45. Callback = callback;
  46. O = o;
  47. }
  48. }
  49. // TODO: These kinds of classes MUST be generalized with JobEngine, etc.
  50. public class IncomingPacketAsyncHandlingEngine
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. public int LogLevel { get; set; }
  54. public bool IsRunning { get; private set; }
  55. /// <summary>
  56. /// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
  57. /// </summary>
  58. public int RequestProcessTimeoutOnStop { get; set; }
  59. /// <summary>
  60. /// Controls whether we need to warn in the log about exceeding the max queue size.
  61. /// </summary>
  62. /// <remarks>
  63. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  64. /// order to avoid spamming the log with lots of warnings.
  65. /// </remarks>
  66. private bool m_warnOverMaxQueue = true;
  67. private BlockingCollection<Job> m_requestQueue;
  68. private CancellationTokenSource m_cancelSource = new CancellationTokenSource();
  69. private LLUDPServer m_udpServer;
  70. private Stat m_requestsWaitingStat;
  71. private Job m_currentJob;
  72. /// <summary>
  73. /// Used to signal that we are ready to complete stop.
  74. /// </summary>
  75. private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
  76. public IncomingPacketAsyncHandlingEngine(LLUDPServer server)
  77. {
  78. //LogLevel = 1;
  79. m_udpServer = server;
  80. RequestProcessTimeoutOnStop = 5000;
  81. // MainConsole.Instance.Commands.AddCommand(
  82. // "Debug",
  83. // false,
  84. // "debug jobengine",
  85. // "debug jobengine <start|stop|status>",
  86. // "Start, stop or get status of the job engine.",
  87. // "If stopped then all jobs are processed immediately.",
  88. // HandleControlCommand);
  89. }
  90. public void Start()
  91. {
  92. lock (this)
  93. {
  94. if (IsRunning)
  95. return;
  96. IsRunning = true;
  97. m_finishedProcessingAfterStop.Reset();
  98. m_requestQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);
  99. m_requestsWaitingStat =
  100. new Stat(
  101. "IncomingPacketAsyncRequestsWaiting",
  102. "Number of incoming packets waiting for async processing in engine.",
  103. "",
  104. "",
  105. "clientstack",
  106. m_udpServer.Scene.Name,
  107. StatType.Pull,
  108. MeasuresOfInterest.None,
  109. stat => stat.Value = m_requestQueue.Count,
  110. StatVerbosity.Debug);
  111. StatsManager.RegisterStat(m_requestsWaitingStat);
  112. WorkManager.StartThread(
  113. ProcessRequests,
  114. string.Format("Incoming Packet Async Handling Engine Thread ({0})", m_udpServer.Scene.Name),
  115. ThreadPriority.Normal,
  116. false,
  117. true,
  118. null,
  119. int.MaxValue);
  120. }
  121. }
  122. public void Stop()
  123. {
  124. lock (this)
  125. {
  126. try
  127. {
  128. if (!IsRunning)
  129. return;
  130. IsRunning = false;
  131. int requestsLeft = m_requestQueue.Count;
  132. if (requestsLeft <= 0)
  133. {
  134. m_cancelSource.Cancel();
  135. }
  136. else
  137. {
  138. m_log.InfoFormat("[INCOMING PACKET ASYNC HANDLING ENGINE]: Waiting to write {0} events after stop.", requestsLeft);
  139. while (requestsLeft > 0)
  140. {
  141. if (!m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
  142. {
  143. // After timeout no events have been written
  144. if (requestsLeft == m_requestQueue.Count)
  145. {
  146. m_log.WarnFormat(
  147. "[INCOMING PACKET ASYNC HANDLING ENGINE]: No requests processed after {0} ms wait. Discarding remaining {1} requests",
  148. RequestProcessTimeoutOnStop, requestsLeft);
  149. break;
  150. }
  151. }
  152. requestsLeft = m_requestQueue.Count;
  153. }
  154. }
  155. }
  156. finally
  157. {
  158. m_cancelSource.Dispose();
  159. StatsManager.DeregisterStat(m_requestsWaitingStat);
  160. m_requestsWaitingStat = null;
  161. m_requestQueue = null;
  162. }
  163. }
  164. }
  165. public bool QueueRequest(string name, WaitCallback req, object o)
  166. {
  167. if (LogLevel >= 1)
  168. m_log.DebugFormat("[INCOMING PACKET ASYNC HANDLING ENGINE]: Queued job {0}", name);
  169. if (m_requestQueue.Count < m_requestQueue.BoundedCapacity)
  170. {
  171. // m_log.DebugFormat(
  172. // "[OUTGOING QUEUE REFILL ENGINE]: Adding request for categories {0} for {1} in {2}",
  173. // categories, client.AgentID, m_udpServer.Scene.Name);
  174. m_requestQueue.Add(new Job(name, req, o));
  175. if (!m_warnOverMaxQueue)
  176. m_warnOverMaxQueue = true;
  177. return true;
  178. }
  179. else
  180. {
  181. if (m_warnOverMaxQueue)
  182. {
  183. // m_log.WarnFormat(
  184. // "[JOB ENGINE]: Request queue at maximum capacity, not recording request from {0} in {1}",
  185. // client.AgentID, m_udpServer.Scene.Name);
  186. m_log.WarnFormat("[INCOMING PACKET ASYNC HANDLING ENGINE]: Request queue at maximum capacity, not recording job");
  187. m_warnOverMaxQueue = false;
  188. }
  189. return false;
  190. }
  191. }
  192. private void ProcessRequests()
  193. {
  194. try
  195. {
  196. while (IsRunning || m_requestQueue.Count > 0)
  197. {
  198. m_currentJob = m_requestQueue.Take(m_cancelSource.Token);
  199. // QueueEmpty callback = req.Client.OnQueueEmpty;
  200. //
  201. // if (callback != null)
  202. // {
  203. // try
  204. // {
  205. // callback(req.Categories);
  206. // }
  207. // catch (Exception e)
  208. // {
  209. // m_log.Error("[OUTGOING QUEUE REFILL ENGINE]: ProcessRequests(" + req.Categories + ") threw an exception: " + e.Message, e);
  210. // }
  211. // }
  212. if (LogLevel >= 1)
  213. m_log.DebugFormat("[INCOMING PACKET ASYNC HANDLING ENGINE]: Processing job {0}", m_currentJob.Name);
  214. try
  215. {
  216. m_currentJob.Callback.Invoke(m_currentJob.O);
  217. }
  218. catch (Exception e)
  219. {
  220. m_log.Error(
  221. string.Format(
  222. "[INCOMING PACKET ASYNC HANDLING ENGINE]: Job {0} failed, continuing. Exception ", m_currentJob.Name), e);
  223. }
  224. if (LogLevel >= 1)
  225. m_log.DebugFormat("[INCOMING PACKET ASYNC HANDLING ENGINE]: Processed job {0}", m_currentJob.Name);
  226. m_currentJob = null;
  227. }
  228. }
  229. catch (OperationCanceledException)
  230. {
  231. }
  232. m_finishedProcessingAfterStop.Set();
  233. }
  234. // private void HandleControlCommand(string module, string[] args)
  235. // {
  236. // // if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
  237. // // return;
  238. //
  239. // if (args.Length < 3)
  240. // {
  241. // MainConsole.Instance.Output("Usage: debug jobengine <stop|start|status|loglevel>");
  242. // return;
  243. // }
  244. //
  245. // string subCommand = args[2];
  246. //
  247. // if (subCommand == "stop")
  248. // {
  249. // Stop();
  250. // MainConsole.Instance.OutputFormat("Stopped job engine.");
  251. // }
  252. // else if (subCommand == "start")
  253. // {
  254. // Start();
  255. // MainConsole.Instance.OutputFormat("Started job engine.");
  256. // }
  257. // else if (subCommand == "status")
  258. // {
  259. // MainConsole.Instance.OutputFormat("Job engine running: {0}", IsRunning);
  260. // MainConsole.Instance.OutputFormat("Current job {0}", m_currentJob != null ? m_currentJob.Name : "none");
  261. // MainConsole.Instance.OutputFormat(
  262. // "Jobs waiting: {0}", IsRunning ? m_requestQueue.Count.ToString() : "n/a");
  263. // MainConsole.Instance.OutputFormat("Log Level: {0}", LogLevel);
  264. // }
  265. //
  266. // else if (subCommand == "loglevel")
  267. // {
  268. // // int logLevel;
  269. // int logLevel = int.Parse(args[3]);
  270. // // if (ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out logLevel))
  271. // // {
  272. // LogLevel = logLevel;
  273. // MainConsole.Instance.OutputFormat("Set log level to {0}", LogLevel);
  274. // // }
  275. // }
  276. // else
  277. // {
  278. // MainConsole.Instance.OutputFormat("Unrecognized job engine subcommand {0}", subCommand);
  279. // }
  280. // }
  281. }
  282. }