EventQueueManager.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. */
  28. /* Original code: Tedd Hansen */
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Threading;
  33. using libsecondlife;
  34. using OpenSim.Framework;
  35. using OpenSim.Grid.ScriptEngine.DotNetEngine.Compiler.LSL;
  36. using OpenSim.Region.Environment.Scenes.Scripting;
  37. namespace OpenSim.Grid.ScriptEngine.DotNetEngine
  38. {
  39. /// <summary>
  40. /// EventQueueManager handles event queues
  41. /// Events are queued and executed in separate thread
  42. /// </summary>
  43. [Serializable]
  44. internal class EventQueueManager
  45. {
  46. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  47. /// <summary>
  48. /// List of threads processing event queue
  49. /// </summary>
  50. private List<Thread> eventQueueThreads = new List<Thread>();
  51. private object queueLock = new object(); // Mutex lock object
  52. /// <summary>
  53. /// How many ms to sleep if queue is empty
  54. /// </summary>
  55. private int nothingToDoSleepms = 50;
  56. /// <summary>
  57. /// How many threads to process queue with
  58. /// </summary>
  59. private int numberOfThreads = 2;
  60. /// <summary>
  61. /// Queue containing events waiting to be executed
  62. /// </summary>
  63. private Queue<QueueItemStruct> eventQueue = new Queue<QueueItemStruct>();
  64. /// <summary>
  65. /// Queue item structure
  66. /// </summary>
  67. private struct QueueItemStruct
  68. {
  69. public uint localID;
  70. public LLUUID itemID;
  71. public string functionName;
  72. public object[] param;
  73. }
  74. /// <summary>
  75. /// List of localID locks for mutex processing of script events
  76. /// </summary>
  77. private List<uint> objectLocks = new List<uint>();
  78. private object tryLockLock = new object(); // Mutex lock object
  79. private ScriptEngine m_ScriptEngine;
  80. public EventQueueManager(ScriptEngine _ScriptEngine)
  81. {
  82. m_ScriptEngine = _ScriptEngine;
  83. //
  84. // Start event queue processing threads (worker threads)
  85. //
  86. for (int ThreadCount = 0; ThreadCount <= numberOfThreads; ThreadCount++)
  87. {
  88. Thread EventQueueThread = new Thread(EventQueueThreadLoop);
  89. eventQueueThreads.Add(EventQueueThread);
  90. EventQueueThread.IsBackground = true;
  91. EventQueueThread.Priority = ThreadPriority.BelowNormal;
  92. EventQueueThread.Name = "EventQueueManagerThread_" + ThreadCount;
  93. EventQueueThread.Start();
  94. }
  95. }
  96. ~EventQueueManager()
  97. {
  98. // Kill worker threads
  99. foreach (Thread EventQueueThread in new ArrayList(eventQueueThreads))
  100. {
  101. if (EventQueueThread != null && EventQueueThread.IsAlive == true)
  102. {
  103. try
  104. {
  105. EventQueueThread.Abort();
  106. EventQueueThread.Join();
  107. }
  108. catch (Exception)
  109. {
  110. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Exception killing worker thread: " + e.ToString());
  111. }
  112. }
  113. }
  114. eventQueueThreads.Clear();
  115. // Todo: Clean up our queues
  116. eventQueue.Clear();
  117. }
  118. /// <summary>
  119. /// Queue processing thread loop
  120. /// </summary>
  121. private void EventQueueThreadLoop()
  122. {
  123. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Worker thread spawned");
  124. try
  125. {
  126. QueueItemStruct BlankQIS = new QueueItemStruct();
  127. while (true)
  128. {
  129. try
  130. {
  131. QueueItemStruct QIS = BlankQIS;
  132. bool GotItem = false;
  133. if (eventQueue.Count == 0)
  134. {
  135. // Nothing to do? Sleep a bit waiting for something to do
  136. Thread.Sleep(nothingToDoSleepms);
  137. }
  138. else
  139. {
  140. // Something in queue, process
  141. //myScriptEngine.m_log.Info("[ScriptEngine]: Processing event for localID: " + QIS.localID + ", itemID: " + QIS.itemID + ", FunctionName: " + QIS.FunctionName);
  142. // OBJECT BASED LOCK - TWO THREADS WORKING ON SAME OBJECT IS NOT GOOD
  143. lock (queueLock)
  144. {
  145. GotItem = false;
  146. for (int qc = 0; qc < eventQueue.Count; qc++)
  147. {
  148. // Get queue item
  149. QIS = eventQueue.Dequeue();
  150. // Check if object is being processed by someone else
  151. if (TryLock(QIS.localID) == false)
  152. {
  153. // Object is already being processed, requeue it
  154. eventQueue.Enqueue(QIS);
  155. }
  156. else
  157. {
  158. // We have lock on an object and can process it
  159. GotItem = true;
  160. break;
  161. }
  162. }
  163. }
  164. if (GotItem == true)
  165. {
  166. // Execute function
  167. try
  168. {
  169. m_ScriptEngine.m_ScriptManager.ExecuteEvent(QIS.localID, QIS.itemID,
  170. QIS.functionName, QIS.param);
  171. }
  172. catch (Exception e)
  173. {
  174. // DISPLAY ERROR INWORLD
  175. string text = "Error executing script function \"" + QIS.functionName + "\":\r\n";
  176. if (e.InnerException != null)
  177. {
  178. // Send inner exception
  179. text += e.InnerException.Message.ToString();
  180. }
  181. else
  182. {
  183. // Send normal
  184. text += e.Message.ToString();
  185. }
  186. try
  187. {
  188. if (text.Length > 1500)
  189. text = text.Substring(0, 1500);
  190. IScriptHost m_host = m_ScriptEngine.World.GetSceneObjectPart(QIS.localID);
  191. //if (m_host != null)
  192. //{
  193. m_ScriptEngine.World.SimChat(Helpers.StringToField(text), ChatTypeEnum.Say, 0,
  194. m_host.AbsolutePosition, m_host.Name, m_host.UUID);
  195. }
  196. catch
  197. {
  198. //}
  199. //else
  200. //{
  201. // T oconsole
  202. Console.WriteLine("Unable to send text in-world:\r\n" + text);
  203. }
  204. }
  205. finally
  206. {
  207. ReleaseLock(QIS.localID);
  208. }
  209. }
  210. }
  211. }
  212. catch (ThreadAbortException tae)
  213. {
  214. throw tae;
  215. }
  216. catch (Exception e)
  217. {
  218. Console.WriteLine("Exception in EventQueueThreadLoop: " + e.ToString());
  219. }
  220. }
  221. }
  222. catch (ThreadAbortException)
  223. {
  224. //myScriptEngine.m_log.Info("[ScriptEngine]: EventQueueManager Worker thread killed: " + tae.Message);
  225. }
  226. }
  227. /// <summary>
  228. /// Try to get a mutex lock on localID
  229. /// </summary>
  230. /// <param name="localID"></param>
  231. /// <returns></returns>
  232. private bool TryLock(uint localID)
  233. {
  234. lock (tryLockLock)
  235. {
  236. if (objectLocks.Contains(localID) == true)
  237. {
  238. return false;
  239. }
  240. else
  241. {
  242. objectLocks.Add(localID);
  243. return true;
  244. }
  245. }
  246. }
  247. /// <summary>
  248. /// Release mutex lock on localID
  249. /// </summary>
  250. /// <param name="localID"></param>
  251. private void ReleaseLock(uint localID)
  252. {
  253. lock (tryLockLock)
  254. {
  255. if (objectLocks.Contains(localID) == true)
  256. {
  257. objectLocks.Remove(localID);
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// Add event to event execution queue
  263. /// </summary>
  264. /// <param name="localID"></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, object[] param)
  268. {
  269. // Determine all scripts in Object and add to their queue
  270. //myScriptEngine.m_log.Info("[ScriptEngine]: 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 \"" + FunctionName + "\" for localID: " + localID + ". No scripts found on this localID.");
  275. return;
  276. }
  277. Dictionary<LLUUID, LSL_BaseClass>.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, param);
  284. }
  285. }
  286. /// <summary>
  287. /// Add event to event execution queue
  288. /// </summary>
  289. /// <param name="localID"></param>
  290. /// <param name="itemID"></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, object[] param)
  294. {
  295. lock (queueLock)
  296. {
  297. // Create a structure and add data
  298. QueueItemStruct QIS = new QueueItemStruct();
  299. QIS.localID = localID;
  300. QIS.itemID = itemID;
  301. QIS.functionName = FunctionName;
  302. QIS.param = param;
  303. // Add it to queue
  304. eventQueue.Enqueue(QIS);
  305. }
  306. }
  307. }
  308. }