1
0

TaskInventoryDictionary.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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.Generic;
  29. using System.Threading;
  30. using System.Reflection;
  31. using System.Xml;
  32. using System.Diagnostics;
  33. using System.Xml.Schema;
  34. using System.Xml.Serialization;
  35. using log4net;
  36. using OpenMetaverse;
  37. namespace OpenSim.Framework
  38. {
  39. /// <summary>
  40. /// A dictionary containing task inventory items. Indexed by item UUID.
  41. /// </summary>
  42. /// <remarks>
  43. /// This class is not thread safe. Callers must synchronize on Dictionary methods or Clone() this object before
  44. /// iterating over it.
  45. /// </remarks>
  46. public class TaskInventoryDictionary : Dictionary<UUID, TaskInventoryItem>,
  47. ICloneable, IXmlSerializable
  48. {
  49. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. private static XmlSerializer tiiSerializer = new XmlSerializer(typeof (TaskInventoryItem));
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private Thread LockedByThread;
  53. // private string WriterStack;
  54. // private Dictionary<Thread, string> ReadLockers =
  55. // new Dictionary<Thread, string>();
  56. /// <value>
  57. /// An advanced lock for inventory data
  58. /// </value>
  59. private volatile System.Threading.ReaderWriterLockSlim m_itemLock = new System.Threading.ReaderWriterLockSlim();
  60. ~TaskInventoryDictionary()
  61. {
  62. m_itemLock.Dispose();
  63. m_itemLock = null;
  64. }
  65. /// <summary>
  66. /// Are we readlocked by the calling thread?
  67. /// </summary>
  68. public bool IsReadLockedByMe()
  69. {
  70. if (m_itemLock.RecursiveReadCount > 0)
  71. {
  72. return true;
  73. }
  74. else
  75. {
  76. return false;
  77. }
  78. }
  79. /// <summary>
  80. /// Lock our inventory list for reading (many can read, one can write)
  81. /// </summary>
  82. public void LockItemsForRead(bool locked)
  83. {
  84. if (locked)
  85. {
  86. if (m_itemLock.IsWriteLockHeld && LockedByThread != null)
  87. {
  88. if (!LockedByThread.IsAlive)
  89. {
  90. //Locked by dead thread, reset.
  91. m_itemLock = new System.Threading.ReaderWriterLockSlim();
  92. }
  93. }
  94. if (m_itemLock.RecursiveReadCount > 0)
  95. {
  96. m_log.Error("[TaskInventoryDictionary] Recursive read lock requested. This should not happen and means something needs to be fixed. For now though, it's safe to continue.");
  97. try
  98. {
  99. // That call stack is useful for end users only. RealProgrammers need a full dump. Commented.
  100. // StackTrace stackTrace = new StackTrace(); // get call stack
  101. // StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  102. //
  103. // // write call stack method names
  104. // foreach (StackFrame stackFrame in stackFrames)
  105. // {
  106. // m_log.Error("[SceneObjectGroup.m_parts] "+(stackFrame.GetMethod().Name)); // write method name
  107. // }
  108. // The below is far more useful
  109. // System.Console.WriteLine("------------------------------------------");
  110. // System.Console.WriteLine("My call stack:\n" + Environment.StackTrace);
  111. // System.Console.WriteLine("------------------------------------------");
  112. // foreach (KeyValuePair<Thread, string> kvp in ReadLockers)
  113. // {
  114. // System.Console.WriteLine("Locker name {0} call stack:\n" + kvp.Value, kvp.Key.Name);
  115. // System.Console.WriteLine("------------------------------------------");
  116. // }
  117. }
  118. catch
  119. {}
  120. m_itemLock.ExitReadLock();
  121. }
  122. if (m_itemLock.RecursiveWriteCount > 0)
  123. {
  124. m_log.Error("[TaskInventoryDictionary] Recursive write lock requested. This should not happen and means something needs to be fixed.");
  125. // try
  126. // {
  127. // System.Console.WriteLine("------------------------------------------");
  128. // System.Console.WriteLine("My call stack:\n" + Environment.StackTrace);
  129. // System.Console.WriteLine("------------------------------------------");
  130. // System.Console.WriteLine("Locker's call stack:\n" + WriterStack);
  131. // System.Console.WriteLine("------------------------------------------");
  132. // }
  133. // catch
  134. // {}
  135. m_itemLock.ExitWriteLock();
  136. }
  137. while (!m_itemLock.TryEnterReadLock(60000))
  138. {
  139. m_log.Error("Thread lock detected while trying to aquire READ lock in TaskInventoryDictionary. Locked by thread " + LockedByThread.Name + ". I'm going to try to solve the thread lock automatically to preserve region stability, but this needs to be fixed.");
  140. //if (m_itemLock.IsWriteLockHeld)
  141. //{
  142. m_itemLock = new System.Threading.ReaderWriterLockSlim();
  143. // System.Console.WriteLine("------------------------------------------");
  144. // System.Console.WriteLine("My call stack:\n" + Environment.StackTrace);
  145. // System.Console.WriteLine("------------------------------------------");
  146. // System.Console.WriteLine("Locker's call stack:\n" + WriterStack);
  147. // System.Console.WriteLine("------------------------------------------");
  148. // LockedByThread = null;
  149. // ReadLockers.Clear();
  150. //}
  151. }
  152. // ReadLockers[Thread.CurrentThread] = Environment.StackTrace;
  153. }
  154. else
  155. {
  156. if (m_itemLock.RecursiveReadCount>0)
  157. {
  158. m_itemLock.ExitReadLock();
  159. }
  160. // if (m_itemLock.RecursiveReadCount == 0)
  161. // ReadLockers.Remove(Thread.CurrentThread);
  162. }
  163. }
  164. /// <summary>
  165. /// Lock our inventory list for writing (many can read, one can write)
  166. /// </summary>
  167. public void LockItemsForWrite(bool locked)
  168. {
  169. if (locked)
  170. {
  171. //Enter a write lock, wait indefinately for one to open.
  172. if (m_itemLock.RecursiveReadCount > 0)
  173. {
  174. m_log.Error("[TaskInventoryDictionary] Recursive read lock requested. This should not happen and means something needs to be fixed. For now though, it's safe to continue.");
  175. m_itemLock.ExitReadLock();
  176. }
  177. if (m_itemLock.RecursiveWriteCount > 0)
  178. {
  179. m_log.Error("[TaskInventoryDictionary] Recursive write lock requested. This should not happen and means something needs to be fixed.");
  180. m_itemLock.ExitWriteLock();
  181. }
  182. while (!m_itemLock.TryEnterWriteLock(60000))
  183. {
  184. if (m_itemLock.IsWriteLockHeld)
  185. {
  186. m_log.Error("Thread lock detected while trying to aquire WRITE lock in TaskInventoryDictionary. Locked by thread " + LockedByThread.Name + ". I'm going to try to solve the thread lock automatically to preserve region stability, but this needs to be fixed.");
  187. // System.Console.WriteLine("------------------------------------------");
  188. // System.Console.WriteLine("My call stack:\n" + Environment.StackTrace);
  189. // System.Console.WriteLine("------------------------------------------");
  190. // System.Console.WriteLine("Locker's call stack:\n" + WriterStack);
  191. // System.Console.WriteLine("------------------------------------------");
  192. }
  193. else
  194. {
  195. m_log.Error("Thread lock detected while trying to aquire WRITE lock in TaskInventoryDictionary. Locked by a reader. I'm going to try to solve the thread lock automatically to preserve region stability, but this needs to be fixed.");
  196. // System.Console.WriteLine("------------------------------------------");
  197. // System.Console.WriteLine("My call stack:\n" + Environment.StackTrace);
  198. // System.Console.WriteLine("------------------------------------------");
  199. // foreach (KeyValuePair<Thread, string> kvp in ReadLockers)
  200. // {
  201. // System.Console.WriteLine("Locker name {0} call stack:\n" + kvp.Value, kvp.Key.Name);
  202. // System.Console.WriteLine("------------------------------------------");
  203. // }
  204. }
  205. m_itemLock = new System.Threading.ReaderWriterLockSlim();
  206. // ReadLockers.Clear();
  207. }
  208. LockedByThread = Thread.CurrentThread;
  209. // WriterStack = Environment.StackTrace;
  210. }
  211. else
  212. {
  213. if (m_itemLock.RecursiveWriteCount > 0)
  214. {
  215. m_itemLock.ExitWriteLock();
  216. }
  217. }
  218. }
  219. #region ICloneable Members
  220. public Object Clone()
  221. {
  222. TaskInventoryDictionary clone = new TaskInventoryDictionary();
  223. m_itemLock.EnterReadLock();
  224. foreach (UUID uuid in Keys)
  225. {
  226. clone.Add(uuid, (TaskInventoryItem) this[uuid].Clone());
  227. }
  228. m_itemLock.ExitReadLock();
  229. return clone;
  230. }
  231. #endregion
  232. // The alternative of simply serializing the list doesn't appear to work on mono, since
  233. // we get a
  234. //
  235. // System.TypeInitializationException: An exception was thrown by the type initializer for OpenSim.Framework.TaskInventoryDictionary ---> System.ArgumentOutOfRangeException: < 0
  236. // Parameter name: length
  237. // at System.String.Substring (Int32 startIndex, Int32 length) [0x00088] in /build/buildd/mono-1.2.4/mcs/class/corlib/System/String.cs:381
  238. // at System.Xml.Serialization.TypeTranslator.GetTypeData (System.Type runtimeType, System.String xmlDataType) [0x001f6] in /build/buildd/mono-1.2.4/mcs/class/System.XML/System.Xml.Serialization/TypeTranslator.cs:217
  239. // ...
  240. // private static XmlSerializer tiiSerializer
  241. // = new XmlSerializer(typeof(Dictionary<UUID, TaskInventoryItem>.ValueCollection));
  242. // see IXmlSerializable
  243. #region IXmlSerializable Members
  244. public XmlSchema GetSchema()
  245. {
  246. return null;
  247. }
  248. // see IXmlSerializable
  249. public void ReadXml(XmlReader reader)
  250. {
  251. // m_log.DebugFormat("[TASK INVENTORY]: ReadXml current node before actions, {0}", reader.Name);
  252. if (!reader.IsEmptyElement)
  253. {
  254. reader.Read();
  255. while (tiiSerializer.CanDeserialize(reader))
  256. {
  257. TaskInventoryItem item = (TaskInventoryItem) tiiSerializer.Deserialize(reader);
  258. Add(item.ItemID, item);
  259. //m_log.DebugFormat("[TASK INVENTORY]: Instanted prim item {0}, {1} from xml", item.Name, item.ItemID);
  260. }
  261. // m_log.DebugFormat("[TASK INVENTORY]: Instantiated {0} prim items in total from xml", Count);
  262. }
  263. // else
  264. // {
  265. // m_log.DebugFormat("[TASK INVENTORY]: Skipping empty element {0}", reader.Name);
  266. // }
  267. // For some .net implementations, this last read is necessary so that we advance beyond the end tag
  268. // of the element wrapping this object so that the rest of the serialization can complete normally.
  269. reader.Read();
  270. // m_log.DebugFormat("[TASK INVENTORY]: ReadXml current node after actions, {0}", reader.Name);
  271. }
  272. // see IXmlSerializable
  273. public void WriteXml(XmlWriter writer)
  274. {
  275. lock (this)
  276. {
  277. foreach (TaskInventoryItem item in Values)
  278. {
  279. tiiSerializer.Serialize(writer, item);
  280. }
  281. }
  282. //tiiSerializer.Serialize(writer, Values);
  283. }
  284. #endregion
  285. // see ICloneable
  286. }
  287. }