LLUDPClient.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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(200);
  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. /// <summary>
  187. /// This is the percentage of the udp texture queue to add to the task queue since
  188. /// textures are now generally handled through http.
  189. /// </summary>
  190. private double m_cannibalrate = 0.0;
  191. private ClientInfo m_info = new ClientInfo();
  192. /// <summary>
  193. /// Default constructor
  194. /// </summary>
  195. /// <param name="server">Reference to the UDP server this client is connected to</param>
  196. /// <param name="rates">Default throttling rates and maximum throttle limits</param>
  197. /// <param name="parentThrottle">Parent HTB (hierarchical token bucket)
  198. /// that the child throttles will be governed by</param>
  199. /// <param name="circuitCode">Circuit code for this connection</param>
  200. /// <param name="agentID">AgentID for the connected agent</param>
  201. /// <param name="remoteEndPoint">Remote endpoint for this connection</param>
  202. /// <param name="defaultRTO">
  203. /// Default retransmission timeout for unacked packets. The RTO will never drop
  204. /// beyond this number.
  205. /// </param>
  206. /// <param name="maxRTO">
  207. /// The maximum retransmission timeout for unacked packets. The RTO will never exceed this number.
  208. /// </param>
  209. public LLUDPClient(
  210. LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID,
  211. IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO)
  212. {
  213. AgentID = agentID;
  214. RemoteEndPoint = remoteEndPoint;
  215. CircuitCode = circuitCode;
  216. m_udpServer = server;
  217. if (defaultRTO != 0)
  218. m_defaultRTO = defaultRTO;
  219. if (maxRTO != 0)
  220. m_maxRTO = maxRTO;
  221. m_burstTime = rates.BrustTime;
  222. float m_burst = rates.ClientMaxRate * m_burstTime;
  223. // Create a token bucket throttle for this client that has the scene token bucket as a parent
  224. m_throttleClient = new AdaptiveTokenBucket(parentThrottle, rates.ClientMaxRate, m_burst, rates.AdaptiveThrottlesEnabled);
  225. // Create an array of token buckets for this clients different throttle categories
  226. m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT];
  227. m_cannibalrate = rates.CannibalizeTextureRate;
  228. m_burst = rates.Total * rates.BrustTime;
  229. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  230. {
  231. ThrottleOutPacketType type = (ThrottleOutPacketType)i;
  232. // Initialize the packet outboxes, where packets sit while they are waiting for tokens
  233. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  234. // Initialize the token buckets that control the throttling for each category
  235. m_throttleCategories[i] = new TokenBucket(m_throttleClient, rates.GetRate(type), m_burst);
  236. }
  237. // Default the retransmission timeout to one second
  238. RTO = m_defaultRTO;
  239. // Initialize this to a sane value to prevent early disconnects
  240. TickLastPacketReceived = Environment.TickCount & Int32.MaxValue;
  241. m_pingMS = (int)(3.0 * server.TickCountResolution); // so filter doesnt start at 0;
  242. }
  243. /// <summary>
  244. /// Shuts down this client connection
  245. /// </summary>
  246. public void Shutdown()
  247. {
  248. IsConnected = false;
  249. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  250. {
  251. m_packetOutboxes[i].Clear();
  252. m_nextPackets[i] = null;
  253. }
  254. // pull the throttle out of the scene throttle
  255. m_throttleClient.Parent.UnregisterRequest(m_throttleClient);
  256. PendingAcks.Clear();
  257. NeedAcks.Clear();
  258. }
  259. /// <summary>
  260. /// Gets information about this client connection
  261. /// </summary>
  262. /// <returns>Information about the client connection</returns>
  263. public ClientInfo GetClientInfo()
  264. {
  265. // TODO: This data structure is wrong in so many ways. Locking and copying the entire lists
  266. // of pending and needed ACKs for every client every time some method wants information about
  267. // this connection is a recipe for poor performance
  268. m_info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate;
  269. m_info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate;
  270. m_info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate;
  271. m_info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate;
  272. m_info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate;
  273. m_info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
  274. m_info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
  275. m_info.totalThrottle = (int)m_throttleClient.DripRate;
  276. return m_info;
  277. }
  278. /// <summary>
  279. /// Modifies the UDP throttles
  280. /// </summary>
  281. /// <param name="info">New throttling values</param>
  282. public void SetClientInfo(ClientInfo info)
  283. {
  284. // TODO: Allowing throttles to be manually set from this function seems like a reasonable
  285. // idea. On the other hand, letting external code manipulate our ACK accounting is not
  286. // going to happen
  287. throw new NotImplementedException();
  288. }
  289. /// <summary>
  290. /// Get the total number of pakcets queued for this client.
  291. /// </summary>
  292. /// <returns></returns>
  293. public int GetTotalPacketsQueuedCount()
  294. {
  295. int total = 0;
  296. for (int i = 0; i <= (int)ThrottleOutPacketType.Asset; i++)
  297. total += m_packetOutboxes[i].Count;
  298. return total;
  299. }
  300. /// <summary>
  301. /// Get the number of packets queued for the given throttle type.
  302. /// </summary>
  303. /// <returns></returns>
  304. /// <param name="throttleType"></param>
  305. public int GetPacketsQueuedCount(ThrottleOutPacketType throttleType)
  306. {
  307. int icat = (int)throttleType;
  308. if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT)
  309. return m_packetOutboxes[icat].Count;
  310. else
  311. return 0;
  312. }
  313. /// <summary>
  314. /// Return statistics information about client packet queues.
  315. /// </summary>
  316. /// <remarks>
  317. /// FIXME: This should really be done in a more sensible manner rather than sending back a formatted string.
  318. /// </remarks>
  319. /// <returns></returns>
  320. public string GetStats()
  321. {
  322. return string.Format(
  323. "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}",
  324. Util.EnvironmentTickCountSubtract(TickLastPacketReceived),
  325. PacketsReceived,
  326. PacketsSent,
  327. PacketsResent,
  328. UnackedBytes,
  329. m_packetOutboxes[(int)ThrottleOutPacketType.Resend].Count,
  330. m_packetOutboxes[(int)ThrottleOutPacketType.Land].Count,
  331. m_packetOutboxes[(int)ThrottleOutPacketType.Wind].Count,
  332. m_packetOutboxes[(int)ThrottleOutPacketType.Cloud].Count,
  333. m_packetOutboxes[(int)ThrottleOutPacketType.Task].Count,
  334. m_packetOutboxes[(int)ThrottleOutPacketType.Texture].Count,
  335. m_packetOutboxes[(int)ThrottleOutPacketType.Asset].Count);
  336. }
  337. public void SendPacketStats()
  338. {
  339. PacketStats callback = OnPacketStats;
  340. if (callback != null)
  341. {
  342. int newPacketsReceived = PacketsReceived - m_packetsReceivedReported;
  343. int newPacketsSent = PacketsSent - m_packetsSentReported;
  344. int newPacketUnAck = UnackedBytes - m_packetsUnAckReported;
  345. callback(newPacketsReceived, newPacketsSent, UnackedBytes);
  346. m_packetsReceivedReported += newPacketsReceived;
  347. m_packetsSentReported += newPacketsSent;
  348. m_packetsUnAckReported += newPacketUnAck;
  349. }
  350. }
  351. public void SetThrottles(byte[] throttleData)
  352. {
  353. SetThrottles(throttleData, 1.0f);
  354. }
  355. public void SetThrottles(byte[] throttleData, float factor)
  356. {
  357. byte[] adjData;
  358. int pos = 0;
  359. if (!BitConverter.IsLittleEndian)
  360. {
  361. byte[] newData = new byte[7 * 4];
  362. Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4);
  363. for (int i = 0; i < 7; i++)
  364. Array.Reverse(newData, i * 4, 4);
  365. adjData = newData;
  366. }
  367. else
  368. {
  369. adjData = throttleData;
  370. }
  371. // 0.125f converts from bits to bytes
  372. float scale = 0.125f * factor;
  373. int resend = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  374. int land = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  375. int wind = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  376. int cloud = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  377. int task = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  378. int texture = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4;
  379. int asset = (int)(BitConverter.ToSingle(adjData, pos) * scale);
  380. // Make sure none of the throttles are set below our packet MTU,
  381. // otherwise a throttle could become permanently clogged
  382. /* now using floats
  383. resend = Math.Max(resend, LLUDPServer.MTU);
  384. land = Math.Max(land, LLUDPServer.MTU);
  385. wind = Math.Max(wind, LLUDPServer.MTU);
  386. cloud = Math.Max(cloud, LLUDPServer.MTU);
  387. task = Math.Max(task, LLUDPServer.MTU);
  388. texture = Math.Max(texture, LLUDPServer.MTU);
  389. asset = Math.Max(asset, LLUDPServer.MTU);
  390. */
  391. // Since most textures are now delivered through http, make it possible
  392. // to cannibalize some of the bw from the texture throttle to use for
  393. // the task queue (e.g. object updates)
  394. task = task + (int)(m_cannibalrate * texture);
  395. texture = (int)((1 - m_cannibalrate) * texture);
  396. int total = resend + land + wind + cloud + task + texture + asset;
  397. float m_burst = total * m_burstTime;
  398. if (ThrottleDebugLevel > 0)
  399. {
  400. m_log.DebugFormat(
  401. "[LLUDPCLIENT]: {0} is setting throttles in {1} to Resend={2}, Land={3}, Wind={4}, Cloud={5}, Task={6}, Texture={7}, Asset={8}, TOTAL = {9}",
  402. AgentID, m_udpServer.Scene.Name, resend, land, wind, cloud, task, texture, asset, total);
  403. }
  404. TokenBucket bucket;
  405. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend];
  406. bucket.RequestedDripRate = resend;
  407. bucket.RequestedBurst = m_burst;
  408. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land];
  409. bucket.RequestedDripRate = land;
  410. bucket.RequestedBurst = m_burst;
  411. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind];
  412. bucket.RequestedDripRate = wind;
  413. bucket.RequestedBurst = m_burst;
  414. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud];
  415. bucket.RequestedDripRate = cloud;
  416. bucket.RequestedBurst = m_burst;
  417. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset];
  418. bucket.RequestedDripRate = asset;
  419. bucket.RequestedBurst = m_burst;
  420. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task];
  421. bucket.RequestedDripRate = task;
  422. bucket.RequestedBurst = m_burst;
  423. bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture];
  424. bucket.RequestedDripRate = texture;
  425. bucket.RequestedBurst = m_burst;
  426. // Reset the packed throttles cached data
  427. m_packedThrottles = null;
  428. }
  429. public byte[] GetThrottlesPacked(float multiplier)
  430. {
  431. byte[] data = m_packedThrottles;
  432. if (data == null)
  433. {
  434. float rate;
  435. data = new byte[7 * 4];
  436. int i = 0;
  437. // multiply by 8 to convert bytes back to bits
  438. multiplier *= 8;
  439. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate * multiplier;
  440. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  441. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate * multiplier;
  442. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  443. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate * multiplier;
  444. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  445. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate * multiplier;
  446. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  447. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate * multiplier;
  448. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  449. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate * multiplier;
  450. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  451. rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate * multiplier;
  452. Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4;
  453. m_packedThrottles = data;
  454. }
  455. return data;
  456. }
  457. public int GetCatBytesCanSend(ThrottleOutPacketType cat, int timeMS)
  458. {
  459. int icat = (int)cat;
  460. if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT)
  461. {
  462. TokenBucket bucket = m_throttleCategories[icat];
  463. return bucket.GetCatBytesCanSend(timeMS);
  464. }
  465. else
  466. return 0;
  467. }
  468. /// <summary>
  469. /// Queue an outgoing packet if appropriate.
  470. /// </summary>
  471. /// <param name="packet"></param>
  472. /// <param name="forceQueue">Always queue the packet if at all possible.</param>
  473. /// <returns>
  474. /// true if the packet has been queued,
  475. /// false if the packet has not been queued and should be sent immediately.
  476. /// </returns>
  477. public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue)
  478. {
  479. return EnqueueOutgoing(packet, forceQueue, false);
  480. }
  481. public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue, bool highPriority)
  482. {
  483. int category = (int)packet.Category;
  484. if (category >= 0 && category < m_packetOutboxes.Length)
  485. {
  486. DoubleLocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category];
  487. if (m_deliverPackets == false)
  488. {
  489. queue.Enqueue(packet, highPriority);
  490. return true;
  491. }
  492. TokenBucket bucket = m_throttleCategories[category];
  493. // Don't send this packet if queue is not empty
  494. if (queue.Count > 0 || m_nextPackets[category] != null)
  495. {
  496. queue.Enqueue(packet, highPriority);
  497. return true;
  498. }
  499. if (!forceQueue && bucket.CheckTokens(packet.Buffer.DataLength))
  500. {
  501. // enough tokens so it can be sent imediatly by caller
  502. bucket.RemoveTokens(packet.Buffer.DataLength);
  503. return false;
  504. }
  505. else
  506. {
  507. // Force queue specified or not enough tokens in the bucket, queue this packet
  508. queue.Enqueue(packet, highPriority);
  509. return true;
  510. }
  511. }
  512. else
  513. {
  514. // We don't have a token bucket for this category, so it will not be queued
  515. return false;
  516. }
  517. }
  518. /// <summary>
  519. /// Loops through all of the packet queues for this client and tries to send
  520. /// an outgoing packet from each, obeying the throttling bucket limits
  521. /// </summary>
  522. ///
  523. /// <remarks>
  524. /// Packet queues are inspected in ascending numerical order starting from 0. Therefore, queues with a lower
  525. /// ThrottleOutPacketType number will see their packet get sent first (e.g. if both Land and Wind queues have
  526. /// packets, then the packet at the front of the Land queue will be sent before the packet at the front of the
  527. /// wind queue).
  528. ///
  529. /// This function is only called from a synchronous loop in the
  530. /// UDPServer so we don't need to bother making this thread safe
  531. /// </remarks>
  532. ///
  533. /// <returns>True if any packets were sent, otherwise false</returns>
  534. public bool DequeueOutgoing()
  535. {
  536. // if (m_deliverPackets == false) return false;
  537. OutgoingPacket packet = null;
  538. DoubleLocklessQueue<OutgoingPacket> queue;
  539. TokenBucket bucket;
  540. bool packetSent = false;
  541. ThrottleOutPacketTypeFlags emptyCategories = 0;
  542. //string queueDebugOutput = String.Empty; // Serious debug business
  543. for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
  544. {
  545. bucket = m_throttleCategories[i];
  546. //queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business
  547. if (m_nextPackets[i] != null)
  548. {
  549. // This bucket was empty the last time we tried to send a packet,
  550. // leaving a dequeued packet still waiting to be sent out. Try to
  551. // send it again
  552. OutgoingPacket nextPacket = m_nextPackets[i];
  553. if (bucket.RemoveTokens(nextPacket.Buffer.DataLength))
  554. {
  555. // Send the packet
  556. m_udpServer.SendPacketFinal(nextPacket);
  557. m_nextPackets[i] = null;
  558. packetSent = true;
  559. if (m_packetOutboxes[i].Count < 5)
  560. emptyCategories |= CategoryToFlag(i);
  561. }
  562. }
  563. else
  564. {
  565. // No dequeued packet waiting to be sent, try to pull one off
  566. // this queue
  567. queue = m_packetOutboxes[i];
  568. if (queue != null)
  569. {
  570. bool success = false;
  571. try
  572. {
  573. success = queue.Dequeue(out packet);
  574. }
  575. catch
  576. {
  577. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  578. }
  579. if (success)
  580. {
  581. // A packet was pulled off the queue. See if we have
  582. // enough tokens in the bucket to send it out
  583. if (bucket.RemoveTokens(packet.Buffer.DataLength))
  584. {
  585. // Send the packet
  586. m_udpServer.SendPacketFinal(packet);
  587. packetSent = true;
  588. if (queue.Count < 5)
  589. emptyCategories |= CategoryToFlag(i);
  590. }
  591. else
  592. {
  593. // Save the dequeued packet for the next iteration
  594. m_nextPackets[i] = packet;
  595. }
  596. }
  597. else
  598. {
  599. // No packets in this queue. Fire the queue empty callback
  600. // if it has not been called recently
  601. emptyCategories |= CategoryToFlag(i);
  602. }
  603. }
  604. else
  605. {
  606. m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>();
  607. emptyCategories |= CategoryToFlag(i);
  608. }
  609. }
  610. }
  611. if (emptyCategories != 0)
  612. BeginFireQueueEmpty(emptyCategories);
  613. //m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business
  614. return packetSent;
  615. }
  616. /// <summary>
  617. /// Called when an ACK packet is received and a round-trip time for a
  618. /// packet is calculated. This is used to calculate the smoothed
  619. /// round-trip time, round trip time variance, and finally the
  620. /// retransmission timeout
  621. /// </summary>
  622. /// <param name="r">Round-trip time of a single packet and its
  623. /// acknowledgement</param>
  624. public void UpdateRoundTrip(float r)
  625. {
  626. const float ALPHA = 0.125f;
  627. const float BETA = 0.25f;
  628. const float K = 4.0f;
  629. if (RTTVAR == 0.0f)
  630. {
  631. // First RTT measurement
  632. SRTT = r;
  633. RTTVAR = r * 0.5f;
  634. }
  635. else
  636. {
  637. // Subsequence RTT measurement
  638. RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r);
  639. SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r;
  640. }
  641. int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR));
  642. // Clamp the retransmission timeout to manageable values
  643. rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO);
  644. RTO = rto;
  645. //if (RTO != rto)
  646. // m_log.Debug("[LLUDPCLIENT]: Setting RTO to " + RTO + "ms from " + rto + "ms with an RTTVAR of " +
  647. //RTTVAR + " based on new RTT of " + r + "ms");
  648. }
  649. /// <summary>
  650. /// Exponential backoff of the retransmission timeout, per section 5.5
  651. /// of RFC 2988
  652. /// </summary>
  653. public void BackoffRTO()
  654. {
  655. // Reset SRTT and RTTVAR, we assume they are bogus since things
  656. // didn't work out and we're backing off the timeout
  657. SRTT = 0.0f;
  658. RTTVAR = 0.0f;
  659. // Double the retransmission timeout
  660. RTO = Math.Min(RTO * 2, m_maxRTO);
  661. }
  662. const double MIN_CALLBACK_MS = 20.0;
  663. private bool m_isQueueEmptyRunning;
  664. /// <summary>
  665. /// Does an early check to see if this queue empty callback is already
  666. /// running, then asynchronously firing the event
  667. /// </summary>
  668. /// <param name="categories">Throttle categories to fire the callback for</param>
  669. private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories)
  670. {
  671. if (!m_isQueueEmptyRunning)
  672. {
  673. if (!HasUpdates(categories))
  674. return;
  675. double start = Util.GetTimeStampMS();
  676. if (start < m_nextOnQueueEmpty)
  677. return;
  678. m_isQueueEmptyRunning = true;
  679. m_nextOnQueueEmpty = start + MIN_CALLBACK_MS;
  680. // Asynchronously run the callback
  681. if (m_udpServer.OqrEngine.IsRunning)
  682. m_udpServer.OqrEngine.QueueJob(AgentID.ToString(), () => FireQueueEmpty(categories));
  683. else
  684. Util.FireAndForget(FireQueueEmpty, categories, "LLUDPClient.BeginFireQueueEmpty");
  685. }
  686. }
  687. /// <summary>
  688. /// Fires the OnQueueEmpty callback and sets the minimum time that it
  689. /// can be called again
  690. /// </summary>
  691. /// <param name="o">Throttle categories to fire the callback for,
  692. /// stored as an object to match the WaitCallback delegate
  693. /// signature</param>
  694. public void FireQueueEmpty(object o)
  695. {
  696. ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o;
  697. QueueEmpty callback = OnQueueEmpty;
  698. if (callback != null)
  699. {
  700. // if (m_udpServer.IsRunningOutbound)
  701. // {
  702. try { callback(categories); }
  703. catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); }
  704. // }
  705. }
  706. m_isQueueEmptyRunning = false;
  707. }
  708. internal void ForceThrottleSetting(int throttle, int setting)
  709. {
  710. if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT)
  711. m_throttleCategories[throttle].RequestedDripRate = Math.Max(setting, LLUDPServer.MTU);
  712. }
  713. internal int GetThrottleSetting(int throttle)
  714. {
  715. if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT)
  716. return (int)m_throttleCategories[throttle].RequestedDripRate;
  717. else
  718. return 0;
  719. }
  720. /// <summary>
  721. /// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a
  722. /// flag value
  723. /// </summary>
  724. /// <param name="i">Throttle category to convert</param>
  725. /// <returns>Flag representation of the throttle category</returns>
  726. private static ThrottleOutPacketTypeFlags CategoryToFlag(int i)
  727. {
  728. ThrottleOutPacketType category = (ThrottleOutPacketType)i;
  729. /*
  730. * Land = 1,
  731. /// <summary>Wind data</summary>
  732. Wind = 2,
  733. /// <summary>Cloud data</summary>
  734. Cloud = 3,
  735. /// <summary>Any packets that do not fit into the other throttles</summary>
  736. Task = 4,
  737. /// <summary>Texture assets</summary>
  738. Texture = 5,
  739. /// <summary>Non-texture assets</summary>
  740. Asset = 6,
  741. */
  742. switch (category)
  743. {
  744. case ThrottleOutPacketType.Land:
  745. return ThrottleOutPacketTypeFlags.Land;
  746. case ThrottleOutPacketType.Wind:
  747. return ThrottleOutPacketTypeFlags.Wind;
  748. case ThrottleOutPacketType.Cloud:
  749. return ThrottleOutPacketTypeFlags.Cloud;
  750. case ThrottleOutPacketType.Task:
  751. return ThrottleOutPacketTypeFlags.Task;
  752. case ThrottleOutPacketType.Texture:
  753. return ThrottleOutPacketTypeFlags.Texture;
  754. case ThrottleOutPacketType.Asset:
  755. return ThrottleOutPacketTypeFlags.Asset;
  756. default:
  757. return 0;
  758. }
  759. }
  760. }
  761. public class DoubleLocklessQueue<T> : OpenSim.Framework.LocklessQueue<T>
  762. {
  763. OpenSim.Framework.LocklessQueue<T> highQueue = new OpenSim.Framework.LocklessQueue<T>();
  764. public override int Count
  765. {
  766. get
  767. {
  768. return base.Count + highQueue.Count;
  769. }
  770. }
  771. public override bool Dequeue(out T item)
  772. {
  773. if (highQueue.Dequeue(out item))
  774. return true;
  775. return base.Dequeue(out item);
  776. }
  777. public void Enqueue(T item, bool highPriority)
  778. {
  779. if (highPriority)
  780. highQueue.Enqueue(item);
  781. else
  782. Enqueue(item);
  783. }
  784. }
  785. }