PacketPool.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. }
  93. /// <summary>
  94. /// Gets a packet of the given type.
  95. /// </summary>
  96. /// <param name='type'></param>
  97. /// <returns>Guaranteed to always return a packet, whether from the pool or newly constructed.</returns>
  98. public Packet GetPacket(PacketType type)
  99. {
  100. PacketsRequested++;
  101. Packet packet;
  102. if (!RecyclePackets)
  103. return Packet.BuildPacket(type);
  104. lock (pool)
  105. {
  106. if (!pool.ContainsKey(type) || pool[type] == null || (pool[type]).Count == 0)
  107. {
  108. // m_log.DebugFormat("[PACKETPOOL]: Building {0} packet", type);
  109. // Creating a new packet if we cannot reuse an old package
  110. packet = Packet.BuildPacket(type);
  111. }
  112. else
  113. {
  114. // m_log.DebugFormat("[PACKETPOOL]: Pulling {0} packet", type);
  115. // Recycle old packages
  116. PacketsReused++;
  117. packet = pool[type].Pop();
  118. }
  119. }
  120. return packet;
  121. }
  122. private static PacketType GetType(byte[] bytes)
  123. {
  124. ushort id;
  125. PacketFrequency freq;
  126. bool isZeroCoded = (bytes[0] & Helpers.MSG_ZEROCODED) != 0;
  127. if (bytes[6] == 0xFF)
  128. {
  129. if (bytes[7] == 0xFF)
  130. {
  131. freq = PacketFrequency.Low;
  132. if (isZeroCoded && bytes[8] == 0)
  133. id = bytes[10];
  134. else
  135. id = (ushort)((bytes[8] << 8) + bytes[9]);
  136. }
  137. else
  138. {
  139. freq = PacketFrequency.Medium;
  140. id = bytes[7];
  141. }
  142. }
  143. else
  144. {
  145. freq = PacketFrequency.High;
  146. id = bytes[6];
  147. }
  148. return Packet.GetType(id, freq);
  149. }
  150. public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer)
  151. {
  152. PacketType type = GetType(bytes);
  153. // Array.Clear(zeroBuffer, 0, zeroBuffer.Length);
  154. int i = 0;
  155. Packet packet = GetPacket(type);
  156. if (packet == null)
  157. m_log.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type);
  158. else
  159. packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer);
  160. return packet;
  161. }
  162. /// <summary>
  163. /// Return a packet to the packet pool
  164. /// </summary>
  165. /// <param name="packet"></param>
  166. public void ReturnPacket(Packet packet)
  167. {
  168. if (!RecyclePackets)
  169. return;
  170. bool trypool = false;
  171. PacketType type = packet.Type;
  172. switch (type)
  173. {
  174. case PacketType.ObjectUpdate:
  175. ObjectUpdatePacket oup = (ObjectUpdatePacket)packet;
  176. oup.ObjectData = null;
  177. trypool = true;
  178. break;
  179. case PacketType.ImprovedTerseObjectUpdate:
  180. ImprovedTerseObjectUpdatePacket itoup = (ImprovedTerseObjectUpdatePacket)packet;
  181. itoup.ObjectData = null;
  182. trypool = true;
  183. break;
  184. case PacketType.PacketAck:
  185. PacketAckPacket ackup = (PacketAckPacket)packet;
  186. ackup.Packets = null;
  187. trypool = true;
  188. break;
  189. case PacketType.AgentUpdate:
  190. trypool = true;
  191. break;
  192. default:
  193. return;
  194. }
  195. if(!trypool)
  196. return;
  197. lock (pool)
  198. {
  199. if (!pool.ContainsKey(type))
  200. {
  201. pool[type] = new Stack<Packet>();
  202. }
  203. if ((pool[type]).Count < 50)
  204. {
  205. // m_log.DebugFormat("[PACKETPOOL]: Pushing {0} packet", type);
  206. pool[type].Push(packet);
  207. }
  208. }
  209. }
  210. public T GetDataBlock<T>() where T: new()
  211. {
  212. lock (DataBlocks)
  213. {
  214. BlocksRequested++;
  215. Stack<Object> s;
  216. if (DataBlocks.TryGetValue(typeof(T), out s))
  217. {
  218. if (s.Count > 0)
  219. {
  220. BlocksReused++;
  221. return (T)s.Pop();
  222. }
  223. }
  224. else
  225. {
  226. DataBlocks[typeof(T)] = new Stack<Object>();
  227. }
  228. return new T();
  229. }
  230. }
  231. public void ReturnDataBlock<T>(T block) where T: new()
  232. {
  233. if (block == null)
  234. return;
  235. lock (DataBlocks)
  236. {
  237. if (!DataBlocks.ContainsKey(typeof(T)))
  238. DataBlocks[typeof(T)] = new Stack<Object>();
  239. if (DataBlocks[typeof(T)].Count < 50)
  240. DataBlocks[typeof(T)].Push(block);
  241. }
  242. }
  243. }
  244. }