EventQueueManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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 OpenSim 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;
  29. using System.Collections.Generic;
  30. using libsecondlife;
  31. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  32. {
  33. /// <summary>
  34. /// EventQueueManager handles event queues
  35. /// Events are queued and executed in separate thread
  36. /// </summary>
  37. [Serializable]
  38. public class EventQueueManager : iScriptEngineFunctionModule
  39. {
  40. //
  41. // Class is instanced in "ScriptEngine" and used by "EventManager" which is also instanced in "ScriptEngine".
  42. //
  43. // Class purpose is to queue and execute functions that are received by "EventManager":
  44. // - allowing "EventManager" to release its event thread immediately, thus not interrupting server execution.
  45. // - allowing us to prioritize and control execution of script functions.
  46. // Class can use multiple threads for simultaneous execution. Mutexes are used for thread safety.
  47. //
  48. // 1. Hold an execution queue for scripts
  49. // 2. Use threads to process queue, each thread executes one script function on each pass.
  50. // 3. Catch any script error and process it
  51. //
  52. //
  53. // Notes:
  54. // * Current execution load balancing is optimized for 1 thread, and can cause unfair execute balancing between scripts.
  55. // Not noticeable unless server is under high load.
  56. //
  57. public ScriptEngine m_ScriptEngine;
  58. /// <summary>
  59. /// List of threads (classes) processing event queue
  60. /// Note that this may or may not be a reference to a static object depending on PrivateRegionThreads config setting.
  61. /// </summary>
  62. internal static List<EventQueueThreadClass> eventQueueThreads = new List<EventQueueThreadClass>(); // Thread pool that we work on
  63. /// <summary>
  64. /// Locking access to eventQueueThreads AND staticGlobalEventQueueThreads.
  65. /// </summary>
  66. // private object eventQueueThreadsLock = new object();
  67. // Static objects for referencing the objects above if we don't have private threads:
  68. //internal static List<EventQueueThreadClass> staticEventQueueThreads; // A static reference used if we don't use private threads
  69. // internal static object staticEventQueueThreadsLock; // Statick lock object reference for same reason
  70. /// <summary>
  71. /// Global static list of all threads (classes) processing event queue -- used by max enforcment thread
  72. /// </summary>
  73. //private List<EventQueueThreadClass> staticGlobalEventQueueThreads = new List<EventQueueThreadClass>();
  74. /// <summary>
  75. /// Used internally to specify how many threads should exit gracefully
  76. /// </summary>
  77. public static int ThreadsToExit;
  78. public static object ThreadsToExitLock = new object();
  79. //public object queueLock = new object(); // Mutex lock object
  80. /// <summary>
  81. /// How many threads to process queue with
  82. /// </summary>
  83. internal static int numberOfThreads;
  84. internal static int EventExecutionMaxQueueSize;
  85. /// <summary>
  86. /// Maximum time one function can use for execution before we perform a thread kill.
  87. /// </summary>
  88. private static int maxFunctionExecutionTimems
  89. {
  90. get { return (int)(maxFunctionExecutionTimens / 10000); }
  91. set { maxFunctionExecutionTimens = value * 10000; }
  92. }
  93. /// <summary>
  94. /// Contains nanoseconds version of maxFunctionExecutionTimems so that it matches time calculations better (performance reasons).
  95. /// WARNING! ONLY UPDATE maxFunctionExecutionTimems, NEVER THIS DIRECTLY.
  96. /// </summary>
  97. public static long maxFunctionExecutionTimens;
  98. /// <summary>
  99. /// Enforce max execution time
  100. /// </summary>
  101. public static bool EnforceMaxExecutionTime;
  102. /// <summary>
  103. /// Kill script (unload) when it exceeds execution time
  104. /// </summary>
  105. private static bool KillScriptOnMaxFunctionExecutionTime;
  106. /// <summary>
  107. /// List of localID locks for mutex processing of script events
  108. /// </summary>
  109. private List<uint> objectLocks = new List<uint>();
  110. private object tryLockLock = new object(); // Mutex lock object
  111. /// <summary>
  112. /// Queue containing events waiting to be executed
  113. /// </summary>
  114. public Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
  115. #region " Queue structures "
  116. /// <summary>
  117. /// Queue item structure
  118. /// </summary>
  119. public struct QueueItemStruct
  120. {
  121. public uint localID;
  122. public LLUUID itemID;
  123. public string functionName;
  124. public Queue_llDetectParams_Struct llDetectParams;
  125. public object[] param;
  126. }
  127. /// <summary>
  128. /// Shared empty llDetectNull
  129. /// </summary>
  130. public readonly static Queue_llDetectParams_Struct llDetectNull = new Queue_llDetectParams_Struct();
  131. /// <summary>
  132. /// Structure to hold data for llDetect* commands
  133. /// </summary>
  134. [Serializable]
  135. public struct Queue_llDetectParams_Struct
  136. {
  137. // More or less just a placeholder for the actual moving of additional data
  138. // should be fixed to something better :)
  139. public LSL_Types.key[] _key;
  140. public LSL_Types.Quaternion[] _Quaternion;
  141. public LSL_Types.Vector3[] _Vector3;
  142. public bool[] _bool;
  143. public int[] _int;
  144. public string[] _string;
  145. }
  146. #endregion
  147. #region " Initialization / Startup "
  148. public EventQueueManager(ScriptEngine _ScriptEngine)
  149. {
  150. m_ScriptEngine = _ScriptEngine;
  151. ReadConfig();
  152. AdjustNumberOfScriptThreads();
  153. }
  154. public void ReadConfig()
  155. {
  156. // Refresh config
  157. numberOfThreads = m_ScriptEngine.ScriptConfigSource.GetInt("NumberOfScriptThreads", 2);
  158. maxFunctionExecutionTimems = m_ScriptEngine.ScriptConfigSource.GetInt("MaxEventExecutionTimeMs", 5000);
  159. EnforceMaxExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("EnforceMaxEventExecutionTime", false);
  160. KillScriptOnMaxFunctionExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("DeactivateScriptOnTimeout", false);
  161. EventExecutionMaxQueueSize = m_ScriptEngine.ScriptConfigSource.GetInt("EventExecutionMaxQueueSize", 300);
  162. // Now refresh config in all threads
  163. lock (eventQueueThreads)
  164. {
  165. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  166. {
  167. EventQueueThread.ReadConfig();
  168. }
  169. }
  170. }
  171. #endregion
  172. #region " Shutdown all threads "
  173. ~EventQueueManager()
  174. {
  175. Stop();
  176. }
  177. private void Stop()
  178. {
  179. if (eventQueueThreads != null)
  180. {
  181. // Kill worker threads
  182. lock (eventQueueThreads)
  183. {
  184. foreach (EventQueueThreadClass EventQueueThread in new ArrayList(eventQueueThreads))
  185. {
  186. AbortThreadClass(EventQueueThread);
  187. }
  188. //eventQueueThreads.Clear();
  189. //staticGlobalEventQueueThreads.Clear();
  190. }
  191. }
  192. // Remove all entries from our event queue
  193. lock (eventQueue)
  194. {
  195. eventQueue.Clear();
  196. }
  197. }
  198. #endregion
  199. #region " Start / stop script execution threads (ThreadClasses) "
  200. private void StartNewThreadClass()
  201. {
  202. EventQueueThreadClass eqtc = new EventQueueThreadClass();
  203. eventQueueThreads.Add(eqtc);
  204. //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started new script execution thread. Current thread count: " + eventQueueThreads.Count);
  205. }
  206. private void AbortThreadClass(EventQueueThreadClass threadClass)
  207. {
  208. if (eventQueueThreads.Contains(threadClass))
  209. eventQueueThreads.Remove(threadClass);
  210. try
  211. {
  212. threadClass.Stop();
  213. }
  214. catch (Exception)
  215. {
  216. //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: If you see this, could you please report it to Tedd:");
  217. //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: Script thread execution timeout kill ended in exception: " + ex.ToString());
  218. }
  219. //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Killed script execution thread. Remaining thread count: " + eventQueueThreads.Count);
  220. }
  221. #endregion
  222. #region " Mutex locks for queue access "
  223. /// <summary>
  224. /// Try to get a mutex lock on localID
  225. /// </summary>
  226. /// <param name="localID"></param>
  227. /// <returns></returns>
  228. public bool TryLock(uint localID)
  229. {
  230. lock (tryLockLock)
  231. {
  232. if (objectLocks.Contains(localID) == true)
  233. {
  234. return false;
  235. }
  236. else
  237. {
  238. objectLocks.Add(localID);
  239. return true;
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// Release mutex lock on localID
  245. /// </summary>
  246. /// <param name="localID"></param>
  247. public void ReleaseLock(uint localID)
  248. {
  249. lock (tryLockLock)
  250. {
  251. if (objectLocks.Contains(localID) == true)
  252. {
  253. objectLocks.Remove(localID);
  254. }
  255. }
  256. }
  257. #endregion
  258. #region " Add events to execution queue "
  259. /// <summary>
  260. /// Add event to event execution queue
  261. /// </summary>
  262. /// <param name="localID">Region object ID</param>
  263. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  264. /// <param name="param">Array of parameters to match event mask</param>
  265. public void AddToObjectQueue(uint localID, string FunctionName, Queue_llDetectParams_Struct qParams, params object[] param)
  266. {
  267. // Determine all scripts in Object and add to their queue
  268. //myScriptEngine.log.Info("[" + ScriptEngineName + "]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
  269. // Do we have any scripts in this object at all? If not, return
  270. if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
  271. {
  272. //Console.WriteLine("Event \String.Empty + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
  273. return;
  274. }
  275. Dictionary<LLUUID, IScript>.KeyCollection scriptKeys =
  276. m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
  277. foreach (LLUUID itemID in scriptKeys)
  278. {
  279. // Add to each script in that object
  280. // TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
  281. AddToScriptQueue(localID, itemID, FunctionName, qParams, param);
  282. }
  283. }
  284. /// <summary>
  285. /// Add event to event execution queue
  286. /// </summary>
  287. /// <param name="localID">Region object ID</param>
  288. /// <param name="itemID">Region script ID</param>
  289. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  290. /// <param name="param">Array of parameters to match event mask</param>
  291. public void AddToScriptQueue(uint localID, LLUUID itemID, string FunctionName, Queue_llDetectParams_Struct qParams, params object[] param)
  292. {
  293. lock (eventQueue)
  294. {
  295. if (eventQueue.Count >= EventExecutionMaxQueueSize)
  296. {
  297. m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: ERROR: Event execution queue item count is at " + eventQueue.Count + ". Config variable \"EventExecutionMaxQueueSize\" is set to " + EventExecutionMaxQueueSize + ", so ignoring new event.");
  298. m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: Event ignored: localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
  299. return;
  300. }
  301. // Create a structure and add data
  302. QueueItemStruct QIS = new QueueItemStruct();
  303. QIS.localID = localID;
  304. QIS.itemID = itemID;
  305. QIS.functionName = FunctionName;
  306. QIS.llDetectParams = qParams;
  307. QIS.param = param;
  308. // Add it to queue
  309. eventQueue.Enqueue(QIS);
  310. }
  311. }
  312. #endregion
  313. #region " Maintenance thread "
  314. /// <summary>
  315. /// Adjust number of script thread classes. It can start new, but if it needs to stop it will just set number of threads in "ThreadsToExit" and threads will have to exit themselves.
  316. /// Called from MaintenanceThread
  317. /// </summary>
  318. public void AdjustNumberOfScriptThreads()
  319. {
  320. // Is there anything here for us to do?
  321. if (eventQueueThreads.Count == numberOfThreads)
  322. return;
  323. lock (eventQueueThreads)
  324. {
  325. int diff = numberOfThreads - eventQueueThreads.Count;
  326. // Positive number: Start
  327. // Negative number: too many are running
  328. if (diff > 0)
  329. {
  330. // We need to add more threads
  331. for (int ThreadCount = eventQueueThreads.Count; ThreadCount < numberOfThreads; ThreadCount++)
  332. {
  333. StartNewThreadClass();
  334. }
  335. }
  336. if (diff < 0)
  337. {
  338. // We need to kill some threads
  339. lock (ThreadsToExitLock)
  340. {
  341. ThreadsToExit = Math.Abs(diff);
  342. }
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Check if any thread class has been executing an event too long
  348. /// </summary>
  349. public void CheckScriptMaxExecTime()
  350. {
  351. // Iterate through all ScriptThreadClasses and check how long their current function has been executing
  352. lock (eventQueueThreads)
  353. {
  354. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  355. {
  356. // Is thread currently executing anything?
  357. if (EventQueueThread.InExecution)
  358. {
  359. // Has execution time expired?
  360. if (DateTime.Now.Ticks - EventQueueThread.LastExecutionStarted >
  361. maxFunctionExecutionTimens)
  362. {
  363. // Yes! We need to kill this thread!
  364. // Set flag if script should be removed or not
  365. EventQueueThread.KillCurrentScript = KillScriptOnMaxFunctionExecutionTime;
  366. // Abort this thread
  367. AbortThreadClass(EventQueueThread);
  368. // We do not need to start another, MaintenenceThread will do that for us
  369. //StartNewThreadClass();
  370. }
  371. }
  372. }
  373. }
  374. }
  375. #endregion
  376. ///// <summary>
  377. ///// If set to true then threads and stuff should try to make a graceful exit
  378. ///// </summary>
  379. //public bool PleaseShutdown
  380. //{
  381. // get { return _PleaseShutdown; }
  382. // set { _PleaseShutdown = value; }
  383. //}
  384. //private bool _PleaseShutdown = false;
  385. }
  386. }