PacketQueue.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 OpenSim 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. */
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Threading;
  31. using System.Timers;
  32. using libsecondlife.Packets;
  33. using OpenSim.Framework;
  34. using Timer=System.Timers.Timer;
  35. namespace OpenSim.Region.ClientStack
  36. {
  37. public class PacketQueue
  38. {
  39. private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  40. private bool m_enabled = true;
  41. private BlockingQueue<QueItem> SendQueue;
  42. private Queue<QueItem> IncomingPacketQueue;
  43. private Queue<QueItem> OutgoingPacketQueue;
  44. private Queue<QueItem> ResendOutgoingPacketQueue;
  45. private Queue<QueItem> LandOutgoingPacketQueue;
  46. private Queue<QueItem> WindOutgoingPacketQueue;
  47. private Queue<QueItem> CloudOutgoingPacketQueue;
  48. private Queue<QueItem> TaskOutgoingPacketQueue;
  49. private Queue<QueItem> TextureOutgoingPacketQueue;
  50. private Queue<QueItem> AssetOutgoingPacketQueue;
  51. private Dictionary<uint, uint> PendingAcks = new Dictionary<uint, uint>();
  52. private Dictionary<uint, Packet> NeedAck = new Dictionary<uint, Packet>();
  53. // All throttle times and number of bytes are calculated by dividing by this value
  54. // This value also determines how many times per throttletimems the timer will run
  55. // If throttleimems is 1000 ms, then the timer will fire every 1000/7 milliseconds
  56. private int throttleTimeDivisor = 7;
  57. private int throttletimems = 1000;
  58. private PacketThrottle ResendThrottle;
  59. private PacketThrottle LandThrottle;
  60. private PacketThrottle WindThrottle;
  61. private PacketThrottle CloudThrottle;
  62. private PacketThrottle TaskThrottle;
  63. private PacketThrottle AssetThrottle;
  64. private PacketThrottle TextureThrottle;
  65. private PacketThrottle TotalThrottle;
  66. // private long LastThrottle;
  67. // private long ThrottleInterval;
  68. private Timer throttleTimer;
  69. public PacketQueue()
  70. {
  71. // While working on this, the BlockingQueue had me fooled for a bit.
  72. // The Blocking queue causes the thread to stop until there's something
  73. // in it to process. it's an on-purpose threadlock though because
  74. // without it, the clientloop will suck up all sim resources.
  75. SendQueue = new BlockingQueue<QueItem>();
  76. IncomingPacketQueue = new Queue<QueItem>();
  77. OutgoingPacketQueue = new Queue<QueItem>();
  78. ResendOutgoingPacketQueue = new Queue<QueItem>();
  79. LandOutgoingPacketQueue = new Queue<QueItem>();
  80. WindOutgoingPacketQueue = new Queue<QueItem>();
  81. CloudOutgoingPacketQueue = new Queue<QueItem>();
  82. TaskOutgoingPacketQueue = new Queue<QueItem>();
  83. TextureOutgoingPacketQueue = new Queue<QueItem>();
  84. AssetOutgoingPacketQueue = new Queue<QueItem>();
  85. // Set up the throttle classes (min, max, current) in bytes
  86. ResendThrottle = new PacketThrottle(5000, 100000, 50000);
  87. LandThrottle = new PacketThrottle(1000, 100000, 100000);
  88. WindThrottle = new PacketThrottle(1000, 100000, 10000);
  89. CloudThrottle = new PacketThrottle(1000, 100000, 50000);
  90. TaskThrottle = new PacketThrottle(1000, 800000, 100000);
  91. AssetThrottle = new PacketThrottle(1000, 800000, 80000);
  92. TextureThrottle = new PacketThrottle(1000, 800000, 100000);
  93. // Total Throttle trumps all
  94. // Number of bytes allowed to go out per second. (256kbps per client)
  95. TotalThrottle = new PacketThrottle(0, 162144, 1536000);
  96. throttleTimer = new Timer((int) (throttletimems/throttleTimeDivisor));
  97. throttleTimer.Elapsed += new ElapsedEventHandler(ThrottleTimerElapsed);
  98. throttleTimer.Start();
  99. // TIMERS needed for this
  100. // LastThrottle = DateTime.Now.Ticks;
  101. // ThrottleInterval = (long)(throttletimems/throttleTimeDivisor);
  102. }
  103. /* STANDARD QUEUE MANIPULATION INTERFACES */
  104. public void Enqueue(QueItem item)
  105. {
  106. if (!m_enabled)
  107. {
  108. return;
  109. }
  110. // We could micro lock, but that will tend to actually
  111. // probably be worse than just synchronizing on SendQueue
  112. lock (this)
  113. {
  114. switch (item.throttleType)
  115. {
  116. case ThrottleOutPacketType.Resend:
  117. ThrottleCheck(ref ResendThrottle, ref ResendOutgoingPacketQueue, item);
  118. break;
  119. case ThrottleOutPacketType.Texture:
  120. ThrottleCheck(ref TextureThrottle, ref TextureOutgoingPacketQueue, item);
  121. break;
  122. case ThrottleOutPacketType.Task:
  123. ThrottleCheck(ref TaskThrottle, ref TaskOutgoingPacketQueue, item);
  124. break;
  125. case ThrottleOutPacketType.Land:
  126. ThrottleCheck(ref LandThrottle, ref LandOutgoingPacketQueue, item);
  127. break;
  128. case ThrottleOutPacketType.Asset:
  129. ThrottleCheck(ref AssetThrottle, ref AssetOutgoingPacketQueue, item);
  130. break;
  131. case ThrottleOutPacketType.Cloud:
  132. ThrottleCheck(ref CloudThrottle, ref CloudOutgoingPacketQueue, item);
  133. break;
  134. case ThrottleOutPacketType.Wind:
  135. ThrottleCheck(ref WindThrottle, ref WindOutgoingPacketQueue, item);
  136. break;
  137. default:
  138. // Acknowledgements and other such stuff should go directly to the blocking Queue
  139. // Throttling them may and likely 'will' be problematic
  140. SendQueue.Enqueue(item);
  141. break;
  142. }
  143. }
  144. }
  145. public QueItem Dequeue()
  146. {
  147. return SendQueue.Dequeue();
  148. }
  149. public void Flush()
  150. {
  151. lock (this)
  152. {
  153. while (PacketsWaiting())
  154. {
  155. //Now comes the fun part.. we dump all our elements into m_packetQueue that we've saved up.
  156. if (ResendOutgoingPacketQueue.Count > 0)
  157. {
  158. SendQueue.Enqueue(ResendOutgoingPacketQueue.Dequeue());
  159. }
  160. if (LandOutgoingPacketQueue.Count > 0)
  161. {
  162. SendQueue.Enqueue(LandOutgoingPacketQueue.Dequeue());
  163. }
  164. if (WindOutgoingPacketQueue.Count > 0)
  165. {
  166. SendQueue.Enqueue(WindOutgoingPacketQueue.Dequeue());
  167. }
  168. if (CloudOutgoingPacketQueue.Count > 0)
  169. {
  170. SendQueue.Enqueue(CloudOutgoingPacketQueue.Dequeue());
  171. }
  172. if (TaskOutgoingPacketQueue.Count > 0)
  173. {
  174. SendQueue.Enqueue(TaskOutgoingPacketQueue.Dequeue());
  175. }
  176. if (TextureOutgoingPacketQueue.Count > 0)
  177. {
  178. SendQueue.Enqueue(TextureOutgoingPacketQueue.Dequeue());
  179. }
  180. if (AssetOutgoingPacketQueue.Count > 0)
  181. {
  182. SendQueue.Enqueue(AssetOutgoingPacketQueue.Dequeue());
  183. }
  184. }
  185. // m_log.Info("[THROTTLE]: Processed " + throttleLoops + " packets");
  186. }
  187. }
  188. public void Close()
  189. {
  190. m_enabled = false;
  191. throttleTimer.Stop();
  192. }
  193. private void ResetCounters()
  194. {
  195. ResendThrottle.Reset();
  196. LandThrottle.Reset();
  197. WindThrottle.Reset();
  198. CloudThrottle.Reset();
  199. TaskThrottle.Reset();
  200. AssetThrottle.Reset();
  201. TextureThrottle.Reset();
  202. TotalThrottle.Reset();
  203. }
  204. private bool PacketsWaiting()
  205. {
  206. return (ResendOutgoingPacketQueue.Count > 0 ||
  207. LandOutgoingPacketQueue.Count > 0 ||
  208. WindOutgoingPacketQueue.Count > 0 ||
  209. CloudOutgoingPacketQueue.Count > 0 ||
  210. TaskOutgoingPacketQueue.Count > 0 ||
  211. AssetOutgoingPacketQueue.Count > 0 ||
  212. TextureOutgoingPacketQueue.Count > 0);
  213. }
  214. public void ProcessThrottle()
  215. {
  216. // I was considering this.. Will an event fire if the thread it's on is blocked?
  217. // Then I figured out.. it doesn't really matter.. because this thread won't be blocked for long
  218. // The General overhead of the UDP protocol gets sent to the queue un-throttled by this
  219. // so This'll pick up about around the right time.
  220. int MaxThrottleLoops = 4550; // 50*7 packets can be dequeued at once.
  221. int throttleLoops = 0;
  222. // We're going to dequeue all of the saved up packets until
  223. // we've hit the throttle limit or there's no more packets to send
  224. lock (this)
  225. {
  226. ResetCounters();
  227. // m_log.Info("[THROTTLE]: Entering Throttle");
  228. while (TotalThrottle.UnderLimit() && PacketsWaiting() &&
  229. (throttleLoops <= MaxThrottleLoops))
  230. {
  231. throttleLoops++;
  232. //Now comes the fun part.. we dump all our elements into m_packetQueue that we've saved up.
  233. if (ResendThrottle.UnderLimit() && ResendOutgoingPacketQueue.Count > 0)
  234. {
  235. QueItem qpack = ResendOutgoingPacketQueue.Dequeue();
  236. SendQueue.Enqueue(qpack);
  237. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  238. ResendThrottle.Add(qpack.Packet.ToBytes().Length);
  239. }
  240. if (LandThrottle.UnderLimit() && LandOutgoingPacketQueue.Count > 0)
  241. {
  242. QueItem qpack = LandOutgoingPacketQueue.Dequeue();
  243. SendQueue.Enqueue(qpack);
  244. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  245. LandThrottle.Add(qpack.Packet.ToBytes().Length);
  246. }
  247. if (WindThrottle.UnderLimit() && WindOutgoingPacketQueue.Count > 0)
  248. {
  249. QueItem qpack = WindOutgoingPacketQueue.Dequeue();
  250. SendQueue.Enqueue(qpack);
  251. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  252. WindThrottle.Add(qpack.Packet.ToBytes().Length);
  253. }
  254. if (CloudThrottle.UnderLimit() && CloudOutgoingPacketQueue.Count > 0)
  255. {
  256. QueItem qpack = CloudOutgoingPacketQueue.Dequeue();
  257. SendQueue.Enqueue(qpack);
  258. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  259. CloudThrottle.Add(qpack.Packet.ToBytes().Length);
  260. }
  261. if (TaskThrottle.UnderLimit() && TaskOutgoingPacketQueue.Count > 0)
  262. {
  263. QueItem qpack = TaskOutgoingPacketQueue.Dequeue();
  264. SendQueue.Enqueue(qpack);
  265. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  266. TaskThrottle.Add(qpack.Packet.ToBytes().Length);
  267. }
  268. if (TextureThrottle.UnderLimit() && TextureOutgoingPacketQueue.Count > 0)
  269. {
  270. QueItem qpack = TextureOutgoingPacketQueue.Dequeue();
  271. SendQueue.Enqueue(qpack);
  272. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  273. TextureThrottle.Add(qpack.Packet.ToBytes().Length);
  274. }
  275. if (AssetThrottle.UnderLimit() && AssetOutgoingPacketQueue.Count > 0)
  276. {
  277. QueItem qpack = AssetOutgoingPacketQueue.Dequeue();
  278. SendQueue.Enqueue(qpack);
  279. TotalThrottle.Add(qpack.Packet.ToBytes().Length);
  280. AssetThrottle.Add(qpack.Packet.ToBytes().Length);
  281. }
  282. }
  283. // m_log.Info("[THROTTLE]: Processed " + throttleLoops + " packets");
  284. }
  285. }
  286. private void ThrottleTimerElapsed(object sender, ElapsedEventArgs e)
  287. {
  288. // just to change the signature, and that ProcessThrottle
  289. // will be used elsewhere possibly
  290. ProcessThrottle();
  291. }
  292. private void ThrottleCheck(ref PacketThrottle throttle, ref Queue<QueItem> q, QueItem item)
  293. {
  294. // The idea.. is if the packet throttle queues are empty
  295. // and the client is under throttle for the type. Queue
  296. // it up directly. This basically short cuts having to
  297. // wait for the timer to fire to put things into the
  298. // output queue
  299. if ((q.Count == 0) && (throttle.UnderLimit()))
  300. {
  301. Monitor.Enter(this);
  302. throttle.Add(item.Packet.ToBytes().Length);
  303. TotalThrottle.Add(item.Packet.ToBytes().Length);
  304. SendQueue.Enqueue(item);
  305. Monitor.Pulse(this);
  306. Monitor.Exit(this);
  307. }
  308. else
  309. {
  310. q.Enqueue(item);
  311. }
  312. }
  313. private int ScaleThrottle(int value, int curmax, int newmax)
  314. {
  315. return (int) (((float) value/(float) curmax)*newmax);
  316. }
  317. public byte[] GetThrottlesPacked(float multiplier)
  318. {
  319. int singlefloat = 4;
  320. float tResend = ResendThrottle.Throttle*multiplier;
  321. float tLand = LandThrottle.Throttle*multiplier;
  322. float tWind = WindThrottle.Throttle*multiplier;
  323. float tCloud = CloudThrottle.Throttle*multiplier;
  324. float tTask = TaskThrottle.Throttle*multiplier;
  325. float tTexture = TextureThrottle.Throttle*multiplier;
  326. float tAsset = AssetThrottle.Throttle*multiplier;
  327. byte[] throttles = new byte[singlefloat*7];
  328. int i = 0;
  329. Buffer.BlockCopy(BitConverter.GetBytes(tResend), 0, throttles, singlefloat*i, singlefloat);
  330. i++;
  331. Buffer.BlockCopy(BitConverter.GetBytes(tLand), 0, throttles, singlefloat*i, singlefloat);
  332. i++;
  333. Buffer.BlockCopy(BitConverter.GetBytes(tWind), 0, throttles, singlefloat*i, singlefloat);
  334. i++;
  335. Buffer.BlockCopy(BitConverter.GetBytes(tCloud), 0, throttles, singlefloat*i, singlefloat);
  336. i++;
  337. Buffer.BlockCopy(BitConverter.GetBytes(tTask), 0, throttles, singlefloat*i, singlefloat);
  338. i++;
  339. Buffer.BlockCopy(BitConverter.GetBytes(tTexture), 0, throttles, singlefloat*i, singlefloat);
  340. i++;
  341. Buffer.BlockCopy(BitConverter.GetBytes(tAsset), 0, throttles, singlefloat*i, singlefloat);
  342. return throttles;
  343. }
  344. public void SetThrottleFromClient(byte[] throttle)
  345. {
  346. int tResend = -1;
  347. int tLand = -1;
  348. int tWind = -1;
  349. int tCloud = -1;
  350. int tTask = -1;
  351. int tTexture = -1;
  352. int tAsset = -1;
  353. int tall = -1;
  354. int singlefloat = 4;
  355. //Agent Throttle Block contains 7 single floatingpoint values.
  356. int j = 0;
  357. // Some Systems may be big endian...
  358. // it might be smart to do this check more often...
  359. if (!BitConverter.IsLittleEndian)
  360. for (int i = 0; i < 7; i++)
  361. Array.Reverse(throttle, j + i*singlefloat, singlefloat);
  362. // values gotten from libsecondlife.org/wiki/Throttle. Thanks MW_
  363. // bytes
  364. // Convert to integer, since.. the full fp space isn't used.
  365. tResend = (int) BitConverter.ToSingle(throttle, j);
  366. j += singlefloat;
  367. tLand = (int) BitConverter.ToSingle(throttle, j);
  368. j += singlefloat;
  369. tWind = (int) BitConverter.ToSingle(throttle, j);
  370. j += singlefloat;
  371. tCloud = (int) BitConverter.ToSingle(throttle, j);
  372. j += singlefloat;
  373. tTask = (int) BitConverter.ToSingle(throttle, j);
  374. j += singlefloat;
  375. tTexture = (int) BitConverter.ToSingle(throttle, j);
  376. j += singlefloat;
  377. tAsset = (int) BitConverter.ToSingle(throttle, j);
  378. tall = tResend + tLand + tWind + tCloud + tTask + tTexture + tAsset;
  379. /*
  380. m_log.Info("[CLIENT]: Client AgentThrottle - Got throttle:resendbytes=" + tResend +
  381. " landbytes=" + tLand +
  382. " windbytes=" + tWind +
  383. " cloudbytes=" + tCloud +
  384. " taskbytes=" + tTask +
  385. " texturebytes=" + tTexture +
  386. " Assetbytes=" + tAsset +
  387. " Allbytes=" + tall);
  388. */
  389. // Total Sanity
  390. // Make sure that the client sent sane total values.
  391. // If the client didn't send acceptable values....
  392. // Scale the clients values down until they are acceptable.
  393. if (tall <= TotalThrottle.Max)
  394. {
  395. ResendThrottle.Throttle = tResend;
  396. LandThrottle.Throttle = tLand;
  397. WindThrottle.Throttle = tWind;
  398. CloudThrottle.Throttle = tCloud;
  399. TaskThrottle.Throttle = tTask;
  400. TextureThrottle.Throttle = tTexture;
  401. AssetThrottle.Throttle = tAsset;
  402. TotalThrottle.Throttle = tall;
  403. }
  404. else if (tall < 1)
  405. {
  406. // client is stupid, penalize him by minning everything
  407. ResendThrottle.Throttle = ResendThrottle.Min;
  408. LandThrottle.Throttle = LandThrottle.Min;
  409. WindThrottle.Throttle = WindThrottle.Min;
  410. CloudThrottle.Throttle = CloudThrottle.Min;
  411. TaskThrottle.Throttle = TaskThrottle.Min;
  412. TextureThrottle.Throttle = TextureThrottle.Min;
  413. AssetThrottle.Throttle = AssetThrottle.Min;
  414. TotalThrottle.Throttle = TotalThrottle.Min;
  415. }
  416. else
  417. {
  418. // we're over so figure out percentages and use those
  419. ResendThrottle.Throttle = tResend;
  420. LandThrottle.Throttle = ScaleThrottle(tLand, tall, TotalThrottle.Max);
  421. WindThrottle.Throttle = ScaleThrottle(tWind, tall, TotalThrottle.Max);
  422. CloudThrottle.Throttle = ScaleThrottle(tCloud, tall, TotalThrottle.Max);
  423. TaskThrottle.Throttle = ScaleThrottle(tTask, tall, TotalThrottle.Max);
  424. TextureThrottle.Throttle = ScaleThrottle(tTexture, tall, TotalThrottle.Max);
  425. AssetThrottle.Throttle = ScaleThrottle(tAsset, tall, TotalThrottle.Max);
  426. TotalThrottle.Throttle = TotalThrottle.Max;
  427. }
  428. // effectively wiggling the slider causes things reset
  429. ResetCounters();
  430. }
  431. }
  432. }