1
0

XEngine.cs 89 KB

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