LLUDPClient.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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.Net;
  30. using System.Threading;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Monitoring;
  34. using OpenMetaverse;
  35. using OpenMetaverse.Packets;
  36. using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
  37. namespace OpenSim.Region.ClientStack.LindenUDP
  38. {
  39. #region Delegates
  40. /// <summary>
  41. /// Fired when updated networking stats are produced for this client
  42. /// </summary>
  43. /// <param name="inPackets">Number of incoming packets received since this
  44. /// event was last fired</param>
  45. /// <param name="outPackets">Number of outgoing packets sent since this
  46. /// event was last fired</param>
  47. /// <param name="unAckedBytes">Current total number of bytes in packets we
  48. /// are waiting on ACKs for</param>
  49. public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes);
  50. /// <summary>
  51. /// Fired when the queue for one or more packet categories is empty. This
  52. /// event can be hooked to put more data on the empty queues
  53. /// </summary>
  54. /// <param name="category">Categories of the packet queues that are empty</param>
  55. public delegate void QueueEmpty(ThrottleOutPacketTypeFlags categories);
  56. #endregion Delegates
  57. /// <summary>
  58. /// Tracks state for a client UDP connection and provides client-specific methods
  59. /// </summary>
  60. public sealed class LLUDPClient
  61. {
  62. // TODO: Make this a config setting
  63. /// <summary>Percentage of the task throttle category that is allocated to avatar and prim
  64. /// state updates</summary>
  65. const float STATE_TASK_PERCENTAGE = 0.8f;
  66. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  67. /// <summary>The number of packet categories to throttle on. If a throttle category is added
  68. /// or removed, this number must also change</summary>
  69. const int THROTTLE_CATEGORY_COUNT = 8;
  70. /// <summary>
  71. /// Controls whether information is logged about each outbound packet immediately before it is sent. For debug purposes.
  72. /// </summary>
  73. /// <remarks>Any level above 0 will turn on logging.</remarks>
  74. public int DebugDataOutLevel { get; set; }
  75. /// <summary>
  76. /// Controls whether information is logged about each outbound packet immediately before it is sent. For debug purposes.
  77. /// </summary>
  78. /// <remarks>Any level above 0 will turn on logging.</remarks>
  79. public int ThrottleDebugLevel
  80. {
  81. get
  82. {
  83. return m_throttleDebugLevel;
  84. }
  85. set
  86. {
  87. m_throttleDebugLevel = value;
  88. /*
  89. m_throttleClient.DebugLevel = m_throttleDebugLevel;
  90. foreach (TokenBucket tb in m_throttleCategories)
  91. tb.DebugLevel = m_throttleDebugLevel;
  92. */
  93. }
  94. }
  95. private int m_throttleDebugLevel;
  96. /// <summary>Fired when updated networking stats are produced for this client</summary>
  97. public event PacketStats OnPacketStats;
  98. /// <summary>Fired when the queue for a packet category is empty. This event can be
  99. /// hooked to put more data on the empty queue</summary>
  100. public event QueueEmpty OnQueueEmpty;
  101. public event Func<ThrottleOutPacketTypeFlags, bool> HasUpdates;
  102. /// <summary>AgentID for this client</summary>
  103. public readonly UUID AgentID;
  104. /// <summary>The remote address of the connected client</summary>
  105. public readonly IPEndPoint RemoteEndPoint;
  106. /// <summary>Circuit code that this client is connected on</summary>
  107. public readonly uint CircuitCode;
  108. /// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary>
  109. public IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(256);
  110. /// <summary>Packets we have sent that need to be ACKed by the client</summary>
  111. public UnackedPacketCollection NeedAcks = new UnackedPacketCollection();
  112. /// <summary>ACKs that are queued up, waiting to be sent to the client</summary>
  113. public DoubleLocklessQueue<uint> PendingAcks = new DoubleLocklessQueue<uint>();
  114. /// <summary>Current packet sequence number</summary>
  115. public int CurrentSequence;
  116. /// <summary>Current ping sequence number</summary>
  117. public byte CurrentPingSequence;
  118. /// <summary>True when this connection is alive, otherwise false</summary>
  119. public bool IsConnected = true;
  120. /// <summary>True when this connection is paused, otherwise false</summary>
  121. public bool IsPaused;
  122. /// <summary>Environment.TickCount when the last packet was received for this client</summary>
  123. public int TickLastPacketReceived;
  124. /// <summary>Smoothed round-trip time. A smoothed average of the round-trip time for sending a
  125. /// reliable packet to the client and receiving an ACK</summary>
  126. public float SRTT;
  127. /// <summary>Round-trip time variance. Measures the consistency of round-trip times</summary>
  128. public float RTTVAR;
  129. /// <summary>Retransmission timeout. Packets that have not been acknowledged in this number of
  130. /// milliseconds or longer will be resent</summary>
  131. /// <remarks>Calculated from <seealso cref="SRTT"/> and <seealso cref="RTTVAR"/> using the
  132. /// guidelines in RFC 2988</remarks>
  133. public int RTO;
  134. /// <summary>Number of bytes received since the last acknowledgement was sent out. This is used
  135. /// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2)</summary>
  136. public int BytesSinceLastACK;
  137. /// <summary>Number of packets received from this client</summary>
  138. public int PacketsReceived;
  139. /// <summary>Number of packets sent to this client</summary>
  140. public int PacketsSent;
  141. /// <summary>Number of packets resent to this client</summary>
  142. public int PacketsResent;
  143. /// <summary>Total byte count of unacked packets sent to this client</summary>
  144. public int UnackedBytes;
  145. private int m_packetsUnAckReported;
  146. /// <summary>Total number of received packets that we have reported to the OnPacketStats event(s)</summary>
  147. private int m_packetsReceivedReported;
  148. /// <summary>Total number of sent packets that we have reported to the OnPacketStats event(s)</summary>
  149. private int m_packetsSentReported;
  150. /// <summary>Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired</summary>
  151. private double m_nextOnQueueEmpty = 0;
  152. /// <summary>Throttle bucket for this agent's connection</summary>
  153. private AdaptiveTokenBucket m_throttleClient;
  154. public AdaptiveTokenBucket FlowThrottle
  155. {
  156. get { return m_throttleClient; }
  157. }
  158. /// <summary>Throttle buckets for each packet category</summary>
  159. private readonly TokenBucket[] m_throttleCategories;
  160. /// <summary>Outgoing queues for throttled packets</summary>
  161. private DoubleLocklessQueue<OutgoingPacket>[] m_packetOutboxes = new DoubleLocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT];
  162. /// <summary>A container that can hold one packet for each outbox, used to store
  163. /// dequeued packets that are being held for throttling</summary>
  164. private OutgoingPacket[] m_nextPackets = new OutgoingPacket[THROTTLE_CATEGORY_COUNT];
  165. /// <summary>A reference to the LLUDPServer that is managing this client</summary>
  166. private readonly LLUDPServer m_udpServer;
  167. /// <summary>Caches packed throttle information</summary>
  168. private byte[] m_packedThrottles;
  169. private int m_defaultRTO = 1000; // 1sec is the recommendation in the RFC
  170. private int m_maxRTO = 60000;
  171. public bool m_deliverPackets = true;
  172. private float m_burstTime;
  173. public int m_lastStartpingTimeMS;
  174. public int m_pingMS;
  175. public int PingTimeMS
  176. {
  177. get
  178. {
  179. if (m_pingMS < 10)
  180. return 10;
  181. if(m_pingMS > 2000)
  182. return 2000;
  183. return m_pingMS;
  184. }
  185. }
  186. private ClientInfo m_info = new ClientInfo();
  187. /// <summary>
  188. /// Default constructor
  189. /// </summary>
  190. /// <param name="server">Reference to the UDP server this client is connected to</param>
  191. /// <param name="rates">Default throttling rates and maximum throttle limits</param>
  192. /// <param name="parentThrottle">Parent HTB (hierarchical token bucket)
  193. /// that the child throttles will be governed by</param>
  194. /// <param name="circuitCode">Circuit code for this connection</param>
  195. /// <param name="agentID">AgentID for the connected agent</param>
  196. /// <param name="remoteEndPoint">Remote endpoint for this connection</param>
  197. /// <param name="defaultRTO">
  198. /// Default retransmission timeout for unacked packets. The RTO will never drop
  199. /// beyond this number.
  200. /// </param>
  201. /// <param name="maxRTO">
  202. /// The maximum retransmission timeout for unacked packets. The RTO will never exceed this number.
  203. /// </param>
  204. public LLUDPClient(
  205. LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID,
  206. IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO)
  207. {
  208. AgentID = agentID;
  209. RemoteEndPoint = remoteEndPoint;
  210. CircuitCode = circuitCode;
  211. m_udpServer = server;
  212. if (defaultRTO != 0)
  213. m_defaultRTO = defaultRTO;
  214. if (maxRTO != 0)
  215. m_maxRTO = maxRTO;
  216. m_burstTime = rates.BrustTime;
  217. float m_burst = rates.ClientMaxRate * m_burstTime;
  218. // Create a token bucket throttle for this client that has the scene token bucket as a parent
  219. m_throttleClient = new AdaptiveTokenBucket(parentThrottle, rates.ClientMaxRate, m_burst, rates.AdaptiveThrottlesEnabled);
  220. // Create an array of token buckets for this clients different throttle categories
  221. m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT];
  222. m_burst = rates.Total * rates.BrustTime;
  223. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  224. {
  225. ThrottleOutPacketType type = (ThrottleOutPacketType)i;
  226. // Initialize the packet outboxes, where packets sit while they are waiting for tokens
  227. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  228. // Initialize the token buckets that control the throttling for each category
  229. m_throttleCategories[i] = new TokenBucket(m_throttleClient, rates.GetRate(type), m_burst);
  230. }
  231. // Default the retransmission timeout to one second
  232. RTO = m_defaultRTO;
  233. // Initialize this to a sane value to prevent early disconnects
  234. TickLastPacketReceived = Environment.TickCount & Int32.MaxValue;
  235. m_pingMS = (int)(3.0 * server.TickCountResolution); // so filter doesnt start at 0;
  236. }
  237. /// <summary>
  238. /// Shuts down this client connection
  239. /// </summary>
  240. public void Shutdown()
  241. {
  242. IsConnected = false;
  243. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  244. {
  245. m_packetOutboxes[i].Clear();
  246. m_nextPackets[i] = null;
  247. }
  248. // pull the throttle out of the scene throttle
  249. m_throttleClient.Parent.UnregisterRequest(m_throttleClient);
  250. PendingAcks.Clear();
  251. NeedAcks.Clear();
  252. }
  253. /// <summary>
  254. /// Gets information about this client connection
  255. /// </summary>
  256. /// <returns>Information about the client connection</returns>
  257. public ClientInfo GetClientInfo()
  258. {
  259. // TODO: This data structure is wrong in so many ways. Locking and copying the entire lists
  260. // of pending and needed ACKs for every client every time some method wants information about
  261. // this connection is a recipe for poor performance
  262. m_info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate;
  263. m_info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate;
  264. m_info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate;
  265. m_info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate;
  266. m_info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate;
  267. m_info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
  268. m_info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
  269. m_info.totalThrottle = (int)m_throttleClient.DripRate;
  270. return m_info;
  271. }
  272. /// <summary>
  273. /// Modifies the UDP throttles
  274. /// </summary>
  275. /// <param name="info">New throttling values</param>
  276. public void SetClientInfo(ClientInfo info)
  277. {
  278. // TODO: Allowing throttles to be manually set from this function seems like a reasonable
  279. // idea. On the other hand, letting external code manipulate our ACK accounting is not
  280. // going to happen
  281. throw new NotImplementedException();
  282. }
  283. /// <summary>
  284. /// Get the total number of pakcets queued for this client.
  285. /// </summary>
  286. /// <returns></returns>
  287. public int GetTotalPacketsQueuedCount()
  288. {
  289. int total = 0;
  290. for (int i = 0; i <= (int)ThrottleOutPacketType.Asset; i++)
  291. total += m_packetOutboxes[i].Count;
  292. return total;
  293. }
  294. /// <summary>
  295. /// Get the number of packets queued for the given throttle type.
  296. /// </summary>
  297. /// <returns></returns>
  298. /// <param name="throttleType"></param>
  299. public int GetPacketsQueuedCount(ThrottleOutPacketType throttleType)
  300. {
  301. int icat = (int)throttleType;
  302. if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT)
  303. return m_packetOutboxes[icat].Count;
  304. else
  305. return 0;
  306. }
  307. /// <summary>
  308. /// Return statistics information about client packet queues.
  309. /// </summary>
  310. /// <remarks>
  311. /// FIXME: This should really be done in a more sensible manner rather than sending back a formatted string.
  312. /// </remarks>
  313. /// <returns></returns>
  314. public string GetStats()
  315. {
  316. return string.Format(
  317. "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}",
  318. Util.EnvironmentTickCountSubtract(TickLastPacketReceived),
  319. PacketsReceived,
  320. PacketsSent,
  321. PacketsResent,
  322. UnackedBytes,
  323. m_packetOutboxes[(int)ThrottleOutPacketType.Resend].Count,
  324. m_packetOutboxes[(int)ThrottleOutPacketType.Land].Count,
  325. m_packetOutboxes[(int)ThrottleOutPacketType.Wind].Count,
  326. m_packetOutboxes[(int)ThrottleOutPacketType.Cloud].Count,
  327. m_packetOutboxes[(int)ThrottleOutPacketType.Task].Count,
  328. m_packetOutboxes[(int)ThrottleOutPacketType.Texture].Count,
  329. m_packetOutboxes[(int)ThrottleOutPacketType.Asset].Count);
  330. }
  331. public void SendPacketStats()
  332. {
  333. PacketStats callback = OnPacketStats;
  334. if (callback != null)
  335. {
  336. int newPacketsReceived = PacketsReceived - m_packetsReceivedReported;
  337. int newPacketsSent = PacketsSent - m_packetsSentReported;
  338. int newPacketUnAck = UnackedBytes - m_packetsUnAckReported;
  339. callback(newPacketsReceived, newPacketsSent, UnackedBytes);
  340. m_packetsReceivedReported += newPacketsReceived;
  341. m_packetsSentReported += newPacketsSent;
  342. m_packetsUnAckReported += newPacketUnAck;
  343. }
  344. }
  345. public void SetThrottles(byte[] throttleData)
  346. {
  347. SetThrottles(throttleData, 1.0f);
  348. }
  349. public void SetThrottles(byte[] throttleData, float factor)
  350. {
  351. byte[] adjData;
  352. int pos = 0;
  353. if (!BitConverter.IsLittleEndian)
  354. {
  355. byte[] newData = new byte[7 * 4];
  356. Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4);
  357. for (int i = 0; i < 7; i++)
  358. Array.Reverse(newData, i * 4, 4);
  359. adjData = newData;
  360. }
  361. else
  362. {
  363. adjData = throttleData;
  364. }
  365. // 0.125f converts from bits to bytes
  366. float scale = 0.125f * factor;
  367. int resend = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  368. int land = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  369. int wind = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  370. int cloud = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  371. int task = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  372. int texture = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  373. int asset = (int)(BitConverter.ToSingle(adjData, pos) * scale);
  374. // Make sure none of the throttles are set below our packet MTU,
  375. // otherwise a throttle could become permanently clogged
  376. /* now using floats
  377. resend = Math.Max(resend, LLUDPServer.MTU);
  378. land = Math.Max(land, LLUDPServer.MTU);
  379. wind = Math.Max(wind, LLUDPServer.MTU);
  380. cloud = Math.Max(cloud, LLUDPServer.MTU);
  381. task = Math.Max(task, LLUDPServer.MTU);
  382. texture = Math.Max(texture, LLUDPServer.MTU);
  383. asset = Math.Max(asset, LLUDPServer.MTU);
  384. */
  385. int total = resend + land + wind + cloud + task + texture + asset;
  386. float m_burst = total * m_burstTime;
  387. if (ThrottleDebugLevel > 0)
  388. {
  389. m_log.DebugFormat(
  390. "[LLUDPCLIENT]: {0} is setting throttles in {1} to Resend={2}, Land={3}, Wind={4}, Cloud={5}, Task={6}, Texture={7}, Asset={8}, TOTAL = {9}",
  391. AgentID, m_udpServer.Scene.Name, resend, land, wind, cloud, task, texture, asset, total);
  392. }
  393. TokenBucket bucket;
  394. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend];
  395. bucket.RequestedDripRate = resend;
  396. bucket.RequestedBurst = m_burst;
  397. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land];
  398. bucket.RequestedDripRate = land;
  399. bucket.RequestedBurst = m_burst;
  400. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind];
  401. bucket.RequestedDripRate = wind;
  402. bucket.RequestedBurst = m_burst;
  403. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud];
  404. bucket.RequestedDripRate = cloud;
  405. bucket.RequestedBurst = m_burst;
  406. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset];
  407. bucket.RequestedDripRate = asset;
  408. bucket.RequestedBurst = m_burst;
  409. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task];
  410. bucket.RequestedDripRate = task;
  411. bucket.RequestedBurst = m_burst;
  412. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture];
  413. bucket.RequestedDripRate = texture;
  414. bucket.RequestedBurst = m_burst;
  415. // Reset the packed throttles cached data
  416. m_packedThrottles = null;
  417. }
  418. public byte[] GetThrottlesPacked(float multiplier)
  419. {
  420. byte[] data = m_packedThrottles;
  421. if (data == null)
  422. {
  423. float rate;
  424. data = new byte[7 * 4];
  425. int i = 0;
  426. // multiply by 8 to convert bytes back to bits
  427. multiplier *= 8;
  428. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate * multiplier;
  429. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  430. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate * multiplier;
  431. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  432. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate * multiplier;
  433. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  434. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate * multiplier;
  435. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  436. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate * multiplier;
  437. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  438. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate * multiplier;
  439. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  440. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate * multiplier;
  441. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  442. m_packedThrottles = data;
  443. }
  444. return data;
  445. }
  446. public int GetCatBytesCanSend(ThrottleOutPacketType cat, int timeMS)
  447. {
  448. int icat = (int)cat;
  449. if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT)
  450. {
  451. TokenBucket bucket = m_throttleCategories[icat];
  452. return bucket.GetCatBytesCanSend(timeMS);
  453. }
  454. else
  455. return 0;
  456. }
  457. /// <summary>
  458. /// Queue an outgoing packet if appropriate.
  459. /// </summary>
  460. /// <param name="packet"></param>
  461. /// <param name="forceQueue">Always queue the packet if at all possible.</param>
  462. /// <returns>
  463. /// true if the packet has been queued,
  464. /// false if the packet has not been queued and should be sent immediately.
  465. /// </returns>
  466. public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue)
  467. {
  468. return EnqueueOutgoing(packet, forceQueue, false);
  469. }
  470. public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue, bool highPriority)
  471. {
  472. int category = (int)packet.Category;
  473. if (category >= 0 && category < m_packetOutboxes.Length)
  474. {
  475. DoubleLocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category];
  476. if (forceQueue || m_deliverPackets == false)
  477. {
  478. queue.Enqueue(packet, highPriority);
  479. return true;
  480. }
  481. // need to enqueue if queue is not empty
  482. if (queue.Count > 0 || m_nextPackets[category] != null)
  483. {
  484. queue.Enqueue(packet, highPriority);
  485. return true;
  486. }
  487. // check bandwidth
  488. TokenBucket bucket = m_throttleCategories[category];
  489. if (bucket.CheckTokens(packet.Buffer.DataLength))
  490. {
  491. // enough tokens so it can be sent imediatly by caller
  492. bucket.RemoveTokens(packet.Buffer.DataLength);
  493. return false;
  494. }
  495. else
  496. {
  497. // Force queue specified or not enough tokens in the bucket, queue this packet
  498. queue.Enqueue(packet, highPriority);
  499. return true;
  500. }
  501. }
  502. else
  503. {
  504. // We don't have a token bucket for this category, so it will not be queued
  505. return false;
  506. }
  507. }
  508. /// <summary>
  509. /// Loops through all of the packet queues for this client and tries to send
  510. /// an outgoing packet from each, obeying the throttling bucket limits
  511. /// </summary>
  512. ///
  513. /// <remarks>
  514. /// Packet queues are inspected in ascending numerical order starting from 0. Therefore, queues with a lower
  515. /// ThrottleOutPacketType number will see their packet get sent first (e.g. if both Land and Wind queues have
  516. /// packets, then the packet at the front of the Land queue will be sent before the packet at the front of the
  517. /// wind queue).
  518. ///
  519. /// This function is only called from a synchronous loop in the
  520. /// UDPServer so we don't need to bother making this thread safe
  521. /// </remarks>
  522. ///
  523. /// <returns>True if any packets were sent, otherwise false</returns>
  524. public bool DequeueOutgoing()
  525. {
  526. // if (m_deliverPackets == false) return false;
  527. OutgoingPacket packet = null;
  528. DoubleLocklessQueue<OutgoingPacket> queue;
  529. TokenBucket bucket;
  530. bool packetSent = false;
  531. ThrottleOutPacketTypeFlags emptyCategories = 0;
  532. //string queueDebugOutput = String.Empty; // Serious debug business
  533. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  534. {
  535. bucket = m_throttleCategories[i];
  536. //queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business
  537. if (m_nextPackets[i] != null)
  538. {
  539. // This bucket was empty the last time we tried to send a packet,
  540. // leaving a dequeued packet still waiting to be sent out. Try to
  541. // send it again
  542. OutgoingPacket nextPacket = m_nextPackets[i];
  543. if(nextPacket.Buffer == null)
  544. {
  545. if (m_packetOutboxes[i].Count < 5)
  546. emptyCategories |= CategoryToFlag(i);
  547. continue;
  548. }
  549. if (bucket.RemoveTokens(nextPacket.Buffer.DataLength))
  550. {
  551. // Send the packet
  552. m_udpServer.SendPacketFinal(nextPacket);
  553. m_nextPackets[i] = null;
  554. packetSent = true;
  555. if (m_packetOutboxes[i].Count < 5)
  556. emptyCategories |= CategoryToFlag(i);
  557. }
  558. }
  559. else
  560. {
  561. // No dequeued packet waiting to be sent, try to pull one off
  562. // this queue
  563. queue = m_packetOutboxes[i];
  564. if (queue != null)
  565. {
  566. bool success = false;
  567. try
  568. {
  569. success = queue.Dequeue(out packet);
  570. }
  571. catch
  572. {
  573. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  574. }
  575. if (success)
  576. {
  577. // A packet was pulled off the queue. See if we have
  578. // enough tokens in the bucket to send it out
  579. if(packet.Buffer == null)
  580. {
  581. // packet canceled elsewhere (by a ack for example)
  582. if (queue.Count < 5)
  583. emptyCategories |= CategoryToFlag(i);
  584. }
  585. else
  586. {
  587. if (bucket.RemoveTokens(packet.Buffer.DataLength))
  588. {
  589. // Send the packet
  590. m_udpServer.SendPacketFinal(packet);
  591. packetSent = true;
  592. if (queue.Count < 5)
  593. emptyCategories |= CategoryToFlag(i);
  594. }
  595. else
  596. {
  597. // Save the dequeued packet for the next iteration
  598. m_nextPackets[i] = packet;
  599. }
  600. }
  601. }
  602. else
  603. {
  604. // No packets in this queue. Fire the queue empty callback
  605. // if it has not been called recently
  606. emptyCategories |= CategoryToFlag(i);
  607. }
  608. }
  609. else
  610. {
  611. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  612. emptyCategories |= CategoryToFlag(i);
  613. }
  614. }
  615. }
  616. if (emptyCategories != 0)
  617. BeginFireQueueEmpty(emptyCategories);
  618. //m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business
  619. return packetSent;
  620. }
  621. /// <summary>
  622. /// Called when an ACK packet is received and a round-trip time for a
  623. /// packet is calculated. This is used to calculate the smoothed
  624. /// round-trip time, round trip time variance, and finally the
  625. /// retransmission timeout
  626. /// </summary>
  627. /// <param name="r">Round-trip time of a single packet and its
  628. /// acknowledgement</param>
  629. public void UpdateRoundTrip(float r)
  630. {
  631. const float ALPHA = 0.125f;
  632. const float BETA = 0.25f;
  633. const float K = 4.0f;
  634. if (RTTVAR == 0.0f)
  635. {
  636. // First RTT measurement
  637. SRTT = r;
  638. RTTVAR = r * 0.5f;
  639. }
  640. else
  641. {
  642. // Subsequence RTT measurement
  643. RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r);
  644. SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r;
  645. }
  646. int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR));
  647. // Clamp the retransmission timeout to manageable values
  648. rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO);
  649. RTO = rto;
  650. //if (RTO != rto)
  651. // m_log.Debug("[LLUDPCLIENT]: Setting RTO to " + RTO + "ms from " + rto + "ms with an RTTVAR of " +
  652. //RTTVAR + " based on new RTT of " + r + "ms");
  653. }
  654. /// <summary>
  655. /// Exponential backoff of the retransmission timeout, per section 5.5
  656. /// of RFC 2988
  657. /// </summary>
  658. public void BackoffRTO()
  659. {
  660. // Reset SRTT and RTTVAR, we assume they are bogus since things
  661. // didn't work out and we're backing off the timeout
  662. SRTT = 0.0f;
  663. RTTVAR = 0.0f;
  664. // Double the retransmission timeout
  665. RTO = Math.Min(RTO * 2, m_maxRTO);
  666. }
  667. const double MIN_CALLBACK_MS = 20.0;
  668. private bool m_isQueueEmptyRunning;
  669. /// <summary>
  670. /// Does an early check to see if this queue empty callback is already
  671. /// running, then asynchronously firing the event
  672. /// </summary>
  673. /// <param name="categories">Throttle categories to fire the callback for</param>
  674. private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories)
  675. {
  676. if (!m_isQueueEmptyRunning)
  677. {
  678. if (!HasUpdates(categories))
  679. return;
  680. double start = Util.GetTimeStampMS();
  681. if (start < m_nextOnQueueEmpty)
  682. return;
  683. m_isQueueEmptyRunning = true;
  684. m_nextOnQueueEmpty = start + MIN_CALLBACK_MS;
  685. // Asynchronously run the callback
  686. if (m_udpServer.OqrEngine.IsRunning)
  687. m_udpServer.OqrEngine.QueueJob(AgentID.ToString(), () => FireQueueEmpty(categories));
  688. else
  689. Util.FireAndForget(FireQueueEmpty, categories, "LLUDPClient.BeginFireQueueEmpty");
  690. }
  691. }
  692. /// <summary>
  693. /// Fires the OnQueueEmpty callback and sets the minimum time that it
  694. /// can be called again
  695. /// </summary>
  696. /// <param name="o">Throttle categories to fire the callback for,
  697. /// stored as an object to match the WaitCallback delegate
  698. /// signature</param>
  699. public void FireQueueEmpty(object o)
  700. {
  701. ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o;
  702. QueueEmpty callback = OnQueueEmpty;
  703. if (callback != null)
  704. {
  705. // if (m_udpServer.IsRunningOutbound)
  706. // {
  707. try { callback(categories); }
  708. catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); }
  709. // }
  710. }
  711. m_isQueueEmptyRunning = false;
  712. }
  713. internal void ForceThrottleSetting(int throttle, int setting)
  714. {
  715. if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT)
  716. m_throttleCategories[throttle].RequestedDripRate = Math.Max(setting, LLUDPServer.MTU);
  717. }
  718. internal int GetThrottleSetting(int throttle)
  719. {
  720. if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT)
  721. return (int)m_throttleCategories[throttle].RequestedDripRate;
  722. else
  723. return 0;
  724. }
  725. public void FreeUDPBuffer(UDPPacketBuffer buf)
  726. {
  727. m_udpServer.FreeUDPBuffer(buf);
  728. }
  729. /// <summary>
  730. /// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a
  731. /// flag value
  732. /// </summary>
  733. /// <param name="i">Throttle category to convert</param>
  734. /// <returns>Flag representation of the throttle category</returns>
  735. private static ThrottleOutPacketTypeFlags CategoryToFlag(int i)
  736. {
  737. ThrottleOutPacketType category = (ThrottleOutPacketType)i;
  738. switch (category)
  739. {
  740. case ThrottleOutPacketType.Land:
  741. return ThrottleOutPacketTypeFlags.Land; // Terrain data
  742. case ThrottleOutPacketType.Wind:
  743. return ThrottleOutPacketTypeFlags.Wind; // Wind data
  744. case ThrottleOutPacketType.Cloud:
  745. return ThrottleOutPacketTypeFlags.Cloud; // Cloud data
  746. case ThrottleOutPacketType.Task:
  747. return ThrottleOutPacketTypeFlags.Task; // Object updates and everything not on the other categories
  748. case ThrottleOutPacketType.Texture:
  749. return ThrottleOutPacketTypeFlags.Texture; // Textures data (also impacts http texture and mesh by default)
  750. case ThrottleOutPacketType.Asset:
  751. return ThrottleOutPacketTypeFlags.Asset; // Non-texture Assets data
  752. default:
  753. return 0;
  754. }
  755. }
  756. }
  757. public class DoubleLocklessQueue<T> : OpenSim.Framework.LocklessQueue<T>
  758. {
  759. OpenSim.Framework.LocklessQueue<T> highQueue = new OpenSim.Framework.LocklessQueue<T>();
  760. public override int Count
  761. {
  762. get
  763. {
  764. return base.Count + highQueue.Count;
  765. }
  766. }
  767. public override bool Dequeue(out T item)
  768. {
  769. if (highQueue.Dequeue(out item))
  770. return true;
  771. return base.Dequeue(out item);
  772. }
  773. public void Enqueue(T item, bool highPriority)
  774. {
  775. if (highPriority)
  776. highQueue.Enqueue(item);
  777. else
  778. Enqueue(item);
  779. }
  780. }
  781. }