LLUDPClient.cs 37 KB

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