ChannelDispatcher.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. //
  2. // ChannelDispatcher.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005,2009 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. class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
  42. {
  43. public EndpointDispatcherCollection (ChannelDispatcher owner)
  44. {
  45. this.owner = owner;
  46. }
  47. ChannelDispatcher owner;
  48. protected override void ClearItems ()
  49. {
  50. foreach (var ed in this)
  51. ed.ChannelDispatcher = null;
  52. base.ClearItems ();
  53. }
  54. protected override void InsertItem (int index, EndpointDispatcher item)
  55. {
  56. item.ChannelDispatcher = owner;
  57. base.InsertItem (index, item);
  58. }
  59. protected virtual void RemoveItem (int index)
  60. {
  61. if (index < Count)
  62. this [index].ChannelDispatcher = null;
  63. base.RemoveItem (index);
  64. }
  65. protected virtual void SetItem (int index, EndpointDispatcher item)
  66. {
  67. item.ChannelDispatcher = owner;
  68. base.SetItem (index, item);
  69. }
  70. }
  71. ServiceHostBase host;
  72. string binding_name;
  73. Collection<IErrorHandler> error_handlers
  74. = new Collection<IErrorHandler> ();
  75. IChannelListener listener;
  76. internal IDefaultCommunicationTimeouts timeouts; // FIXME: remove internal
  77. MessageVersion message_version;
  78. bool receive_sync, include_exception_detail_in_faults,
  79. manual_addressing, is_tx_receive;
  80. int max_tx_batch_size;
  81. SynchronizedCollection<IChannelInitializer> initializers
  82. = new SynchronizedCollection<IChannelInitializer> ();
  83. IsolationLevel tx_isolation_level;
  84. TimeSpan tx_timeout;
  85. ServiceThrottle throttle;
  86. Guid identifier = Guid.NewGuid ();
  87. ManualResetEvent async_event = new ManualResetEvent (false);
  88. ListenerLoopManager loop_manager;
  89. SynchronizedCollection<EndpointDispatcher> endpoints;
  90. [MonoTODO ("get binding info from config")]
  91. public ChannelDispatcher (IChannelListener listener)
  92. : this (listener, null)
  93. {
  94. }
  95. public ChannelDispatcher (
  96. IChannelListener listener, string bindingName)
  97. : this (listener, bindingName, null)
  98. {
  99. }
  100. public ChannelDispatcher (
  101. IChannelListener listener, string bindingName,
  102. IDefaultCommunicationTimeouts timeouts)
  103. {
  104. if (listener == null)
  105. throw new ArgumentNullException ("listener");
  106. Init (listener, bindingName, timeouts);
  107. }
  108. private void Init (IChannelListener listener, string bindingName,
  109. IDefaultCommunicationTimeouts timeouts)
  110. {
  111. this.listener = listener;
  112. this.binding_name = bindingName;
  113. // IChannelListener is often a ChannelListenerBase
  114. // which implements IDefaultCommunicationTimeouts.
  115. this.timeouts = timeouts ?? listener as IDefaultCommunicationTimeouts ?? DefaultCommunicationTimeouts.Instance;
  116. endpoints = new EndpointDispatcherCollection (this);
  117. }
  118. internal void InitializeServiceEndpoint (Type serviceType, ServiceEndpoint se)
  119. {
  120. this.MessageVersion = se.Binding.MessageVersion;
  121. if (this.MessageVersion == null)
  122. this.MessageVersion = MessageVersion.Default;
  123. //Attach one EndpointDispacher to the ChannelDispatcher
  124. EndpointDispatcher ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
  125. this.Endpoints.Add (ed);
  126. ed.InitializeServiceEndpoint (false, serviceType, se);
  127. }
  128. public string BindingName {
  129. get { return binding_name; }
  130. }
  131. public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
  132. get { return initializers; }
  133. }
  134. protected internal override TimeSpan DefaultCloseTimeout {
  135. get { return timeouts.CloseTimeout; }
  136. }
  137. protected internal override TimeSpan DefaultOpenTimeout {
  138. get { return timeouts.OpenTimeout; }
  139. }
  140. public Collection<IErrorHandler> ErrorHandlers {
  141. get { return error_handlers; }
  142. }
  143. public SynchronizedCollection<EndpointDispatcher> Endpoints {
  144. get { return endpoints; }
  145. }
  146. [MonoTODO]
  147. public bool IsTransactedAccept {
  148. get { throw new NotImplementedException (); }
  149. }
  150. public bool IsTransactedReceive {
  151. get { return is_tx_receive; }
  152. set { is_tx_receive = value; }
  153. }
  154. public bool ManualAddressing {
  155. get { return manual_addressing; }
  156. set { manual_addressing = value; }
  157. }
  158. public int MaxTransactedBatchSize {
  159. get { return max_tx_batch_size; }
  160. set { max_tx_batch_size = value; }
  161. }
  162. public override ServiceHostBase Host {
  163. get { return host; }
  164. }
  165. public override IChannelListener Listener {
  166. get { return listener; }
  167. }
  168. public MessageVersion MessageVersion {
  169. get { return message_version; }
  170. set { message_version = value; }
  171. }
  172. public bool ReceiveSynchronously {
  173. get { return receive_sync; }
  174. set {
  175. ThrowIfDisposedOrImmutable ();
  176. receive_sync = value;
  177. }
  178. }
  179. public bool IncludeExceptionDetailInFaults {
  180. get { return include_exception_detail_in_faults; }
  181. set { include_exception_detail_in_faults = value; }
  182. }
  183. public ServiceThrottle ServiceThrottle {
  184. get { return throttle; }
  185. set { throttle = value; }
  186. }
  187. public IsolationLevel TransactionIsolationLevel {
  188. get { return tx_isolation_level; }
  189. set { tx_isolation_level = value; }
  190. }
  191. public TimeSpan TransactionTimeout {
  192. get { return tx_timeout; }
  193. set { tx_timeout = value; }
  194. }
  195. protected internal override void Attach (ServiceHostBase host)
  196. {
  197. this.host = host;
  198. }
  199. public override void CloseInput ()
  200. {
  201. if (loop_manager != null)
  202. loop_manager.CloseInput ();
  203. }
  204. protected internal override void Detach (ServiceHostBase host)
  205. {
  206. this.host = null;
  207. }
  208. protected override void OnAbort ()
  209. {
  210. if (loop_manager != null)
  211. loop_manager.Stop (TimeSpan.FromTicks (1));
  212. }
  213. Action<TimeSpan> open_delegate;
  214. Action<TimeSpan> close_delegate;
  215. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  216. AsyncCallback callback, object state)
  217. {
  218. if (close_delegate == null)
  219. close_delegate = new Action<TimeSpan> (OnClose);
  220. return close_delegate.BeginInvoke (timeout, callback, state);
  221. }
  222. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  223. AsyncCallback callback, object state)
  224. {
  225. if (open_delegate == null)
  226. open_delegate = new Action<TimeSpan> (OnClose);
  227. return open_delegate.BeginInvoke (timeout, callback, state);
  228. }
  229. protected override void OnClose (TimeSpan timeout)
  230. {
  231. if (loop_manager != null)
  232. loop_manager.Stop (timeout);
  233. }
  234. protected override void OnClosed ()
  235. {
  236. if (host != null)
  237. host.ChannelDispatchers.Remove (this);
  238. base.OnClosed ();
  239. }
  240. protected override void OnEndClose (IAsyncResult result)
  241. {
  242. close_delegate.EndInvoke (result);
  243. }
  244. protected override void OnEndOpen (IAsyncResult result)
  245. {
  246. open_delegate.EndInvoke (result);
  247. }
  248. protected override void OnOpen (TimeSpan timeout)
  249. {
  250. if (Host == null || MessageVersion == null)
  251. throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
  252. loop_manager.Setup (timeout);
  253. }
  254. protected override void OnOpening ()
  255. {
  256. base.OnOpening ();
  257. loop_manager = new ListenerLoopManager (this);
  258. }
  259. protected override void OnOpened ()
  260. {
  261. base.OnOpened ();
  262. StartLoop ();
  263. }
  264. void StartLoop ()
  265. {
  266. // FIXME: not sure if it should be filled here.
  267. if (ServiceThrottle == null)
  268. ServiceThrottle = new ServiceThrottle ();
  269. loop_manager.Start ();
  270. }
  271. }
  272. // isolated from ChannelDispatcher
  273. class ListenerLoopManager
  274. {
  275. ChannelDispatcher owner;
  276. AutoResetEvent throttle_wait_handle = new AutoResetEvent (false);
  277. AutoResetEvent creator_handle = new AutoResetEvent (false);
  278. ManualResetEvent stop_handle = new ManualResetEvent (false);
  279. bool loop;
  280. Thread loop_thread;
  281. DateTime close_started;
  282. TimeSpan close_timeout;
  283. Func<IAsyncResult> channel_acceptor;
  284. List<IChannel> channels = new List<IChannel> ();
  285. public ListenerLoopManager (ChannelDispatcher owner)
  286. {
  287. this.owner = owner;
  288. }
  289. public void Setup (TimeSpan openTimeout)
  290. {
  291. if (owner.Listener.State != CommunicationState.Opened)
  292. owner.Listener.Open (openTimeout);
  293. // It is tested at Open(), but strangely it is not instantiated at this point.
  294. foreach (var ed in owner.Endpoints)
  295. if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
  296. throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
  297. SetupChannelAcceptor ();
  298. }
  299. public void Start ()
  300. {
  301. foreach (var ed in owner.Endpoints)
  302. if (ed.DispatchRuntime.InstanceContextProvider == null)
  303. ed.DispatchRuntime.InstanceContextProvider = new DefaultInstanceContextProvider ();
  304. if (loop_thread == null)
  305. loop_thread = new Thread (new ThreadStart (Loop));
  306. loop_thread.Start ();
  307. }
  308. Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
  309. {
  310. IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
  311. if (r == null)
  312. return null;
  313. AsyncCallback callback = delegate (IAsyncResult result) {
  314. try {
  315. ChannelAccepted (r.EndAcceptChannel (result));
  316. } catch (Exception ex) {
  317. Console.WriteLine ("Exception during finishing channel acceptance.");
  318. Console.WriteLine (ex);
  319. }
  320. };
  321. return delegate {
  322. try {
  323. return r.BeginAcceptChannel (callback, null);
  324. } catch (Exception ex) {
  325. Console.WriteLine ("Exception during accepting channel.");
  326. Console.WriteLine (ex);
  327. throw;
  328. }
  329. };
  330. }
  331. void SetupChannelAcceptor ()
  332. {
  333. var l = owner.Listener;
  334. channel_acceptor =
  335. CreateAcceptor<IReplyChannel> (l) ??
  336. CreateAcceptor<IReplySessionChannel> (l) ??
  337. CreateAcceptor<IInputChannel> (l) ??
  338. CreateAcceptor<IInputSessionChannel> (l) ??
  339. CreateAcceptor<IDuplexChannel> (l) ??
  340. CreateAcceptor<IDuplexSessionChannel> (l);
  341. if (channel_acceptor == null)
  342. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
  343. }
  344. public void Stop (TimeSpan timeout)
  345. {
  346. if (loop_thread == null)
  347. return;
  348. close_started = DateTime.Now;
  349. close_timeout = timeout;
  350. loop = false;
  351. creator_handle.Set ();
  352. throttle_wait_handle.Set (); // break primary loop
  353. if (stop_handle != null) {
  354. stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
  355. stop_handle.Close ();
  356. stop_handle = null;
  357. }
  358. if (owner.Listener.State != CommunicationState.Closed)
  359. owner.Listener.Abort ();
  360. if (loop_thread != null && loop_thread.IsAlive)
  361. loop_thread.Abort ();
  362. loop_thread = null;
  363. }
  364. public void CloseInput ()
  365. {
  366. foreach (var ch in channels.ToArray ()) {
  367. if (ch.State == CommunicationState.Closed)
  368. channels.Remove (ch); // zonbie, if exists
  369. else {
  370. try {
  371. ch.Close (close_timeout - (DateTime.Now - close_started));
  372. } catch (Exception ex) {
  373. // FIXME: log it.
  374. Console.WriteLine (ex);
  375. ch.Abort ();
  376. }
  377. }
  378. }
  379. }
  380. void Loop ()
  381. {
  382. try {
  383. LoopCore ();
  384. } catch (Exception ex) {
  385. // FIXME: log it
  386. Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
  387. Console.WriteLine (ex);
  388. } finally {
  389. if (stop_handle != null)
  390. stop_handle.Set ();
  391. }
  392. }
  393. void LoopCore ()
  394. {
  395. loop = true;
  396. // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
  397. // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
  398. //FIXME: The logic here should be somewhat different as follows:
  399. //1. Get the message
  400. //2. Get the appropriate EndPointDispatcher that can handle the message
  401. // which is done using the filters (AddressFilter, ContractFilter).
  402. //3. Let the appropriate endpoint handle the request.
  403. while (loop) {
  404. while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
  405. channel_acceptor ();
  406. creator_handle.WaitOne (); // released by ChannelAccepted()
  407. }
  408. if (!loop)
  409. break;
  410. throttle_wait_handle.WaitOne (); // released by IChannel.Close()
  411. }
  412. try {
  413. owner.Listener.Close ();
  414. } finally {
  415. // make sure to close both listener and channels.
  416. owner.CloseInput ();
  417. }
  418. }
  419. void ChannelAccepted (IChannel ch)
  420. {
  421. try {
  422. if (ch == null) // could happen when it was aborted
  423. return;
  424. if (!loop) {
  425. var dis = ch as IDisposable;
  426. if (dis != null)
  427. dis.Dispose ();
  428. return;
  429. }
  430. channels.Add (ch);
  431. ch.Opened += delegate {
  432. ch.Faulted += delegate {
  433. if (channels.Contains (ch))
  434. channels.Remove (ch);
  435. throttle_wait_handle.Set (); // release loop wait lock.
  436. };
  437. ch.Closed += delegate {
  438. if (channels.Contains (ch))
  439. channels.Remove (ch);
  440. throttle_wait_handle.Set (); // release loop wait lock.
  441. };
  442. };
  443. ch.Open ();
  444. } finally {
  445. creator_handle.Set ();
  446. }
  447. ProcessRequestOrInput (ch);
  448. }
  449. void ProcessRequestOrInput (IChannel ch)
  450. {
  451. var reply = ch as IReplyChannel;
  452. var input = ch as IInputChannel;
  453. if (reply != null) {
  454. if (owner.ReceiveSynchronously) {
  455. RequestContext rc;
  456. if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
  457. ProcessRequest (reply, rc);
  458. } else {
  459. reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
  460. }
  461. } else if (input != null) {
  462. if (owner.ReceiveSynchronously) {
  463. Message msg;
  464. if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
  465. ProcessInput (input, msg);
  466. } else {
  467. input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
  468. }
  469. }
  470. }
  471. void TryReceiveRequestDone (IAsyncResult result)
  472. {
  473. RequestContext rc;
  474. var reply = (IReplyChannel) result.AsyncState;
  475. if (reply.EndTryReceiveRequest (result, out rc))
  476. ProcessRequest (reply, rc);
  477. }
  478. void TryReceiveDone (IAsyncResult result)
  479. {
  480. Message msg;
  481. var input = (IInputChannel) result.AsyncState;
  482. if (input.EndTryReceive (result, out msg))
  483. ProcessInput (input, msg);
  484. }
  485. void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  486. {
  487. try {
  488. MessageVersion version = rc.RequestMessage.Version;
  489. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  490. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  491. rc.Reply (res);
  492. }
  493. catch (Exception e) { }
  494. }
  495. void ProcessRequest (IReplyChannel reply, RequestContext rc)
  496. {
  497. try {
  498. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  499. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  500. ProcessReply (rc);
  501. } catch (EndpointNotFoundException ex) {
  502. SendEndpointNotFound (rc, ex);
  503. } catch (Exception ex) {
  504. // FIXME: log it.
  505. Console.WriteLine (ex);
  506. } finally {
  507. if (rc != null)
  508. rc.Close ();
  509. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  510. if (reply.State != CommunicationState.Closed)
  511. ProcessRequestOrInput (reply);
  512. }
  513. }
  514. void ProcessInput (IInputChannel input, Message message)
  515. {
  516. try {
  517. EndpointDispatcher candidate = null;
  518. candidate = FindEndpointDispatcher (message);
  519. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  520. ProcessInput (message);
  521. }
  522. catch (Exception ex) {
  523. // FIXME: log it.
  524. Console.WriteLine (ex);
  525. } finally {
  526. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  527. if (input.State != CommunicationState.Closed)
  528. ProcessRequestOrInput (input);
  529. }
  530. }
  531. EndpointDispatcher FindEndpointDispatcher (Message message) {
  532. EndpointDispatcher candidate = null;
  533. for (int i = 0; i < owner.Endpoints.Count; i++) {
  534. if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  535. var newdis = owner.Endpoints [i];
  536. if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
  537. candidate = newdis;
  538. else if (candidate.FilterPriority == newdis.FilterPriority)
  539. throw new MultipleFilterMatchesException ();
  540. }
  541. }
  542. if (candidate == null && owner.Host != null)
  543. owner.Host.OnUnknownMessageReceived (message);
  544. return candidate;
  545. }
  546. bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  547. {
  548. Uri to = req.Headers.To;
  549. if (to == null)
  550. return false;
  551. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  552. return false;
  553. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  554. }
  555. }
  556. }