EventQueueManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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; // detected key
  140. public LSL_Types.key[] _key2; // ownerkey
  141. public LSL_Types.Quaternion[] _Quaternion;
  142. public LSL_Types.Vector3[] _Vector3; // Pos
  143. public LSL_Types.Vector3[] _Vector32; // Vel
  144. public bool[] _bool;
  145. public int[] _int;
  146. public string[] _string;
  147. }
  148. #endregion
  149. #region " Initialization / Startup "
  150. public EventQueueManager(ScriptEngine _ScriptEngine)
  151. {
  152. m_ScriptEngine = _ScriptEngine;
  153. ReadConfig();
  154. AdjustNumberOfScriptThreads();
  155. }
  156. public void ReadConfig()
  157. {
  158. // Refresh config
  159. numberOfThreads = m_ScriptEngine.ScriptConfigSource.GetInt("NumberOfScriptThreads", 2);
  160. maxFunctionExecutionTimems = m_ScriptEngine.ScriptConfigSource.GetInt("MaxEventExecutionTimeMs", 5000);
  161. EnforceMaxExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("EnforceMaxEventExecutionTime", false);
  162. KillScriptOnMaxFunctionExecutionTime = m_ScriptEngine.ScriptConfigSource.GetBoolean("DeactivateScriptOnTimeout", false);
  163. EventExecutionMaxQueueSize = m_ScriptEngine.ScriptConfigSource.GetInt("EventExecutionMaxQueueSize", 300);
  164. // Now refresh config in all threads
  165. lock (eventQueueThreads)
  166. {
  167. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  168. {
  169. EventQueueThread.ReadConfig();
  170. }
  171. }
  172. }
  173. #endregion
  174. #region " Shutdown all threads "
  175. ~EventQueueManager()
  176. {
  177. Stop();
  178. }
  179. private void Stop()
  180. {
  181. if (eventQueueThreads != null)
  182. {
  183. // Kill worker threads
  184. lock (eventQueueThreads)
  185. {
  186. foreach (EventQueueThreadClass EventQueueThread in new ArrayList(eventQueueThreads))
  187. {
  188. AbortThreadClass(EventQueueThread);
  189. }
  190. //eventQueueThreads.Clear();
  191. //staticGlobalEventQueueThreads.Clear();
  192. }
  193. }
  194. // Remove all entries from our event queue
  195. lock (eventQueue)
  196. {
  197. eventQueue.Clear();
  198. }
  199. }
  200. #endregion
  201. #region " Start / stop script execution threads (ThreadClasses) "
  202. private void StartNewThreadClass()
  203. {
  204. EventQueueThreadClass eqtc = new EventQueueThreadClass();
  205. eventQueueThreads.Add(eqtc);
  206. //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Started new script execution thread. Current thread count: " + eventQueueThreads.Count);
  207. }
  208. private void AbortThreadClass(EventQueueThreadClass threadClass)
  209. {
  210. if (eventQueueThreads.Contains(threadClass))
  211. eventQueueThreads.Remove(threadClass);
  212. try
  213. {
  214. threadClass.Stop();
  215. }
  216. catch (Exception)
  217. {
  218. //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: If you see this, could you please report it to Tedd:");
  219. //m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + ":EventQueueManager]: Script thread execution timeout kill ended in exception: " + ex.ToString());
  220. }
  221. //m_ScriptEngine.Log.Debug("[" + m_ScriptEngine.ScriptEngineName + "]: Killed script execution thread. Remaining thread count: " + eventQueueThreads.Count);
  222. }
  223. #endregion
  224. #region " Mutex locks for queue access "
  225. /// <summary>
  226. /// Try to get a mutex lock on localID
  227. /// </summary>
  228. /// <param name="localID"></param>
  229. /// <returns></returns>
  230. public bool TryLock(uint localID)
  231. {
  232. lock (tryLockLock)
  233. {
  234. if (objectLocks.Contains(localID) == true)
  235. {
  236. return false;
  237. }
  238. else
  239. {
  240. objectLocks.Add(localID);
  241. return true;
  242. }
  243. }
  244. }
  245. /// <summary>
  246. /// Release mutex lock on localID
  247. /// </summary>
  248. /// <param name="localID"></param>
  249. public void ReleaseLock(uint localID)
  250. {
  251. lock (tryLockLock)
  252. {
  253. if (objectLocks.Contains(localID) == true)
  254. {
  255. objectLocks.Remove(localID);
  256. }
  257. }
  258. }
  259. #endregion
  260. #region " Add events to execution queue "
  261. /// <summary>
  262. /// Add event to event execution queue
  263. /// </summary>
  264. /// <param name="localID">Region object ID</param>
  265. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  266. /// <param name="param">Array of parameters to match event mask</param>
  267. public void AddToObjectQueue(uint localID, string FunctionName, Queue_llDetectParams_Struct qParams, params object[] param)
  268. {
  269. // Determine all scripts in Object and add to their queue
  270. //myScriptEngine.log.Info("[" + ScriptEngineName + "]: EventQueueManager Adding localID: " + localID + ", FunctionName: " + FunctionName);
  271. // Do we have any scripts in this object at all? If not, return
  272. if (m_ScriptEngine.m_ScriptManager.Scripts.ContainsKey(localID) == false)
  273. {
  274. //Console.WriteLine("Event \String.Empty + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
  275. return;
  276. }
  277. Dictionary<LLUUID, IScript>.KeyCollection scriptKeys =
  278. m_ScriptEngine.m_ScriptManager.GetScriptKeys(localID);
  279. foreach (LLUUID itemID in scriptKeys)
  280. {
  281. // Add to each script in that object
  282. // TODO: Some scripts may not subscribe to this event. Should we NOT add it? Does it matter?
  283. AddToScriptQueue(localID, itemID, FunctionName, qParams, param);
  284. }
  285. }
  286. /// <summary>
  287. /// Add event to event execution queue
  288. /// </summary>
  289. /// <param name="localID">Region object ID</param>
  290. /// <param name="itemID">Region script ID</param>
  291. /// <param name="FunctionName">Name of the function, will be state + "_event_" + FunctionName</param>
  292. /// <param name="param">Array of parameters to match event mask</param>
  293. public void AddToScriptQueue(uint localID, LLUUID itemID, string FunctionName, Queue_llDetectParams_Struct qParams, params object[] param)
  294. {
  295. lock (eventQueue)
  296. {
  297. if (eventQueue.Count >= EventExecutionMaxQueueSize)
  298. {
  299. 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.");
  300. m_ScriptEngine.Log.Error("[" + m_ScriptEngine.ScriptEngineName + "]: Event ignored: localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
  301. return;
  302. }
  303. // Create a structure and add data
  304. QueueItemStruct QIS = new QueueItemStruct();
  305. QIS.localID = localID;
  306. QIS.itemID = itemID;
  307. QIS.functionName = FunctionName;
  308. QIS.llDetectParams = qParams;
  309. QIS.param = param;
  310. // Add it to queue
  311. eventQueue.Enqueue(QIS);
  312. }
  313. }
  314. #endregion
  315. #region " Maintenance thread "
  316. /// <summary>
  317. /// 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.
  318. /// Called from MaintenanceThread
  319. /// </summary>
  320. public void AdjustNumberOfScriptThreads()
  321. {
  322. // Is there anything here for us to do?
  323. if (eventQueueThreads.Count == numberOfThreads)
  324. return;
  325. lock (eventQueueThreads)
  326. {
  327. int diff = numberOfThreads - eventQueueThreads.Count;
  328. // Positive number: Start
  329. // Negative number: too many are running
  330. if (diff > 0)
  331. {
  332. // We need to add more threads
  333. for (int ThreadCount = eventQueueThreads.Count; ThreadCount < numberOfThreads; ThreadCount++)
  334. {
  335. StartNewThreadClass();
  336. }
  337. }
  338. if (diff < 0)
  339. {
  340. // We need to kill some threads
  341. lock (ThreadsToExitLock)
  342. {
  343. ThreadsToExit = Math.Abs(diff);
  344. }
  345. }
  346. }
  347. }
  348. /// <summary>
  349. /// Check if any thread class has been executing an event too long
  350. /// </summary>
  351. public void CheckScriptMaxExecTime()
  352. {
  353. // Iterate through all ScriptThreadClasses and check how long their current function has been executing
  354. lock (eventQueueThreads)
  355. {
  356. foreach (EventQueueThreadClass EventQueueThread in eventQueueThreads)
  357. {
  358. // Is thread currently executing anything?
  359. if (EventQueueThread.InExecution)
  360. {
  361. // Has execution time expired?
  362. if (DateTime.Now.Ticks - EventQueueThread.LastExecutionStarted >
  363. maxFunctionExecutionTimens)
  364. {
  365. // Yes! We need to kill this thread!
  366. // Set flag if script should be removed or not
  367. EventQueueThread.KillCurrentScript = KillScriptOnMaxFunctionExecutionTime;
  368. // Abort this thread
  369. AbortThreadClass(EventQueueThread);
  370. // We do not need to start another, MaintenenceThread will do that for us
  371. //StartNewThreadClass();
  372. }
  373. }
  374. }
  375. }
  376. }
  377. #endregion
  378. ///// <summary>
  379. ///// If set to true then threads and stuff should try to make a graceful exit
  380. ///// </summary>
  381. //public bool PleaseShutdown
  382. //{
  383. // get { return _PleaseShutdown; }
  384. // set { _PleaseShutdown = value; }
  385. //}
  386. //private bool _PleaseShutdown = false;
  387. }
  388. }