ChannelDispatcher.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  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 (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. void HandleError (Exception ex)
  240. {
  241. foreach (IErrorHandler handler in ErrorHandlers)
  242. if (handler.HandleError (ex))
  243. break;
  244. }
  245. }
  246. // isolated from ChannelDispatcher
  247. class ListenerLoopManager
  248. {
  249. ChannelDispatcher owner;
  250. AutoResetEvent handle = new AutoResetEvent (false);
  251. AutoResetEvent creator_handle = new AutoResetEvent (false);
  252. ManualResetEvent stop_handle = new ManualResetEvent (false);
  253. bool loop;
  254. Thread loop_thread;
  255. TimeSpan open_timeout;
  256. Func<IAsyncResult> channel_acceptor;
  257. List<IChannel> channels = new List<IChannel> ();
  258. public ListenerLoopManager (ChannelDispatcher owner, TimeSpan openTimeout)
  259. {
  260. this.owner = owner;
  261. open_timeout = openTimeout;
  262. }
  263. public void Setup ()
  264. {
  265. if (owner.Listener.State != CommunicationState.Opened)
  266. owner.Listener.Open (open_timeout);
  267. // It is tested at Open(), but strangely it is not instantiated at this point.
  268. foreach (var ed in owner.Endpoints)
  269. if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
  270. throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
  271. SetupChannelAcceptor ();
  272. }
  273. public void Start ()
  274. {
  275. foreach (var ed in owner.Endpoints)
  276. if (ed.DispatchRuntime.InstanceContextProvider == null)
  277. ed.DispatchRuntime.InstanceContextProvider = new DefaultInstanceContextProvider ();
  278. if (loop_thread == null)
  279. loop_thread = new Thread (new ThreadStart (Loop));
  280. loop_thread.Start ();
  281. }
  282. Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
  283. {
  284. IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
  285. if (r == null)
  286. return null;
  287. AsyncCallback callback = delegate (IAsyncResult result) {
  288. try {
  289. ChannelAccepted (r.EndAcceptChannel (result));
  290. } catch (Exception ex) {
  291. Console.WriteLine ("Exception during finishing channel acceptance.");
  292. Console.WriteLine (ex);
  293. }
  294. };
  295. return delegate {
  296. try {
  297. return r.BeginAcceptChannel (callback, null);
  298. } catch (Exception ex) {
  299. Console.WriteLine ("Exception during accepting channel.");
  300. Console.WriteLine (ex);
  301. throw;
  302. }
  303. };
  304. }
  305. void SetupChannelAcceptor ()
  306. {
  307. var l = owner.Listener;
  308. channel_acceptor =
  309. CreateAcceptor<IReplyChannel> (l) ??
  310. CreateAcceptor<IReplySessionChannel> (l) ??
  311. CreateAcceptor<IInputChannel> (l) ??
  312. CreateAcceptor<IInputSessionChannel> (l) ??
  313. CreateAcceptor<IDuplexChannel> (l) ??
  314. CreateAcceptor<IDuplexSessionChannel> (l);
  315. if (channel_acceptor == null)
  316. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
  317. }
  318. public void Stop (TimeSpan timeout)
  319. {
  320. loop = false;
  321. creator_handle.Set ();
  322. handle.Set ();
  323. if (stop_handle != null) {
  324. stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
  325. stop_handle.Close ();
  326. stop_handle = null;
  327. }
  328. if (owner.Listener.State != CommunicationState.Closed)
  329. owner.Listener.Abort ();
  330. if (loop_thread != null && loop_thread.IsAlive)
  331. loop_thread.Abort ();
  332. loop_thread = null;
  333. }
  334. public void CloseInput ()
  335. {
  336. foreach (var ch in channels.ToArray ()) {
  337. if (ch.State == CommunicationState.Closed)
  338. channels.Remove (ch); // zonbie, if exists
  339. else
  340. ch.Close ();
  341. }
  342. }
  343. void Loop ()
  344. {
  345. try {
  346. LoopCore ();
  347. } catch (Exception ex) {
  348. // FIXME: log it
  349. Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
  350. Console.WriteLine (ex);
  351. } finally {
  352. if (stop_handle != null)
  353. stop_handle.Set ();
  354. }
  355. }
  356. void LoopCore ()
  357. {
  358. loop = true;
  359. // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
  360. // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
  361. //FIXME: The logic here should be somewhat different as follows:
  362. //1. Get the message
  363. //2. Get the appropriate EndPointDispatcher that can handle the message
  364. // which is done using the filters (AddressFilter, ContractFilter).
  365. //3. Let the appropriate endpoint handle the request.
  366. while (loop) {
  367. while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
  368. channel_acceptor ();
  369. creator_handle.WaitOne (); // released by ChannelAccepted()
  370. creator_handle.Reset ();
  371. }
  372. if (!loop)
  373. break;
  374. handle.WaitOne (); // released by IChannel.Close()
  375. handle.Reset ();
  376. }
  377. owner.Listener.Close ();
  378. owner.CloseInput ();
  379. }
  380. void ChannelAccepted (IChannel ch)
  381. {
  382. try {
  383. if (ch == null) // could happen when it was aborted
  384. return;
  385. if (!loop) {
  386. var dis = ch as IDisposable;
  387. if (dis != null)
  388. dis.Dispose ();
  389. return;
  390. }
  391. channels.Add (ch);
  392. ch.Opened += delegate {
  393. ch.Faulted += delegate {
  394. if (channels.Contains (ch))
  395. channels.Remove (ch);
  396. handle.Set (); // release loop wait lock.
  397. };
  398. ch.Closed += delegate {
  399. if (channels.Contains (ch))
  400. channels.Remove (ch);
  401. handle.Set (); // release loop wait lock.
  402. };
  403. };
  404. ch.Open ();
  405. } finally {
  406. creator_handle.Set ();
  407. }
  408. ProcessRequestOrInput (ch);
  409. }
  410. void ProcessRequestOrInput (IChannel ch)
  411. {
  412. var reply = ch as IReplyChannel;
  413. var input = ch as IInputChannel;
  414. if (reply != null) {
  415. if (owner.ReceiveSynchronously) {
  416. RequestContext rc;
  417. if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
  418. ProcessRequest (reply, rc);
  419. } else {
  420. reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
  421. }
  422. } else if (input != null) {
  423. if (owner.ReceiveSynchronously) {
  424. Message msg;
  425. if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
  426. ProcessInput (input, msg);
  427. } else {
  428. input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
  429. }
  430. }
  431. }
  432. void TryReceiveRequestDone (IAsyncResult result)
  433. {
  434. RequestContext rc;
  435. var reply = (IReplyChannel) result.AsyncState;
  436. if (reply.EndTryReceiveRequest (result, out rc))
  437. ProcessRequest (reply, rc);
  438. }
  439. void TryReceiveDone (IAsyncResult result)
  440. {
  441. Message msg;
  442. var input = (IInputChannel) result.AsyncState;
  443. if (input.EndTryReceive (result, out msg))
  444. ProcessInput (input, msg);
  445. }
  446. void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  447. {
  448. try {
  449. MessageVersion version = rc.RequestMessage.Version;
  450. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  451. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  452. rc.Reply (res);
  453. }
  454. catch (Exception e) { }
  455. }
  456. void ProcessRequest (IReplyChannel reply, RequestContext rc)
  457. {
  458. try {
  459. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  460. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  461. ProcessReply (rc);
  462. } catch (EndpointNotFoundException ex) {
  463. SendEndpointNotFound (rc, ex);
  464. } catch (Exception ex) {
  465. // FIXME: log it.
  466. Console.WriteLine (ex);
  467. } finally {
  468. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  469. if (reply.State != CommunicationState.Closed)
  470. ProcessRequestOrInput (reply);
  471. }
  472. }
  473. void ProcessInput (IInputChannel input, Message message)
  474. {
  475. try {
  476. EndpointDispatcher candidate = null;
  477. candidate = FindEndpointDispatcher (message);
  478. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  479. ProcessInput (message);
  480. }
  481. catch (Exception ex) {
  482. // FIXME: log it.
  483. Console.WriteLine (ex);
  484. } finally {
  485. // unless it is closed by session/call manager, move it back to the loop to receive the next message.
  486. if (input.State != CommunicationState.Closed)
  487. ProcessRequestOrInput (input);
  488. }
  489. }
  490. EndpointDispatcher FindEndpointDispatcher (Message message) {
  491. EndpointDispatcher candidate = null;
  492. for (int i = 0; i < owner.Endpoints.Count; i++) {
  493. if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  494. var newdis = owner.Endpoints [i];
  495. if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
  496. candidate = newdis;
  497. else if (candidate.FilterPriority == newdis.FilterPriority)
  498. throw new MultipleFilterMatchesException ();
  499. }
  500. }
  501. if (candidate == null && owner.Host != null)
  502. owner.Host.OnUnknownMessageReceived (message);
  503. return candidate;
  504. }
  505. bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  506. {
  507. Uri to = req.Headers.To;
  508. if (to == null)
  509. return false;
  510. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  511. return false;
  512. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  513. }
  514. }
  515. }