ScriptManager.cs 17 KB

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