ChannelDispatcher.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. 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. return ed;
  128. }
  129. public string BindingName {
  130. get { return binding_name; }
  131. }
  132. public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
  133. get { return initializers; }
  134. }
  135. protected internal override TimeSpan DefaultCloseTimeout {
  136. get { return timeouts.CloseTimeout; }
  137. }
  138. protected internal override TimeSpan DefaultOpenTimeout {
  139. get { return timeouts.OpenTimeout; }
  140. }
  141. public Collection<IErrorHandler> ErrorHandlers {
  142. get { return error_handlers; }
  143. }
  144. public SynchronizedCollection<EndpointDispatcher> Endpoints {
  145. get { return endpoints; }
  146. }
  147. [MonoTODO]
  148. public bool IsTransactedAccept {
  149. get { throw new NotImplementedException (); }
  150. }
  151. public bool IsTransactedReceive {
  152. get { return is_tx_receive; }
  153. set { is_tx_receive = value; }
  154. }
  155. public bool ManualAddressing {
  156. get { return manual_addressing; }
  157. set { manual_addressing = value; }
  158. }
  159. public int MaxTransactedBatchSize {
  160. get { return max_tx_batch_size; }
  161. set { max_tx_batch_size = value; }
  162. }
  163. public override ServiceHostBase Host {
  164. get { return host; }
  165. }
  166. public override IChannelListener Listener {
  167. get { return listener; }
  168. }
  169. public MessageVersion MessageVersion {
  170. get { return message_version; }
  171. set { message_version = value; }
  172. }
  173. public bool ReceiveSynchronously {
  174. get { return receive_sync; }
  175. set {
  176. ThrowIfDisposedOrImmutable ();
  177. receive_sync = value;
  178. }
  179. }
  180. public bool IncludeExceptionDetailInFaults {
  181. get { return include_exception_detail_in_faults; }
  182. set { include_exception_detail_in_faults = value; }
  183. }
  184. public ServiceThrottle ServiceThrottle {
  185. get { return throttle; }
  186. set { throttle = value; }
  187. }
  188. public IsolationLevel TransactionIsolationLevel {
  189. get { return tx_isolation_level; }
  190. set { tx_isolation_level = value; }
  191. }
  192. public TimeSpan TransactionTimeout {
  193. get { return tx_timeout; }
  194. set { tx_timeout = value; }
  195. }
  196. protected internal override void Attach (ServiceHostBase host)
  197. {
  198. this.host = host;
  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 and allow more than one connection to process at a time.
  406. while (loop && channels.Count < 1) {
  407. // while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
  408. channel_acceptor ();
  409. creator_handle.WaitOne (); // released by ChannelAccepted()
  410. }
  411. if (!loop)
  412. break;
  413. throttle_wait_handle.WaitOne (); // released by IChannel.Close()
  414. }
  415. try {
  416. owner.Listener.Close ();
  417. } finally {
  418. // make sure to close both listener and channels.
  419. owner.CloseInput ();
  420. }
  421. }
  422. void ChannelAccepted (IChannel ch)
  423. {
  424. try {
  425. if (ch == null) // could happen when it was aborted
  426. return;
  427. if (!loop) {
  428. var dis = ch as IDisposable;
  429. if (dis != null)
  430. dis.Dispose ();
  431. return;
  432. }
  433. lock (channels)
  434. channels.Add (ch);
  435. ch.Opened += delegate {
  436. ch.Faulted += delegate {
  437. lock (channels)
  438. if (channels.Contains (ch))
  439. channels.Remove (ch);
  440. throttle_wait_handle.Set (); // release loop wait lock.
  441. };
  442. ch.Closed += delegate {
  443. lock (channels)
  444. if (channels.Contains (ch))
  445. channels.Remove (ch);
  446. throttle_wait_handle.Set (); // release loop wait lock.
  447. };
  448. };
  449. ch.Open ();
  450. } finally {
  451. creator_handle.Set ();
  452. }
  453. ProcessRequestOrInput (ch);
  454. }
  455. void ProcessRequestOrInput (IChannel ch)
  456. {
  457. var reply = ch as IReplyChannel;
  458. var input = ch as IInputChannel;
  459. if (reply != null) {
  460. if (owner.ReceiveSynchronously) {
  461. RequestContext rc;
  462. if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
  463. ProcessRequest (reply, rc);
  464. } else {
  465. reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
  466. }
  467. } else if (input != null) {
  468. if (owner.ReceiveSynchronously) {
  469. Message msg;
  470. if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
  471. ProcessInput (input, msg);
  472. } else {
  473. input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
  474. }
  475. }
  476. }
  477. void TryReceiveRequestDone (IAsyncResult result)
  478. {
  479. RequestContext rc;
  480. var reply = (IReplyChannel) result.AsyncState;
  481. if (reply.EndTryReceiveRequest (result, out rc))
  482. ProcessRequest (reply, rc);
  483. else
  484. reply.Close ();
  485. }
  486. void TryReceiveDone (IAsyncResult result)
  487. {
  488. Message msg;
  489. var input = (IInputChannel) result.AsyncState;
  490. if (input.EndTryReceive (result, out msg))
  491. ProcessInput (input, msg);
  492. else
  493. input.Close ();
  494. }
  495. void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  496. {
  497. try {
  498. MessageVersion version = rc.RequestMessage.Version;
  499. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  500. Message res = Message.CreateMessage (version, fc, ex.Message, rc.RequestMessage.Headers.Action);
  501. rc.Reply (res);
  502. } catch (Exception e) {
  503. // FIXME: log it
  504. Console.WriteLine ("Error on sending DestinationUnreachable fault message: " + e);
  505. }
  506. }
  507. void ProcessRequest (IReplyChannel reply, RequestContext rc)
  508. {
  509. try {
  510. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  511. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  512. ProcessReply (rc);
  513. } catch (EndpointNotFoundException ex) {
  514. SendEndpointNotFound (rc, ex);
  515. } catch (Exception ex) {
  516. // FIXME: log it.
  517. Console.WriteLine (ex);
  518. } finally {
  519. if (rc != null)
  520. rc.Close ();
  521. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  522. if (loop && reply.State != CommunicationState.Closed)
  523. ProcessRequestOrInput (reply);
  524. }
  525. }
  526. void ProcessInput (IInputChannel input, Message message)
  527. {
  528. try {
  529. EndpointDispatcher candidate = null;
  530. candidate = FindEndpointDispatcher (message);
  531. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  532. ProcessInput (message);
  533. }
  534. catch (Exception ex) {
  535. // FIXME: log it.
  536. Console.WriteLine (ex);
  537. } finally {
  538. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  539. if (loop && input.State != CommunicationState.Closed)
  540. ProcessRequestOrInput (input);
  541. }
  542. }
  543. EndpointDispatcher FindEndpointDispatcher (Message message) {
  544. EndpointDispatcher candidate = null;
  545. for (int i = 0; i < owner.Endpoints.Count; i++) {
  546. if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  547. var newdis = owner.Endpoints [i];
  548. if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
  549. candidate = newdis;
  550. else if (candidate.FilterPriority == newdis.FilterPriority)
  551. throw new MultipleFilterMatchesException ();
  552. }
  553. }
  554. if (candidate == null && owner.Host != null)
  555. owner.Host.OnUnknownMessageReceived (message);
  556. return candidate;
  557. }
  558. bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  559. {
  560. // FIXME: handle AddressFilterMode.Prefix too.
  561. Uri to = req.Headers.To;
  562. if (to == null)
  563. return address_filter_mode == AddressFilterMode.Any;
  564. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  565. return false;
  566. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  567. }
  568. }
  569. }