2
0

MsmqSubqueueLockingQueue.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Globalization;
  7. using System.Collections.Generic;
  8. using System.EnterpriseServices;
  9. using System.Runtime;
  10. using System.Runtime.InteropServices;
  11. using System.Threading;
  12. using System.ServiceModel.Diagnostics;
  13. using System.Transactions;
  14. class MsmqSubqueueLockingQueue : MsmqQueue, ILockingQueue
  15. {
  16. string lockQueueName;
  17. MsmqQueue mainQueueForMove;
  18. MsmqQueue lockQueueForMove;
  19. MsmqQueue lockQueueForReceive;
  20. IOThreadTimer lockCollectionTimer;
  21. TimeSpan lockCollectionInterval = TimeSpan.FromMinutes(5);
  22. object timerLock = new object();
  23. bool disposed;
  24. string hostname;
  25. bool validHostName;
  26. private const string LockSubqueuePrefix = "lock_";
  27. public MsmqSubqueueLockingQueue(string formatName, string hostname, int accessMode)
  28. : base(formatName, accessMode)
  29. {
  30. // The hostname will be empty for MsmqIntegrationBinding
  31. if (string.Compare(hostname, string.Empty, StringComparison.OrdinalIgnoreCase) == 0)
  32. {
  33. this.validHostName = MsmqSubqueueLockingQueue.TryGetHostName(formatName, out hostname);
  34. }
  35. else
  36. {
  37. this.validHostName = true;
  38. }
  39. this.disposed = false;
  40. this.lockQueueName = this.formatName + ";" + MsmqSubqueueLockingQueue.GenerateLockQueueName();
  41. this.lockQueueForReceive = new MsmqQueue(this.lockQueueName, UnsafeNativeMethods.MQ_RECEIVE_ACCESS, UnsafeNativeMethods.MQ_DENY_RECEIVE_SHARE);
  42. this.lockQueueForMove = new MsmqQueue(this.lockQueueName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
  43. this.mainQueueForMove = new MsmqQueue(this.formatName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
  44. this.lockCollectionTimer = new IOThreadTimer(new Action<object>(OnCollectionTimer), null, false);
  45. if (string.Compare(hostname, "localhost", StringComparison.OrdinalIgnoreCase) == 0)
  46. {
  47. this.hostname = null;
  48. }
  49. else
  50. {
  51. this.hostname = hostname;
  52. }
  53. }
  54. private static string GenerateLockQueueName()
  55. {
  56. string lockGuid = Guid.NewGuid().ToString();
  57. return MsmqSubqueueLockingQueue.LockSubqueuePrefix + lockGuid.Substring(lockGuid.Length - 8, 8);
  58. }
  59. public MsmqQueue LockQueueForReceive
  60. {
  61. get
  62. {
  63. return this.lockQueueForReceive;
  64. }
  65. }
  66. internal override MsmqQueueHandle OpenQueue()
  67. {
  68. if (!this.validHostName)
  69. {
  70. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqOpenError,
  71. MsmqError.GetErrorString(UnsafeNativeMethods.MQ_ERROR_UNSUPPORTED_FORMATNAME_OPERATION)),
  72. UnsafeNativeMethods.MQ_ERROR_UNSUPPORTED_FORMATNAME_OPERATION));
  73. }
  74. this.EnsureLockQueuesOpen();
  75. this.mainQueueForMove.EnsureOpen();
  76. // first time collection
  77. this.OnCollectionTimer(null);
  78. return base.OpenQueue();
  79. }
  80. internal void EnsureLockQueuesOpen()
  81. {
  82. int attempts = 0;
  83. // handle lock queue name collisions, if we fail three times in a row it is probably not the name
  84. // collision that is causing the open to fail
  85. while (true)
  86. {
  87. try
  88. {
  89. this.lockQueueForReceive.EnsureOpen();
  90. break;
  91. }
  92. catch (MsmqException ex)
  93. {
  94. if (attempts >= 3)
  95. {
  96. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
  97. }
  98. MsmqDiagnostics.ExpectedException(ex);
  99. }
  100. this.lockQueueForReceive.Dispose();
  101. this.lockQueueForMove.Dispose();
  102. this.lockQueueName = this.formatName + ";" + MsmqSubqueueLockingQueue.GenerateLockQueueName();
  103. this.lockQueueForReceive = new MsmqQueue(this.lockQueueName, UnsafeNativeMethods.MQ_RECEIVE_ACCESS, UnsafeNativeMethods.MQ_DENY_RECEIVE_SHARE);
  104. this.lockQueueForMove = new MsmqQueue(this.lockQueueName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
  105. attempts++;
  106. }
  107. this.lockQueueForMove.EnsureOpen();
  108. }
  109. public override ReceiveResult TryReceive(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode)
  110. {
  111. // we ignore transaction mode for receive context receives
  112. TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
  113. bool receivedMessage = false;
  114. long lookupId = 0;
  115. // peek for new message, move it to the lock queue and then receive the full message
  116. // if move fails because another thread moved it ahead of us then peek again
  117. while (!receivedMessage)
  118. {
  119. ReceiveResult result;
  120. MoveReceiveResult moveResult;
  121. using (MsmqMessageLookupId emptyMessage = new MsmqMessageLookupId())
  122. {
  123. result = this.TryPeek(emptyMessage, timeoutHelper.RemainingTime());
  124. if (result != ReceiveResult.MessageReceived)
  125. {
  126. return result;
  127. }
  128. lookupId = emptyMessage.lookupId.Value;
  129. }
  130. try
  131. {
  132. moveResult = this.TryMoveMessage(lookupId, this.lockQueueForMove, MsmqTransactionMode.None);
  133. if (moveResult == MoveReceiveResult.Succeeded)
  134. {
  135. receivedMessage = true;
  136. }
  137. }
  138. catch (MsmqException ex)
  139. {
  140. MsmqDiagnostics.ExpectedException(ex);
  141. }
  142. }
  143. MoveReceiveResult lookupIdReceiveResult;
  144. try
  145. {
  146. lookupIdReceiveResult = this.lockQueueForReceive.TryReceiveByLookupId(lookupId, message, MsmqTransactionMode.None, UnsafeNativeMethods.MQ_LOOKUP_PEEK_CURRENT);
  147. }
  148. catch (MsmqException ex)
  149. {
  150. this.UnlockMessage(lookupId, TimeSpan.Zero);
  151. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex);
  152. }
  153. if (lookupIdReceiveResult == MoveReceiveResult.Succeeded)
  154. {
  155. return ReceiveResult.MessageReceived;
  156. }
  157. else
  158. {
  159. this.UnlockMessage(lookupId, TimeSpan.Zero);
  160. return ReceiveResult.OperationCancelled;
  161. }
  162. }
  163. public void DeleteMessage(long lookupId, TimeSpan timeout)
  164. {
  165. // operations on the lock subqueue need to be protected from ---- with close
  166. MoveReceiveResult receiveResult;
  167. IPostRollbackErrorStrategy postRollBack = new SimplePostRollbackErrorStrategy(lookupId);
  168. do
  169. {
  170. using (MsmqEmptyMessage emptyMessage = new MsmqEmptyMessage())
  171. {
  172. receiveResult = this.lockQueueForReceive.TryReceiveByLookupId(lookupId, emptyMessage, MsmqTransactionMode.CurrentOrNone);
  173. }
  174. if (receiveResult != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
  175. break;
  176. // We could have failed because of ---- with transaction.abort() for the transaction
  177. // that had this message locked previously. We will retry in these cases.
  178. } while (postRollBack.AnotherTryNeeded());
  179. // We could have failed because of
  180. // a) failure in the underlying queue manager
  181. // b) expiration of the native message timer
  182. // c) ---- with Channel.Close()
  183. // ..not much we can do in any of these cases
  184. if (receiveResult != MoveReceiveResult.Succeeded)
  185. {
  186. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveContextMessageNotReceived, lookupId.ToString(CultureInfo.InvariantCulture))));
  187. }
  188. }
  189. public void UnlockMessage(long lookupId, TimeSpan timeout)
  190. {
  191. MoveReceiveResult moveResult;
  192. IPostRollbackErrorStrategy postRollBack = new SimplePostRollbackErrorStrategy(lookupId);
  193. do
  194. {
  195. moveResult = this.lockQueueForReceive.TryMoveMessage(lookupId, this.mainQueueForMove, MsmqTransactionMode.None);
  196. if (moveResult != MsmqQueue.MoveReceiveResult.MessageLockedUnderTransaction)
  197. break;
  198. // We could have failed because of ---- with transaction.abort() for the transaction
  199. // that had this message locked previously. We will retry in these cases.
  200. } while (postRollBack.AnotherTryNeeded());
  201. if (moveResult != MoveReceiveResult.Succeeded)
  202. {
  203. // We could have failed because of
  204. // a) failure in the underlying queue manager
  205. // b) expiration of the native message timer
  206. // c) ---- with Channel.Close()
  207. // ..not much we can do in any of these cases
  208. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveContextMessageNotMoved, lookupId.ToString(CultureInfo.InvariantCulture))));
  209. }
  210. }
  211. public override void CloseQueue()
  212. {
  213. lock (this.timerLock)
  214. {
  215. if (!this.disposed)
  216. {
  217. this.disposed = true;
  218. this.lockCollectionTimer.Cancel();
  219. this.lockCollectionTimer = null;
  220. }
  221. }
  222. this.CollectLocks(this.lockQueueForReceive);
  223. this.mainQueueForMove.CloseQueue();
  224. this.lockQueueForMove.CloseQueue();
  225. this.lockQueueForReceive.CloseQueue();
  226. base.CloseQueue();
  227. }
  228. private void OnCollectionTimer(object state)
  229. {
  230. lock (this.timerLock)
  231. {
  232. if (this.disposed)
  233. {
  234. return;
  235. }
  236. List<string> subqueues;
  237. if (TryEnumerateSubqueues(out subqueues))
  238. {
  239. foreach (string subqueueName in subqueues)
  240. {
  241. if (subqueueName.StartsWith(MsmqSubqueueLockingQueue.LockSubqueuePrefix, StringComparison.OrdinalIgnoreCase))
  242. {
  243. MsmqQueue collectQueue;
  244. if (TryOpenLockQueueForCollection(subqueueName, out collectQueue))
  245. {
  246. this.CollectLocks(collectQueue);
  247. }
  248. }
  249. }
  250. }
  251. this.lockCollectionTimer.Set(this.lockCollectionInterval);
  252. }
  253. }
  254. private bool TryOpenLockQueueForCollection(string subqueueName, out MsmqQueue lockQueue)
  255. {
  256. lockQueue = null;
  257. string formatName = this.formatName + ";" + subqueueName;
  258. int accessMode = UnsafeNativeMethods.MQ_RECEIVE_ACCESS;
  259. int shareMode = UnsafeNativeMethods.MQ_DENY_RECEIVE_SHARE;
  260. try
  261. {
  262. int error = 0;
  263. if (MsmqQueue.IsQueueOpenable(formatName, accessMode, shareMode, out error))
  264. {
  265. lockQueue = new MsmqQueue(formatName, accessMode, shareMode);
  266. lockQueue.EnsureOpen();
  267. }
  268. else
  269. {
  270. // The lock subqueue is either being actively used by a channel or is not available.
  271. // So, we do not have to collect this lock queue.
  272. if (error == UnsafeNativeMethods.MQ_ERROR_SHARING_VIOLATION ||
  273. error == UnsafeNativeMethods.MQ_ERROR_QUEUE_NOT_FOUND)
  274. {
  275. return false;
  276. }
  277. else
  278. {
  279. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqOpenError, MsmqError.GetErrorString(error)), error));
  280. }
  281. }
  282. }
  283. catch (MsmqException)
  284. {
  285. // The error has already been logged. Since this function is to decide whether to collect
  286. // the lock queue, we return false.
  287. return false;
  288. }
  289. return true;
  290. }
  291. private void CollectLocks(MsmqQueue lockQueue)
  292. {
  293. ReceiveResult result = ReceiveResult.MessageReceived;
  294. while (result == ReceiveResult.MessageReceived)
  295. {
  296. using (MsmqMessageLookupId message = new MsmqMessageLookupId())
  297. {
  298. try
  299. {
  300. result = lockQueue.TryPeek(message, TimeSpan.FromSeconds(0));
  301. if (result == ReceiveResult.MessageReceived)
  302. {
  303. lockQueue.TryMoveMessage(message.lookupId.Value, this.mainQueueForMove, MsmqTransactionMode.None);
  304. }
  305. }
  306. catch (MsmqException ex)
  307. {
  308. // we will retry the collection in the next cleanup round
  309. MsmqDiagnostics.ExpectedException(ex);
  310. result = ReceiveResult.Unknown;
  311. }
  312. }
  313. }
  314. }
  315. private bool TryEnumerateSubqueues(out List<String> subqueues)
  316. {
  317. subqueues = new List<string>();
  318. int[] ids = new int[1];
  319. UnsafeNativeMethods.MQMSGPROPS props = new UnsafeNativeMethods.MQMSGPROPS();
  320. UnsafeNativeMethods.MQPROPVARIANT prop = new UnsafeNativeMethods.MQPROPVARIANT();
  321. UnsafeNativeMethods.MQPROPVARIANT retProp;
  322. GCHandle propsHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
  323. GCHandle nativePropertyIdsHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
  324. GCHandle propHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
  325. props.status = IntPtr.Zero;
  326. props.count = 1;
  327. ids[0] = UnsafeNativeMethods.PROPID_MGMT_QUEUE_SUBQUEUE_NAMES;
  328. prop.vt = UnsafeNativeMethods.VT_NULL;
  329. try
  330. {
  331. // pin
  332. propsHandle.Target = props;
  333. nativePropertyIdsHandle.Target = ids;
  334. propHandle.Target = prop;
  335. props.variants = propHandle.AddrOfPinnedObject();
  336. props.ids = nativePropertyIdsHandle.AddrOfPinnedObject();
  337. if (UnsafeNativeMethods.MQMgmtGetInfo(this.hostname, "queue=" + this.formatName, propsHandle.AddrOfPinnedObject()) == 0)
  338. {
  339. retProp = (UnsafeNativeMethods.MQPROPVARIANT)Marshal.PtrToStructure(props.variants, typeof(UnsafeNativeMethods.MQPROPVARIANT));
  340. IntPtr[] stringArrays = new IntPtr[retProp.stringArraysValue.count];
  341. Marshal.Copy(retProp.stringArraysValue.stringArrays, stringArrays, 0, retProp.stringArraysValue.count);
  342. for (int i = 0; i < retProp.stringArraysValue.count; i++)
  343. {
  344. subqueues.Add(Marshal.PtrToStringUni(stringArrays[i]));
  345. UnsafeNativeMethods.MQFreeMemory(stringArrays[i]);
  346. }
  347. UnsafeNativeMethods.MQFreeMemory(retProp.stringArraysValue.stringArrays);
  348. }
  349. else
  350. {
  351. return false;
  352. }
  353. }
  354. finally
  355. {
  356. // unpin
  357. nativePropertyIdsHandle.Target = null;
  358. propsHandle.Target = null;
  359. propHandle.Target = null;
  360. }
  361. return true;
  362. }
  363. private class MsmqMessageLookupId : NativeMsmqMessage
  364. {
  365. public LongProperty lookupId;
  366. public MsmqMessageLookupId()
  367. : base(1)
  368. {
  369. this.lookupId = new LongProperty(this, UnsafeNativeMethods.PROPID_M_LOOKUPID);
  370. }
  371. }
  372. private static bool TryGetHostName(string formatName, out string hostName)
  373. {
  374. string directFormatNamePrefix = "DIRECT=";
  375. string tcpProtocolPrefix = "TCP:";
  376. string osProtocolPrefix = "OS:";
  377. hostName = null;
  378. if (formatName.StartsWith(directFormatNamePrefix, StringComparison.OrdinalIgnoreCase))
  379. {
  380. // The direct format name of the form DIRECT=OS:.\sampleq is parsed here
  381. string formatNameWithProtocol = formatName.Substring(directFormatNamePrefix.Length,
  382. formatName.Length - directFormatNamePrefix.Length);
  383. int addressStartPos = formatNameWithProtocol.IndexOf(':') + 1;
  384. string address = formatNameWithProtocol.Substring(addressStartPos,
  385. formatNameWithProtocol.IndexOf('\\') - addressStartPos);
  386. if (formatNameWithProtocol.StartsWith(tcpProtocolPrefix, StringComparison.OrdinalIgnoreCase))
  387. {
  388. // formatNameWithProtocol is TCP:<tcp-address>\<queue-type>\<queue-name>
  389. hostName = address;
  390. return true;
  391. }
  392. else if (formatNameWithProtocol.StartsWith(osProtocolPrefix, StringComparison.OrdinalIgnoreCase))
  393. {
  394. if (address.Equals("."))
  395. {
  396. // formatNameWithProtocol is OS:.\<queue-type>\<queue-name>
  397. hostName = "localhost";
  398. }
  399. else
  400. {
  401. // formatNameWithProtocol is OS:<machine-name>\<queue-type>\<queue-name>
  402. hostName = address;
  403. }
  404. return true;
  405. }
  406. else
  407. {
  408. // Other protocols not supported. IPX is valid only on NT, w2k
  409. // HTTP/HTTPS: can be used only to send messages. If support changes in future,
  410. // use Dns.GetHostEntry to obtain the IP address
  411. return false;
  412. }
  413. }
  414. else
  415. {
  416. // Other format names are not supported
  417. return false;
  418. }
  419. }
  420. }
  421. }