JobEngine.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. /// Number of jobs waiting to be processed.
  48. /// </summary>
  49. public int JobsWaiting { get { return m_jobQueue.Count; } }
  50. /// <summary>
  51. /// Controls whether we need to warn in the log about exceeding the max queue size.
  52. /// </summary>
  53. /// <remarks>
  54. /// This is flipped to false once queue max has been exceeded and back to true when it falls below max, in
  55. /// order to avoid spamming the log with lots of warnings.
  56. /// </remarks>
  57. private bool m_warnOverMaxQueue = true;
  58. private BlockingCollection<Job> m_jobQueue = new BlockingCollection<Job>(5000);
  59. private CancellationTokenSource m_cancelSource;
  60. private int m_timeout = -1;
  61. private int m_concurrency = 1;
  62. private int m_numberThreads = 0;
  63. public JobEngine(string name, string loggingName, int timeout = -1, int concurrency = 1)
  64. {
  65. Name = name;
  66. LoggingName = loggingName;
  67. m_timeout = timeout;
  68. m_concurrency = concurrency;
  69. }
  70. public void Start()
  71. {
  72. lock (JobLock)
  73. {
  74. if (IsRunning)
  75. return;
  76. if(m_concurrency < 1)
  77. m_concurrency = 1;
  78. IsRunning = true;
  79. m_cancelSource = new CancellationTokenSource();
  80. }
  81. }
  82. public void Stop()
  83. {
  84. lock (JobLock)
  85. {
  86. try
  87. {
  88. if (!IsRunning)
  89. return;
  90. m_log.DebugFormat("[JobEngine] Stopping {0}", Name);
  91. IsRunning = false;
  92. if(m_numberThreads > 0)
  93. {
  94. m_cancelSource.Cancel();
  95. Thread.Yield();
  96. }
  97. }
  98. finally
  99. {
  100. if(m_cancelSource != null)
  101. {
  102. m_cancelSource.Dispose();
  103. m_cancelSource = null;
  104. }
  105. if (m_jobQueue != null)
  106. {
  107. m_jobQueue.Dispose();
  108. m_jobQueue = null;
  109. }
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// Make a job.
  115. /// </summary>
  116. /// <remarks>
  117. /// We provide this method to replace the constructor so that we can later pool job objects if necessary to
  118. /// reduce memory churn. Normally one would directly call QueueJob() with parameters anyway.
  119. /// </remarks>
  120. /// <returns></returns>
  121. /// <param name="name">Name.</param>
  122. /// <param name="action">Action.</param>
  123. /// <param name="commonId">Common identifier.</param>
  124. public static Job MakeJob(string name, Action action, string commonId = null)
  125. {
  126. return Job.MakeJob(name, action, commonId);
  127. }
  128. /// <summary>
  129. /// Remove the next job queued for processing.
  130. /// </summary>
  131. /// <remarks>
  132. /// Returns null if there is no next job.
  133. /// Will not remove a job currently being performed.
  134. /// </remarks>
  135. public Job RemoveNextJob()
  136. {
  137. Job nextJob;
  138. m_jobQueue.TryTake(out nextJob);
  139. return nextJob;
  140. }
  141. /// <summary>
  142. /// Queue the job for processing.
  143. /// </summary>
  144. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  145. /// <param name="name">Name of job. This appears on the console and in logging.</param>
  146. /// <param name="action">Action to perform.</param>
  147. /// <param name="commonId">
  148. /// Common identifier for a set of jobs. This is allows a set of jobs to be removed
  149. /// if required (e.g. all jobs for a given agent. Optional.
  150. /// </param>
  151. public bool QueueJob(string name, Action action, string commonId = null)
  152. {
  153. return QueueJob(MakeJob(name, action, commonId));
  154. }
  155. /// <summary>
  156. /// Queue the job for processing.
  157. /// </summary>
  158. /// <returns><c>true</c>, if job was queued, <c>false</c> otherwise.</returns>
  159. /// <param name="job">The job</param>
  160. /// </param>
  161. public bool QueueJob(Job job)
  162. {
  163. if (!IsRunning)
  164. return false;
  165. if (m_jobQueue.Count < m_jobQueue.BoundedCapacity)
  166. {
  167. m_jobQueue.Add(job);
  168. lock (JobLock)
  169. {
  170. if (m_numberThreads < m_concurrency && m_numberThreads < m_jobQueue.Count)
  171. {
  172. Util.FireAndForget(ProcessRequests, null, Name, false);
  173. ++m_numberThreads;
  174. }
  175. }
  176. if (!m_warnOverMaxQueue)
  177. m_warnOverMaxQueue = true;
  178. return true;
  179. }
  180. else
  181. {
  182. if (m_warnOverMaxQueue)
  183. {
  184. m_log.WarnFormat(
  185. "[{0}]: Job queue at maximum capacity, not recording job from {1} in {2}",
  186. LoggingName, job.Name, Name);
  187. m_warnOverMaxQueue = false;
  188. }
  189. return false;
  190. }
  191. }
  192. private void ProcessRequests(object o)
  193. {
  194. Job currentJob;
  195. while (IsRunning)
  196. {
  197. try
  198. {
  199. if(!m_jobQueue.TryTake(out currentJob, m_timeout, m_cancelSource.Token))
  200. break;
  201. }
  202. catch
  203. {
  204. break;
  205. }
  206. if(LogLevel >= 1)
  207. m_log.DebugFormat("[{0}]: Processing job {1}",LoggingName,currentJob.Name);
  208. try
  209. {
  210. currentJob.Action();
  211. }
  212. catch(Exception e)
  213. {
  214. m_log.ErrorFormat(
  215. "[{0}]: Job {1} failed, continuing. Exception {2}",LoggingName, currentJob.Name, e);
  216. }
  217. if(LogLevel >= 1)
  218. m_log.DebugFormat("[{0}]: Processed job {1}",LoggingName,currentJob.Name);
  219. currentJob.Action = null;
  220. currentJob = null;
  221. }
  222. lock (JobLock)
  223. --m_numberThreads;
  224. }
  225. public class Job
  226. {
  227. /// <summary>
  228. /// Name of the job.
  229. /// </summary>
  230. /// <remarks>
  231. /// This appears on console and debug output.
  232. /// </remarks>
  233. public string Name { get; private set; }
  234. /// <summary>
  235. /// Common ID for this job.
  236. /// </summary>
  237. /// <remarks>
  238. /// This allows all jobs with a certain common ID (e.g. a client UUID) to be removed en-masse if required.
  239. /// Can be null if this is not required.
  240. /// </remarks>
  241. public string CommonId { get; private set; }
  242. /// <summary>
  243. /// Action to perform when this job is processed.
  244. /// </summary>
  245. public Action Action { get; set; }
  246. private Job(string name, string commonId, Action action)
  247. {
  248. Name = name;
  249. CommonId = commonId;
  250. Action = action;
  251. }
  252. /// <summary>
  253. /// Make a job. It needs to be separately queued.
  254. /// </summary>
  255. /// <remarks>
  256. /// We provide this method to replace the constructor so that we can pool job objects if necessary to
  257. /// to reduce memory churn. Normally one would directly call JobEngine.QueueJob() with parameters anyway.
  258. /// </remarks>
  259. /// <returns></returns>
  260. /// <param name="name">Name.</param>
  261. /// <param name="action">Action.</param>
  262. /// <param name="commonId">Common identifier.</param>
  263. public static Job MakeJob(string name, Action action, string commonId = null)
  264. {
  265. return new Job(name, commonId, action);
  266. }
  267. }
  268. }
  269. }