PacketPool.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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.Reflection;
  30. using OpenMetaverse;
  31. using OpenMetaverse.Packets;
  32. using log4net;
  33. using OpenSim.Framework.Monitoring;
  34. namespace OpenSim.Region.ClientStack.LindenUDP
  35. {
  36. public sealed class PacketPool
  37. {
  38. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. private static readonly PacketPool instance = new PacketPool();
  40. /// <summary>
  41. /// Pool of packets available for reuse.
  42. /// </summary>
  43. private readonly Dictionary<PacketType, Stack<Packet>> pool = new Dictionary<PacketType, Stack<Packet>>();
  44. private static Dictionary<Type, Stack<Object>> DataBlocks = new Dictionary<Type, Stack<Object>>();
  45. public static PacketPool Instance
  46. {
  47. get { return instance; }
  48. }
  49. public bool RecyclePackets { get; set; }
  50. /// <summary>
  51. /// The number of packets pooled
  52. /// </summary>
  53. public int PacketsPooled
  54. {
  55. get
  56. {
  57. lock (pool)
  58. return pool.Count;
  59. }
  60. }
  61. /// <summary>
  62. /// The number of blocks pooled.
  63. /// </summary>
  64. public int BlocksPooled
  65. {
  66. get
  67. {
  68. lock (DataBlocks)
  69. return DataBlocks.Count;
  70. }
  71. }
  72. /// <summary>
  73. /// Number of packets requested.
  74. /// </summary>
  75. public long PacketsRequested { get; private set; }
  76. /// <summary>
  77. /// Number of packets reused.
  78. /// </summary>
  79. public long PacketsReused { get; private set; }
  80. /// <summary>
  81. /// Number of packet blocks requested.
  82. /// </summary>
  83. public long BlocksRequested { get; private set; }
  84. /// <summary>
  85. /// Number of packet blocks reused.
  86. /// </summary>
  87. public long BlocksReused { get; private set; }
  88. private PacketPool()
  89. {
  90. // defaults
  91. RecyclePackets = true;
  92. //RecyclePackets = false;
  93. }
  94. /// <summary>
  95. /// Gets a packet of the given type.
  96. /// </summary>
  97. /// <param name='type'></param>
  98. /// <returns>Guaranteed to always return a packet, whether from the pool or newly constructed.</returns>
  99. public Packet GetPacket(PacketType type)
  100. {
  101. PacketsRequested++;
  102. Packet packet;
  103. if (!RecyclePackets)
  104. return Packet.BuildPacket(type);
  105. lock (pool)
  106. {
  107. if (!pool.ContainsKey(type) || pool[type] == null || (pool[type]).Count == 0)
  108. {
  109. // m_log.DebugFormat("[PACKETPOOL]: Building {0} packet", type);
  110. // Creating a new packet if we cannot reuse an old package
  111. packet = Packet.BuildPacket(type);
  112. }
  113. else
  114. {
  115. // m_log.DebugFormat("[PACKETPOOL]: Pulling {0} packet", type);
  116. // Recycle old packages
  117. PacketsReused++;
  118. packet = pool[type].Pop();
  119. }
  120. }
  121. return packet;
  122. }
  123. private static PacketType GetType(byte[] bytes)
  124. {
  125. ushort id;
  126. PacketFrequency freq;
  127. bool isZeroCoded = (bytes[0] & Helpers.MSG_ZEROCODED) != 0;
  128. if (bytes[6] == 0xFF)
  129. {
  130. if (bytes[7] == 0xFF)
  131. {
  132. freq = PacketFrequency.Low;
  133. if (isZeroCoded && bytes[8] == 0)
  134. id = bytes[10];
  135. else
  136. id = (ushort)((bytes[8] << 8) + bytes[9]);
  137. }
  138. else
  139. {
  140. freq = PacketFrequency.Medium;
  141. id = bytes[7];
  142. }
  143. }
  144. else
  145. {
  146. freq = PacketFrequency.High;
  147. id = bytes[6];
  148. }
  149. return Packet.GetType(id, freq);
  150. }
  151. public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer)
  152. {
  153. PacketType type = GetType(bytes);
  154. // Array.Clear(zeroBuffer, 0, zeroBuffer.Length);
  155. int i = 0;
  156. Packet packet = GetPacket(type);
  157. if (packet == null)
  158. m_log.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type);
  159. else
  160. packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer);
  161. return packet;
  162. }
  163. /// <summary>
  164. /// Return a packet to the packet pool
  165. /// </summary>
  166. /// <param name="packet"></param>
  167. public void ReturnPacket(Packet packet)
  168. {
  169. if (!RecyclePackets)
  170. return;
  171. bool trypool = false;
  172. PacketType type = packet.Type;
  173. switch (type)
  174. {
  175. case PacketType.ObjectUpdate:
  176. ObjectUpdatePacket oup = (ObjectUpdatePacket)packet;
  177. oup.ObjectData = null;
  178. trypool = true;
  179. break;
  180. case PacketType.ImprovedTerseObjectUpdate:
  181. ImprovedTerseObjectUpdatePacket itoup = (ImprovedTerseObjectUpdatePacket)packet;
  182. itoup.ObjectData = null;
  183. trypool = true;
  184. break;
  185. case PacketType.PacketAck:
  186. PacketAckPacket ackup = (PacketAckPacket)packet;
  187. ackup.Packets = null;
  188. trypool = true;
  189. break;
  190. case PacketType.AgentUpdate:
  191. trypool = true;
  192. break;
  193. default:
  194. return;
  195. }
  196. if(!trypool)
  197. return;
  198. lock (pool)
  199. {
  200. if (!pool.ContainsKey(type))
  201. {
  202. pool[type] = new Stack<Packet>();
  203. }
  204. if ((pool[type]).Count < 50)
  205. {
  206. // m_log.DebugFormat("[PACKETPOOL]: Pushing {0} packet", type);
  207. pool[type].Push(packet);
  208. }
  209. }
  210. }
  211. public T GetDataBlock<T>() where T: new()
  212. {
  213. lock (DataBlocks)
  214. {
  215. BlocksRequested++;
  216. Stack<Object> s;
  217. if (DataBlocks.TryGetValue(typeof(T), out s))
  218. {
  219. if (s.Count > 0)
  220. {
  221. BlocksReused++;
  222. return (T)s.Pop();
  223. }
  224. }
  225. else
  226. {
  227. DataBlocks[typeof(T)] = new Stack<Object>();
  228. }
  229. return new T();
  230. }
  231. }
  232. public void ReturnDataBlock<T>(T block) where T: new()
  233. {
  234. if (block == null)
  235. return;
  236. lock (DataBlocks)
  237. {
  238. if (!DataBlocks.ContainsKey(typeof(T)))
  239. DataBlocks[typeof(T)] = new Stack<Object>();
  240. if (DataBlocks[typeof(T)].Count < 50)
  241. DataBlocks[typeof(T)].Push(block);
  242. }
  243. }
  244. }
  245. }