UtilityExtension.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Diagnostics;
  7. using System.Runtime;
  8. using System.ServiceModel;
  9. using System.ServiceModel.Description;
  10. using System.Threading;
  11. class UtilityExtension : IExtension<IPeerNeighbor>
  12. {
  13. uint linkUtility;
  14. uint updateCount;
  15. IOThreadTimer ackTimer;
  16. const uint linkUtilityIncrement = 128;
  17. const uint maxLinkUtility = 4096;
  18. int outTotal;
  19. uint inTotal;
  20. uint inUseful;
  21. IPeerNeighbor owner;
  22. object thisLock = new object();
  23. object throttleLock = new object();
  24. public event EventHandler UtilityInfoReceived;
  25. public event EventHandler UtilityInfoSent;
  26. TypedMessageConverter messageConverter;
  27. public const int AcceptableMissDistance = 2;
  28. int pendingSends = 0;
  29. int checkPointPendingSends = 0;
  30. bool isMonitoring = false;
  31. int expectedClearance;
  32. IOThreadTimer pruneTimer;
  33. const int PruneIntervalMilliseconds = 10000;
  34. TimeSpan pruneInterval;
  35. const int MinimumPendingMessages = 8;
  36. public delegate void PruneNeighborCallback(IPeerNeighbor peer);
  37. PruneNeighborCallback pruneNeighbor;
  38. UtilityExtension()
  39. {
  40. ackTimer = new IOThreadTimer(new Action<object>(AcknowledgeLoop), null, false);
  41. pendingSends = 0;
  42. pruneTimer = new IOThreadTimer(new Action<object>(VerifyCheckPoint), null, false);
  43. pruneInterval = TimeSpan.FromMilliseconds(PruneIntervalMilliseconds + new Random(Process.GetCurrentProcess().Id).Next(PruneIntervalMilliseconds));
  44. }
  45. public bool IsAccurate
  46. {
  47. get { return updateCount >= 32; }
  48. }
  49. public uint LinkUtility
  50. {
  51. get
  52. {
  53. return linkUtility;
  54. }
  55. }
  56. internal TypedMessageConverter MessageConverter
  57. {
  58. get
  59. {
  60. if (messageConverter == null)
  61. {
  62. messageConverter = TypedMessageConverter.Create(typeof(UtilityInfo), PeerStrings.LinkUtilityAction);
  63. }
  64. return messageConverter;
  65. }
  66. }
  67. public void Attach(IPeerNeighbor host)
  68. {
  69. this.owner = host;
  70. ackTimer.Set(PeerTransportConstants.AckTimeout);
  71. }
  72. static public void OnNeighborConnected(IPeerNeighbor neighbor)
  73. {
  74. Fx.Assert(neighbor != null, "Neighbor must have a value");
  75. neighbor.Extensions.Add(new UtilityExtension());
  76. }
  77. static public void OnNeighborClosed(IPeerNeighbor neighbor)
  78. {
  79. Fx.Assert(neighbor != null, "Neighbor must have a value");
  80. UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
  81. if (ext != null) neighbor.Extensions.Remove(ext);
  82. }
  83. public void Detach(IPeerNeighbor host)
  84. {
  85. ackTimer.Cancel();
  86. owner = null;
  87. lock (throttleLock)
  88. {
  89. pruneTimer.Cancel();
  90. }
  91. }
  92. public object ThisLock
  93. {
  94. get
  95. {
  96. return thisLock;
  97. }
  98. }
  99. public static void OnMessageSent(IPeerNeighbor neighbor)
  100. {
  101. UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
  102. if (ext != null) ext.OnMessageSent();
  103. }
  104. void OnMessageSent()
  105. {
  106. lock (ThisLock)
  107. {
  108. outTotal++;
  109. }
  110. Interlocked.Increment(ref pendingSends);
  111. }
  112. public static void OnEndSend(IPeerNeighbor neighbor, FloodAsyncResult fresult)
  113. {
  114. if (neighbor.State >= PeerNeighborState.Disconnecting)
  115. return;
  116. UtilityExtension instance = neighbor.Utility;
  117. if (instance == null)
  118. return;
  119. instance.OnEndSend(fresult);
  120. }
  121. public void OnEndSend(FloodAsyncResult fresult)
  122. {
  123. Interlocked.Decrement(ref pendingSends);
  124. }
  125. void AcknowledgeLoop(object state)
  126. {
  127. IPeerNeighbor peer = owner;
  128. if (peer == null || !peer.IsConnected)
  129. return;
  130. FlushAcknowledge();
  131. if (owner != null)
  132. ackTimer.Set(PeerTransportConstants.AckTimeout);
  133. }
  134. static public void ProcessLinkUtility(IPeerNeighbor neighbor, UtilityInfo umessage)
  135. {
  136. Fx.Assert(neighbor != null, "Neighbor must have a value");
  137. UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
  138. if (ext != null)
  139. {
  140. ext.ProcessLinkUtility(umessage.Useful, umessage.Total);
  141. }
  142. }
  143. // Update link utility for the neighbor. received from the neighbor
  144. void ProcessLinkUtility(uint useful, uint total)
  145. {
  146. uint i = 0;
  147. lock (ThisLock)
  148. {
  149. if (total > PeerTransportConstants.AckWindow
  150. || useful > total
  151. || (uint)outTotal < total
  152. )
  153. {
  154. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.PeerLinkUtilityInvalidValues, useful, total)));
  155. }
  156. //VERIFY with in this range, we are hoping that the order of useful/useless messages doesnt matter much.
  157. for (i = 0; i < useful; i++)
  158. {
  159. this.linkUtility = Calculate(this.linkUtility, true);
  160. }
  161. for (; i < total; i++)
  162. {
  163. this.linkUtility = Calculate(this.linkUtility, false);
  164. }
  165. outTotal -= (int)total;
  166. }
  167. if (UtilityInfoReceived != null)
  168. {
  169. UtilityInfoReceived(this, EventArgs.Empty);
  170. }
  171. }
  172. uint Calculate(uint current, bool increase)
  173. {
  174. uint utility = 0;
  175. // Refer to graph maintenance white paper for explanation of the formula
  176. // used to compute utility index.
  177. utility = (uint)current * 31 / 32;
  178. if (increase)
  179. utility += linkUtilityIncrement;
  180. if (!(utility <= maxLinkUtility))
  181. {
  182. throw Fx.AssertAndThrow("Link utility should not exceed " + maxLinkUtility);
  183. }
  184. if (!IsAccurate)
  185. ++updateCount;
  186. return utility;
  187. }
  188. public static uint UpdateLinkUtility(IPeerNeighbor neighbor, bool useful)
  189. {
  190. Fx.Assert(neighbor != null, "Neighbor must have a value");
  191. uint linkUtility = 0;
  192. UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
  193. if (ext != null)
  194. {
  195. // Can happen if the neighbor has been closed for instance
  196. linkUtility = ext.UpdateLinkUtility(useful);
  197. }
  198. return linkUtility;
  199. }
  200. public uint UpdateLinkUtility(bool useful)
  201. {
  202. lock (ThisLock)
  203. {
  204. inTotal++;
  205. if (useful)
  206. inUseful++;
  207. linkUtility = Calculate(linkUtility, useful);
  208. if (inTotal == PeerTransportConstants.AckWindow)
  209. {
  210. FlushAcknowledge();
  211. }
  212. }
  213. return linkUtility;
  214. }
  215. public void FlushAcknowledge()
  216. {
  217. if (inTotal == 0)
  218. return;
  219. uint tempUseful = 0, tempTotal = 0;
  220. lock (ThisLock)
  221. {
  222. tempUseful = inUseful;
  223. tempTotal = inTotal;
  224. inUseful = 0;
  225. inTotal = 0;
  226. }
  227. SendUtilityMessage(tempUseful, tempTotal);
  228. }
  229. class AsyncUtilityState
  230. {
  231. public Message message;
  232. public UtilityInfo info;
  233. public AsyncUtilityState(Message message, UtilityInfo info)
  234. {
  235. this.message = message;
  236. this.info = info;
  237. }
  238. }
  239. void SendUtilityMessage(uint useful, uint total)
  240. {
  241. IPeerNeighbor host = owner;
  242. if (host == null || !PeerNeighborStateHelper.IsConnected(host.State) || total == 0)
  243. return;
  244. UtilityInfo umessage = new UtilityInfo(useful, total);
  245. IAsyncResult result = null;
  246. Message message = MessageConverter.ToMessage(umessage, MessageVersion.Soap12WSAddressing10);
  247. bool fatal = false;
  248. try
  249. {
  250. result = host.BeginSend(message, Fx.ThunkCallback(new AsyncCallback(UtilityMessageSent)), new AsyncUtilityState(message, umessage));
  251. if (result.CompletedSynchronously)
  252. {
  253. host.EndSend(result);
  254. EventHandler handler = UtilityInfoSent;
  255. if (handler != null)
  256. handler(this, EventArgs.Empty);
  257. }
  258. }
  259. catch (Exception e)
  260. {
  261. if (Fx.IsFatal(e))
  262. {
  263. fatal = true;
  264. throw;
  265. }
  266. if (null != HandleSendException(host, e, umessage))
  267. throw;
  268. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  269. }
  270. finally
  271. {
  272. if (!fatal && (result == null || result.CompletedSynchronously))
  273. message.Close();
  274. }
  275. }
  276. void UtilityMessageSent(IAsyncResult result)
  277. {
  278. if (result == null || result.AsyncState == null)
  279. return;
  280. IPeerNeighbor host = this.owner;
  281. if (host == null || !PeerNeighborStateHelper.IsConnected(host.State))
  282. return;
  283. if (result.CompletedSynchronously)
  284. return;
  285. AsyncUtilityState state = (AsyncUtilityState)result.AsyncState;
  286. Fx.Assert(state != null, "IAsyncResult.AsyncState does not contain AsyncUtilityState");
  287. Message message = state.message;
  288. UtilityInfo umessage = state.info;
  289. bool fatal = false;
  290. if (!(umessage != null))
  291. {
  292. throw Fx.AssertAndThrow("expecting a UtilityInfo message in the AsyncState!");
  293. }
  294. try
  295. {
  296. host.EndSend(result);
  297. }
  298. catch (Exception e)
  299. {
  300. if (Fx.IsFatal(e))
  301. {
  302. fatal = true;
  303. throw;
  304. }
  305. if (null != HandleSendException(host, e, umessage))
  306. throw;
  307. DiagnosticUtility.TraceHandledException(e, TraceEventType.Information);
  308. }
  309. finally
  310. {
  311. if (!fatal)
  312. {
  313. Fx.Assert(!result.CompletedSynchronously, "result.CompletedSynchronously");
  314. message.Close();
  315. }
  316. }
  317. EventHandler handler = UtilityInfoSent;
  318. if (handler != null)
  319. handler(this, EventArgs.Empty);
  320. }
  321. Exception HandleSendException(IPeerNeighbor host, Exception e, UtilityInfo umessage)
  322. {
  323. if ((e is ObjectDisposedException) ||
  324. (e is TimeoutException) ||
  325. (e is CommunicationException))
  326. {
  327. if (!(!(e.InnerException is QuotaExceededException)))
  328. {
  329. throw Fx.AssertAndThrow("insufficient quota for sending messages!");
  330. }
  331. lock (ThisLock)
  332. {
  333. this.inTotal += umessage.Total;
  334. this.inUseful += umessage.Useful;
  335. }
  336. return null;
  337. }
  338. else
  339. {
  340. return e;
  341. }
  342. }
  343. static internal void ReportCacheMiss(IPeerNeighbor neighbor, int missedBy)
  344. {
  345. Fx.Assert(missedBy > AcceptableMissDistance, "Call this method for cache misses ONLY!");
  346. Fx.Assert(neighbor != null, "Neighbor must have a value");
  347. if (!neighbor.IsConnected)
  348. return;
  349. UtilityExtension ext = neighbor.Extensions.Find<UtilityExtension>();
  350. if (ext != null)
  351. {
  352. ext.ReportCacheMiss(missedBy);
  353. }
  354. }
  355. void ReportCacheMiss(int missedBy)
  356. {
  357. lock (ThisLock)
  358. {
  359. for (int i = 0; i < missedBy; i++)
  360. {
  361. this.linkUtility = Calculate(this.linkUtility, false);
  362. }
  363. }
  364. }
  365. public int PendingMessages
  366. {
  367. get
  368. {
  369. return this.pendingSends;
  370. }
  371. }
  372. public void BeginCheckPoint(PruneNeighborCallback pruneCallback)
  373. {
  374. if (this.isMonitoring)
  375. return;
  376. lock (throttleLock)
  377. {
  378. if (this.isMonitoring)
  379. return;
  380. this.checkPointPendingSends = this.pendingSends;
  381. this.pruneNeighbor = pruneCallback;
  382. this.expectedClearance = this.pendingSends / 2;
  383. this.isMonitoring = true;
  384. if (owner == null)
  385. return;
  386. pruneTimer.Set(pruneInterval);
  387. }
  388. }
  389. void VerifyCheckPoint(object state)
  390. {
  391. int lclPendingSends;
  392. int lclCheckPointPendingSends;
  393. IPeerNeighbor peer = (IPeerNeighbor)owner;
  394. if (peer == null || !peer.IsConnected)
  395. return;
  396. lock (throttleLock)
  397. {
  398. lclPendingSends = this.pendingSends;
  399. lclCheckPointPendingSends = this.checkPointPendingSends;
  400. }
  401. if (lclPendingSends <= MinimumPendingMessages)
  402. {
  403. lock (throttleLock)
  404. {
  405. isMonitoring = false;
  406. }
  407. }
  408. else if (lclPendingSends + this.expectedClearance >= lclCheckPointPendingSends)
  409. {
  410. pruneNeighbor(peer);
  411. }
  412. else
  413. {
  414. lock (throttleLock)
  415. {
  416. if (owner == null)
  417. return;
  418. this.checkPointPendingSends = this.pendingSends;
  419. this.expectedClearance = this.expectedClearance / 2;
  420. pruneTimer.Set(pruneInterval);
  421. }
  422. }
  423. }
  424. }
  425. }