JobEngine.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. namespace OpenSim.Framework.Monitoring
  34. {
  35. public class JobEngine
  36. {
  37. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  38. public int LogLevel { get; set; }
  39. private object JobLock = new object();
  40. public string Name { get; private set; }
  41. public string LoggingName { get; private set; }
  42. /// <summary>
  43. /// Is this engine running?
  44. /// </summary>
  45. public bool IsRunning { get; private set; }
  46. /// <summary>
  47. /// The current job that the engine is running.
  48. /// </summary>
  49. /// <remarks>
  50. /// Will be null if no job is currently running.
  51. /// </remarks>
  52. public Job CurrentJob { get; private set; }
  53. /// <summary>
  54. /// Number of jobs waiting to be processed.
  55. /// </summary>
  56. public int JobsWaiting { get { return m_jobQueue.Count; } }
  57. /// <summary>
  58. /// The timeout in milliseconds to wait for at least one event to be written when the recorder is stopping.
  59. /// </summary>
  60. public int RequestProcessTimeoutOnStop { get; set; }
  61. /// <summary>
  62. /// Controls whether we need to warn in the log about exceeding the max queue size.
  63. /// </summary>
  64. /// <remarks>
  65. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  66. /// order to avoid spamming the log with lots of warnings.
  67. /// </remarks>
  68. private bool m_warnOverMaxQueue = true;
  69. private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(new ConcurrentQueue<Job>(), 5000);
  70. private CancellationTokenSource m_cancelSource;
  71. /// <summary>
  72. /// Used to signal that we are ready to complete stop.
  73. /// </summary>
  74. private ManualResetEvent m_finishedProcessingAfterStop = new ManualResetEvent(false);
  75. public JobEngine(string name, string loggingName)
  76. {
  77. Name = name;
  78. LoggingName = loggingName;
  79. RequestProcessTimeoutOnStop = 5000;
  80. }
  81. public void Start()
  82. {
  83. lock (JobLock)
  84. {
  85. if (IsRunning)
  86. return;
  87. IsRunning = true;
  88. m_finishedProcessingAfterStop.Reset();
  89. m_cancelSource = new CancellationTokenSource();
  90. WorkManager.StartThread(
  91. ProcessRequests,
  92. Name,
  93. ThreadPriority.Normal,
  94. false,
  95. true,
  96. null,
  97. int.MaxValue);
  98. }
  99. }
  100. public void Stop()
  101. {
  102. lock (JobLock)
  103. {
  104. try
  105. {
  106. if (!IsRunning)
  107. return;
  108. m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
  109. IsRunning = false;
  110. m_finishedProcessingAfterStop.Reset();
  111. if(m_jobQueue.Count <= 0)
  112. m_cancelSource.Cancel();
  113. if(m_finishedProcessingAfterStop.WaitOne(RequestProcessTimeoutOnStop))
  114. m_finishedProcessingAfterStop.Close();
  115. }
  116. finally
  117. {
  118. m_cancelSource.Dispose();
  119. }
  120. }
  121. }
  122. /// <summary>
  123. /// Make a job.
  124. /// </summary>
  125. /// <remarks>
  126. /// We provide this method to replace the constructor so that we can later pool job objects if necessary to
  127. /// reduce memory churn. Normally one would directly call QueueJob() with parameters anyway.
  128. /// </remarks>
  129. /// <returns></returns>
  130. /// <param name="name">Name.</param>
  131. /// <param name="action">Action.</param>
  132. /// <param name="commonId">Common identifier.</param>
  133. public static Job MakeJob(string name, Action action, string commonId = null)
  134. {
  135. return Job.MakeJob(name, action, commonId);
  136. }
  137. /// <summary>
  138. /// Remove the next job queued for processing.
  139. /// </summary>
  140. /// <remarks>
  141. /// Returns null if there is no next job.
  142. /// Will not remove a job currently being performed.
  143. /// </remarks>
  144. public Job RemoveNextJob()
  145. {
  146. Job nextJob;
  147. m_jobQueue.TryTake(out nextJob);
  148. return nextJob;
  149. }
  150. /// <summary>
  151. /// Queue the job for processing.
  152. /// </summary>
  153. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  154. /// <param name="name">Name of job. This appears on the console and in logging.</param>
  155. /// <param name="action">Action to perform.</param>
  156. /// <param name="commonId">
  157. /// Common identifier for a set of jobs. This is allows a set of jobs to be removed
  158. /// if required (e.g. all jobs for a given agent. Optional.
  159. /// </param>
  160. public bool QueueJob(string name, Action action, string commonId = null)
  161. {
  162. return QueueJob(MakeJob(name, action, commonId));
  163. }
  164. /// <summary>
  165. /// Queue the job for processing.
  166. /// </summary>
  167. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  168. /// <param name="job">The job</param>
  169. /// </param>
  170. public bool QueueJob(Job job)
  171. {
  172. if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
  173. {
  174. m_jobQueue.Add(job);
  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. "[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
  185. LoggingName, job.Name, Name);
  186. m_warnOverMaxQueue = false;
  187. }
  188. return false;
  189. }
  190. }
  191. private void ProcessRequests()
  192. {
  193. while(IsRunning || m_jobQueue.Count > 0)
  194. {
  195. try
  196. {
  197. CurrentJob = m_jobQueue.Take(m_cancelSource.Token);
  198. }
  199. catch(ObjectDisposedException e)
  200. {
  201. // If we see this whilst not running then it may be due to a race where this thread checks
  202. // IsRunning after the stopping thread sets it to false and disposes of the cancellation source.
  203. if(IsRunning)
  204. throw e;
  205. else
  206. {
  207. m_log.DebugFormat("[JobEngine] {0} stopping ignoring {1} jobs in queue",
  208. Name,m_jobQueue.Count);
  209. break;
  210. }
  211. }
  212. catch(OperationCanceledException)
  213. {
  214. break;
  215. }
  216. if(LogLevel >= 1)
  217. m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,CurrentJob.Name);
  218. try
  219. {
  220. CurrentJob.Action();
  221. }
  222. catch(Exception e)
  223. {
  224. m_log.Error(
  225. string.Format(
  226. "[{0}]: Job {1} failed, continuing. Exception ",LoggingName,CurrentJob.Name),e);
  227. }
  228. if(LogLevel >= 1)
  229. m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,CurrentJob.Name);
  230. CurrentJob = null;
  231. }
  232. Watchdog.RemoveThread(false);
  233. m_finishedProcessingAfterStop.Set();
  234. }
  235. public class Job
  236. {
  237. /// <summary>
  238. /// Name of the job.
  239. /// </summary>
  240. /// <remarks>
  241. /// This appears on console and debug output.
  242. /// </remarks>
  243. public string Name { get; private set; }
  244. /// <summary>
  245. /// Common ID for this job.
  246. /// </summary>
  247. /// <remarks>
  248. /// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
  249. /// Can be null if this is not required.
  250. /// </remarks>
  251. public string CommonId { get; private set; }
  252. /// <summary>
  253. /// Action to perform when this job is processed.
  254. /// </summary>
  255. public Action Action { get; private set; }
  256. private Job(string name, string commonId, Action action)
  257. {
  258. Name = name;
  259. CommonId = commonId;
  260. Action = action;
  261. }
  262. /// <summary>
  263. /// Make a job. It needs to be separately queued.
  264. /// </summary>
  265. /// <remarks>
  266. /// We provide this method to replace the constructor so that we can pool job objects if necessary to
  267. /// to reduce memory churn. Normally one would directly call JobEngine.QueueJob() with parameters anyway.
  268. /// </remarks>
  269. /// <returns></returns>
  270. /// <param name="name">Name.</param>
  271. /// <param name="action">Action.</param>
  272. /// <param name="commonId">Common identifier.</param>
  273. public static Job MakeJob(string name, Action action, string commonId = null)
  274. {
  275. return new Job(name, commonId, action);
  276. }
  277. }
  278. }
  279. }