Work in progress on SECS stuff. Have been holding it off until after 0.6 release. Still messy as hell and doesn't really work yet. Will undergo dramatic changes. AND MOST IMPORTANTLY: Will be conformed to work in coop with todays DNE and XEngine, hopefully one day providing a common interface for all components.

This commit is contained in:
Tedd Hansen
2008-11-08 17:35:48 +00:00
parent cf0a14bec9
commit 9511a8c763
53 changed files with 2997 additions and 573 deletions

View File

@@ -0,0 +1,213 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public class BaseClassFactory
{
public static void MakeBaseClass(ScriptStructure script)
{
string asmName = "ScriptAssemblies";
string ModuleID = asmName;
string ClassID = "Script";
string moveToDir = "ScriptEngines";
string asmFileName = ModuleID + "_" + ClassID + ".dll";
if (!Directory.Exists(moveToDir))
Directory.CreateDirectory(moveToDir);
ILGenerator ilgen;
AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName(asmName), AssemblyBuilderAccess.RunAndSave);
// The module builder
ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule(ModuleID, asmFileName);
// The class builder
TypeBuilder classBuilder = modBuilder.DefineType(ClassID, TypeAttributes.Class | TypeAttributes.Public);
// The default constructor
ConstructorBuilder ctorBuilder = classBuilder.DefineDefaultConstructor(MethodAttributes.Public);
Type[] paramsTypeArray = new Type[] {typeof (System.ParamArrayAttribute)};
Type[] executeFunctionTypeArray = new Type[] {typeof (string), typeof (System.ParamArrayAttribute)};
foreach (IScriptCommandProvider cp in script.RegionInfo.CommandProviders.Values)
{
Type t = cp.GetType();
foreach (MethodInfo mi in t.GetMethods())
{
MethodBuilder methodBuilder = classBuilder.DefineMethod(mi.Name, mi.Attributes, mi.GetType(), Type.EmptyTypes);
methodBuilder.SetParameters(paramsTypeArray);
//ParameterBuilder paramBuilder = methodBuilder.DefineParameter(1, ParameterAttributes.None, "args");
ilgen = methodBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Nop);
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldc_I4_0);
//ilgen.Emit(OpCodes.Ldelem_Ref);
//ilgen.MarkSequencePoint(doc, 6, 1, 6, 100);
MethodInfo ExecuteFunction = typeof(ScriptAssemblies.IScript).GetMethod(
"ExecuteFunction",
executeFunctionTypeArray);
ilgen.DeclareLocal(typeof(string));
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Ldstr, mi.Name);
ilgen.Emit(OpCodes.Stloc_0);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Ldloc_0);
ilgen.Emit(OpCodes.Ldarg_1);
// FieldInfo testInfo = classBuilder.
//BindingFlags.NonPublic | BindingFlags.Instance);
//ilgen.Emit(OpCodes.Ldfld, testInfo);
//ilgen.EmitCall(OpCodes.Call, ExecuteFunction, executeFunctionTypeArray);
ilgen.EmitCall(OpCodes.Call, typeof(System.Console).GetMethod("WriteLine"), executeFunctionTypeArray);
// // string.Format("Hello, {0} World!", toWhom)
// //
// ilgen.Emit(OpCodes.Ldstr, "Hello, {0} World!");
// ilgen.Emit(OpCodes.Ldarg_1);
// ilgen.Emit(OpCodes.Call, typeof(string).GetMethod
//("Format", new Type[] { typeof(string), typeof(object) }));
// // Console.WriteLine("Hello, World!");
// //
// ilgen.Emit(OpCodes.Call, typeof(Console).GetMethod
// ("WriteLine", new Type[] { typeof(string) }));
ilgen.Emit(OpCodes.Ret);
//Label eom = ilgen.DefineLabel();
//ilgen.Emit(OpCodes.Br_S, eom);
//ilgen.MarkLabel(eom);
//ilgen.Emit(OpCodes.Ret);
//Type test = methodBuilder.SetParameters();
//methodBuilder.SetParameters(typeof (object[]));
}
}
//// Two fields: m_firstname, m_lastname
//FieldBuilder fBuilderFirstName = classBuilder.DefineField("m_firstname", typeof(string), FieldAttributes.Private);
//FieldBuilder fBuilderLastName = classBuilder.DefineField("m_lastname", typeof(string), FieldAttributes.Private);
//// Two properties for this object: FirstName, LastName
//PropertyBuilder pBuilderFirstName = classBuilder.DefineProperty("FirstName", System.Reflection.PropertyAttributes.HasDefault, typeof(string), null);
//PropertyBuilder pBuilderLastName = classBuilder.DefineProperty("LastName", System.Reflection.PropertyAttributes.HasDefault, typeof(string), null);
//// Custom attributes for get, set accessors
//MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName;
//// get,set accessors for FirstName
//MethodBuilder mGetFirstNameBuilder = classBuilder.DefineMethod("get_FirstName", getSetAttr, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetFirstNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldfld, fBuilderFirstName); // returning the firstname field
//ilgen.Emit(OpCodes.Ret);
//MethodBuilder mSetFirstNameBuilder = classBuilder.DefineMethod("set_FirstName", getSetAttr, null, new Type[] { typeof(string) });
//// Code generation
//ilgen = mSetFirstNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Stfld, fBuilderFirstName); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ret);
//// get,set accessors for LastName
//MethodBuilder mGetLastNameBuilder = classBuilder.DefineMethod("get_LastName", getSetAttr, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetLastNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldfld, fBuilderLastName); // returning the firstname field
//ilgen.Emit(OpCodes.Ret);
//MethodBuilder mSetLastNameBuilder = classBuilder.DefineMethod("set_LastName", getSetAttr, null, new Type[] { typeof(string) });
//// Code generation
//ilgen = mSetLastNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Stfld, fBuilderLastName); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ret);
//// Assigning get/set accessors
//pBuilderFirstName.SetGetMethod(mGetFirstNameBuilder);
//pBuilderFirstName.SetSetMethod(mSetFirstNameBuilder);
//pBuilderLastName.SetGetMethod(mGetLastNameBuilder);
//pBuilderLastName.SetSetMethod(mSetLastNameBuilder);
//// Now, a custom method named GetFullName that concatenates FirstName and LastName properties
//MethodBuilder mGetFullNameBuilder = classBuilder.DefineMethod("GetFullName", MethodAttributes.Public, typeof(string), Type.EmptyTypes);
//// Code generation
//ilgen = mGetFullNameBuilder.GetILGenerator();
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, mGetFirstNameBuilder); // getting the firstname
//ilgen.Emit(OpCodes.Ldstr, " "); // an space
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, mGetLastNameBuilder); // getting the lastname
//// We need the 'Concat' method from string type
//MethodInfo concatMethod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string), typeof(string) });
//ilgen.Emit(OpCodes.Call, concatMethod); // calling concat and returning the result
//ilgen.Emit(OpCodes.Ret);
//// Another constructor that initializes firstname and lastname
//ConstructorBuilder ctorBuilder2 = classBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string), typeof(string) });
//ctorBuilder2.DefineParameter(1, ParameterAttributes.In, "firstname");
//ctorBuilder2.DefineParameter(2, ParameterAttributes.In, "lastname");
//// Code generation
//ilgen = ctorBuilder2.GetILGenerator();
//// First of all, we need to call the base constructor,
//// the Object's constructor in this sample
//Type objType = Type.GetType("System.Object");
//ConstructorInfo objCtor = objType.GetConstructor(Type.EmptyTypes);
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Call, objCtor); // calling the Object's constructor
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_1);
//ilgen.Emit(OpCodes.Call, mSetFirstNameBuilder); // setting the firstname field from the first argument (1)
//ilgen.Emit(OpCodes.Ldarg_0);
//ilgen.Emit(OpCodes.Ldarg_2);
//ilgen.Emit(OpCodes.Call, mSetLastNameBuilder); // setting the lastname field from the second argument (2)
//ilgen.Emit(OpCodes.Ret);
// Finally, create the type and save the assembly
classBuilder.CreateType();
asmBuilder.Save(asmFileName);
string toFile = Path.Combine(moveToDir, asmFileName);
if (File.Exists(toFile))
File.Delete(toFile);
File.Move(asmFileName, toFile);
string a = "";
}
}
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public struct LoadUnloadStructure
{
public ScriptStructure Script;
public LUType Action;
public bool PostOnRez;
public int StartParam;
public enum LUType
{
Unknown = 0,
Load = 1,
Unload = 2
}
}
}

