ChannelDispatcher.cs 17 KB

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