HGIncomingSceneObjectEngine.cs 13 KB

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