View File

@@ -27,18 +27,29 @@
using System;
using System.Collections.Generic;
using System.Text;
using OpenSim.ApplicationPlugins.ScriptEngine.Components;
using OpenMetaverse;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public class Scheduler: SchedulerBase
public class Scheduler : IScriptScheduler
{
public override void Start()
private ScriptManager m_ScriptManager = new ScriptManager();
public void AddScript(ScriptStructure scriptStructure)
{
m_ScriptManager.AddScript(scriptStructure);
}
public override void Close()
public void Removecript(uint id, UUID itemID)
{
m_ScriptManager.RemoveScript(id, itemID);
}
public void Close()
{
m_ScriptManager.Close();
}
}
}

View File

@@ -0,0 +1,216 @@
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenSim.ScriptEngine.Shared;
using IScript=OpenSim.Region.ScriptEngine.Shared.ScriptBase.IScript;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public class ScriptLoader : IScriptLoader
{
//
// This class does AppDomain handling and loading/unloading of
// scripts in it. It is instanced in "ScriptEngine" and controlled
// from "ScriptManager"
//
// 1. Create a new AppDomain if old one is full (or doesn't exist)
// 2. Load scripts into AppDomain
// 3. Unload scripts from AppDomain (stopping them and marking
// them as inactive)
// 4. Unload AppDomain completely when all scripts in it has stopped
//
public string Name { get { return "SECS.DotNetEngine.Scheduler.ScriptLoader"; } }
private int maxScriptsPerAppDomain = 10;
// Internal list of all AppDomains
private List<AppDomainStructure> appDomains =
new List<AppDomainStructure>();
private Dictionary<string, AppDomainStructure> AppDomainFiles = new Dictionary<string, AppDomainStructure>();
public readonly string[] AssembliesInAppDomain = new string[] { "OpenSim.ScriptEngine.Shared.Script.dll", "OpenSim.Region.ScriptEngine.Shared.dll" };
internal static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Structure to keep track of data around AppDomain
private class AppDomainStructure
{
public AppDomain CurrentAppDomain; // The AppDomain itself
public int ScriptsLoaded; // Number of scripts loaded into AppDomain
public int ScriptsWaitingUnload; // Number of dead scripts
}
// Current AppDomain
private AppDomainStructure currentAD;
private object getLock = new object(); // Mutex
private object freeLock = new object(); // Mutex
// Find a free AppDomain, creating one if necessary
private AppDomainStructure GetFreeAppDomain()
{
lock (getLock)
{
// Current full?
if (currentAD != null &&
currentAD.ScriptsLoaded >= maxScriptsPerAppDomain)
{
// Add it to AppDomains list and empty current
appDomains.Add(currentAD);
currentAD = null;
}
// No current
if (currentAD == null)
{
// Create a new current AppDomain
currentAD = new AppDomainStructure();
currentAD.CurrentAppDomain = PrepareNewAppDomain();
}
return currentAD;
}
}
private int AppDomainNameCount;
public ScriptAssemblies.IScript LoadScript(ScriptStructure script)
{
// Find next available AppDomain to put it in
AppDomainStructure FreeAppDomain;
// If we already have loaded file, then reuse that AppDomains
if (AppDomainFiles.ContainsKey(script.AssemblyFileName))
FreeAppDomain = AppDomainFiles[script.AssemblyFileName];
else
FreeAppDomain = GetFreeAppDomain();
// Set script object AppDomain
script.AppDomain = FreeAppDomain.CurrentAppDomain;
// Create instance of script
ScriptAssemblies.IScript mbrt = (ScriptAssemblies.IScript)
FreeAppDomain.CurrentAppDomain.CreateInstanceFromAndUnwrap(
script.AssemblyFileName, "ScriptAssemblies.Script");
//, true, BindingFlags.CreateInstance, null);
FreeAppDomain.ScriptsLoaded++;
return mbrt;
}
// Create and prepare a new AppDomain for scripts
private AppDomain PrepareNewAppDomain()
{
// Create and prepare a new AppDomain
AppDomainNameCount++;
// TODO: Currently security match current appdomain
// Construct and initialize settings for a second AppDomain.
AppDomainSetup ads = new AppDomainSetup();
ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
ads.DisallowBindingRedirects = true;
ads.DisallowCodeDownload = true;
ads.LoaderOptimization = LoaderOptimization.MultiDomainHost;
ads.ShadowCopyFiles = "false"; // Disable shadowing
ads.ConfigurationFile =
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
AppDomain AD = AppDomain.CreateDomain("ScriptAppDomain_" +
AppDomainNameCount, null, ads);
foreach (string file in AssembliesInAppDomain)
{
m_log.InfoFormat("[{0}] AppDomain Loading: \"{1}\"->\"{2}\".", Name, file,
AssemblyName.GetAssemblyName(file).ToString());
AD.Load(AssemblyName.GetAssemblyName(file));
}
// Return the new AppDomain
return AD;
}
// Unload appdomains that are full and have only dead scripts
private void UnloadAppDomains()
{
lock (freeLock)
{
// Go through all
foreach (AppDomainStructure ads in new ArrayList(appDomains))
{
// Don't process current AppDomain
if (ads.CurrentAppDomain != currentAD.CurrentAppDomain)
{
// Not current AppDomain
// Is number of unloaded bigger or equal to number of loaded?
if (ads.ScriptsLoaded <= ads.ScriptsWaitingUnload)
{
// Remove from internal list
appDomains.Remove(ads);
// Unload
AppDomain.Unload(ads.CurrentAppDomain);
}
}
}
}
}
// Increase "dead script" counter for an AppDomain
public void StopScript(AppDomain ad)
{
lock (freeLock)
{
// Check if it is current AppDomain
if (currentAD.CurrentAppDomain == ad)
{
// Yes - increase
currentAD.ScriptsWaitingUnload++;
return;
}
// Lopp through all AppDomains
foreach (AppDomainStructure ads in new ArrayList(appDomains))
{
if (ads.CurrentAppDomain == ad)
{
// Found it
ads.ScriptsWaitingUnload++;
break;
}
}
}
UnloadAppDomains(); // Outsite lock, has its own GetLock
}
}
}

