ChannelDispatcher.cs 18 KB

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