TaskInventoryDictionary.cs 14 KB

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