View File

@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.ScriptEngine.Shared;
using EventParams=OpenSim.ScriptEngine.Shared.EventParams;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public partial class ScriptManager: IScriptExecutor
{
private const int NoWorkSleepMs = 50;
private const int NoWorkSleepMsInc = 1; // How much time to increase wait with on every iteration
private const int NoWorkSleepMsIncMax = 300; // Max time to wait
internal static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "SECS.DotNetEngine.ScriptManager"; } }
private static Thread ScriptLoadUnloadThread;
public Dictionary<uint, Dictionary<UUID, ScriptStructure>> Scripts = new Dictionary<uint, Dictionary<UUID, ScriptStructure>>();
private RegionInfoStructure CurrentRegion;
public void Initialize(RegionInfoStructure currentRegion)
{
CurrentRegion = currentRegion;
}
public ScriptManager()
{
ScriptLoadUnloadThread = new Thread(LoadUnloadLoop);
ScriptLoadUnloadThread.Name = "ScriptLoadUnloadThread";
ScriptLoadUnloadThread.IsBackground = true;
ScriptLoadUnloadThread.Start();
}
public void Close() { }
private void LoadUnloadLoop ()
{
int _NoWorkSleepMsInc = 0;
while (true)
{
if (DoScriptLoadUnload())
{
// We found work, reset counter
_NoWorkSleepMsInc = NoWorkSleepMs;
} else
{
// We didn't find work
// Sleep
Thread.Sleep(NoWorkSleepMs + NoWorkSleepMsInc);
// Increase sleep delay
_NoWorkSleepMsInc += NoWorkSleepMsInc;
// Make sure we don't exceed max
if (_NoWorkSleepMsInc > NoWorkSleepMsIncMax)
_NoWorkSleepMsInc = NoWorkSleepMsIncMax;
}
}
}
#region Add/Remove/Find script functions for our Script memory structure
private void MemAddScript(ScriptStructure script)
{
lock (scriptLock)
{
// Create object if it doesn't exist
if (!Scripts.ContainsKey(script.LocalID))
Scripts.Add(script.LocalID, new Dictionary<UUID, ScriptStructure>());
// Delete script if it exists
Dictionary<UUID, ScriptStructure> Obj;
if (Scripts.TryGetValue(script.LocalID, out Obj))
if (Obj.ContainsKey(script.ItemID) == true)
Obj.Remove(script.ItemID);
// Add to object
Obj.Add(script.ItemID, script);
}
}
private void MemRemoveScript(uint LocalID, UUID ItemID)
{
// TODO: Also clean up command queue and async commands for object
lock (scriptLock)
{
// Create object if it doesn't exist
if (!Scripts.ContainsKey(LocalID))
return;
// Delete script if it exists
Dictionary<UUID, ScriptStructure> Obj;
if (Scripts.TryGetValue(LocalID, out Obj))
if (Obj.ContainsKey(ItemID) == true)
Obj.Remove(ItemID);
// Empty?
if (Obj.Count == 0)
Scripts.Remove(LocalID);
}
}
public bool TryGetScript(uint localID, UUID itemID, ref ScriptStructure script)
{
lock (scriptLock)
{
if (Scripts.ContainsKey(localID) == false)
return false;
Dictionary<UUID, ScriptStructure> Obj;
if (Scripts.TryGetValue(localID, out Obj))
if (Obj.ContainsKey(itemID) == false)
return false;
// Get script
return Obj.TryGetValue(itemID, out script);
}
}
public ScriptStructure GetScript(uint localID, UUID itemID)
{
lock (scriptLock)
{
if (Scripts.ContainsKey(localID) == false)
throw new Exception("No script with LocalID " + localID + " was found.");
Dictionary<UUID, ScriptStructure> Obj;
if (Scripts.TryGetValue(localID, out Obj))
if (Obj.ContainsKey(itemID) == false)
throw new Exception("No script with ItemID " + itemID + " was found.");
// Get script
return Obj[itemID];
}
}
public bool TryGetScripts(uint localID, ref Dictionary<UUID, ScriptStructure> returnList)
{
Dictionary<UUID, ScriptStructure> getList = GetScripts(localID);
if (getList != null)
{
returnList = getList;
return true;
}
return false;
}
public Dictionary<UUID, ScriptStructure> GetScripts(uint localID)
{
lock (scriptLock)
{
if (Scripts.ContainsKey(localID) == false)
return null;
return Scripts[localID];
}
}
#endregion
public void ExecuteCommand(EventParams p)
{
ScriptStructure ss = new ScriptStructure();
if (TryGetScript(p.LocalID, p.ItemID, ref ss))
ExecuteCommand(ref ss, p);
}
public void ExecuteCommand(ref ScriptStructure scriptContainer, EventParams p)
{
m_log.DebugFormat("[{0}] ######################################################", Name);
m_log.DebugFormat("[{0}] Command execution ItemID {1}: \"{2}\".", Name, scriptContainer.ItemID, p.EventName);
scriptContainer.ExecuteEvent(p);
m_log.DebugFormat("[{0}] ######################################################", Name);
}
}
}

