ChannelDispatcher.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 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. AddressFilterMode address_filter_mode;
  286. public ListenerLoopManager (ChannelDispatcher owner)
  287. {
  288. this.owner = owner;
  289. var sba = owner.Host != null ? owner.Host.Description.Behaviors.Find<ServiceBehaviorAttribute> () : null;
  290. if (sba != null)
  291. address_filter_mode = sba.AddressFilterMode;
  292. }
  293. public void Setup (TimeSpan openTimeout)
  294. {
  295. if (owner.Listener.State != CommunicationState.Opened)
  296. owner.Listener.Open (openTimeout);
  297. // It is tested at Open(), but strangely it is not instantiated at this point.
  298. foreach (var ed in owner.Endpoints)
  299. if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
  300. throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
  301. SetupChannelAcceptor ();
  302. }
  303. public void Start ()
  304. {
  305. foreach (var ed in owner.Endpoints)
  306. if (ed.DispatchRuntime.InstanceContextProvider == null)
  307. ed.DispatchRuntime.InstanceContextProvider = new DefaultInstanceContextProvider ();
  308. if (loop_thread == null)
  309. loop_thread = new Thread (new ThreadStart (Loop));
  310. loop_thread.Start ();
  311. }
  312. Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
  313. {
  314. IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
  315. if (r == null)
  316. return null;
  317. AsyncCallback callback = delegate (IAsyncResult result) {
  318. try {
  319. ChannelAccepted (r.EndAcceptChannel (result));
  320. } catch (Exception ex) {
  321. Console.WriteLine ("Exception during finishing channel acceptance.");
  322. Console.WriteLine (ex);
  323. creator_handle.Set ();
  324. }
  325. };
  326. return delegate {
  327. try {
  328. return r.BeginAcceptChannel (callback, null);
  329. } catch (Exception ex) {
  330. Console.WriteLine ("Exception during accepting channel.");
  331. Console.WriteLine (ex);
  332. throw;
  333. }
  334. };
  335. }
  336. void SetupChannelAcceptor ()
  337. {
  338. var l = owner.Listener;
  339. channel_acceptor =
  340. CreateAcceptor<IReplyChannel> (l) ??
  341. CreateAcceptor<IReplySessionChannel> (l) ??
  342. CreateAcceptor<IInputChannel> (l) ??
  343. CreateAcceptor<IInputSessionChannel> (l) ??
  344. CreateAcceptor<IDuplexChannel> (l) ??
  345. CreateAcceptor<IDuplexSessionChannel> (l);
  346. if (channel_acceptor == null)
  347. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
  348. }
  349. public void Stop (TimeSpan timeout)
  350. {
  351. if (loop_thread == null)
  352. return;
  353. close_started = DateTime.Now;
  354. close_timeout = timeout;
  355. loop = false;
  356. creator_handle.Set ();
  357. throttle_wait_handle.Set (); // break primary loop
  358. if (stop_handle != null) {
  359. stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
  360. stop_handle.Close ();
  361. stop_handle = null;
  362. }
  363. if (owner.Listener.State != CommunicationState.Closed)
  364. owner.Listener.Abort ();
  365. if (loop_thread != null && loop_thread.IsAlive)
  366. loop_thread.Abort ();
  367. loop_thread = null;
  368. }
  369. public void CloseInput ()
  370. {
  371. foreach (var ch in channels.ToArray ()) {
  372. if (ch.State == CommunicationState.Closed)
  373. channels.Remove (ch); // zonbie, if exists
  374. else {
  375. try {
  376. ch.Close (close_timeout - (DateTime.Now - close_started));
  377. } catch (Exception ex) {
  378. // FIXME: log it.
  379. Console.WriteLine (ex);
  380. ch.Abort ();
  381. }
  382. }
  383. }
  384. }
  385. void Loop ()
  386. {
  387. try {
  388. LoopCore ();
  389. } catch (Exception ex) {
  390. // FIXME: log it
  391. Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
  392. Console.WriteLine (ex);
  393. } finally {
  394. if (stop_handle != null)
  395. stop_handle.Set ();
  396. }
  397. }
  398. void LoopCore ()
  399. {
  400. loop = true;
  401. // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
  402. // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
  403. while (loop) {
  404. // FIXME: enable throttling and allow more than one connection to process at a time.
  405. while (loop && channels.Count < 1) {
  406. // while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
  407. channel_acceptor ();
  408. creator_handle.WaitOne (); // released by ChannelAccepted()
  409. }
  410. if (!loop)
  411. break;
  412. throttle_wait_handle.WaitOne (); // released by IChannel.Close()
  413. }
  414. try {
  415. owner.Listener.Close ();
  416. } finally {
  417. // make sure to close both listener and channels.
  418. owner.CloseInput ();
  419. }
  420. }
  421. void ChannelAccepted (IChannel ch)
  422. {
  423. try {
  424. if (ch == null) // could happen when it was aborted
  425. return;
  426. if (!loop) {
  427. var dis = ch as IDisposable;
  428. if (dis != null)
  429. dis.Dispose ();
  430. return;
  431. }
  432. channels.Add (ch);
  433. ch.Opened += delegate {
  434. ch.Faulted += delegate {
  435. if (channels.Contains (ch))
  436. channels.Remove (ch);
  437. throttle_wait_handle.Set (); // release loop wait lock.
  438. };
  439. ch.Closed += delegate {
  440. if (channels.Contains (ch))
  441. channels.Remove (ch);
  442. throttle_wait_handle.Set (); // release loop wait lock.
  443. };
  444. };
  445. ch.Open ();
  446. } finally {
  447. creator_handle.Set ();
  448. }
  449. ProcessRequestOrInput (ch);
  450. }
  451. void ProcessRequestOrInput (IChannel ch)
  452. {
  453. var reply = ch as IReplyChannel;
  454. var input = ch as IInputChannel;
  455. if (reply != null) {
  456. if (owner.ReceiveSynchronously) {
  457. RequestContext rc;
  458. if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
  459. ProcessRequest (reply, rc);
  460. } else {
  461. reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
  462. }
  463. } else if (input != null) {
  464. if (owner.ReceiveSynchronously) {
  465. Message msg;
  466. if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
  467. ProcessInput (input, msg);
  468. } else {
  469. input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
  470. }
  471. }
  472. }
  473. void TryReceiveRequestDone (IAsyncResult result)
  474. {
  475. RequestContext rc;
  476. var reply = (IReplyChannel) result.AsyncState;
  477. if (reply.EndTryReceiveRequest (result, out rc))
  478. ProcessRequest (reply, rc);
  479. else
  480. reply.Close ();
  481. }
  482. void TryReceiveDone (IAsyncResult result)
  483. {
  484. Message msg;
  485. var input = (IInputChannel) result.AsyncState;
  486. if (input.EndTryReceive (result, out msg))
  487. ProcessInput (input, msg);
  488. else
  489. input.Close ();
  490. }
  491. void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  492. {
  493. try {
  494. MessageVersion version = rc.RequestMessage.Version;
  495. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  496. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  497. rc.Reply (res);
  498. } catch (Exception e) {
  499. // FIXME: log it
  500. Console.WriteLine ("Error on sending DestinationUnreachable fault message: " + e);
  501. }
  502. }
  503. void ProcessRequest (IReplyChannel reply, RequestContext rc)
  504. {
  505. try {
  506. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  507. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  508. ProcessReply (rc);
  509. } catch (EndpointNotFoundException ex) {
  510. SendEndpointNotFound (rc, ex);
  511. } catch (Exception ex) {
  512. // FIXME: log it.
  513. Console.WriteLine (ex);
  514. } finally {
  515. if (rc != null)
  516. rc.Close ();
  517. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  518. if (reply.State != CommunicationState.Closed)
  519. ProcessRequestOrInput (reply);
  520. }
  521. }
  522. void ProcessInput (IInputChannel input, Message message)
  523. {
  524. try {
  525. EndpointDispatcher candidate = null;
  526. candidate = FindEndpointDispatcher (message);
  527. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  528. ProcessInput (message);
  529. }
  530. catch (Exception ex) {
  531. // FIXME: log it.
  532. Console.WriteLine (ex);
  533. } finally {
  534. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  535. if (input.State != CommunicationState.Closed)
  536. ProcessRequestOrInput (input);
  537. }
  538. }
  539. EndpointDispatcher FindEndpointDispatcher (Message message) {
  540. EndpointDispatcher candidate = null;
  541. for (int i = 0; i < owner.Endpoints.Count; i++) {
  542. if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  543. var newdis = owner.Endpoints [i];
  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 && owner.Host != null)
  551. owner.Host.OnUnknownMessageReceived (message);
  552. return candidate;
  553. }
  554. bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  555. {
  556. // FIXME: handle AddressFilterMode.Prefix too.
  557. Uri to = req.Headers.To;
  558. if (to == null)
  559. return address_filter_mode == AddressFilterMode.Any;
  560. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  561. return false;
  562. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  563. }
  564. }
  565. }