ScriptManager.cs 15 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.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Runtime.Serialization.Formatters.Binary;
  32. using System.Threading;
  33. using libsecondlife;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Environment.Scenes;
  36. using OpenSim.Region.ScriptEngine.Common;
  37. namespace OpenSim.Region.ScriptEngine.Common.ScriptEngineBase
  38. {
  39. /// <summary>
  40. /// Loads scripts
  41. /// Compiles them if necessary
  42. /// Execute functions for EventQueueManager (Sends them to script on other AppDomain for execution)
  43. /// </summary>
  44. ///
  45. // This class is as close as you get to the script without being inside script class. It handles all the dirty work for other classes.
  46. // * Keeps track of running scripts
  47. // * Compiles script if necessary (through "Compiler")
  48. // * Loads script (through "AppDomainManager" called from for example "EventQueueManager")
  49. // * Executes functions inside script (called from for example "EventQueueManager" class)
  50. // * Unloads script (through "AppDomainManager" called from for example "EventQueueManager")
  51. // * Dedicated load/unload thread, and queues loading/unloading.
  52. // This so that scripts starting or stopping will not slow down other theads or whole system.
  53. //
  54. [Serializable]
  55. public abstract class ScriptManager : iScriptEngineFunctionModule
  56. {
  57. #region Declares
  58. private Thread scriptLoadUnloadThread;
  59. private static Thread staticScriptLoadUnloadThread;
  60. private int scriptLoadUnloadThread_IdleSleepms;
  61. private Queue<LUStruct> LUQueue = new Queue<LUStruct>();
  62. private static bool PrivateThread;
  63. private int LoadUnloadMaxQueueSize;
  64. private Object scriptLock = new Object();
  65. // Load/Unload structure
  66. private struct LUStruct
  67. {
  68. public uint localID;
  69. public LLUUID itemID;
  70. public string script;
  71. public LUType Action;
  72. }
  73. private enum LUType
  74. {
  75. Unknown = 0,
  76. Load = 1,
  77. Unload = 2
  78. }
  79. // Object<string, Script<string, script>>
  80. // IMPORTANT: Types and MemberInfo-derived objects require a LOT of memory.
  81. // Instead use RuntimeTypeHandle, RuntimeFieldHandle and RunTimeHandle (IntPtr) instead!
  82. public Dictionary<uint, Dictionary<LLUUID, IScript>> Scripts =
  83. new Dictionary<uint, Dictionary<LLUUID, IScript>>();
  84. public Scene World
  85. {
  86. get { return m_scriptEngine.World; }
  87. }
  88. #endregion
  89. public void ReadConfig()
  90. {
  91. scriptLoadUnloadThread_IdleSleepms = m_scriptEngine.ScriptConfigSource.GetInt("ScriptLoadUnloadLoopms", 30);
  92. // TODO: Requires sharing of all ScriptManagers to single thread
  93. PrivateThread = true; // m_scriptEngine.ScriptConfigSource.GetBoolean("PrivateScriptLoadUnloadThread", false);
  94. LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt("LoadUnloadMaxQueueSize", 100);
  95. }
  96. #region Object init/shutdown
  97. public ScriptEngineBase.ScriptEngine m_scriptEngine;
  98. public ScriptManager(ScriptEngineBase.ScriptEngine scriptEngine)
  99. {
  100. m_scriptEngine = scriptEngine;
  101. }
  102. public abstract void Initialize();
  103. public void Start()
  104. {
  105. ReadConfig();
  106. Initialize();
  107. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  108. //
  109. // CREATE THREAD
  110. // Private or shared
  111. //
  112. if (PrivateThread)
  113. {
  114. // Assign one thread per region
  115. //scriptLoadUnloadThread = StartScriptLoadUnloadThread();
  116. }
  117. else
  118. {
  119. // Shared thread - make sure one exist, then assign it to the private
  120. if (staticScriptLoadUnloadThread == null)
  121. {
  122. //staticScriptLoadUnloadThread = StartScriptLoadUnloadThread();
  123. }
  124. scriptLoadUnloadThread = staticScriptLoadUnloadThread;
  125. }
  126. }
  127. private static int privateThreadCount = 0;
  128. // TODO: unused
  129. // private Thread StartScriptLoadUnloadThread()
  130. // {
  131. // Thread t = new Thread(ScriptLoadUnloadThreadLoop);
  132. // string name = "ScriptLoadUnloadThread:";
  133. // if (PrivateThread)
  134. // {
  135. // name += "Private:" + privateThreadCount;
  136. // privateThreadCount++;
  137. // }
  138. // else
  139. // {
  140. // name += "Shared";
  141. // }
  142. // t.Name = name;
  143. // t.IsBackground = true;
  144. // t.Priority = ThreadPriority.Normal;
  145. // t.Start();
  146. // OpenSim.Framework.ThreadTracker.Add(t);
  147. // return t;
  148. // }
  149. ~ScriptManager()
  150. {
  151. // Abort load/unload thread
  152. try
  153. {
  154. //PleaseShutdown = true;
  155. //Thread.Sleep(100);
  156. if (scriptLoadUnloadThread != null && scriptLoadUnloadThread.IsAlive == true)
  157. {
  158. scriptLoadUnloadThread.Abort();
  159. //scriptLoadUnloadThread.Join();
  160. }
  161. }
  162. catch
  163. {
  164. }
  165. }
  166. #endregion
  167. #region Load / Unload scripts (Thread loop)
  168. // TODO: unused
  169. // private void ScriptLoadUnloadThreadLoop()
  170. // {
  171. // try
  172. // {
  173. // while (true)
  174. // {
  175. // if (LUQueue.Count == 0)
  176. // Thread.Sleep(scriptLoadUnloadThread_IdleSleepms);
  177. // //if (PleaseShutdown)
  178. // // return;
  179. // DoScriptLoadUnload();
  180. // }
  181. // }
  182. // catch (ThreadAbortException tae)
  183. // {
  184. // string a = tae.ToString();
  185. // a = String.Empty;
  186. // // Expected
  187. // }
  188. // }
  189. public void DoScriptLoadUnload()
  190. {
  191. if (LUQueue.Count > 0)
  192. {
  193. LUStruct item = LUQueue.Dequeue();
  194. lock (startStopLock) // Lock so we have only 1 thread working on loading/unloading of scripts
  195. {
  196. if (item.Action == LUType.Unload)
  197. {
  198. _StopScript(item.localID, item.itemID);
  199. }
  200. if (item.Action == LUType.Load)
  201. {
  202. _StartScript(item.localID, item.itemID, item.script);
  203. }
  204. }
  205. }
  206. }
  207. #endregion
  208. #region Helper functions
  209. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
  210. {
  211. //Console.WriteLine("ScriptManager.CurrentDomain_AssemblyResolve: " + args.Name);
  212. return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null;
  213. }
  214. #endregion
  215. #region Start/Stop/Reset script
  216. private readonly Object startStopLock = new Object();
  217. /// <summary>
  218. /// Fetches, loads and hooks up a script to an objects events
  219. /// </summary>
  220. /// <param name="itemID"></param>
  221. /// <param name="localID"></param>
  222. public void StartScript(uint localID, LLUUID itemID, string Script)
  223. {
  224. if (LUQueue.Count >= LoadUnloadMaxQueueSize)
  225. {
  226. m_scriptEngine.Log.Error("[" + m_scriptEngine.ScriptEngineName + "]: ERROR: Load/unload queue item count is at " + LUQueue.Count + ". Config variable \"LoadUnloadMaxQueueSize\" is set to " + LoadUnloadMaxQueueSize + ", so ignoring new script.");
  227. return;
  228. }
  229. LUStruct ls = new LUStruct();
  230. ls.localID = localID;
  231. ls.itemID = itemID;
  232. ls.script = Script;
  233. ls.Action = LUType.Load;
  234. LUQueue.Enqueue(ls);
  235. }
  236. /// <summary>
  237. /// Disables and unloads a script
  238. /// </summary>
  239. /// <param name="localID"></param>
  240. /// <param name="itemID"></param>
  241. public void StopScript(uint localID, LLUUID itemID)
  242. {
  243. LUStruct ls = new LUStruct();
  244. ls.localID = localID;
  245. ls.itemID = itemID;
  246. ls.Action = LUType.Unload;
  247. LUQueue.Enqueue(ls);
  248. }
  249. // Create a new instance of the compiler (reuse)
  250. //private Compiler.LSL.Compiler LSLCompiler = new Compiler.LSL.Compiler();
  251. public abstract void _StartScript(uint localID, LLUUID itemID, string Script);
  252. public abstract void _StopScript(uint localID, LLUUID itemID);
  253. #endregion
  254. #region Perform event execution in script
  255. /// <summary>
  256. /// Execute a LL-event-function in Script
  257. /// </summary>
  258. /// <param name="localID">Object the script is located in</param>
  259. /// <param name="itemID">Script ID</param>
  260. /// <param name="FunctionName">Name of function</param>
  261. /// <param name="args">Arguments to pass to function</param>
  262. internal void ExecuteEvent(uint localID, LLUUID itemID, string FunctionName, EventQueueManager.Queue_llDetectParams_Struct qParams, object[] args)
  263. {
  264. //cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  265. ///#if DEBUG
  266. /// Console.WriteLine("ScriptEngine: Inside ExecuteEvent for event " + FunctionName);
  267. ///#endif
  268. // Execute a function in the script
  269. //m_scriptEngine.Log.Info("[" + ScriptEngineName + "]: Executing Function localID: " + localID + ", itemID: " + itemID + ", FunctionName: " + FunctionName);
  270. //ScriptBaseInterface Script = (ScriptBaseInterface)GetScript(localID, itemID);
  271. IScript Script = GetScript(localID, itemID);
  272. if (Script == null)
  273. {
  274. return;
  275. }
  276. //cfk 2-7-08 dont need this right now and the default Linux build has DEBUG defined
  277. ///#if DEBUG
  278. /// Console.WriteLine("ScriptEngine: Executing event: " + FunctionName);
  279. ///#endif
  280. // Must be done in correct AppDomain, so leaving it up to the script itself
  281. Script.llDetectParams = qParams;
  282. Script.Exec.ExecuteEvent(FunctionName, args);
  283. }
  284. #endregion
  285. #region Internal functions to keep track of script
  286. public Dictionary<LLUUID, IScript>.KeyCollection GetScriptKeys(uint localID)
  287. {
  288. if (Scripts.ContainsKey(localID) == false)
  289. return null;
  290. Dictionary<LLUUID, IScript> Obj;
  291. Scripts.TryGetValue(localID, out Obj);
  292. return Obj.Keys;
  293. }
  294. public IScript GetScript(uint localID, LLUUID itemID)
  295. {
  296. lock (scriptLock)
  297. {
  298. if (Scripts.ContainsKey(localID) == false)
  299. return null;
  300. Dictionary<LLUUID, IScript> Obj;
  301. Scripts.TryGetValue(localID, out Obj);
  302. if (Obj.ContainsKey(itemID) == false)
  303. return null;
  304. // Get script
  305. IScript Script;
  306. Obj.TryGetValue(itemID, out Script);
  307. return Script;
  308. }
  309. }
  310. public void SetScript(uint localID, LLUUID itemID, IScript Script)
  311. {
  312. lock (scriptLock)
  313. {
  314. // Create object if it doesn't exist
  315. if (Scripts.ContainsKey(localID) == false)
  316. {
  317. Scripts.Add(localID, new Dictionary<LLUUID, IScript>());
  318. }
  319. // Delete script if it exists
  320. Dictionary<LLUUID, IScript> Obj;
  321. Scripts.TryGetValue(localID, out Obj);
  322. if (Obj.ContainsKey(itemID) == true)
  323. Obj.Remove(itemID);
  324. // Add to object
  325. Obj.Add(itemID, Script);
  326. }
  327. }
  328. public void RemoveScript(uint localID, LLUUID itemID)
  329. {
  330. // Don't have that object?
  331. if (Scripts.ContainsKey(localID) == false)
  332. return;
  333. // Delete script if it exists
  334. Dictionary<LLUUID, IScript> Obj;
  335. Scripts.TryGetValue(localID, out Obj);
  336. if (Obj.ContainsKey(itemID) == true)
  337. Obj.Remove(itemID);
  338. }
  339. #endregion
  340. public void ResetScript(uint localID, LLUUID itemID)
  341. {
  342. string script = GetScript(localID, itemID).Source;
  343. StopScript(localID, itemID);
  344. StartScript(localID, itemID, script);
  345. }
  346. #region Script serialization/deserialization
  347. public void GetSerializedScript(uint localID, LLUUID itemID)
  348. {
  349. // Serialize the script and return it
  350. // Should not be a problem
  351. FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID);
  352. BinaryFormatter b = new BinaryFormatter();
  353. b.Serialize(fs, GetScript(localID, itemID));
  354. fs.Close();
  355. }
  356. public void PutSerializedScript(uint localID, LLUUID itemID)
  357. {
  358. // Deserialize the script and inject it into an AppDomain
  359. // How to inject into an AppDomain?
  360. }
  361. #endregion
  362. ///// <summary>
  363. ///// If set to true then threads and stuff should try to make a graceful exit
  364. ///// </summary>
  365. //public bool PleaseShutdown
  366. //{
  367. // get { return _PleaseShutdown; }
  368. // set { _PleaseShutdown = value; }
  369. //}
  370. //private bool _PleaseShutdown = false;
  371. }
  372. }