XEngine.cs 96 KB

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