LLUDPClient.cs 38 KB

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