For scripts in attachments, don't save .state files apart from the initial one as these are ignored since .state is saved in the attachment's asset.

This eliminates pointless work and exceptions when an appdomain is unloaded whilst an attachment script state is persisted.
Adds test for this case.
Relates to http://opensimulator.org/mantis/view.php?id=7407
0.8.1-post-fixes
Justin Clark-Casey (justincc) 2015-01-16 22:44:54 +00:00
parent 97ac80d664
commit 8d724e90de
5 changed files with 220 additions and 15 deletions

View File

@ -97,6 +97,12 @@ namespace OpenSim.Region.ScriptEngine.Interfaces
/// </summary> /// </summary>
string State { get; set; } string State { get; set; }
/// <summary>
/// If true then the engine is responsible for persisted state. If false then some other component may
/// persist state (e.g. attachments persisting in assets).
/// </summary>
bool StatePersistedHere { get; }
/// <summary> /// <summary>
/// Time the script was last started /// Time the script was last started
/// </summary> /// </summary>

View File

@ -58,6 +58,8 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
{ {
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool StatePersistedHere { get { return m_AttachedAvatar == UUID.Zero; } }
/// <summary> /// <summary>
/// The current work item if an event for this script is running or waiting to run, /// The current work item if an event for this script is running or waiting to run,
/// </summary> /// </summary>
@ -76,7 +78,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
private string m_CurrentEvent = String.Empty; private string m_CurrentEvent = String.Empty;
private bool m_InSelfDelete; private bool m_InSelfDelete;
private int m_MaxScriptQueue; private int m_MaxScriptQueue;
private bool m_SaveState = true; private bool m_SaveState;
private int m_ControlEventsInQueue; private int m_ControlEventsInQueue;
private int m_LastControlLevel; private int m_LastControlLevel;
private bool m_CollisionInQueue; private bool m_CollisionInQueue;
@ -238,6 +240,12 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
m_postOnRez = postOnRez; m_postOnRez = postOnRez;
m_AttachedAvatar = Part.ParentGroup.AttachedAvatar; m_AttachedAvatar = Part.ParentGroup.AttachedAvatar;
m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID; m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID;
m_SaveState = StatePersistedHere;
// m_log.DebugFormat(
// "[SCRIPT INSTANCE]: Instantiated script instance {0} (id {1}) in part {2} (id {3}) in object {4} attached avatar {5} in {6}",
// ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, m_AttachedAvatar, Engine.World.Name);
} }
/// <summary> /// <summary>
@ -339,8 +347,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
return false; return false;
} }
m_SaveState = true; // For attachments, XEngine saves the state into a .state file when XEngine.SetXMLState() is called.
string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state"); string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state");
if (File.Exists(savedState)) if (File.Exists(savedState))
@ -389,6 +396,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
m_SaveState = false; m_SaveState = false;
m_startedFromSavedState = true; m_startedFromSavedState = true;
} }
// If this script is in an attachment then we no longer need the state file.
if (!StatePersistedHere)
RemoveState();
} }
// else // else
// { // {
@ -984,7 +995,9 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
(int)m_Script.GetStateEventFlags(State)); (int)m_Script.GetStateEventFlags(State));
if (running) if (running)
Start(); Start();
m_SaveState = true;
m_SaveState = StatePersistedHere;
PostEvent(new EventParams("state_entry", PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0])); new Object[0], new DetectParams[0]));
} }
@ -1010,7 +1023,7 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
if (m_CurrentEvent != "state_entry") if (m_CurrentEvent != "state_entry")
{ {
m_SaveState = true; m_SaveState = StatePersistedHere;
PostEvent(new EventParams("state_entry", PostEvent(new EventParams("state_entry",
new Object[0], new DetectParams[0])); new Object[0], new DetectParams[0]));
throw new EventAbortException(); throw new EventAbortException();
@ -1060,6 +1073,10 @@ namespace OpenSim.Region.ScriptEngine.Shared.Instance
return; return;
} }
// m_log.DebugFormat(
// "[SCRIPT INSTANCE]: Saving state for script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}",
// ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name);
PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID);
string xml = ScriptSerializer.Serialize(this); string xml = ScriptSerializer.Serialize(this);

