EventQueueThreadClass.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 System.Text;
  31. using System.Threading;
  32. using libsecondlife;
  33. using Nini.Config;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Environment.Scenes.Scripting;
  36. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  37. {
  38. /// <summary>
  39. /// Because every thread needs some data set for it (time started to execute current function), it will do its work within a class
  40. /// </summary>
  41. public class EventQueueThreadClass : iScriptEngineFunctionModule
  42. {
  43. /// <summary>
  44. /// How many ms to sleep if queue is empty
  45. /// </summary>
  46. private static int nothingToDoSleepms;// = 50;
  47. private static ThreadPriority MyThreadPriority;
  48. public long LastExecutionStarted;
  49. public bool InExecution = false;
  50. public bool KillCurrentScript = false;
  51. //private EventQueueManager eventQueueManager;
  52. public Thread EventQueueThread;
  53. private static int ThreadCount = 0;
  54. private string ScriptEngineName = "ScriptEngine.Common";
  55. public EventQueueThreadClass()//EventQueueManager eqm
  56. {
  57. //eventQueueManager = eqm;
  58. ReadConfig();
  59. Start();
  60. }
  61. ~EventQueueThreadClass()
  62. {
  63. Stop();
  64. }
  65. public void ReadConfig()
  66. {
  67. lock (ScriptEngine.ScriptEngines)
  68. {
  69. foreach (ScriptEngine m_ScriptEngine in ScriptEngine.ScriptEngines)
  70. {
  71. ScriptEngineName = m_ScriptEngine.ScriptEngineName;
  72. nothingToDoSleepms = m_ScriptEngine.ScriptConfigSource.GetInt("SleepTimeIfNoScriptExecutionMs", 50);
  73. // Later with ScriptServer we might want to ask OS for stuff too, so doing this a bit manually
  74. string pri = m_ScriptEngine.ScriptConfigSource.GetString("ScriptThreadPriority", "BelowNormal");
  75. switch (pri.ToLower())
  76. {
  77. case "lowest":
  78. MyThreadPriority = ThreadPriority.Lowest;
  79. break;
  80. case "belownormal":
  81. MyThreadPriority = ThreadPriority.BelowNormal;
  82. break;
  83. case "normal":
  84. MyThreadPriority = ThreadPriority.Normal;
  85. break;
  86. case "abovenormal":
  87. MyThreadPriority = ThreadPriority.AboveNormal;
  88. break;
  89. case "highest":
  90. MyThreadPriority = ThreadPriority.Highest;
  91. break;
  92. default:
  93. MyThreadPriority = ThreadPriority.BelowNormal; // Default
  94. m_ScriptEngine.Log.Error("[ScriptEngineBase]: Unknown priority type \"" + pri +
  95. "\" in config file. Defaulting to \"BelowNormal\".");
  96. break;
  97. }
  98. }
  99. }
  100. // Now set that priority
  101. if (EventQueueThread != null)
  102. if (EventQueueThread.IsAlive)
  103. EventQueueThread.Priority = MyThreadPriority;
  104. }
  105. /// <summary>
  106. /// Start thread
  107. /// </summary>
  108. private void Start()
  109. {
  110. EventQueueThread = new Thread(EventQueueThreadLoop);
  111. EventQueueThread.IsBackground = true;
  112. EventQueueThread.Priority = MyThreadPriority;
  113. EventQueueThread.Name = "EventQueueManagerThread_" + ThreadCount;
  114. EventQueueThread.Start();
  115. OpenSim.Framework.ThreadTracker.Add(EventQueueThread);
  116. // Look at this... Don't you wish everyone did that solid coding everywhere? :P
  117. if (ThreadCount == int.MaxValue)
  118. ThreadCount = 0;
  119. ThreadCount++;
  120. }
  121. public void Stop()
  122. {
  123. //PleaseShutdown = true; // Set shutdown flag
  124. //Thread.Sleep(100); // Wait a bit
  125. if (EventQueueThread != null && EventQueueThread.IsAlive == true)
  126. {
  127. try
  128. {
  129. EventQueueThread.Abort(); // Send abort
  130. //EventQueueThread.Join(); // Wait for it
  131. }
  132. catch (Exception)
  133. {
  134. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Exception killing worker thread: " + e.ToString());
  135. }
  136. }
  137. }
  138. private EventQueueManager.QueueItemStruct BlankQIS = new EventQueueManager.QueueItemStruct();
  139. private ScriptEngine lastScriptEngine;
  140. /// <summary>
  141. /// Queue processing thread loop
  142. /// </summary>
  143. private void EventQueueThreadLoop()
  144. {
  145. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Worker thread spawned");
  146. try
  147. {
  148. while (true)
  149. {
  150. try
  151. {
  152. while (true)
  153. {
  154. DoProcessQueue();
  155. }
  156. }
  157. catch (ThreadAbortException)
  158. {
  159. if (lastScriptEngine != null)
  160. lastScriptEngine.Log.Info("[" + ScriptEngineName + "]: ThreadAbortException while executing function.");
  161. }
  162. catch (Exception e)
  163. {
  164. if (lastScriptEngine != null)
  165. lastScriptEngine.Log.Error("[" + ScriptEngineName + "]: Exception in EventQueueThreadLoop: " + e.ToString());
  166. }
  167. }
  168. }
  169. catch (ThreadAbortException)
  170. {
  171. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: EventQueueManager Worker thread killed: " + tae.Message);
  172. }
  173. }
  174. public void DoProcessQueue()
  175. {
  176. //lock (ScriptEngine.ScriptEngines)
  177. //{
  178. foreach (ScriptEngine m_ScriptEngine in new ArrayList(ScriptEngine.ScriptEngines))
  179. {
  180. lastScriptEngine = m_ScriptEngine;
  181. // Every now and then check if we should shut down
  182. //if (PleaseShutdown || EventQueueManager.ThreadsToExit > 0)
  183. //{
  184. // // Someone should shut down, lets get exclusive lock
  185. // lock (EventQueueManager.ThreadsToExitLock)
  186. // {
  187. // // Lets re-check in case someone grabbed it
  188. // if (EventQueueManager.ThreadsToExit > 0)
  189. // {
  190. // // Its crowded here so we'll shut down
  191. // EventQueueManager.ThreadsToExit--;
  192. // Stop();
  193. // return;
  194. // }
  195. // else
  196. // {
  197. // // We have been asked to shut down
  198. // Stop();
  199. // return;
  200. // }
  201. // }
  202. //}
  203. //try
  204. // {
  205. EventQueueManager.QueueItemStruct QIS = BlankQIS;
  206. bool GotItem = false;
  207. //if (PleaseShutdown)
  208. // return;
  209. if (m_ScriptEngine.m_EventQueueManager == null || m_ScriptEngine.m_EventQueueManager.eventQueue == null)
  210. continue;
  211. if (m_ScriptEngine.m_EventQueueManager.eventQueue.Count == 0)
  212. {
  213. // Nothing to do? Sleep a bit waiting for something to do
  214. Thread.Sleep(nothingToDoSleepms);
  215. }
  216. else
  217. {
  218. // Something in queue, process
  219. //myScriptEngine.Log.Info("[" + ScriptEngineName + "]: Processing event for localID: " + QIS.localID + ", itemID: " + QIS.itemID + ", FunctionName: " + QIS.FunctionName);
  220. // OBJECT BASED LOCK - TWO THREADS WORKING ON SAME OBJECT IS NOT GOOD
  221. lock (m_ScriptEngine.m_EventQueueManager.eventQueue)
  222. {
  223. GotItem = false;
  224. for (int qc = 0; qc < m_ScriptEngine.m_EventQueueManager.eventQueue.Count; qc++)
  225. {
  226. // Get queue item
  227. QIS = m_ScriptEngine.m_EventQueueManager.eventQueue.Dequeue();
  228. // Check if object is being processed by someone else
  229. if (m_ScriptEngine.m_EventQueueManager.TryLock(QIS.localID) == false)
  230. {
  231. // Object is already being processed, requeue it
  232. m_ScriptEngine.m_EventQueueManager.eventQueue.Enqueue(QIS);
  233. }
  234. else
  235. {
  236. // We have lock on an object and can process it
  237. GotItem = true;
  238. break;
  239. }
  240. }
  241. }
  242. if (GotItem == true)
  243. {
  244. // Execute function
  245. try
  246. {
  247. ///cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  248. #if DEBUG
  249. //eventQueueManager.m_ScriptEngine.Log.Debug("[" + ScriptEngineName + "]: " +
  250. // "Executing event:\r\n"
  251. // + "QIS.localID: " + QIS.localID
  252. // + ", QIS.itemID: " + QIS.itemID
  253. // + ", QIS.functionName: " +
  254. // QIS.functionName);
  255. #endif
  256. LastExecutionStarted = DateTime.Now.Ticks;
  257. KillCurrentScript = false;
  258. InExecution = true;
  259. m_ScriptEngine.m_ScriptManager.ExecuteEvent(QIS.localID,
  260. QIS.itemID,
  261. QIS.functionName,
  262. QIS.llDetectParams,
  263. QIS.param);
  264. InExecution = false;
  265. }
  266. catch (Exception e)
  267. {
  268. InExecution = false;
  269. // DISPLAY ERROR INWORLD
  270. string text = "Error executing script function \"" + QIS.functionName +
  271. "\":\r\n";
  272. if (e.InnerException != null)
  273. {
  274. // Send inner exception
  275. text += e.InnerException.Message.ToString();
  276. }
  277. else
  278. {
  279. text += "\r\n";
  280. // Send normal
  281. text += e.Message.ToString();
  282. }
  283. if (KillCurrentScript)
  284. text += "\r\nScript will be deactivated!";
  285. try
  286. {
  287. if (text.Length > 1500)
  288. text = text.Substring(0, 1500);
  289. IScriptHost m_host =
  290. m_ScriptEngine.World.GetSceneObjectPart(QIS.localID);
  291. //if (m_host != null)
  292. //{
  293. m_ScriptEngine.World.SimChat(Helpers.StringToField(text),
  294. ChatTypeEnum.Say, 0,
  295. m_host.AbsolutePosition,
  296. m_host.Name, m_host.UUID);
  297. }
  298. catch
  299. {
  300. //}
  301. //else
  302. //{
  303. // T oconsole
  304. m_ScriptEngine.m_EventQueueManager.m_ScriptEngine.Log.Error("[" + ScriptEngineName +
  305. "]: " +
  306. "Unable to send text in-world:\r\n" +
  307. text);
  308. }
  309. finally
  310. {
  311. // So we are done sending message in-world
  312. if (KillCurrentScript)
  313. {
  314. m_ScriptEngine.m_EventQueueManager.m_ScriptEngine.m_ScriptManager.StopScript(
  315. QIS.localID, QIS.itemID);
  316. }
  317. }
  318. }
  319. finally
  320. {
  321. InExecution = false;
  322. m_ScriptEngine.m_EventQueueManager.ReleaseLock(QIS.localID);
  323. }
  324. }
  325. }
  326. }
  327. // }
  328. }
  329. ///// <summary>
  330. ///// If set to true then threads and stuff should try to make a graceful exit
  331. ///// </summary>
  332. //public bool PleaseShutdown
  333. //{
  334. // get { return _PleaseShutdown; }
  335. // set { _PleaseShutdown = value; }
  336. //}
  337. //private bool _PleaseShutdown = false;
  338. }
  339. }