XEngine.cs 99 KB

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