ChannelDispatcher.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. //
  2. // ChannelDispatcher.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2005 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. EndpointListenerAsyncResult async_result;
  59. ListenerLoopManager loop_manager;
  60. SynchronizedCollection<EndpointDispatcher> endpoints;
  61. [MonoTODO ("get binding info from config")]
  62. public ChannelDispatcher (IChannelListener listener)
  63. : this (listener, null)
  64. {
  65. }
  66. public ChannelDispatcher (
  67. IChannelListener listener, string bindingName)
  68. : this (listener, bindingName, null)
  69. {
  70. }
  71. public ChannelDispatcher (
  72. IChannelListener listener, string bindingName,
  73. IDefaultCommunicationTimeouts timeouts)
  74. {
  75. if (listener == null)
  76. throw new ArgumentNullException ("listener");
  77. Init (listener, bindingName, timeouts);
  78. }
  79. private void Init (IChannelListener listener, string bindingName,
  80. IDefaultCommunicationTimeouts timeouts)
  81. {
  82. this.listener = listener;
  83. this.binding_name = bindingName;
  84. // IChannelListener is often a ChannelListenerBase
  85. // which implements IDefaultCommunicationTimeouts.
  86. this.timeouts = timeouts ?? listener as IDefaultCommunicationTimeouts ?? DefaultCommunicationTimeouts.Instance;
  87. endpoints = new SynchronizedCollection<EndpointDispatcher> ();
  88. }
  89. public string BindingName {
  90. get { return binding_name; }
  91. }
  92. public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
  93. get { return initializers; }
  94. }
  95. protected internal override TimeSpan DefaultCloseTimeout {
  96. get { return timeouts.CloseTimeout; }
  97. }
  98. protected internal override TimeSpan DefaultOpenTimeout {
  99. get { return timeouts.OpenTimeout; }
  100. }
  101. public Collection<IErrorHandler> ErrorHandlers {
  102. get { return error_handlers; }
  103. }
  104. public SynchronizedCollection<EndpointDispatcher> Endpoints {
  105. get { return endpoints; }
  106. }
  107. [MonoTODO]
  108. public bool IsTransactedAccept {
  109. get { throw new NotImplementedException (); }
  110. }
  111. public bool IsTransactedReceive {
  112. get { return is_tx_receive; }
  113. set { is_tx_receive = value; }
  114. }
  115. public bool ManualAddressing {
  116. get { return manual_addressing; }
  117. set { manual_addressing = value; }
  118. }
  119. public int MaxTransactedBatchSize {
  120. get { return max_tx_batch_size; }
  121. set { max_tx_batch_size = value; }
  122. }
  123. public override ServiceHostBase Host {
  124. get { return host; }
  125. }
  126. public override IChannelListener Listener {
  127. get { return listener; }
  128. }
  129. public MessageVersion MessageVersion {
  130. get { return message_version; }
  131. set { message_version = value; }
  132. }
  133. public bool ReceiveSynchronously {
  134. get { return receive_sync; }
  135. set { receive_sync = value; }
  136. }
  137. public bool IncludeExceptionDetailInFaults {
  138. get { return include_exception_detail_in_faults; }
  139. set { include_exception_detail_in_faults = value; }
  140. }
  141. public ServiceThrottle ServiceThrottle {
  142. get { return throttle; }
  143. set { throttle = value; }
  144. }
  145. public IsolationLevel TransactionIsolationLevel {
  146. get { return tx_isolation_level; }
  147. set { tx_isolation_level = value; }
  148. }
  149. public TimeSpan TransactionTimeout {
  150. get { return tx_timeout; }
  151. set { tx_timeout = value; }
  152. }
  153. protected internal override void Attach (ServiceHostBase host)
  154. {
  155. this.host = host;
  156. }
  157. public override void CloseInput ()
  158. {
  159. if (State == CommunicationState.Closed)
  160. return;
  161. try {
  162. try {
  163. listener.Close ();
  164. } finally {
  165. listener = null;
  166. }
  167. } finally {
  168. if (async_result != null)
  169. async_result.Complete (false);
  170. }
  171. }
  172. protected internal override void Detach (ServiceHostBase host)
  173. {
  174. this.host = null;
  175. }
  176. protected override void OnAbort ()
  177. {
  178. throw new NotImplementedException ();
  179. }
  180. protected override IAsyncResult OnBeginClose (TimeSpan timeout,
  181. AsyncCallback callback, object state)
  182. {
  183. async_event.Reset ();
  184. async_result = new CloseAsyncResult (
  185. async_event, identifier, timeout,
  186. callback, state);
  187. return async_result;
  188. }
  189. protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
  190. AsyncCallback callback, object state)
  191. {
  192. async_event.Reset ();
  193. async_result = new OpenAsyncResult (
  194. async_event, identifier, timeout,
  195. callback, state);
  196. return async_result;
  197. }
  198. protected override void OnClose (TimeSpan timeout)
  199. {
  200. ProcessClose (timeout);
  201. }
  202. protected override void OnClosed ()
  203. {
  204. if (host != null)
  205. host.ChannelDispatchers.Remove (this);
  206. base.OnClosed ();
  207. }
  208. protected override void OnEndClose (IAsyncResult result)
  209. {
  210. if (result == null)
  211. throw new ArgumentNullException ("result");
  212. OpenAsyncResult or = result as OpenAsyncResult;
  213. if (or == null)
  214. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  215. CloseInput ();
  216. or.AsyncWaitHandle.WaitOne ();
  217. }
  218. [MonoTODO ("this is not a real async method.")]
  219. protected override void OnEndOpen (IAsyncResult result)
  220. {
  221. if (result == null)
  222. throw new ArgumentNullException ("result");
  223. OpenAsyncResult or = result as OpenAsyncResult;
  224. if (or == null)
  225. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  226. or.AsyncWaitHandle.WaitOne ();
  227. }
  228. protected override void OnOpen (TimeSpan timeout)
  229. {
  230. if (Host == null || MessageVersion == null)
  231. throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
  232. // FIXME: hack, just to make it runnable
  233. loop_manager = new ListenerLoopManager (this, timeout);
  234. }
  235. [MonoTODO ("what to do here?")]
  236. protected override void OnOpening ()
  237. {
  238. }
  239. protected override void OnOpened ()
  240. {
  241. ProcessOpened ();
  242. }
  243. void ProcessClose (TimeSpan timeout)
  244. {
  245. if (loop_manager != null)
  246. loop_manager.Stop (timeout);
  247. CloseInput ();
  248. }
  249. void ProcessOpened ()
  250. {
  251. try {
  252. loop_manager.Setup ();
  253. } finally {
  254. if (async_result != null)
  255. async_result.Complete (false);
  256. }
  257. }
  258. internal void StartLoop ()
  259. {
  260. loop_manager.Start ();
  261. }
  262. bool IsMessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  263. {
  264. Uri to = req.Headers.To;
  265. if (to == null)
  266. return false;
  267. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  268. return false;
  269. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  270. }
  271. void HandleError (Exception ex)
  272. {
  273. foreach (IErrorHandler handler in ErrorHandlers)
  274. if (handler.HandleError (ex))
  275. break;
  276. }
  277. class ListenerLoopManager
  278. {
  279. delegate IChannel ChannelAcceptor ();
  280. ChannelDispatcher owner;
  281. AutoResetEvent handle;
  282. IReplyChannel reply;
  283. IInputChannel input;
  284. bool loop;
  285. Thread loop_thread;
  286. TimeSpan open_timeout;
  287. ChannelAcceptor channel_acceptor;
  288. public ListenerLoopManager (ChannelDispatcher owner, TimeSpan openTimeout)
  289. {
  290. this.owner = owner;
  291. open_timeout = openTimeout;
  292. }
  293. public void Setup ()
  294. {
  295. if (owner.Listener.State != CommunicationState.Opened)
  296. owner.Listener.Open (open_timeout);
  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.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. SetupChannel ();
  302. }
  303. public void Start ()
  304. {
  305. if (loop_thread == null)
  306. loop_thread = new Thread (new ThreadStart (StartLoop));
  307. loop_thread.Start ();
  308. }
  309. void SetupChannel ()
  310. {
  311. IChannelListener<IReplyChannel> r = owner.Listener as IChannelListener<IReplyChannel>;
  312. if (r != null) {
  313. channel_acceptor = delegate { return r.AcceptChannel (); };
  314. return;
  315. }
  316. IChannelListener<IReplySessionChannel> rs = owner.Listener as IChannelListener<IReplySessionChannel>;
  317. if (rs != null) {
  318. channel_acceptor = delegate { return rs.AcceptChannel (); };
  319. return;
  320. }
  321. IChannelListener<IInputChannel> i = owner.Listener as IChannelListener<IInputChannel>;
  322. if (i != null) {
  323. channel_acceptor = delegate { return i.AcceptChannel (); };
  324. return;
  325. }
  326. IChannelListener<IInputSessionChannel> iss = owner.Listener as IChannelListener<IInputSessionChannel>;
  327. if (iss != null) {
  328. channel_acceptor = delegate { return iss.AcceptChannel (); };
  329. return;
  330. }
  331. IChannelListener<IDuplexChannel> d = owner.Listener as IChannelListener<IDuplexChannel>;
  332. if (d != null) {
  333. channel_acceptor = delegate { return d.AcceptChannel (); };
  334. return;
  335. }
  336. IChannelListener<IDuplexSessionChannel> ds = owner.Listener as IChannelListener<IDuplexSessionChannel>;
  337. if (ds != null) {
  338. channel_acceptor = delegate { return ds.AcceptChannel (); };
  339. return;
  340. }
  341. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", owner.Listener.GetType ()));
  342. }
  343. public void Stop (TimeSpan timeout)
  344. {
  345. StopLoop ();
  346. owner.Listener.Close ();
  347. if (loop_thread.IsAlive)
  348. loop_thread.Abort ();
  349. loop_thread = null;
  350. }
  351. void StartLoop ()
  352. {
  353. try {
  354. StartLoopCore ();
  355. } catch (ThreadAbortException) {
  356. Thread.ResetAbort ();
  357. }
  358. }
  359. void StartLoopCore ()
  360. {
  361. loop = true;
  362. // FIXME: use async WaitForBlah() method so
  363. // that we can stop them at our own will.
  364. //FIXME: The logic here should be entirely different as follows:
  365. //1. Get the message
  366. //2. Get the appropriate EndPointDispatcher that can handle the message
  367. // which is done using the filters (AddressFilter, ContractFilter).
  368. //3. Let the appropriate endpoint handle the request.
  369. IChannel ch = channel_acceptor ();
  370. ch.Open (owner.timeouts.OpenTimeout);
  371. reply = ch as IReplyChannel;
  372. input = ch as IInputChannel;
  373. if (reply != null) {
  374. while (loop) {
  375. if (reply.WaitForRequest (owner.timeouts.ReceiveTimeout))
  376. ProcessRequest ();
  377. }
  378. } else if (input != null) {
  379. while (loop) {
  380. if (input.WaitForMessage (owner.timeouts.ReceiveTimeout))
  381. ProcessInput ();
  382. }
  383. }
  384. }
  385. void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  386. {
  387. try {
  388. MessageVersion version = rc.RequestMessage.Version;
  389. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  390. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  391. rc.Reply (res);
  392. }
  393. catch (Exception e) { }
  394. }
  395. void ProcessRequest ()
  396. {
  397. RequestContext rc = null;
  398. try {
  399. rc = reply.ReceiveRequest (owner.timeouts.ReceiveTimeout);
  400. if (rc == null)
  401. throw new InvalidOperationException ("The reply channel didn't return RequestContext");
  402. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  403. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  404. ProcessReply (rc);
  405. } catch (EndpointNotFoundException ex) {
  406. SendEndpointNotFound (rc, ex);
  407. } catch (Exception ex) {
  408. // FIXME: log it.
  409. Console.WriteLine (ex);
  410. }
  411. }
  412. void ProcessInput ()
  413. {
  414. try {
  415. Message message = input.Receive ();
  416. EndpointDispatcher candidate = null;
  417. candidate = FindEndpointDispatcher (message);
  418. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  419. ProcessInput(message);
  420. }
  421. catch (Exception ex) {
  422. // FIXME: log it.
  423. Console.WriteLine (ex);
  424. }
  425. }
  426. EndpointDispatcher FindEndpointDispatcher (Message message) {
  427. EndpointDispatcher candidate = null;
  428. for (int i = 0; i < owner.Endpoints.Count; i++) {
  429. if (owner.IsMessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  430. candidate = owner.Endpoints [i];
  431. break;
  432. }
  433. }
  434. if (candidate == null)
  435. throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' which is not reachable in this service contract", message.Headers.To));
  436. return candidate;
  437. }
  438. void StopLoop ()
  439. {
  440. loop = false;
  441. // FIXME: send manual stop for reply or input channel.
  442. }
  443. }
  444. #region AsyncResult classes
  445. class CloseAsyncResult : EndpointListenerAsyncResult
  446. {
  447. public CloseAsyncResult (ManualResetEvent asyncEvent,
  448. Guid identifier, TimeSpan timeout,
  449. AsyncCallback callback, object state)
  450. : base (asyncEvent, identifier, timeout,
  451. callback, state)
  452. {
  453. }
  454. }
  455. class OpenAsyncResult : EndpointListenerAsyncResult
  456. {
  457. public OpenAsyncResult (ManualResetEvent asyncEvent,
  458. Guid identifier, TimeSpan timeout,
  459. AsyncCallback callback, object state)
  460. : base (asyncEvent, identifier, timeout,
  461. callback, state)
  462. {
  463. }
  464. }
  465. abstract class EndpointListenerAsyncResult : IAsyncResult
  466. {
  467. ManualResetEvent async_event;
  468. Guid identifier;
  469. TimeSpan timeout;
  470. AsyncCallback callback;
  471. object state;
  472. bool completed, completed_async;
  473. public EndpointListenerAsyncResult (
  474. ManualResetEvent asyncEvent,
  475. Guid identifier, TimeSpan timeout,
  476. AsyncCallback callback, object state)
  477. {
  478. async_event = asyncEvent;
  479. this.identifier = identifier;
  480. this.timeout = timeout;
  481. this.callback = callback;
  482. this.state = state;
  483. }
  484. public WaitHandle AsyncWaitHandle {
  485. get { return async_event; }
  486. }
  487. public bool IsCompleted {
  488. get { return completed; }
  489. }
  490. public TimeSpan Timeout {
  491. get { return timeout; }
  492. }
  493. public void Complete (bool async)
  494. {
  495. completed_async = async;
  496. if (callback != null)
  497. callback (this);
  498. async_event.Set ();
  499. }
  500. public object AsyncState {
  501. get { return state; }
  502. }
  503. public bool CompletedSynchronously {
  504. get { return completed_async; }
  505. }
  506. }
  507. #endregion
  508. }
  509. }