ChannelDispatcher.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. //
  2. // ChannelDispatcher.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.ObjectModel;
  31. using System.Reflection;
  32. using System.ServiceModel.Channels;
  33. using System.Threading;
  34. using System.Transactions;
  35. using System.ServiceModel;
  36. using System.ServiceModel.Description;
  37. namespace System.ServiceModel.Dispatcher
  38. {
  39. public class ChannelDispatcher : ChannelDispatcherBase
  40. {
  41. ServiceHostBase host;
  42. string binding_name;
  43. Collection<IErrorHandler> error_handlers
  44. = new Collection<IErrorHandler> ();
  45. IChannelListener listener;
  46. IDefaultCommunicationTimeouts timeouts;
  47. MessageVersion message_version;
  48. bool receive_sync, include_exception_detail_in_faults,
  49. manual_addressing, is_tx_receive;
  50. int max_tx_batch_size;
  51. SynchronizedCollection<IChannelInitializer> initializers
  52. = new SynchronizedCollection<IChannelInitializer> ();
  53. IsolationLevel tx_isolation_level;
  54. TimeSpan tx_timeout;
  55. ServiceThrottle throttle;
  56. Guid identifier = Guid.NewGuid ();
  57. ManualResetEvent async_event = new ManualResetEvent (false);
  58. EndpointListenerAsyncResult async_result;
  59. ListenerLoopManager loop_manager;
  60. SynchronizedCollection<EndpointDispatcher> _endpoints;
  61. [MonoTODO ("get binding info from config")]
  62. public ChannelDispatcher (IChannelListener listener)
  63. {
  64. if (listener == null)
  65. throw new ArgumentNullException ("listener");
  66. Init (listener, null, null);
  67. }
  68. public ChannelDispatcher (
  69. IChannelListener listener, string bindingName)
  70. : this (listener, bindingName,
  71. DefaultCommunicationTimeouts.Instance)
  72. {
  73. }
  74. public ChannelDispatcher (
  75. IChannelListener listener, string bindingName,
  76. IDefaultCommunicationTimeouts timeouts)
  77. {
  78. if (listener == null)
  79. throw new ArgumentNullException ("listener");
  80. if (bindingName == null)
  81. throw new ArgumentNullException ("bindingName");
  82. if (timeouts == null)
  83. throw new ArgumentNullException ("timeouts");
  84. Init (listener, bindingName, timeouts);
  85. }
  86. private void Init (IChannelListener listener, string bindingName,
  87. IDefaultCommunicationTimeouts timeouts) {
  88. this.listener = listener;
  89. this.binding_name = bindingName;
  90. this.timeouts = timeouts;
  91. _endpoints = new SynchronizedCollection<EndpointDispatcher> ();
  92. }
  93. public string BindingName {
  94. get { return binding_name; }
  95. }
  96. public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
  97. get { return initializers; }
  98. }
  99. protected internal override TimeSpan DefaultCloseTimeout {
  100. get { return timeouts.CloseTimeout; }
  101. }
  102. protected internal override TimeSpan DefaultOpenTimeout {
  103. get { return timeouts.OpenTimeout; }
  104. }
  105. public Collection<IErrorHandler> ErrorHandlers {
  106. get { return error_handlers; }
  107. }
  108. public SynchronizedCollection<EndpointDispatcher> Endpoints {
  109. get {
  110. return _endpoints;
  111. }
  112. }
  113. [MonoTODO]
  114. public bool IsTransactedAccept {
  115. get { throw new NotImplementedException (); }
  116. }
  117. public bool IsTransactedReceive {
  118. get { return is_tx_receive; }
  119. set { is_tx_receive = value; }
  120. }
  121. public bool ManualAddressing {
  122. get { return manual_addressing; }
  123. set { manual_addressing = value; }
  124. }
  125. public int MaxTransactedBatchSize {
  126. get { return max_tx_batch_size; }
  127. set { max_tx_batch_size = value; }
  128. }
  129. public override ServiceHostBase Host {
  130. get { return host; }
  131. }
  132. public override IChannelListener Listener {
  133. get { return listener; }
  134. }
  135. public MessageVersion MessageVersion {
  136. get { return message_version; }
  137. set { message_version = value; }
  138. }
  139. public bool ReceiveSynchronously {
  140. get { return receive_sync; }
  141. set { receive_sync = value; }
  142. }
  143. public bool IncludeExceptionDetailInFaults {
  144. get { return include_exception_detail_in_faults; }
  145. set { include_exception_detail_in_faults = value; }
  146. }
  147. public ServiceThrottle ServiceThrottle {
  148. get { return throttle; }
  149. set { throttle = value; }
  150. }
  151. public IsolationLevel TransactionIsolationLevel {
  152. get { return tx_isolation_level; }
  153. set { tx_isolation_level = value; }
  154. }
  155. public TimeSpan TransactionTimeout {
  156. get { return tx_timeout; }
  157. set { tx_timeout = value; }
  158. }
  159. protected internal override void Attach (ServiceHostBase host)
  160. {
  161. this.host = host;
  162. }
  163. public override void CloseInput ()
  164. {
  165. if (State == CommunicationState.Closed)
  166. return;
  167. try {
  168. try {
  169. listener.Close ();
  170. } finally {
  171. listener = null;
  172. }
  173. } finally {
  174. if (async_result != null)
  175. async_result.Complete (false);
  176. }
  177. }
  178. protected internal override void Detach (ServiceHostBase host)
  179. {
  180. this.host = null;
  181. }
  182. protected override void OnAbort ()
  183. {
  184. throw new NotImplementedException ();
  185. }
  186. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  187. AsyncCallback callback, object state)
  188. {
  189. async_event.Reset ();
  190. async_result = new CloseAsyncResult (
  191. async_event, identifier, timeout,
  192. callback, state);
  193. return async_result;
  194. }
  195. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  196. AsyncCallback callback, object state)
  197. {
  198. async_event.Reset ();
  199. async_result = new OpenAsyncResult (
  200. async_event, identifier, timeout,
  201. callback, state);
  202. return async_result;
  203. }
  204. protected override void OnClose (TimeSpan timeout)
  205. {
  206. ProcessClose (timeout);
  207. }
  208. protected override void OnClosed ()
  209. {
  210. if (host != null)
  211. host.ChannelDispatchers.Remove (this);
  212. }
  213. protected override void OnEndClose (IAsyncResult result)
  214. {
  215. if (result == null)
  216. throw new ArgumentNullException ("result");
  217. OpenAsyncResult or = result as OpenAsyncResult;
  218. if (or == null)
  219. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  220. CloseInput ();
  221. or.AsyncWaitHandle.WaitOne ();
  222. }
  223. [MonoTODO ("this is not a real async method.")]
  224. protected override void OnEndOpen (IAsyncResult result)
  225. {
  226. if (result == null)
  227. throw new ArgumentNullException ("result");
  228. OpenAsyncResult or = result as OpenAsyncResult;
  229. if (or == null)
  230. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  231. or.AsyncWaitHandle.WaitOne ();
  232. }
  233. protected override void OnOpen (TimeSpan timeout)
  234. {
  235. ProcessOpen (timeout);
  236. }
  237. [MonoTODO ("what to do here?")]
  238. protected override void OnOpening ()
  239. {
  240. }
  241. [MonoTODO ("what to do here?")]
  242. protected override void OnOpened ()
  243. {
  244. }
  245. void ProcessClose (TimeSpan timeout)
  246. {
  247. if (loop_manager != null)
  248. loop_manager.Stop ();
  249. CloseInput ();
  250. }
  251. void ProcessOpen (TimeSpan timeout)
  252. {
  253. if (Host == null || MessageVersion == null)
  254. throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
  255. try {
  256. // FIXME: hack, just to make it runnable
  257. listener.Open (timeout);
  258. loop_manager = new ListenerLoopManager (this);
  259. loop_manager.Start ();
  260. } finally {
  261. if (async_result != null)
  262. async_result.Complete (false);
  263. }
  264. }
  265. bool IsMessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  266. {
  267. Uri to = req.Headers.To;
  268. if (to == null)
  269. return false;
  270. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  271. return false;
  272. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  273. }
  274. void HandleError (Exception ex)
  275. {
  276. foreach (IErrorHandler handler in ErrorHandlers)
  277. if (handler.HandleError (ex))
  278. break;
  279. }
  280. class ListenerLoopManager
  281. {
  282. ChannelDispatcher owner;
  283. AutoResetEvent handle;
  284. IReplyChannel reply;
  285. IInputChannel input;
  286. bool loop;
  287. Thread loop_thread;
  288. public ListenerLoopManager (ChannelDispatcher owner)
  289. {
  290. this.owner = owner;
  291. MethodInfo mi = owner.Listener.GetType ().GetMethod ("AcceptChannel", Type.EmptyTypes);
  292. object channel = mi.Invoke (owner.Listener, new object [0]);
  293. reply = channel as IReplyChannel;
  294. input = channel as IInputChannel;
  295. }
  296. public void Start ()
  297. {
  298. if (loop_thread == null)
  299. loop_thread = new Thread (new ThreadStart (StartLoop));
  300. loop_thread.Start ();
  301. }
  302. public void Stop ()
  303. {
  304. StopLoop ();
  305. owner.Listener.Close ();
  306. if (loop_thread.IsAlive)
  307. loop_thread.Abort ();
  308. loop_thread = null;
  309. }
  310. void StartLoop ()
  311. {
  312. try {
  313. StartLoopCore ();
  314. } catch (ThreadAbortException) {
  315. Thread.ResetAbort ();
  316. }
  317. }
  318. void StartLoopCore ()
  319. {
  320. loop = true;
  321. // FIXME: use async WaitForBlah() method so
  322. // that we can stop them at our own will.
  323. //FIXME: The logic here should be entirely different as follows:
  324. //1. Get the message
  325. //2. Get the appropriate EndPointDispatcher that can handle the message
  326. // which is done using the filters (AddressFilter, ContractFilter).
  327. //3. Let the appropriate endpoint handle the request.
  328. if (reply != null) {
  329. while (loop) {
  330. if (reply.WaitForRequest (owner.timeouts.ReceiveTimeout))
  331. ProcessRequest ();
  332. }
  333. } else if (input != null) {
  334. while (loop) {
  335. if (input.WaitForMessage (owner.timeouts.ReceiveTimeout))
  336. ProcessInput ();
  337. }
  338. }
  339. }
  340. void sendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  341. {
  342. try {
  343. MessageVersion version = rc.RequestMessage.Version;
  344. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  345. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  346. rc.Reply (res);
  347. }
  348. catch (Exception e) { }
  349. }
  350. void ProcessRequest ()
  351. {
  352. RequestContext rc = null;
  353. try {
  354. rc = reply.ReceiveRequest (owner.timeouts.ReceiveTimeout);
  355. if (rc == null)
  356. throw new InvalidOperationException ("The reply channel didn't return RequestContext");
  357. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  358. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply, owner.timeouts).
  359. ProcessReply (rc);
  360. }
  361. catch (EndpointNotFoundException ex) {
  362. sendEndpointNotFound (rc, ex);
  363. }
  364. }
  365. void ProcessInput ()
  366. {
  367. Message message = input.Receive ();
  368. EndpointDispatcher candidate = null;
  369. try {
  370. candidate = FindEndpointDispatcher (message);
  371. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply, owner.timeouts).
  372. ProcessInput(message);
  373. }
  374. catch (EndpointNotFoundException ex) {
  375. // silently ignore
  376. }
  377. }
  378. EndpointDispatcher FindEndpointDispatcher (Message message) {
  379. EndpointDispatcher candidate = null;
  380. for (int i = 0; i < owner.Endpoints.Count; i++) {
  381. if (owner.IsMessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  382. candidate = owner.Endpoints [i];
  383. break;
  384. }
  385. }
  386. if (candidate == null)
  387. throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' which is not reachable in this service contract", message.Headers.To));
  388. return candidate;
  389. }
  390. void StopLoop ()
  391. {
  392. loop = false;
  393. // FIXME: send manual stop for reply or input channel.
  394. }
  395. }
  396. #region AsyncResult classes
  397. class CloseAsyncResult : EndpointListenerAsyncResult
  398. {
  399. public CloseAsyncResult (ManualResetEvent asyncEvent,
  400. Guid identifier, TimeSpan timeout,
  401. AsyncCallback callback, object state)
  402. : base (asyncEvent, identifier, timeout,
  403. callback, state)
  404. {
  405. }
  406. }
  407. class OpenAsyncResult : EndpointListenerAsyncResult
  408. {
  409. public OpenAsyncResult (ManualResetEvent asyncEvent,
  410. Guid identifier, TimeSpan timeout,
  411. AsyncCallback callback, object state)
  412. : base (asyncEvent, identifier, timeout,
  413. callback, state)
  414. {
  415. }
  416. }
  417. abstract class EndpointListenerAsyncResult : IAsyncResult
  418. {
  419. ManualResetEvent async_event;
  420. Guid identifier;
  421. TimeSpan timeout;
  422. AsyncCallback callback;
  423. object state;
  424. bool completed, completed_async;
  425. public EndpointListenerAsyncResult (
  426. ManualResetEvent asyncEvent,
  427. Guid identifier, TimeSpan timeout,
  428. AsyncCallback callback, object state)
  429. {
  430. async_event = asyncEvent;
  431. this.identifier = identifier;
  432. this.timeout = timeout;
  433. this.callback = callback;
  434. this.state = state;
  435. }
  436. public WaitHandle AsyncWaitHandle {
  437. get { return async_event; }
  438. }
  439. public bool IsCompleted {
  440. get { return completed; }
  441. }
  442. public TimeSpan Timeout {
  443. get { return timeout; }
  444. }
  445. public void Complete (bool async)
  446. {
  447. completed_async = async;
  448. if (callback != null)
  449. callback (this);
  450. async_event.Set ();
  451. }
  452. public object AsyncState {
  453. get { return state; }
  454. }
  455. public bool CompletedSynchronously {
  456. get { return completed_async; }
  457. }
  458. }
  459. #endregion
  460. }
  461. }