1
0

TaskInventoryDictionary.cs 14 KB

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