View File

@@ -0,0 +1,259 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Environment.Scenes;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.ScriptEngine.Shared;
namespace OpenSim.ScriptEngine.Components.DotNetEngine.Scheduler
{
public partial class ScriptManager
{
private Queue<LoadUnloadStructure> LUQueue = new Queue<LoadUnloadStructure>();
private int LoadUnloadMaxQueueSize = 500;
private Object scriptLock = new Object();
//private Dictionary<InstanceData, DetectParams[]> detparms = new Dictionary<InstanceData, DetectParams[]>();
// Load/Unload structure
public void AddScript(ScriptStructure script)
{
lock (LUQueue)
{
if ((LUQueue.Count >= LoadUnloadMaxQueueSize))
{
m_log.ErrorFormat("[{0}] ERROR: Load queue count is at {1} of max {2}. Ignoring load request for script LocalID: {3}, ItemID: {4}.",
Name, LUQueue.Count, LoadUnloadMaxQueueSize, script.LocalID, script.ItemID);
return;
}
LoadUnloadStructure ls = new LoadUnloadStructure();
ls.Script = script;
ls.Action = LoadUnloadStructure.LUType.Load;
LUQueue.Enqueue(ls);
}
}
public void RemoveScript(uint localID, UUID itemID)
{
LoadUnloadStructure ls = new LoadUnloadStructure();
// See if we can find script
if (!TryGetScript(localID, itemID, ref ls.Script))
{
// Set manually
ls.Script.LocalID = localID;
ls.Script.ItemID = itemID;
}
ls.Script.StartParam = 0;
ls.Action = LoadUnloadStructure.LUType.Unload;
ls.PostOnRez = false;
lock (LUQueue)
{
LUQueue.Enqueue(ls);
}
}
internal bool DoScriptLoadUnload()
{
bool ret = false;
// if (!m_started)
// return;
lock (LUQueue)
{
if (LUQueue.Count > 0)
{
LoadUnloadStructure item = LUQueue.Dequeue();
ret = true;
if (item.Action == LoadUnloadStructure.LUType.Unload)
{
m_log.DebugFormat("[{0}] Unloading script", Name);
_StopScript(item.Script.LocalID, item.Script.ItemID);
RemoveScript(item.Script.LocalID, item.Script.ItemID);
}
else if (item.Action == LoadUnloadStructure.LUType.Load)
{
m_log.DebugFormat("[{0}] Loading script", Name);
_StartScript(item);
}
}
}
return ret;
}
//public void _StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez)
private void _StartScript(LoadUnloadStructure ScriptObject)
{
m_log.DebugFormat(
"[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}",
Name, ScriptObject.Script.LocalID, ScriptObject.Script.ItemID);
// We will initialize and start the script.
// It will be up to the script itself to hook up the correct events.
SceneObjectPart m_host = ScriptObject.Script.RegionInfo.Scene.GetSceneObjectPart(ScriptObject.Script.LocalID);
if (null == m_host)
{
m_log.ErrorFormat(
"[{0}]: Could not find scene object part corresponding " +
"to localID {1} to start script",
Name, ScriptObject.Script.LocalID);
return;
}
UUID assetID = UUID.Zero;
TaskInventoryItem taskInventoryItem = new TaskInventoryItem();
if (m_host.TaskInventory.TryGetValue(ScriptObject.Script.ItemID, out taskInventoryItem))
assetID = taskInventoryItem.AssetID;
ScenePresence presence =
ScriptObject.Script.RegionInfo.Scene.GetScenePresence(taskInventoryItem.OwnerID);
CultureInfo USCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = USCulture;
try
{
//
// Compile script to an assembly
//
//TODO: DEBUG
BaseClassFactory.MakeBaseClass(ScriptObject.Script);
m_log.DebugFormat("[{0}] Compiling script {1}", Name, ScriptObject.Script.Name);
string fileName = "";
try
{
IScriptCompiler compiler =
ScriptObject.Script.RegionInfo.FindCompiler(ScriptObject.Script.ScriptMetaData);
RegionInfoStructure currentRegionInfo = ScriptObject.Script.RegionInfo;
fileName = compiler.Compile(ScriptObject.Script.ScriptMetaData,
ref ScriptObject.Script.Source);
ScriptObject.Script.AssemblyFileName = fileName;
}
catch (Exception e)
{
m_log.ErrorFormat("[{0}] Internal error while compiling \"{1}\": {2}", Name, ScriptObject.Script.Name, e.ToString());
}
m_log.DebugFormat("[{0}] Compiled \"{1}\" to assembly: \"{2}\".", Name, ScriptObject.Script.Name, fileName);
// Add it to our script memstruct
MemAddScript(ScriptObject.Script);
ScriptAssemblies.IScript CompiledScript;
CompiledScript = CurrentRegion.ScriptLoader.LoadScript(ScriptObject.Script);
ScriptObject.Script.State = "default";
ScriptObject.Script.ScriptObject = CompiledScript;
ScriptObject.Script.Disabled = false;
ScriptObject.Script.Running = true;
//id.LineMap = LSLCompiler.LineMap();
//id.Script = CompiledScript;
//id.Source = item.Script.Script;
//item.StartParam = startParam;
// TODO: Fire the first start-event
//int eventFlags =
// m_scriptEngine.m_ScriptManager.GetStateEventFlags(
// localID, itemID);
//m_host.SetScriptEvents(itemID, eventFlags);
ScriptObject.Script.RegionInfo.Executors_Execute(ScriptObject.Script,
new EventParams(ScriptObject.Script.LocalID, ScriptObject.Script.ItemID, "state_entry", new object[] { }, new Region.ScriptEngine.Shared.DetectParams[0])
);
if (ScriptObject.PostOnRez)
{
ScriptObject.Script.RegionInfo.Executors_Execute(ScriptObject.Script,
new EventParams(ScriptObject.Script.LocalID, "on_rez", new object[]
{new Region.ScriptEngine.Shared.LSL_Types.LSLInteger(ScriptObject.StartParam)
}, new Region.ScriptEngine.Shared.DetectParams[0]));
}
}
catch (Exception e) // LEGIT: User Scripting
{
if (presence != null && (!ScriptObject.PostOnRez))
presence.ControllingClient.SendAgentAlertMessage(
"Script saved with errors, check debug window!",
false);
try
{
// DISPLAY ERROR INWORLD
string text = "Error compiling script:\n" +
e.Message.ToString();
if (text.Length > 1100)
text = text.Substring(0, 1099);
ScriptObject.Script.RegionInfo.Scene.SimChat(Utils.StringToBytes(text),
ChatTypeEnum.DebugChannel, 2147483647,
m_host.AbsolutePosition, m_host.Name, m_host.UUID,
false);
}
catch (Exception e2) // LEGIT: User Scripting
{
m_log.Error("[" +
Name +
"]: Error displaying error in-world: " +
e2.ToString());
m_log.Error("[" +
Name + "]: " +
"Errormessage: Error compiling script:\r\n" +
e2.Message.ToString());
}
}
}
public void _StopScript(uint localID, UUID itemID)
{
ScriptStructure ss = new ScriptStructure();
if (!TryGetScript(localID, itemID, ref ss))
return;
// Stop long command on script
//AsyncCommandManager.RemoveScript(ss);
try
{
// Get AppDomain
// Tell script not to accept new requests
ss.Running = false;
ss.Disabled = true;
AppDomain ad = ss.AppDomain;
// Remove from internal structure
MemRemoveScript(localID, itemID);
// TODO: Tell AppDomain that we have stopped script
}
catch (Exception e) // LEGIT: User Scripting
{
m_log.Error("[" +
Name +
"]: Exception stopping script localID: " +
localID + " LLUID: " + itemID.ToString() +
": " + e.ToString());
}
}
}
}