View File

@ -0,0 +1,152 @@
/*
* 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 OpenSimulator 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.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.Attachments;
using OpenSim.Region.CoreModules.Framework.InventoryAccess;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.XEngine;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
namespace OpenSim.Region.ScriptEngine.Tests
{
[TestFixture]
public class XEnginePersistenceTests : OpenSimTestCase
{
private AutoResetEvent m_chatEvent = new AutoResetEvent(false);
private void OnChatFromWorld(object sender, OSChatMessage oscm)
{
// Console.WriteLine("Got chat [{0}]", oscm.Message);
// m_osChatMessageReceived = oscm;
m_chatEvent.Set();
}
private void AddCommonConfig(IConfigSource config, List<object> modules)
{
config.AddConfig("Modules");
config.Configs["Modules"].Set("InventoryAccessModule", "BasicInventoryAccessModule");
AttachmentsModule attMod = new AttachmentsModule();
attMod.DebugLevel = 1;
modules.Add(attMod);
modules.Add(new BasicInventoryAccessModule());
}
private void AddScriptingConfig(IConfigSource config, XEngine.XEngine xEngine, List<object> modules)
{
IConfig startupConfig = config.AddConfig("Startup");
startupConfig.Set("DefaultScriptEngine", "XEngine");
IConfig xEngineConfig = config.AddConfig("XEngine");
xEngineConfig.Set("Enabled", "true");
xEngineConfig.Set("StartDelay", "0");
// These tests will not run with AppDomainLoading = true, at least on mono. For unknown reasons, the call
// to AssemblyResolver.OnAssemblyResolve fails.
xEngineConfig.Set("AppDomainLoading", "false");
modules.Add(xEngine);
}
private Scene CreateScriptingEnabledTestScene(XEngine.XEngine xEngine)
{
IConfigSource config = new IniConfigSource();
List<object> modules = new List<object>();
AddCommonConfig(config, modules);
AddScriptingConfig(config, xEngine, modules);
Scene scene
= new SceneHelpers().SetupScene(
"attachments-test-scene", TestHelpers.ParseTail(999), 1000, 1000, config);
SceneHelpers.SetupSceneModules(scene, config, modules.ToArray());
scene.StartScripts();
return scene;
}
[Test]
public void TestScriptedAttachmentPersistence()
{
TestHelpers.InMethod();
// TestHelpers.EnableLogging();
XEngine.XEngine xEngine = new XEngine.XEngine();
Scene scene = CreateScriptingEnabledTestScene(xEngine);
UserAccount ua1 = UserAccountHelpers.CreateUserWithInventory(scene, 0x1);
ScenePresence sp = SceneHelpers.AddScenePresence(scene, ua1);
SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, sp.UUID, "att-name", 0x10);
TaskInventoryHelpers.AddScript(
scene,
so.RootPart,
"scriptItem",
"default { attach(key id) { if (id != NULL_KEY) { llSay(0, \"Hello World\"); } } }");
InventoryItemBase userItem = UserInventoryHelpers.AddInventoryItem(scene, so, 0x100, 0x1000);
// FIXME: Right now, we have to do a tricksy chat listen to make sure we know when the script is running.
// In the future, we need to be able to do this programatically more predicably.
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
SceneObjectGroup rezzedSo
= scene.AttachmentsModule.RezSingleAttachmentFromInventory(sp, userItem.ID, (uint)AttachmentPoint.Chest);
TaskInventoryItem rezzedScriptItem = rezzedSo.RootPart.Inventory.GetInventoryItem("scriptItem");
// Wait for chat to signal rezzed script has been started.
m_chatEvent.WaitOne(60000);
// Force save
xEngine.DoBackup(new Object[] { 0 });
// Console.WriteLine("ItemID {0}", rezzedScriptItem.ItemID);
//
// foreach (
// string s in Directory.EnumerateFileSystemEntries(
// string.Format("ScriptEngines/{0}", scene.RegionInfo.RegionID)))
// Console.WriteLine(s);
Assert.IsFalse(
File.Exists(
string.Format("ScriptEngines/{0}/{1}.state", scene.RegionInfo.RegionID, rezzedScriptItem.ItemID)));
scene.AttachmentsModule.DetachSingleAttachmentToInv(sp, rezzedSo);
}
}
}

View File

@ -718,7 +718,8 @@ namespace OpenSim.Region.ScriptEngine.XEngine
// //
try try
{ {
instance.SaveState(); if (instance.StatePersistedHere)
instance.SaveState();
} }
catch (Exception e) catch (Exception e)
{ {
@ -830,7 +831,16 @@ namespace OpenSim.Region.ScriptEngine.XEngine
lock (m_Scripts) lock (m_Scripts)
{ {
foreach (IScriptInstance instance in m_Scripts.Values) foreach (IScriptInstance instance in m_Scripts.Values)
instances.Add(instance); {
if (instance.StatePersistedHere)
{
// m_log.DebugFormat(
// "[XEngine]: Adding script {0}.{1}, item UUID {2}, prim UUID {3} in {4} for state persistence",
// instance.PrimName, instance.ScriptName, instance.ItemID, instance.ObjectID, World.Name);
instances.Add(instance);
}
}
} }
foreach (IScriptInstance i in instances) foreach (IScriptInstance i in instances)
@ -1457,7 +1467,9 @@ namespace OpenSim.Region.ScriptEngine.XEngine
} }
} }
instance.RemoveState(); if (instance.StatePersistedHere)
instance.RemoveState();
instance.DestroyScriptInstance(); instance.DestroyScriptInstance();
m_DomainScripts[instance.AppDomain].Remove(instance.ItemID); m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);

View File

@ -116,26 +116,44 @@ namespace OpenSim.Tests.Common
/// <returns>The item that was added</returns> /// <returns>The item that was added</returns>
public static TaskInventoryItem AddScript( public static TaskInventoryItem AddScript(
Scene scene, SceneObjectPart part, string scriptName, string scriptSource) Scene scene, SceneObjectPart part, string scriptName, string scriptSource)
{
return AddScript(scene, part, UUID.Random(), UUID.Random(), scriptName, scriptSource);
}
/// <summary>
/// Add a simple script to the given part.
/// </summary>
/// <remarks>
/// TODO: Accept input for item and asset IDs so that we have completely replicatable regression tests rather
/// than a random component.
/// </remarks>
/// <param name="scene"></param>
/// <param name="part"></param>
/// <param name="itemId">Item UUID for the script</param>
/// <param name="assetId">Asset UUID for the script</param>
/// <param name="scriptName">Name of the script to add</param>
/// <param name="scriptSource">LSL script source</param>
/// <returns>The item that was added</returns>
public static TaskInventoryItem AddScript(
Scene scene, SceneObjectPart part, UUID itemId, UUID assetId, string scriptName, string scriptSource)
{ {
AssetScriptText ast = new AssetScriptText(); AssetScriptText ast = new AssetScriptText();
ast.Source = scriptSource; ast.Source = scriptSource;
ast.Encode(); ast.Encode();
UUID assetUuid = UUID.Random();
UUID itemUuid = UUID.Random();
AssetBase asset AssetBase asset
= AssetHelpers.CreateAsset(assetUuid, AssetType.LSLText, ast.AssetData, UUID.Zero); = AssetHelpers.CreateAsset(assetId, AssetType.LSLText, ast.AssetData, UUID.Zero);
scene.AssetService.Store(asset); scene.AssetService.Store(asset);
TaskInventoryItem item TaskInventoryItem item
= new TaskInventoryItem = new TaskInventoryItem
{ Name = scriptName, AssetID = assetUuid, ItemID = itemUuid, { Name = scriptName, AssetID = assetId, ItemID = itemId,
Type = (int)AssetType.LSLText, InvType = (int)InventoryType.LSL }; Type = (int)AssetType.LSLText, InvType = (int)InventoryType.LSL };
part.Inventory.AddInventoryItem(item, true); part.Inventory.AddInventoryItem(item, true);
return item; return item;
} }
/// <summary> /// <summary>
/// Add a scene object item to the given part. /// Add a scene object item to the given part.
/// </summary> /// </summary>