1
0

PacketPool.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 static PacketType GetType(byte[] bytes)
  125. {
  126. ushort id;
  127. PacketFrequency freq;
  128. bool isZeroCoded = (bytes[0] & Helpers.MSG_ZEROCODED) != 0;
  129. if (bytes[6] == 0xFF)
  130. {
  131. if (bytes[7] == 0xFF)
  132. {
  133. freq = PacketFrequency.Low;
  134. if (isZeroCoded && bytes[8] == 0)
  135. id = bytes[10];
  136. else
  137. id = (ushort)((bytes[8] << 8) + bytes[9]);
  138. }
  139. else
  140. {
  141. freq = PacketFrequency.Medium;
  142. id = bytes[7];
  143. }
  144. }
  145. else
  146. {
  147. freq = PacketFrequency.High;
  148. id = bytes[6];
  149. }
  150. return Packet.GetType(id, freq);
  151. }
  152. public Packet GetPacket(byte[] bytes, ref int packetEnd, byte[] zeroBuffer)
  153. {
  154. PacketType type = GetType(bytes);
  155. // Array.Clear(zeroBuffer, 0, zeroBuffer.Length);
  156. int i = 0;
  157. Packet packet = GetPacket(type);
  158. if (packet == null)
  159. m_log.WarnFormat("[PACKETPOOL]: Failed to get packet of type {0}", type);
  160. else
  161. packet.FromBytes(bytes, ref i, ref packetEnd, zeroBuffer);
  162. return packet;
  163. }
  164. /// <summary>
  165. /// Return a packet to the packet pool
  166. /// </summary>
  167. /// <param name="packet"></param>
  168. public void ReturnPacket(Packet packet)
  169. {
  170. if (RecycleDataBlocks)
  171. {
  172. switch (packet.Type)
  173. {
  174. case PacketType.ObjectUpdate:
  175. ObjectUpdatePacket oup = (ObjectUpdatePacket)packet;
  176. foreach (ObjectUpdatePacket.ObjectDataBlock oupod in oup.ObjectData)
  177. ReturnDataBlock<ObjectUpdatePacket.ObjectDataBlock>(oupod);
  178. oup.ObjectData = null;
  179. break;
  180. case PacketType.ImprovedTerseObjectUpdate:
  181. ImprovedTerseObjectUpdatePacket itoup = (ImprovedTerseObjectUpdatePacket)packet;
  182. foreach (ImprovedTerseObjectUpdatePacket.ObjectDataBlock itoupod in itoup.ObjectData)
  183. ReturnDataBlock<ImprovedTerseObjectUpdatePacket.ObjectDataBlock>(itoupod);
  184. itoup.ObjectData = null;
  185. break;
  186. }
  187. }
  188. if (RecyclePackets)
  189. {
  190. switch (packet.Type)
  191. {
  192. // List pooling packets here
  193. case PacketType.AgentUpdate:
  194. case PacketType.PacketAck:
  195. case PacketType.ObjectUpdate:
  196. case PacketType.ImprovedTerseObjectUpdate:
  197. lock (pool)
  198. {
  199. PacketType type = packet.Type;
  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. break;
  211. // Other packets wont pool
  212. default:
  213. return;
  214. }
  215. }
  216. }
  217. public T GetDataBlock<T>() where T: new()
  218. {
  219. lock (DataBlocks)
  220. {
  221. BlocksRequested++;
  222. Stack<Object> s;
  223. if (DataBlocks.TryGetValue(typeof(T), out s))
  224. {
  225. if (s.Count > 0)
  226. {
  227. BlocksReused++;
  228. return (T)s.Pop();
  229. }
  230. }
  231. else
  232. {
  233. DataBlocks[typeof(T)] = new Stack<Object>();
  234. }
  235. return new T();
  236. }
  237. }
  238. public void ReturnDataBlock<T>(T block) where T: new()
  239. {
  240. if (block == null)
  241. return;
  242. lock (DataBlocks)
  243. {
  244. if (!DataBlocks.ContainsKey(typeof(T)))
  245. DataBlocks[typeof(T)] = new Stack<Object>();
  246. if (DataBlocks[typeof(T)].Count < 50)
  247. DataBlocks[typeof(T)].Push(block);
  248. }
  249. }
  250. }
  251. }