XEngine.cs 99 KB

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