XEngine.cs 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  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 OpenSimulator 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.Globalization;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Reflection;
  34. using System.Security;
  35. using System.Security.Policy;
  36. using System.Text;
  37. using System.Threading;
  38. using System.Xml;
  39. using OpenMetaverse;
  40. using OpenMetaverse.StructuredData;
  41. using log4net;
  42. using Nini.Config;
  43. using Amib.Threading;
  44. using OpenSim.Framework;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Region.Framework.Scenes;
  47. using OpenSim.Region.Framework.Interfaces;
  48. using OpenSim.Region.ScriptEngine.Interfaces;
  49. using OpenSim.Region.ScriptEngine.Shared;
  50. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  51. using OpenSim.Region.ScriptEngine.Shared.Instance;
  52. using OpenSim.Region.ScriptEngine.Shared.Api;
  53. using OpenSim.Region.ScriptEngine.Shared.Api.Plugins;
  54. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  55. using OpenSim.Region.ScriptEngine.XEngine.ScriptBase;
  56. using Timer = OpenSim.Region.ScriptEngine.Shared.Api.Plugins.Timer;
  57. using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;
  58. namespace OpenSim.Region.ScriptEngine.XEngine
  59. {
  60. public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
  61. {
  62. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  63. /// <summary>
  64. /// Control the printing of certain debug messages.
  65. /// </summary>
  66. /// <remarks>
  67. /// If DebugLevel >= 1, then we log every time that a script is started.
  68. /// </remarks>
  69. // public int DebugLevel { get; set; }
  70. private SmartThreadPool m_ThreadPool;
  71. private int m_MaxScriptQueue;
  72. private Scene m_Scene;
  73. private IConfig m_ScriptConfig = null;
  74. private IConfigSource m_ConfigSource = null;
  75. private ICompiler m_Compiler;
  76. private int m_MinThreads;
  77. private int m_MaxThreads;
  78. /// <summary>
  79. /// Amount of time to delay before starting.
  80. /// </summary>
  81. private int m_StartDelay;
  82. private int m_IdleTimeout;
  83. private int m_StackSize;
  84. private int m_SleepTime;
  85. private int m_SaveTime;
  86. private ThreadPriority m_Prio;
  87. private bool m_Enabled = false;
  88. private bool m_InitialStartup = true;
  89. private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
  90. private string m_ScriptErrorMessage;
  91. private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
  92. private bool m_AppDomainLoading;
  93. private Dictionary<UUID,ArrayList> m_ScriptErrors =
  94. new Dictionary<UUID,ArrayList>();
  95. // disable warning: need to keep a reference to XEngine.EventManager
  96. // alive to avoid it being garbage collected
  97. #pragma warning disable 414
  98. private EventManager m_EventManager;
  99. #pragma warning restore 414
  100. private IXmlRpcRouter m_XmlRpcRouter;
  101. private int m_EventLimit;
  102. private bool m_KillTimedOutScripts;
  103. /// <summary>
  104. /// Number of milliseconds we will wait for a script event to complete on script stop before we forcibly abort
  105. /// its thread.
  106. /// </summary>
  107. /// <remarks>
  108. /// It appears that if a script thread is aborted whilst it is holding ReaderWriterLockSlim (possibly the write
  109. /// lock) then the lock is not properly released. This causes mono 2.6, 2.10 and possibly
  110. /// later to crash, sometimes with symptoms such as a leap to 100% script usage and a vm thead dump showing
  111. /// all threads waiting on release of ReaderWriterLockSlim write thread which none of the threads listed
  112. /// actually hold.
  113. ///
  114. /// Pausing for event completion reduces the risk of this happening. However, it may be that aborting threads
  115. /// is not a mono issue per se but rather a risky activity in itself in an AppDomain that is not immediately
  116. /// shutting down.
  117. /// </remarks>
  118. private int m_WaitForEventCompletionOnScriptStop = 1000;
  119. private string m_ScriptEnginesPath = null;
  120. private ExpiringCache<UUID, bool> m_runFlags = new ExpiringCache<UUID, bool>();
  121. /// <summary>
  122. /// Is the entire simulator in the process of shutting down?
  123. /// </summary>
  124. private bool m_SimulatorShuttingDown;
  125. private static List<XEngine> m_ScriptEngines =
  126. new List<XEngine>();
  127. // Maps the local id to the script inventory items in it
  128. private Dictionary<uint, List<UUID> > m_PrimObjects =
  129. new Dictionary<uint, List<UUID> >();
  130. // Maps the UUID above to the script instance
  131. private Dictionary<UUID, IScriptInstance> m_Scripts =
  132. new Dictionary<UUID, IScriptInstance>();
  133. // Maps the asset ID to the assembly
  134. private Dictionary<UUID, string> m_Assemblies =
  135. new Dictionary<UUID, string>();
  136. private Dictionary<string, int> m_AddingAssemblies =
  137. new Dictionary<string, int>();
  138. // This will list AppDomains by script asset
  139. private Dictionary<UUID, AppDomain> m_AppDomains =
  140. new Dictionary<UUID, AppDomain>();
  141. // List the scripts running in each appdomain
  142. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  143. new Dictionary<UUID, List<UUID> >();
  144. private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
  145. IWorkItemResult m_CurrentCompile = null;
  146. private Dictionary<UUID, int> m_CompileDict = new Dictionary<UUID, int>();
  147. private ScriptEngineConsoleCommands m_consoleCommands;
  148. public string ScriptEngineName
  149. {
  150. get { return "XEngine"; }
  151. }
  152. public string ScriptClassName { get; private set; }
  153. public string ScriptBaseClassName { get; private set; }
  154. public ParameterInfo[] ScriptBaseClassParameters { get; private set; }
  155. public string[] ScriptReferencedAssemblies { get; private set; }
  156. public Scene World
  157. {
  158. get { return m_Scene; }
  159. }
  160. public static List<XEngine> ScriptEngines
  161. {
  162. get { return m_ScriptEngines; }
  163. }
  164. public IScriptModule ScriptModule
  165. {
  166. get { return this; }
  167. }
  168. // private struct RezScriptParms
  169. // {
  170. // uint LocalID;
  171. // UUID ItemID;
  172. // string Script;
  173. // }
  174. public IConfig Config
  175. {
  176. get { return m_ScriptConfig; }
  177. }
  178. public string ScriptEnginePath
  179. {
  180. get { return m_ScriptEnginesPath; }
  181. }
  182. public IConfigSource ConfigSource
  183. {
  184. get { return m_ConfigSource; }
  185. }
  186. /// <summary>
  187. /// Event fired after the script engine has finished removing a script.
  188. /// </summary>
  189. public event ScriptRemoved OnScriptRemoved;
  190. /// <summary>
  191. /// Event fired after the script engine has finished removing a script from an object.
  192. /// </summary>
  193. public event ObjectRemoved OnObjectRemoved;
  194. public void Initialise(IConfigSource configSource)
  195. {
  196. if (configSource.Configs["XEngine"] == null)
  197. return;
  198. m_ScriptConfig = configSource.Configs["XEngine"];
  199. m_ConfigSource = configSource;
  200. string rawScriptStopStrategy = m_ScriptConfig.GetString("ScriptStopStrategy", "abort");
  201. m_log.InfoFormat("[XEngine]: Script stop strategy is {0}", rawScriptStopStrategy);
  202. if (rawScriptStopStrategy == "co-op")
  203. {
  204. ScriptClassName = "XEngineScript";
  205. ScriptBaseClassName = typeof(XEngineScriptBase).FullName;
  206. ScriptBaseClassParameters = typeof(XEngineScriptBase).GetConstructor(new Type[] { typeof(WaitHandle) }).GetParameters();
  207. ScriptReferencedAssemblies = new string[] { Path.GetFileName(typeof(XEngineScriptBase).Assembly.Location) };
  208. }
  209. else
  210. {
  211. ScriptClassName = "Script";
  212. ScriptBaseClassName = typeof(ScriptBaseClass).FullName;
  213. }
  214. // Console.WriteLine("ASSEMBLY NAME: {0}", ScriptReferencedAssemblies[0]);
  215. }
  216. public void AddRegion(Scene scene)
  217. {
  218. if (m_ScriptConfig == null)
  219. return;
  220. m_ScriptFailCount = 0;
  221. m_ScriptErrorMessage = String.Empty;
  222. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  223. if (!m_Enabled)
  224. return;
  225. AppDomain.CurrentDomain.AssemblyResolve +=
  226. OnAssemblyResolve;
  227. m_Scene = scene;
  228. m_log.InfoFormat("[XEngine]: Initializing scripts in region {0}", m_Scene.RegionInfo.RegionName);
  229. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  230. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  231. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  232. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  233. m_StartDelay = m_ScriptConfig.GetInt("StartDelay", 15000);
  234. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  235. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  236. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  237. m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);
  238. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  239. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  240. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  241. m_WaitForEventCompletionOnScriptStop
  242. = m_ScriptConfig.GetInt("WaitForEventCompletionOnScriptStop", m_WaitForEventCompletionOnScriptStop);
  243. m_ScriptEnginesPath = m_ScriptConfig.GetString("ScriptEnginesPath", "ScriptEngines");
  244. m_Prio = ThreadPriority.BelowNormal;
  245. switch (priority)
  246. {
  247. case "Lowest":
  248. m_Prio = ThreadPriority.Lowest;
  249. break;
  250. case "BelowNormal":
  251. m_Prio = ThreadPriority.BelowNormal;
  252. break;
  253. case "Normal":
  254. m_Prio = ThreadPriority.Normal;
  255. break;
  256. case "AboveNormal":
  257. m_Prio = ThreadPriority.AboveNormal;
  258. break;
  259. case "Highest":
  260. m_Prio = ThreadPriority.Highest;
  261. break;
  262. default:
  263. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  264. break;
  265. }
  266. lock (m_ScriptEngines)
  267. {
  268. m_ScriptEngines.Add(this);
  269. }
  270. // Needs to be here so we can queue the scripts that need starting
  271. //
  272. m_Scene.EventManager.OnRezScript += OnRezScript;
  273. // Complete basic setup of the thread pool
  274. //
  275. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  276. m_MaxScriptQueue, m_StackSize);
  277. m_Scene.StackModuleInterface<IScriptModule>(this);
  278. m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
  279. if (m_XmlRpcRouter != null)
  280. {
  281. OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
  282. OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
  283. }
  284. m_consoleCommands = new ScriptEngineConsoleCommands(this);
  285. m_consoleCommands.RegisterCommands();
  286. MainConsole.Instance.Commands.AddCommand(
  287. "Scripts", false, "xengine status", "xengine status", "Show status information",
  288. "Show status information on the script engine.",
  289. HandleShowStatus);
  290. MainConsole.Instance.Commands.AddCommand(
  291. "Scripts", false, "scripts show", "scripts show [<script-item-uuid>+]", "Show script information",
  292. "Show information on all scripts known to the script engine.\n"
  293. + "If one or more <script-item-uuid>s are given then only information on that script will be shown.",
  294. HandleShowScripts);
  295. MainConsole.Instance.Commands.AddCommand(
  296. "Scripts", false, "show scripts", "show scripts [<script-item-uuid>+]", "Show script information",
  297. "Synonym for scripts show command", HandleShowScripts);
  298. MainConsole.Instance.Commands.AddCommand(
  299. "Scripts", false, "scripts suspend", "scripts suspend [<script-item-uuid>+]", "Suspends all running scripts",
  300. "Suspends all currently running scripts. This only suspends event delivery, it will not suspend a"
  301. + " script that is currently processing an event.\n"
  302. + "Suspended scripts will continue to accumulate events but won't process them.\n"
  303. + "If one or more <script-item-uuid>s are given then only that script will be suspended. Otherwise, all suitable scripts are suspended.",
  304. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleSuspendScript));
  305. MainConsole.Instance.Commands.AddCommand(
  306. "Scripts", false, "scripts resume", "scripts resume [<script-item-uuid>+]", "Resumes all suspended scripts",
  307. "Resumes all currently suspended scripts.\n"
  308. + "Resumed scripts will process all events accumulated whilst suspended.\n"
  309. + "If one or more <script-item-uuid>s are given then only that script will be resumed. Otherwise, all suitable scripts are resumed.",
  310. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleResumeScript));
  311. MainConsole.Instance.Commands.AddCommand(
  312. "Scripts", false, "scripts stop", "scripts stop [<script-item-uuid>+]", "Stops all running scripts",
  313. "Stops all running scripts.\n"
  314. + "If one or more <script-item-uuid>s are given then only that script will be stopped. Otherwise, all suitable scripts are stopped.",
  315. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStopScript));
  316. MainConsole.Instance.Commands.AddCommand(
  317. "Scripts", false, "scripts start", "scripts start [<script-item-uuid>+]", "Starts all stopped scripts",
  318. "Starts all stopped scripts.\n"
  319. + "If one or more <script-item-uuid>s are given then only that script will be started. Otherwise, all suitable scripts are started.",
  320. (module, cmdparams) => HandleScriptsAction(cmdparams, HandleStartScript));
  321. MainConsole.Instance.Commands.AddCommand(
  322. "Scripts", false, "debug scripts log", "debug scripts log <item-id> <log-level>", "Extra debug logging for a script",
  323. "Activates or deactivates extra debug logging for the given script.\n"
  324. + "Level == 0, deactivate extra debug logging.\n"
  325. + "Level >= 1, log state changes.\n"
  326. + "Level >= 2, log event invocations.\n",
  327. HandleDebugScriptLogCommand);
  328. // MainConsole.Instance.Commands.AddCommand(
  329. // "Debug", false, "debug xengine", "debug xengine [<level>]",
  330. // "Turn on detailed xengine debugging.",
  331. // "If level <= 0, then no extra logging is done.\n"
  332. // + "If level >= 1, then we log every time that a script is started.",
  333. // HandleDebugLevelCommand);
  334. }
  335. private void HandleDebugScriptLogCommand(string module, string[] args)
  336. {
  337. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  338. return;
  339. if (args.Length != 5)
  340. {
  341. MainConsole.Instance.Output("Usage: debug script log <item-id> <log-level>");
  342. return;
  343. }
  344. UUID itemId;
  345. if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, args[3], out itemId))
  346. return;
  347. int newLevel;
  348. if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out newLevel))
  349. return;
  350. IScriptInstance si;
  351. lock (m_Scripts)
  352. {
  353. // XXX: We can't give the user feedback on a bad item id because this may apply to a different script
  354. // engine
  355. if (!m_Scripts.TryGetValue(itemId, out si))
  356. return;
  357. }
  358. si.DebugLevel = newLevel;
  359. MainConsole.Instance.OutputFormat("Set debug level of {0} {1} to {2}", si.ScriptName, si.ItemID, newLevel);
  360. }
  361. /// <summary>
  362. /// Change debug level
  363. /// </summary>
  364. /// <param name="module"></param>
  365. /// <param name="args"></param>
  366. // private void HandleDebugLevelCommand(string module, string[] args)
  367. // {
  368. // if (args.Length == 3)
  369. // {
  370. // int newDebug;
  371. // if (int.TryParse(args[2], out newDebug))
  372. // {
  373. // DebugLevel = newDebug;
  374. // MainConsole.Instance.OutputFormat("Debug level set to {0}", newDebug);
  375. // }
  376. // }
  377. // else if (args.Length == 2)
  378. // {
  379. // MainConsole.Instance.OutputFormat("Current debug level is {0}", DebugLevel);
  380. // }
  381. // else
  382. // {
  383. // MainConsole.Instance.Output("Usage: debug xengine 0..1");
  384. // }
  385. // }
  386. /// <summary>
  387. /// Parse the raw item id into a script instance from the command params if it's present.
  388. /// </summary>
  389. /// <param name="cmdparams"></param>
  390. /// <param name="instance"></param>
  391. /// <param name="comparer">Basis on which to sort output. Can be null if no sort needs to take place</param>
  392. private void HandleScriptsAction(string[] cmdparams, Action<IScriptInstance> action)
  393. {
  394. HandleScriptsAction<object>(cmdparams, action, null);
  395. }
  396. /// <summary>
  397. /// Parse the raw item id into a script instance from the command params if it's present.
  398. /// </summary>
  399. /// <param name="cmdparams"></param>
  400. /// <param name="instance"></param>
  401. /// <param name="keySelector">Basis on which to sort output. Can be null if no sort needs to take place</param>
  402. private void HandleScriptsAction<TKey>(
  403. string[] cmdparams, Action<IScriptInstance> action, System.Func<IScriptInstance, TKey> keySelector)
  404. {
  405. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  406. return;
  407. lock (m_Scripts)
  408. {
  409. string rawItemId;
  410. UUID itemId = UUID.Zero;
  411. if (cmdparams.Length == 2)
  412. {
  413. IEnumerable<IScriptInstance> scripts = m_Scripts.Values;
  414. if (keySelector != null)
  415. scripts = scripts.OrderBy<IScriptInstance, TKey>(keySelector);
  416. foreach (IScriptInstance instance in scripts)
  417. action(instance);
  418. return;
  419. }
  420. for (int i = 2; i < cmdparams.Length; i++)
  421. {
  422. rawItemId = cmdparams[i];
  423. if (!UUID.TryParse(rawItemId, out itemId))
  424. {
  425. MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid UUID", rawItemId);
  426. continue;
  427. }
  428. if (itemId != UUID.Zero)
  429. {
  430. IScriptInstance instance = GetInstance(itemId);
  431. if (instance == null)
  432. {
  433. // Commented out for now since this will cause false reports on simulators with more than
  434. // one scene where the current command line set region is 'root' (which causes commands to
  435. // go to both regions... (sigh)
  436. // MainConsole.Instance.OutputFormat("Error - No item found with id {0}", itemId);
  437. continue;
  438. }
  439. else
  440. {
  441. action(instance);
  442. }
  443. }
  444. }
  445. }
  446. }
  447. private void HandleShowStatus(string module, string[] cmdparams)
  448. {
  449. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  450. return;
  451. MainConsole.Instance.Output(GetStatusReport());
  452. }
  453. public string GetStatusReport()
  454. {
  455. StringBuilder sb = new StringBuilder();
  456. sb.AppendFormat("Status of XEngine instance for {0}\n", m_Scene.RegionInfo.RegionName);
  457. long scriptsLoaded, eventsQueued = 0, eventsProcessed = 0;
  458. lock (m_Scripts)
  459. {
  460. scriptsLoaded = m_Scripts.Count;
  461. foreach (IScriptInstance si in m_Scripts.Values)
  462. {
  463. eventsQueued += si.EventsQueued;
  464. eventsProcessed += si.EventsProcessed;
  465. }
  466. }
  467. sb.AppendFormat("Scripts loaded : {0}\n", scriptsLoaded);
  468. sb.AppendFormat("Unique scripts : {0}\n", m_uniqueScripts.Count);
  469. sb.AppendFormat("Scripts waiting for load : {0}\n", m_CompileQueue.Count);
  470. sb.AppendFormat("Max threads : {0}\n", m_ThreadPool.MaxThreads);
  471. sb.AppendFormat("Min threads : {0}\n", m_ThreadPool.MinThreads);
  472. sb.AppendFormat("Allocated threads : {0}\n", m_ThreadPool.ActiveThreads);
  473. sb.AppendFormat("In use threads : {0}\n", m_ThreadPool.InUseThreads);
  474. sb.AppendFormat("Work items waiting : {0}\n", m_ThreadPool.WaitingCallbacks);
  475. // sb.AppendFormat("Assemblies loaded : {0}\n", m_Assemblies.Count);
  476. sb.AppendFormat("Events queued : {0}\n", eventsQueued);
  477. sb.AppendFormat("Events processed : {0}\n", eventsProcessed);
  478. SensorRepeat sr = AsyncCommandManager.GetSensorRepeatPlugin(this);
  479. sb.AppendFormat("Sensors : {0}\n", sr != null ? sr.SensorsCount : 0);
  480. Dataserver ds = AsyncCommandManager.GetDataserverPlugin(this);
  481. sb.AppendFormat("Dataserver requests : {0}\n", ds != null ? ds.DataserverRequestsCount : 0);
  482. Timer t = AsyncCommandManager.GetTimerPlugin(this);
  483. sb.AppendFormat("Timers : {0}\n", t != null ? t.TimersCount : 0);
  484. Listener l = AsyncCommandManager.GetListenerPlugin(this);
  485. sb.AppendFormat("Listeners : {0}\n", l != null ? l.ListenerCount : 0);
  486. return sb.ToString();
  487. }
  488. public void HandleShowScripts(string module, string[] cmdparams)
  489. {
  490. if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_Scene))
  491. return;
  492. if (cmdparams.Length == 2)
  493. {
  494. lock (m_Scripts)
  495. {
  496. MainConsole.Instance.OutputFormat(
  497. "Showing {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
  498. }
  499. }
  500. HandleScriptsAction<long>(cmdparams, HandleShowScript, si => si.EventsProcessed);
  501. }
  502. private void HandleShowScript(IScriptInstance instance)
  503. {
  504. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  505. string status;
  506. if (instance.ShuttingDown)
  507. {
  508. status = "shutting down";
  509. }
  510. else if (instance.Suspended)
  511. {
  512. status = "suspended";
  513. }
  514. else if (!instance.Running)
  515. {
  516. status = "stopped";
  517. }
  518. else
  519. {
  520. status = "running";
  521. }
  522. StringBuilder sb = new StringBuilder();
  523. sb.AppendFormat("Script name : {0}\n", instance.ScriptName);
  524. sb.AppendFormat("Status : {0}\n", status);
  525. sb.AppendFormat("Queued events : {0}\n", instance.EventsQueued);
  526. sb.AppendFormat("Processed events : {0}\n", instance.EventsProcessed);
  527. sb.AppendFormat("Item UUID : {0}\n", instance.ItemID);
  528. sb.AppendFormat("Asset UUID : {0}\n", instance.AssetID);
  529. sb.AppendFormat("Containing part name: {0}\n", instance.PrimName);
  530. sb.AppendFormat("Containing part UUID: {0}\n", instance.ObjectID);
  531. sb.AppendFormat("Position : {0}\n", sop.AbsolutePosition);
  532. MainConsole.Instance.Output(sb.ToString());
  533. }
  534. private void HandleSuspendScript(IScriptInstance instance)
  535. {
  536. if (!instance.Suspended)
  537. {
  538. instance.Suspend();
  539. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  540. MainConsole.Instance.OutputFormat(
  541. "Suspended {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  542. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  543. }
  544. }
  545. private void HandleResumeScript(IScriptInstance instance)
  546. {
  547. if (instance.Suspended)
  548. {
  549. instance.Resume();
  550. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  551. MainConsole.Instance.OutputFormat(
  552. "Resumed {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  553. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  554. }
  555. }
  556. private void HandleStartScript(IScriptInstance instance)
  557. {
  558. if (!instance.Running)
  559. {
  560. instance.Start();
  561. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  562. MainConsole.Instance.OutputFormat(
  563. "Started {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  564. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  565. }
  566. }
  567. private void HandleStopScript(IScriptInstance instance)
  568. {
  569. if (instance.Running)
  570. {
  571. instance.Stop(0);
  572. SceneObjectPart sop = m_Scene.GetSceneObjectPart(instance.ObjectID);
  573. MainConsole.Instance.OutputFormat(
  574. "Stopped {0}.{1}, item UUID {2}, prim UUID {3} @ {4}",
  575. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, sop.AbsolutePosition);
  576. }
  577. }
  578. public void RemoveRegion(Scene scene)
  579. {
  580. if (!m_Enabled)
  581. return;
  582. lock (m_Scripts)
  583. {
  584. m_log.InfoFormat(
  585. "[XEngine]: Shutting down {0} scripts in {1}", m_Scripts.Count, m_Scene.RegionInfo.RegionName);
  586. foreach (IScriptInstance instance in m_Scripts.Values)
  587. {
  588. // Force a final state save
  589. //
  590. if (m_Assemblies.ContainsKey(instance.AssetID))
  591. {
  592. string assembly = m_Assemblies[instance.AssetID];
  593. try
  594. {
  595. instance.SaveState(assembly);
  596. }
  597. catch (Exception e)
  598. {
  599. m_log.Error(
  600. string.Format(
  601. "[XEngine]: Failed final state save for script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  602. instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name)
  603. , e);
  604. }
  605. }
  606. // Clear the event queue and abort the instance thread
  607. //
  608. instance.ClearQueue();
  609. instance.Stop(0);
  610. // Release events, timer, etc
  611. //
  612. instance.DestroyScriptInstance();
  613. // Unload scripts and app domains.
  614. // Must be done explicitly because they have infinite
  615. // lifetime.
  616. // However, don't bother to do this if the simulator is shutting
  617. // down since it takes a long time with many scripts.
  618. if (!m_SimulatorShuttingDown)
  619. {
  620. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  621. if (m_DomainScripts[instance.AppDomain].Count == 0)
  622. {
  623. m_DomainScripts.Remove(instance.AppDomain);
  624. UnloadAppDomain(instance.AppDomain);
  625. }
  626. }
  627. }
  628. m_Scripts.Clear();
  629. m_PrimObjects.Clear();
  630. m_Assemblies.Clear();
  631. m_DomainScripts.Clear();
  632. }
  633. lock (m_ScriptEngines)
  634. {
  635. m_ScriptEngines.Remove(this);
  636. }
  637. }
  638. public void RegionLoaded(Scene scene)
  639. {
  640. if (!m_Enabled)
  641. return;
  642. m_EventManager = new EventManager(this);
  643. m_Compiler = new Compiler(this);
  644. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  645. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  646. m_Scene.EventManager.OnStartScript += OnStartScript;
  647. m_Scene.EventManager.OnStopScript += OnStopScript;
  648. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  649. m_Scene.EventManager.OnShutdown += OnShutdown;
  650. // If region ready has been triggered, then the region had no scripts to compile and completed its other
  651. // work.
  652. m_Scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) m_InitialStartup = false; };
  653. if (m_SleepTime > 0)
  654. {
  655. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  656. new Object[]{ m_SleepTime });
  657. }
  658. if (m_SaveTime > 0)
  659. {
  660. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  661. new Object[] { m_SaveTime });
  662. }
  663. }
  664. public void StartProcessing()
  665. {
  666. m_ThreadPool.Start();
  667. }
  668. public void Close()
  669. {
  670. if (!m_Enabled)
  671. return;
  672. lock (m_ScriptEngines)
  673. {
  674. if (m_ScriptEngines.Contains(this))
  675. m_ScriptEngines.Remove(this);
  676. }
  677. }
  678. public object DoBackup(object o)
  679. {
  680. Object[] p = (Object[])o;
  681. int saveTime = (int)p[0];
  682. if (saveTime > 0)
  683. System.Threading.Thread.Sleep(saveTime);
  684. // m_log.Debug("[XEngine] Backing up script states");
  685. List<IScriptInstance> instances = new List<IScriptInstance>();
  686. lock (m_Scripts)
  687. {
  688. foreach (IScriptInstance instance in m_Scripts.Values)
  689. instances.Add(instance);
  690. }
  691. foreach (IScriptInstance i in instances)
  692. {
  693. string assembly = String.Empty;
  694. lock (m_Scripts)
  695. {
  696. if (!m_Assemblies.ContainsKey(i.AssetID))
  697. continue;
  698. assembly = m_Assemblies[i.AssetID];
  699. }
  700. try
  701. {
  702. i.SaveState(assembly);
  703. }
  704. catch (Exception e)
  705. {
  706. m_log.Error(
  707. string.Format(
  708. "[XEngine]: Failed to save state of script {0}.{1}, item UUID {2}, prim UUID {3} in {4}. Exception ",
  709. i.PrimName, i.ScriptName, i.ItemID, i.ObjectID, World.Name)
  710. , e);
  711. }
  712. }
  713. instances.Clear();
  714. if (saveTime > 0)
  715. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  716. new Object[] { saveTime });
  717. return 0;
  718. }
  719. public void SaveAllState()
  720. {
  721. foreach (IScriptInstance inst in m_Scripts.Values)
  722. {
  723. if (inst.EventTime() > m_EventLimit)
  724. {
  725. inst.Stop(100);
  726. if (!m_KillTimedOutScripts)
  727. inst.Start();
  728. }
  729. }
  730. }
  731. public object DoMaintenance(object p)
  732. {
  733. object[] parms = (object[])p;
  734. int sleepTime = (int)parms[0];
  735. SaveAllState();
  736. System.Threading.Thread.Sleep(sleepTime);
  737. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  738. new Object[]{ sleepTime });
  739. return 0;
  740. }
  741. public Type ReplaceableInterface
  742. {
  743. get { return null; }
  744. }
  745. public string Name
  746. {
  747. get { return "XEngine"; }
  748. }
  749. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  750. {
  751. // m_log.DebugFormat(
  752. // "[XEngine]: OnRezScript event triggered for script {0}, startParam {1}, postOnRez {2}, engine {3}, stateSource {4}, script\n{5}",
  753. // itemID, startParam, postOnRez, engine, stateSource, script);
  754. if (script.StartsWith("//MRM:"))
  755. return;
  756. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  757. List<string> names = new List<string>();
  758. foreach (IScriptModule m in engines)
  759. names.Add(m.ScriptEngineName);
  760. int lineEnd = script.IndexOf('\n');
  761. if (lineEnd > 1)
  762. {
  763. string firstline = script.Substring(0, lineEnd).Trim();
  764. int colon = firstline.IndexOf(':');
  765. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  766. {
  767. string engineName = firstline.Substring(2, colon - 2);
  768. if (names.Contains(engineName))
  769. {
  770. engine = engineName;
  771. script = "//" + script.Substring(colon + 1);
  772. }
  773. else
  774. {
  775. if (engine == ScriptEngineName)
  776. {
  777. // If we are falling back on XEngine as the default engine, then only complain to the user
  778. // if a script language has been explicitly set and it's one that we recognize or there are
  779. // no non-whitespace characters after the colon.
  780. //
  781. // If the script is
  782. // explicitly not allowed or the script is not in LSL then the user will be informed by a later compiler message.
  783. //
  784. // If the colon ends the line then we'll risk the false positive as this is more likely
  785. // to signal a real scriptengine line where the user wants to use the default compile language.
  786. //
  787. // This avoids the overwhelming number of false positives where we're in this code because
  788. // there's a colon in a comment in the first line of a script for entirely
  789. // unrelated reasons (e.g. vim settings).
  790. //
  791. // TODO: A better fix would be to deprecate simple : detection and look for some less likely
  792. // string to begin the comment (like #! in unix shell scripts).
  793. bool warnRunningInXEngine = false;
  794. string restOfFirstLine = firstline.Substring(colon + 1);
  795. // FIXME: These are hardcoded because they are currently hardcoded in Compiler.cs
  796. if (restOfFirstLine.StartsWith("c#")
  797. || restOfFirstLine.StartsWith("vb")
  798. || restOfFirstLine.StartsWith("lsl")
  799. || restOfFirstLine.StartsWith("js")
  800. || restOfFirstLine.StartsWith("yp")
  801. || restOfFirstLine.Length == 0)
  802. warnRunningInXEngine = true;
  803. if (warnRunningInXEngine)
  804. {
  805. SceneObjectPart part =
  806. m_Scene.GetSceneObjectPart(
  807. localID);
  808. TaskInventoryItem item =
  809. part.Inventory.GetInventoryItem(itemID);
  810. ScenePresence presence =
  811. m_Scene.GetScenePresence(
  812. item.OwnerID);
  813. if (presence != null)
  814. {
  815. presence.ControllingClient.SendAgentAlertMessage(
  816. "Selected engine unavailable. "+
  817. "Running script on "+
  818. ScriptEngineName,
  819. false);
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. if (engine != ScriptEngineName)
  827. return;
  828. // If we've seen this exact script text before, use that reference instead
  829. if (m_uniqueScripts.ContainsKey(script))
  830. script = m_uniqueScripts[script];
  831. else
  832. m_uniqueScripts[script] = script;
  833. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  834. if (stateSource == (int)StateSource.ScriptedRez)
  835. {
  836. lock (m_CompileDict)
  837. {
  838. m_CompileDict[itemID] = 0;
  839. }
  840. DoOnRezScript(parms);
  841. }
  842. else
  843. {
  844. m_CompileQueue.Enqueue(parms);
  845. lock (m_CompileDict)
  846. {
  847. m_CompileDict[itemID] = 0;
  848. }
  849. // m_log.DebugFormat("[XEngine]: Added script {0} to compile queue", itemID);
  850. if (m_CurrentCompile == null)
  851. {
  852. // NOTE: Although we use a lockless queue, the lock here
  853. // is required. It ensures that there are never two
  854. // compile threads running, which, due to a race
  855. // conndition, might otherwise happen
  856. //
  857. lock (m_CompileQueue)
  858. {
  859. if (m_CurrentCompile == null)
  860. m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
  861. }
  862. }
  863. }
  864. }
  865. public Object DoOnRezScriptQueue(Object dummy)
  866. {
  867. if (m_InitialStartup)
  868. {
  869. // This delay exists to stop mono problems where script compilation and startup would stop the sim
  870. // working properly for the session.
  871. System.Threading.Thread.Sleep(m_StartDelay);
  872. m_log.InfoFormat("[XEngine]: Performing initial script startup on {0}", m_Scene.Name);
  873. }
  874. object[] o;
  875. int scriptsStarted = 0;
  876. while (m_CompileQueue.Dequeue(out o))
  877. {
  878. if (DoOnRezScript(o))
  879. {
  880. scriptsStarted++;
  881. if (m_InitialStartup)
  882. if (scriptsStarted % 50 == 0)
  883. m_log.InfoFormat(
  884. "[XEngine]: Started {0} scripts in {1}", scriptsStarted, m_Scene.Name);
  885. }
  886. }
  887. if (m_InitialStartup)
  888. m_log.InfoFormat(
  889. "[XEngine]: Completed starting {0} scripts on {1}", scriptsStarted, m_Scene.Name);
  890. // NOTE: Despite having a lockless queue, this lock is required
  891. // to make sure there is never no compile thread while there
  892. // are still scripts to compile. This could otherwise happen
  893. // due to a race condition
  894. //
  895. lock (m_CompileQueue)
  896. m_CurrentCompile = null;
  897. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  898. m_ScriptErrorMessage);
  899. m_ScriptFailCount = 0;
  900. m_InitialStartup = false;
  901. return null;
  902. }
  903. private bool DoOnRezScript(object[] parms)
  904. {
  905. Object[] p = parms;
  906. uint localID = (uint)p[0];
  907. UUID itemID = (UUID)p[1];
  908. string script =(string)p[2];
  909. int startParam = (int)p[3];
  910. bool postOnRez = (bool)p[4];
  911. StateSource stateSource = (StateSource)p[5];
  912. // m_log.DebugFormat("[XEngine]: DoOnRezScript called for script {0}", itemID);
  913. lock (m_CompileDict)
  914. {
  915. if (!m_CompileDict.ContainsKey(itemID))
  916. return false;
  917. m_CompileDict.Remove(itemID);
  918. }
  919. // Get the asset ID of the script, so we can check if we
  920. // already have it.
  921. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  922. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  923. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  924. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  925. if (part == null)
  926. {
  927. m_log.ErrorFormat("[Script]: SceneObjectPart with localID {0} unavailable. Script NOT started.", localID);
  928. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  929. m_ScriptFailCount++;
  930. return false;
  931. }
  932. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  933. if (item == null)
  934. {
  935. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  936. m_ScriptFailCount++;
  937. return false;
  938. }
  939. m_log.DebugFormat(
  940. "[XEngine]: Loading script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  941. part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  942. part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  943. UUID assetID = item.AssetID;
  944. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  945. string assembly = "";
  946. Culture.SetCurrentCulture();
  947. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  948. lock (m_ScriptErrors)
  949. {
  950. try
  951. {
  952. lock (m_AddingAssemblies)
  953. {
  954. m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
  955. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  956. m_AddingAssemblies[assembly] = 1;
  957. } else {
  958. m_AddingAssemblies[assembly]++;
  959. }
  960. }
  961. string[] warnings = m_Compiler.GetWarnings();
  962. if (warnings != null && warnings.Length != 0)
  963. {
  964. foreach (string warning in warnings)
  965. {
  966. if (!m_ScriptErrors.ContainsKey(itemID))
  967. m_ScriptErrors[itemID] = new ArrayList();
  968. m_ScriptErrors[itemID].Add(warning);
  969. // try
  970. // {
  971. // // DISPLAY WARNING INWORLD
  972. // string text = "Warning:\n" + warning;
  973. // if (text.Length > 1000)
  974. // text = text.Substring(0, 1000);
  975. // if (!ShowScriptSaveResponse(item.OwnerID,
  976. // assetID, text, true))
  977. // {
  978. // if (presence != null && (!postOnRez))
  979. // presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  980. //
  981. // World.SimChat(Utils.StringToBytes(text),
  982. // ChatTypeEnum.DebugChannel, 2147483647,
  983. // part.AbsolutePosition,
  984. // part.Name, part.UUID, false);
  985. // }
  986. // }
  987. // catch (Exception e2) // LEGIT: User Scripting
  988. // {
  989. // m_log.Error("[XEngine]: " +
  990. // "Error displaying warning in-world: " +
  991. // e2.ToString());
  992. // m_log.Error("[XEngine]: " +
  993. // "Warning:\r\n" +
  994. // warning);
  995. // }
  996. }
  997. }
  998. }
  999. catch (Exception e)
  1000. {
  1001. // m_log.ErrorFormat(
  1002. // "[XEngine]: Exception when rezzing script with item ID {0}, {1}{2}",
  1003. // itemID, e.Message, e.StackTrace);
  1004. // try
  1005. // {
  1006. if (!m_ScriptErrors.ContainsKey(itemID))
  1007. m_ScriptErrors[itemID] = new ArrayList();
  1008. // DISPLAY ERROR INWORLD
  1009. // m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  1010. //
  1011. m_ScriptFailCount++;
  1012. m_ScriptErrors[itemID].Add(e.Message.ToString());
  1013. // string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
  1014. // if (text.Length > 1000)
  1015. // text = text.Substring(0, 1000);
  1016. // if (!ShowScriptSaveResponse(item.OwnerID,
  1017. // assetID, text, false))
  1018. // {
  1019. // if (presence != null && (!postOnRez))
  1020. // presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  1021. // World.SimChat(Utils.StringToBytes(text),
  1022. // ChatTypeEnum.DebugChannel, 2147483647,
  1023. // part.AbsolutePosition,
  1024. // part.Name, part.UUID, false);
  1025. // }
  1026. // }
  1027. // catch (Exception e2) // LEGIT: User Scripting
  1028. // {
  1029. // m_log.Error("[XEngine]: "+
  1030. // "Error displaying error in-world: " +
  1031. // e2.ToString());
  1032. // m_log.Error("[XEngine]: " +
  1033. // "Errormessage: Error compiling script:\r\n" +
  1034. // e.Message.ToString());
  1035. // }
  1036. return false;
  1037. }
  1038. }
  1039. ScriptInstance instance = null;
  1040. lock (m_Scripts)
  1041. {
  1042. // Create the object record
  1043. if ((!m_Scripts.ContainsKey(itemID)) ||
  1044. (m_Scripts[itemID].AssetID != assetID))
  1045. {
  1046. UUID appDomain = assetID;
  1047. if (part.ParentGroup.IsAttachment)
  1048. appDomain = part.ParentGroup.RootPart.UUID;
  1049. if (!m_AppDomains.ContainsKey(appDomain))
  1050. {
  1051. try
  1052. {
  1053. AppDomainSetup appSetup = new AppDomainSetup();
  1054. appSetup.PrivateBinPath = Path.Combine(
  1055. m_ScriptEnginesPath,
  1056. m_Scene.RegionInfo.RegionID.ToString());
  1057. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  1058. Evidence evidence = new Evidence(baseEvidence);
  1059. AppDomain sandbox;
  1060. if (m_AppDomainLoading)
  1061. {
  1062. sandbox = AppDomain.CreateDomain(
  1063. m_Scene.RegionInfo.RegionID.ToString(),
  1064. evidence, appSetup);
  1065. sandbox.AssemblyResolve +=
  1066. new ResolveEventHandler(
  1067. AssemblyResolver.OnAssemblyResolve);
  1068. }
  1069. else
  1070. {
  1071. sandbox = AppDomain.CurrentDomain;
  1072. }
  1073. //PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  1074. //AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  1075. //PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  1076. //PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  1077. //CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  1078. //sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  1079. //sandbox.SetAppDomainPolicy(sandboxPolicy);
  1080. m_AppDomains[appDomain] = sandbox;
  1081. m_DomainScripts[appDomain] = new List<UUID>();
  1082. }
  1083. catch (Exception e)
  1084. {
  1085. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  1086. m_ScriptErrorMessage += "Exception creating app domain:\n";
  1087. m_ScriptFailCount++;
  1088. lock (m_AddingAssemblies)
  1089. {
  1090. m_AddingAssemblies[assembly]--;
  1091. }
  1092. return false;
  1093. }
  1094. }
  1095. m_DomainScripts[appDomain].Add(itemID);
  1096. instance = new ScriptInstance(this, part,
  1097. item,
  1098. startParam, postOnRez,
  1099. m_MaxScriptQueue);
  1100. if (!instance.Load(m_AppDomains[appDomain], assembly, stateSource))
  1101. return false;
  1102. // if (DebugLevel >= 1)
  1103. // m_log.DebugFormat(
  1104. // "[XEngine] Loaded script {0}.{1}, item UUID {2}, prim UUID {3} @ {4}.{5}",
  1105. // part.ParentGroup.RootPart.Name, item.Name, itemID, part.UUID,
  1106. // part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  1107. if (presence != null)
  1108. {
  1109. ShowScriptSaveResponse(item.OwnerID,
  1110. assetID, "Compile successful", true);
  1111. }
  1112. instance.AppDomain = appDomain;
  1113. instance.LineMap = linemap;
  1114. m_Scripts[itemID] = instance;
  1115. }
  1116. }
  1117. lock (m_PrimObjects)
  1118. {
  1119. if (!m_PrimObjects.ContainsKey(localID))
  1120. m_PrimObjects[localID] = new List<UUID>();
  1121. if (!m_PrimObjects[localID].Contains(itemID))
  1122. m_PrimObjects[localID].Add(itemID);
  1123. }
  1124. if (!m_Assemblies.ContainsKey(assetID))
  1125. m_Assemblies[assetID] = assembly;
  1126. lock (m_AddingAssemblies)
  1127. {
  1128. m_AddingAssemblies[assembly]--;
  1129. }
  1130. if (instance != null)
  1131. instance.Init();
  1132. bool runIt;
  1133. if (m_runFlags.TryGetValue(itemID, out runIt))
  1134. {
  1135. if (!runIt)
  1136. StopScript(itemID);
  1137. m_runFlags.Remove(itemID);
  1138. }
  1139. return true;
  1140. }
  1141. public void OnRemoveScript(uint localID, UUID itemID)
  1142. {
  1143. // If it's not yet been compiled, make sure we don't try
  1144. lock (m_CompileDict)
  1145. {
  1146. if (m_CompileDict.ContainsKey(itemID))
  1147. m_CompileDict.Remove(itemID);
  1148. }
  1149. IScriptInstance instance = null;
  1150. lock (m_Scripts)
  1151. {
  1152. // Do we even have it?
  1153. if (!m_Scripts.ContainsKey(itemID))
  1154. return;
  1155. instance = m_Scripts[itemID];
  1156. m_Scripts.Remove(itemID);
  1157. }
  1158. instance.ClearQueue();
  1159. instance.Stop(m_WaitForEventCompletionOnScriptStop);
  1160. // bool objectRemoved = false;
  1161. lock (m_PrimObjects)
  1162. {
  1163. // Remove the script from it's prim
  1164. if (m_PrimObjects.ContainsKey(localID))
  1165. {
  1166. // Remove inventory item record
  1167. if (m_PrimObjects[localID].Contains(itemID))
  1168. m_PrimObjects[localID].Remove(itemID);
  1169. // If there are no more scripts, remove prim
  1170. if (m_PrimObjects[localID].Count == 0)
  1171. {
  1172. m_PrimObjects.Remove(localID);
  1173. // objectRemoved = true;
  1174. }
  1175. }
  1176. }
  1177. instance.RemoveState();
  1178. instance.DestroyScriptInstance();
  1179. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  1180. if (m_DomainScripts[instance.AppDomain].Count == 0)
  1181. {
  1182. m_DomainScripts.Remove(instance.AppDomain);
  1183. UnloadAppDomain(instance.AppDomain);
  1184. }
  1185. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  1186. if (handlerObjectRemoved != null)
  1187. handlerObjectRemoved(instance.ObjectID);
  1188. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  1189. if (handlerScriptRemoved != null)
  1190. handlerScriptRemoved(itemID);
  1191. }
  1192. public void OnScriptReset(uint localID, UUID itemID)
  1193. {
  1194. ResetScript(itemID);
  1195. }
  1196. public void OnStartScript(uint localID, UUID itemID)
  1197. {
  1198. StartScript(itemID);
  1199. }
  1200. public void OnStopScript(uint localID, UUID itemID)
  1201. {
  1202. StopScript(itemID);
  1203. }
  1204. private void CleanAssemblies()
  1205. {
  1206. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  1207. foreach (IScriptInstance i in m_Scripts.Values)
  1208. {
  1209. if (assetIDList.Contains(i.AssetID))
  1210. assetIDList.Remove(i.AssetID);
  1211. }
  1212. lock (m_AddingAssemblies)
  1213. {
  1214. foreach (UUID assetID in assetIDList)
  1215. {
  1216. // Do not remove assembly files if another instance of the script
  1217. // is currently initialising
  1218. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  1219. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  1220. {
  1221. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  1222. try
  1223. {
  1224. if (File.Exists(m_Assemblies[assetID]))
  1225. File.Delete(m_Assemblies[assetID]);
  1226. if (File.Exists(m_Assemblies[assetID]+".text"))
  1227. File.Delete(m_Assemblies[assetID]+".text");
  1228. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  1229. File.Delete(m_Assemblies[assetID]+".mdb");
  1230. if (File.Exists(m_Assemblies[assetID]+".map"))
  1231. File.Delete(m_Assemblies[assetID]+".map");
  1232. }
  1233. catch (Exception)
  1234. {
  1235. }
  1236. m_Assemblies.Remove(assetID);
  1237. }
  1238. }
  1239. }
  1240. }
  1241. private void UnloadAppDomain(UUID id)
  1242. {
  1243. if (m_AppDomains.ContainsKey(id))
  1244. {
  1245. AppDomain domain = m_AppDomains[id];
  1246. m_AppDomains.Remove(id);
  1247. if (domain != AppDomain.CurrentDomain)
  1248. AppDomain.Unload(domain);
  1249. domain = null;
  1250. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  1251. }
  1252. }
  1253. //
  1254. // Start processing
  1255. //
  1256. private void SetupEngine(int minThreads, int maxThreads,
  1257. int idleTimeout, ThreadPriority threadPriority,
  1258. int maxScriptQueue, int stackSize)
  1259. {
  1260. m_MaxScriptQueue = maxScriptQueue;
  1261. STPStartInfo startInfo = new STPStartInfo();
  1262. startInfo.ThreadPoolName = "XEngine";
  1263. startInfo.IdleTimeout = idleTimeout * 1000; // convert to seconds as stated in .ini
  1264. startInfo.MaxWorkerThreads = maxThreads;
  1265. startInfo.MinWorkerThreads = minThreads;
  1266. startInfo.ThreadPriority = threadPriority;;
  1267. startInfo.MaxStackSize = stackSize;
  1268. startInfo.StartSuspended = true;
  1269. m_ThreadPool = new SmartThreadPool(startInfo);
  1270. }
  1271. //
  1272. // Used by script instances to queue event handler jobs
  1273. //
  1274. public IScriptWorkItem QueueEventHandler(object parms)
  1275. {
  1276. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  1277. new WorkItemCallback(this.ProcessEventHandler),
  1278. parms));
  1279. }
  1280. /// <summary>
  1281. /// Process a previously posted script event.
  1282. /// </summary>
  1283. /// <param name="parms"></param>
  1284. /// <returns></returns>
  1285. private object ProcessEventHandler(object parms)
  1286. {
  1287. Culture.SetCurrentCulture();
  1288. IScriptInstance instance = (ScriptInstance) parms;
  1289. //m_log.DebugFormat("[XEngine]: Processing event for {0}", instance);
  1290. return instance.EventProcessor();
  1291. }
  1292. /// <summary>
  1293. /// Post event to an entire prim
  1294. /// </summary>
  1295. /// <param name="localID"></param>
  1296. /// <param name="p"></param>
  1297. /// <returns></returns>
  1298. public bool PostObjectEvent(uint localID, EventParams p)
  1299. {
  1300. bool result = false;
  1301. List<UUID> uuids = null;
  1302. lock (m_PrimObjects)
  1303. {
  1304. if (!m_PrimObjects.ContainsKey(localID))
  1305. return false;
  1306. uuids = m_PrimObjects[localID];
  1307. foreach (UUID itemID in uuids)
  1308. {
  1309. IScriptInstance instance = null;
  1310. try
  1311. {
  1312. if (m_Scripts.ContainsKey(itemID))
  1313. instance = m_Scripts[itemID];
  1314. }
  1315. catch { /* ignore race conditions */ }
  1316. if (instance != null)
  1317. {
  1318. instance.PostEvent(p);
  1319. result = true;
  1320. }
  1321. }
  1322. }
  1323. return result;
  1324. }
  1325. /// <summary>
  1326. /// Post an event to a single script
  1327. /// </summary>
  1328. /// <param name="itemID"></param>
  1329. /// <param name="p"></param>
  1330. /// <returns></returns>
  1331. public bool PostScriptEvent(UUID itemID, EventParams p)
  1332. {
  1333. if (m_Scripts.ContainsKey(itemID))
  1334. {
  1335. IScriptInstance instance = m_Scripts[itemID];
  1336. if (instance != null)
  1337. instance.PostEvent(p);
  1338. return true;
  1339. }
  1340. return false;
  1341. }
  1342. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  1343. {
  1344. Object[] lsl_p = new Object[p.Length];
  1345. for (int i = 0; i < p.Length ; i++)
  1346. {
  1347. if (p[i] is int)
  1348. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1349. else if (p[i] is string)
  1350. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1351. else if (p[i] is Vector3)
  1352. lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
  1353. else if (p[i] is Quaternion)
  1354. lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
  1355. else if (p[i] is float)
  1356. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1357. else
  1358. lsl_p[i] = p[i];
  1359. }
  1360. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  1361. }
  1362. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  1363. {
  1364. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  1365. if (part == null)
  1366. return false;
  1367. Object[] lsl_p = new Object[p.Length];
  1368. for (int i = 0; i < p.Length ; i++)
  1369. {
  1370. if (p[i] is int)
  1371. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  1372. else if (p[i] is string)
  1373. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  1374. else if (p[i] is Vector3)
  1375. lsl_p[i] = new LSL_Types.Vector3((Vector3)p[i]);
  1376. else if (p[i] is Quaternion)
  1377. lsl_p[i] = new LSL_Types.Quaternion((Quaternion)p[i]);
  1378. else if (p[i] is float)
  1379. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  1380. else
  1381. lsl_p[i] = p[i];
  1382. }
  1383. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  1384. }
  1385. public Assembly OnAssemblyResolve(object sender,
  1386. ResolveEventArgs args)
  1387. {
  1388. if (!(sender is System.AppDomain))
  1389. return null;
  1390. string[] pathList = new string[] {"bin", m_ScriptEnginesPath,
  1391. Path.Combine(m_ScriptEnginesPath,
  1392. m_Scene.RegionInfo.RegionID.ToString())};
  1393. string assemblyName = args.Name;
  1394. if (assemblyName.IndexOf(",") != -1)
  1395. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  1396. foreach (string s in pathList)
  1397. {
  1398. string path = Path.Combine(Directory.GetCurrentDirectory(),
  1399. Path.Combine(s, assemblyName))+".dll";
  1400. // Console.WriteLine("[XEngine]: Trying to resolve {0}", path);
  1401. if (File.Exists(path))
  1402. return Assembly.LoadFrom(path);
  1403. }
  1404. return null;
  1405. }
  1406. private IScriptInstance GetInstance(UUID itemID)
  1407. {
  1408. IScriptInstance instance;
  1409. lock (m_Scripts)
  1410. {
  1411. if (!m_Scripts.ContainsKey(itemID))
  1412. return null;
  1413. instance = m_Scripts[itemID];
  1414. }
  1415. return instance;
  1416. }
  1417. public void SetScriptState(UUID itemID, bool running)
  1418. {
  1419. IScriptInstance instance = GetInstance(itemID);
  1420. if (instance != null)
  1421. {
  1422. if (running)
  1423. instance.Start();
  1424. else
  1425. instance.Stop(100);
  1426. }
  1427. }
  1428. public bool GetScriptState(UUID itemID)
  1429. {
  1430. IScriptInstance instance = GetInstance(itemID);
  1431. return instance != null && instance.Running;
  1432. }
  1433. public void ApiResetScript(UUID itemID)
  1434. {
  1435. IScriptInstance instance = GetInstance(itemID);
  1436. if (instance != null)
  1437. instance.ApiResetScript();
  1438. }
  1439. public void ResetScript(UUID itemID)
  1440. {
  1441. IScriptInstance instance = GetInstance(itemID);
  1442. if (instance != null)
  1443. instance.ResetScript(m_WaitForEventCompletionOnScriptStop);
  1444. }
  1445. public void StartScript(UUID itemID)
  1446. {
  1447. IScriptInstance instance = GetInstance(itemID);
  1448. if (instance != null)
  1449. instance.Start();
  1450. else
  1451. m_runFlags.AddOrUpdate(itemID, true, 240);
  1452. }
  1453. public void StopScript(UUID itemID)
  1454. {
  1455. IScriptInstance instance = GetInstance(itemID);
  1456. if (instance != null)
  1457. {
  1458. instance.Stop(m_WaitForEventCompletionOnScriptStop);
  1459. }
  1460. else
  1461. {
  1462. // m_log.DebugFormat("[XENGINE]: Could not find script with ID {0} to stop in {1}", itemID, World.Name);
  1463. m_runFlags.AddOrUpdate(itemID, false, 240);
  1464. }
  1465. }
  1466. public DetectParams GetDetectParams(UUID itemID, int idx)
  1467. {
  1468. IScriptInstance instance = GetInstance(itemID);
  1469. return instance != null ? instance.GetDetectParams(idx) : null;
  1470. }
  1471. public void SetMinEventDelay(UUID itemID, double delay)
  1472. {
  1473. IScriptInstance instance = GetInstance(itemID);
  1474. if (instance != null)
  1475. instance.MinEventDelay = delay;
  1476. }
  1477. public UUID GetDetectID(UUID itemID, int idx)
  1478. {
  1479. IScriptInstance instance = GetInstance(itemID);
  1480. return instance != null ? instance.GetDetectID(idx) : UUID.Zero;
  1481. }
  1482. public void SetState(UUID itemID, string newState)
  1483. {
  1484. IScriptInstance instance = GetInstance(itemID);
  1485. if (instance == null)
  1486. return;
  1487. instance.SetState(newState);
  1488. }
  1489. public int GetStartParameter(UUID itemID)
  1490. {
  1491. IScriptInstance instance = GetInstance(itemID);
  1492. return instance == null ? 0 : instance.StartParam;
  1493. }
  1494. public void OnShutdown()
  1495. {
  1496. m_SimulatorShuttingDown = true;
  1497. List<IScriptInstance> instances = new List<IScriptInstance>();
  1498. lock (m_Scripts)
  1499. {
  1500. foreach (IScriptInstance instance in m_Scripts.Values)
  1501. instances.Add(instance);
  1502. }
  1503. foreach (IScriptInstance i in instances)
  1504. {
  1505. // Stop the script, even forcibly if needed. Then flag
  1506. // it as shutting down and restore the previous run state
  1507. // for serialization, so the scripts don't come back
  1508. // dead after region restart
  1509. //
  1510. bool prevRunning = i.Running;
  1511. i.Stop(50);
  1512. i.ShuttingDown = true;
  1513. i.Running = prevRunning;
  1514. }
  1515. DoBackup(new Object[] {0});
  1516. }
  1517. public IScriptApi GetApi(UUID itemID, string name)
  1518. {
  1519. IScriptInstance instance = GetInstance(itemID);
  1520. return instance == null ? null : instance.GetApi(name);
  1521. }
  1522. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1523. {
  1524. IScriptInstance instance = GetInstance(itemID);
  1525. if (instance == null)
  1526. return;
  1527. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1528. if (eq == null)
  1529. {
  1530. controllingClient.SendScriptRunningReply(objectID, itemID,
  1531. GetScriptState(itemID));
  1532. }
  1533. else
  1534. {
  1535. eq.Enqueue(eq.ScriptRunningEvent(objectID, itemID, GetScriptState(itemID), true),
  1536. controllingClient.AgentId);
  1537. }
  1538. }
  1539. public string GetXMLState(UUID itemID)
  1540. {
  1541. // m_log.DebugFormat("[XEngine]: Getting XML state for script instance {0}", itemID);
  1542. IScriptInstance instance = GetInstance(itemID);
  1543. if (instance == null)
  1544. {
  1545. // m_log.DebugFormat("[XEngine]: Found no script instance for {0}, returning empty string", itemID);
  1546. return "";
  1547. }
  1548. string xml = instance.GetXMLState();
  1549. XmlDocument sdoc = new XmlDocument();
  1550. bool loadedState = true;
  1551. try
  1552. {
  1553. sdoc.LoadXml(xml);
  1554. }
  1555. catch (System.Xml.XmlException)
  1556. {
  1557. loadedState = false;
  1558. }
  1559. XmlNodeList rootL = null;
  1560. XmlNode rootNode = null;
  1561. if (loadedState)
  1562. {
  1563. rootL = sdoc.GetElementsByTagName("ScriptState");
  1564. rootNode = rootL[0];
  1565. }
  1566. // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
  1567. XmlDocument doc = new XmlDocument();
  1568. XmlElement stateData = doc.CreateElement("", "State", "");
  1569. XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
  1570. stateID.Value = itemID.ToString();
  1571. stateData.Attributes.Append(stateID);
  1572. XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
  1573. assetID.Value = instance.AssetID.ToString();
  1574. stateData.Attributes.Append(assetID);
  1575. XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
  1576. engineName.Value = ScriptEngineName;
  1577. stateData.Attributes.Append(engineName);
  1578. doc.AppendChild(stateData);
  1579. XmlNode xmlstate = null;
  1580. // Add <ScriptState>...</ScriptState>
  1581. if (loadedState)
  1582. {
  1583. xmlstate = doc.ImportNode(rootNode, true);
  1584. }
  1585. else
  1586. {
  1587. xmlstate = doc.CreateElement("", "ScriptState", "");
  1588. }
  1589. stateData.AppendChild(xmlstate);
  1590. string assemName = instance.GetAssemblyName();
  1591. string fn = Path.GetFileName(assemName);
  1592. string assem = String.Empty;
  1593. if (File.Exists(assemName + ".text"))
  1594. {
  1595. FileInfo tfi = new FileInfo(assemName + ".text");
  1596. if (tfi != null)
  1597. {
  1598. Byte[] tdata = new Byte[tfi.Length];
  1599. try
  1600. {
  1601. using (FileStream tfs = File.Open(assemName + ".text",
  1602. FileMode.Open, FileAccess.Read))
  1603. {
  1604. tfs.Read(tdata, 0, tdata.Length);
  1605. }
  1606. assem = Encoding.ASCII.GetString(tdata);
  1607. }
  1608. catch (Exception e)
  1609. {
  1610. m_log.ErrorFormat(
  1611. "[XEngine]: Unable to open script textfile {0}{1}, reason: {2}",
  1612. assemName, ".text", e.Message);
  1613. }
  1614. }
  1615. }
  1616. else
  1617. {
  1618. FileInfo fi = new FileInfo(assemName);
  1619. if (fi != null)
  1620. {
  1621. Byte[] data = new Byte[fi.Length];
  1622. try
  1623. {
  1624. using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
  1625. {
  1626. fs.Read(data, 0, data.Length);
  1627. }
  1628. assem = System.Convert.ToBase64String(data);
  1629. }
  1630. catch (Exception e)
  1631. {
  1632. m_log.ErrorFormat(
  1633. "[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
  1634. }
  1635. }
  1636. }
  1637. string map = String.Empty;
  1638. if (File.Exists(fn + ".map"))
  1639. {
  1640. using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
  1641. {
  1642. using (StreamReader msr = new StreamReader(mfs))
  1643. {
  1644. map = msr.ReadToEnd();
  1645. }
  1646. }
  1647. }
  1648. XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
  1649. XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
  1650. assemblyName.Value = fn;
  1651. assemblyData.Attributes.Append(assemblyName);
  1652. assemblyData.InnerText = assem;
  1653. stateData.AppendChild(assemblyData);
  1654. XmlElement mapData = doc.CreateElement("", "LineMap", "");
  1655. XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
  1656. mapName.Value = fn + ".map";
  1657. mapData.Attributes.Append(mapName);
  1658. mapData.InnerText = map;
  1659. stateData.AppendChild(mapData);
  1660. // m_log.DebugFormat("[XEngine]: Got XML state for {0}", itemID);
  1661. return doc.InnerXml;
  1662. }
  1663. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1664. {
  1665. return false;
  1666. }
  1667. public bool SetXMLState(UUID itemID, string xml)
  1668. {
  1669. // m_log.DebugFormat("[XEngine]: Writing state for script item with ID {0}", itemID);
  1670. if (xml == String.Empty)
  1671. return false;
  1672. XmlDocument doc = new XmlDocument();
  1673. try
  1674. {
  1675. doc.LoadXml(xml);
  1676. }
  1677. catch (Exception)
  1678. {
  1679. m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
  1680. return false;
  1681. }
  1682. XmlNodeList rootL = doc.GetElementsByTagName("State");
  1683. if (rootL.Count < 1)
  1684. return false;
  1685. XmlElement rootE = (XmlElement)rootL[0];
  1686. if (rootE.GetAttribute("Engine") != ScriptEngineName)
  1687. return false;
  1688. // On rez from inventory, that ID will have changed. It was only
  1689. // advisory anyway. So we don't check it anymore.
  1690. //
  1691. // if (rootE.GetAttribute("UUID") != itemID.ToString())
  1692. // return;
  1693. XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
  1694. if (stateL.Count != 1)
  1695. return false;
  1696. XmlElement stateE = (XmlElement)stateL[0];
  1697. if (World.m_trustBinaries)
  1698. {
  1699. XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
  1700. if (assemL.Count != 1)
  1701. return false;
  1702. XmlElement assemE = (XmlElement)assemL[0];
  1703. string fn = assemE.GetAttribute("Filename");
  1704. string base64 = assemE.InnerText;
  1705. string path = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1706. path = Path.Combine(path, fn);
  1707. if (!File.Exists(path))
  1708. {
  1709. Byte[] filedata = Convert.FromBase64String(base64);
  1710. try
  1711. {
  1712. using (FileStream fs = File.Create(path))
  1713. {
  1714. // m_log.DebugFormat("[XEngine]: Writing assembly file {0}", path);
  1715. fs.Write(filedata, 0, filedata.Length);
  1716. }
  1717. }
  1718. catch (IOException ex)
  1719. {
  1720. // if there already exists a file at that location, it may be locked.
  1721. m_log.ErrorFormat("[XEngine]: Error whilst writing assembly file {0}, {1}", path, ex.Message);
  1722. }
  1723. string textpath = path + ".text";
  1724. try
  1725. {
  1726. using (FileStream fs = File.Create(textpath))
  1727. {
  1728. using (StreamWriter sw = new StreamWriter(fs))
  1729. {
  1730. // m_log.DebugFormat("[XEngine]: Writing .text file {0}", textpath);
  1731. sw.Write(base64);
  1732. }
  1733. }
  1734. }
  1735. catch (IOException ex)
  1736. {
  1737. // if there already exists a file at that location, it may be locked.
  1738. m_log.ErrorFormat("[XEngine]: Error whilst writing .text file {0}, {1}", textpath, ex.Message);
  1739. }
  1740. }
  1741. XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
  1742. if (mapL.Count > 0)
  1743. {
  1744. XmlElement mapE = (XmlElement)mapL[0];
  1745. string mappath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1746. mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
  1747. try
  1748. {
  1749. using (FileStream mfs = File.Create(mappath))
  1750. {
  1751. using (StreamWriter msw = new StreamWriter(mfs))
  1752. {
  1753. // m_log.DebugFormat("[XEngine]: Writing linemap file {0}", mappath);
  1754. msw.Write(mapE.InnerText);
  1755. }
  1756. }
  1757. }
  1758. catch (IOException ex)
  1759. {
  1760. // if there already exists a file at that location, it may be locked.
  1761. m_log.ErrorFormat("[XEngine]: Linemap file {0} already exists! {1}", mappath, ex.Message);
  1762. }
  1763. }
  1764. }
  1765. string statepath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1766. statepath = Path.Combine(statepath, itemID.ToString() + ".state");
  1767. try
  1768. {
  1769. using (FileStream sfs = File.Create(statepath))
  1770. {
  1771. using (StreamWriter ssw = new StreamWriter(sfs))
  1772. {
  1773. // m_log.DebugFormat("[XEngine]: Writing state file {0}", statepath);
  1774. ssw.Write(stateE.OuterXml);
  1775. }
  1776. }
  1777. }
  1778. catch (IOException ex)
  1779. {
  1780. // if there already exists a file at that location, it may be locked.
  1781. m_log.ErrorFormat("[XEngine]: Error whilst writing state file {0}, {1}", statepath, ex.Message);
  1782. }
  1783. return true;
  1784. }
  1785. public ArrayList GetScriptErrors(UUID itemID)
  1786. {
  1787. System.Threading.Thread.Sleep(1000);
  1788. lock (m_ScriptErrors)
  1789. {
  1790. if (m_ScriptErrors.ContainsKey(itemID))
  1791. {
  1792. ArrayList ret = m_ScriptErrors[itemID];
  1793. m_ScriptErrors.Remove(itemID);
  1794. return ret;
  1795. }
  1796. return new ArrayList();
  1797. }
  1798. }
  1799. public Dictionary<uint, float> GetObjectScriptsExecutionTimes()
  1800. {
  1801. long tickNow = Util.EnvironmentTickCount();
  1802. Dictionary<uint, float> topScripts = new Dictionary<uint, float>();
  1803. lock (m_Scripts)
  1804. {
  1805. foreach (IScriptInstance si in m_Scripts.Values)
  1806. {
  1807. if (!topScripts.ContainsKey(si.LocalID))
  1808. topScripts[si.RootLocalID] = 0;
  1809. topScripts[si.RootLocalID] += CalculateAdjustedExectionTime(si, tickNow);
  1810. }
  1811. }
  1812. return topScripts;
  1813. }
  1814. public float GetScriptExecutionTime(List<UUID> itemIDs)
  1815. {
  1816. if (itemIDs == null|| itemIDs.Count == 0)
  1817. {
  1818. return 0.0f;
  1819. }
  1820. float time = 0.0f;
  1821. long tickNow = Util.EnvironmentTickCount();
  1822. IScriptInstance si;
  1823. // Calculate the time for all scripts that this engine is executing
  1824. // Ignore any others
  1825. foreach (UUID id in itemIDs)
  1826. {
  1827. si = GetInstance(id);
  1828. if (si != null && si.Running)
  1829. {
  1830. time += CalculateAdjustedExectionTime(si, tickNow);
  1831. }
  1832. }
  1833. return time;
  1834. }
  1835. private float CalculateAdjustedExectionTime(IScriptInstance si, long tickNow)
  1836. {
  1837. long ticksElapsed = tickNow - si.MeasurementPeriodTickStart;
  1838. // Avoid divide by zero
  1839. if (ticksElapsed == 0)
  1840. ticksElapsed = 1;
  1841. // Scale execution time to the ideal 55 fps frame time for these reasons.
  1842. //
  1843. // 1) XEngine does not execute scripts per frame, unlike other script engines. Hence, there is no
  1844. // 'script execution time per frame', which is the original purpose of this value.
  1845. //
  1846. // 2) Giving the raw execution times is misleading since scripts start at different times, making
  1847. // it impossible to compare scripts.
  1848. //
  1849. // 3) Scaling the raw execution time to the time that the script has been running is better but
  1850. // is still misleading since a script that has just been rezzed may appear to have been running
  1851. // for much longer.
  1852. //
  1853. // 4) Hence, we scale execution time to an idealised frame time (55 fps). This is also not perfect
  1854. // since the figure does not represent actual execution time and very hard running scripts will
  1855. // never exceed 18ms (though this is a very high number for script execution so is a warning sign).
  1856. return ((float)si.MeasurementPeriodExecutionTime / ticksElapsed) * 18.1818f;
  1857. }
  1858. public void SuspendScript(UUID itemID)
  1859. {
  1860. // m_log.DebugFormat("[XEngine]: Received request to suspend script with ID {0}", itemID);
  1861. IScriptInstance instance = GetInstance(itemID);
  1862. if (instance != null)
  1863. instance.Suspend();
  1864. // else
  1865. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  1866. }
  1867. public void ResumeScript(UUID itemID)
  1868. {
  1869. // m_log.DebugFormat("[XEngine]: Received request to resume script with ID {0}", itemID);
  1870. IScriptInstance instance = GetInstance(itemID);
  1871. if (instance != null)
  1872. instance.Resume();
  1873. // else
  1874. // m_log.DebugFormat("[XEngine]: Could not find script with ID {0} to resume", itemID);
  1875. }
  1876. public bool HasScript(UUID itemID, out bool running)
  1877. {
  1878. running = true;
  1879. IScriptInstance instance = GetInstance(itemID);
  1880. if (instance == null)
  1881. return false;
  1882. running = instance.Running;
  1883. return true;
  1884. }
  1885. }
  1886. }