XEngine.cs 87 KB

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