PacketPool.cs 9.8 KB

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