ChannelDispatcher.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. }
  207. protected override void OnEndClose (IAsyncResult result)
  208. {
  209. if (result == null)
  210. throw new ArgumentNullException ("result");
  211. OpenAsyncResult or = result as OpenAsyncResult;
  212. if (or == null)
  213. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  214. CloseInput ();
  215. or.AsyncWaitHandle.WaitOne ();
  216. }
  217. [MonoTODO ("this is not a real async method.")]
  218. protected override void OnEndOpen (IAsyncResult result)
  219. {
  220. if (result == null)
  221. throw new ArgumentNullException ("result");
  222. OpenAsyncResult or = result as OpenAsyncResult;
  223. if (or == null)
  224. throw new ArgumentException ("Pass an IAsyncResult instance that is returned from BeginOpen().");
  225. or.AsyncWaitHandle.WaitOne ();
  226. }
  227. protected override void OnOpen (TimeSpan timeout)
  228. {
  229. if (Host == null || MessageVersion == null)
  230. throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
  231. // FIXME: hack, just to make it runnable
  232. loop_manager = new ListenerLoopManager (this, timeout);
  233. }
  234. [MonoTODO ("what to do here?")]
  235. protected override void OnOpening ()
  236. {
  237. }
  238. protected override void OnOpened ()
  239. {
  240. ProcessOpened ();
  241. }
  242. void ProcessClose (TimeSpan timeout)
  243. {
  244. if (loop_manager != null)
  245. loop_manager.Stop (timeout);
  246. CloseInput ();
  247. }
  248. void ProcessOpened ()
  249. {
  250. try {
  251. loop_manager.Setup ();
  252. } finally {
  253. if (async_result != null)
  254. async_result.Complete (false);
  255. }
  256. }
  257. internal void StartLoop ()
  258. {
  259. loop_manager.Start ();
  260. }
  261. bool IsMessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
  262. {
  263. Uri to = req.Headers.To;
  264. if (to == null)
  265. return false;
  266. if (to.AbsoluteUri == Constants.WsaAnonymousUri)
  267. return false;
  268. return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
  269. }
  270. void HandleError (Exception ex)
  271. {
  272. foreach (IErrorHandler handler in ErrorHandlers)
  273. if (handler.HandleError (ex))
  274. break;
  275. }
  276. class ListenerLoopManager
  277. {
  278. delegate IChannel ChannelAcceptor ();
  279. ChannelDispatcher owner;
  280. AutoResetEvent handle;
  281. IReplyChannel reply;
  282. IInputChannel input;
  283. bool loop;
  284. Thread loop_thread;
  285. TimeSpan open_timeout;
  286. ChannelAcceptor channel_acceptor;
  287. public ListenerLoopManager (ChannelDispatcher owner, TimeSpan openTimeout)
  288. {
  289. this.owner = owner;
  290. open_timeout = openTimeout;
  291. }
  292. public void Setup ()
  293. {
  294. if (owner.Listener.State != CommunicationState.Opened)
  295. owner.Listener.Open (open_timeout);
  296. // It is tested at Open(), but strangely it is not instantiated at this point.
  297. foreach (var ed in owner.Endpoints)
  298. if (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null)
  299. throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
  300. SetupChannel ();
  301. }
  302. public void Start ()
  303. {
  304. if (loop_thread == null)
  305. loop_thread = new Thread (new ThreadStart (StartLoop));
  306. loop_thread.Start ();
  307. }
  308. void SetupChannel ()
  309. {
  310. IChannelListener<IReplyChannel> r = owner.Listener as IChannelListener<IReplyChannel>;
  311. if (r != null) {
  312. channel_acceptor = delegate { return r.AcceptChannel (); };
  313. return;
  314. }
  315. IChannelListener<IReplySessionChannel> rs = owner.Listener as IChannelListener<IReplySessionChannel>;
  316. if (rs != null) {
  317. channel_acceptor = delegate { return rs.AcceptChannel (); };
  318. return;
  319. }
  320. IChannelListener<IInputChannel> i = owner.Listener as IChannelListener<IInputChannel>;
  321. if (i != null) {
  322. channel_acceptor = delegate { return i.AcceptChannel (); };
  323. return;
  324. }
  325. IChannelListener<IInputSessionChannel> iss = owner.Listener as IChannelListener<IInputSessionChannel>;
  326. if (iss != null) {
  327. channel_acceptor = delegate { return iss.AcceptChannel (); };
  328. return;
  329. }
  330. IChannelListener<IDuplexChannel> d = owner.Listener as IChannelListener<IDuplexChannel>;
  331. if (d != null) {
  332. channel_acceptor = delegate { return d.AcceptChannel (); };
  333. return;
  334. }
  335. IChannelListener<IDuplexSessionChannel> ds = owner.Listener as IChannelListener<IDuplexSessionChannel>;
  336. if (ds != null) {
  337. channel_acceptor = delegate { return ds.AcceptChannel (); };
  338. return;
  339. }
  340. throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", owner.Listener.GetType ()));
  341. }
  342. public void Stop (TimeSpan timeout)
  343. {
  344. StopLoop ();
  345. owner.Listener.Close ();
  346. if (loop_thread.IsAlive)
  347. loop_thread.Abort ();
  348. loop_thread = null;
  349. }
  350. void StartLoop ()
  351. {
  352. try {
  353. StartLoopCore ();
  354. } catch (ThreadAbortException) {
  355. Thread.ResetAbort ();
  356. }
  357. }
  358. void StartLoopCore ()
  359. {
  360. loop = true;
  361. // FIXME: use async WaitForBlah() method so
  362. // that we can stop them at our own will.
  363. //FIXME: The logic here should be entirely different as follows:
  364. //1. Get the message
  365. //2. Get the appropriate EndPointDispatcher that can handle the message
  366. // which is done using the filters (AddressFilter, ContractFilter).
  367. //3. Let the appropriate endpoint handle the request.
  368. IChannel ch = channel_acceptor ();
  369. reply = ch as IReplyChannel;
  370. input = ch as IInputChannel;
  371. if (reply != null) {
  372. while (loop) {
  373. if (reply.WaitForRequest (owner.timeouts.ReceiveTimeout))
  374. ProcessRequest ();
  375. }
  376. } else if (input != null) {
  377. while (loop) {
  378. if (input.WaitForMessage (owner.timeouts.ReceiveTimeout))
  379. ProcessInput ();
  380. }
  381. }
  382. }
  383. void sendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
  384. {
  385. try {
  386. MessageVersion version = rc.RequestMessage.Version;
  387. FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
  388. Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
  389. rc.Reply (res);
  390. }
  391. catch (Exception e) { }
  392. }
  393. void ProcessRequest ()
  394. {
  395. RequestContext rc = null;
  396. try {
  397. rc = reply.ReceiveRequest (owner.timeouts.ReceiveTimeout);
  398. if (rc == null)
  399. throw new InvalidOperationException ("The reply channel didn't return RequestContext");
  400. EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
  401. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
  402. ProcessReply (rc);
  403. }
  404. catch (EndpointNotFoundException ex) {
  405. sendEndpointNotFound (rc, ex);
  406. }
  407. }
  408. void ProcessInput ()
  409. {
  410. Message message = input.Receive ();
  411. EndpointDispatcher candidate = null;
  412. try {
  413. candidate = FindEndpointDispatcher (message);
  414. new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
  415. ProcessInput(message);
  416. }
  417. catch (EndpointNotFoundException ex) {
  418. // silently ignore
  419. }
  420. }
  421. EndpointDispatcher FindEndpointDispatcher (Message message) {
  422. EndpointDispatcher candidate = null;
  423. for (int i = 0; i < owner.Endpoints.Count; i++) {
  424. if (owner.IsMessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
  425. candidate = owner.Endpoints [i];
  426. break;
  427. }
  428. }
  429. if (candidate == null)
  430. throw new EndpointNotFoundException (String.Format ("The request message has the target '{0}' which is not reachable in this service contract", message.Headers.To));
  431. return candidate;
  432. }
  433. void StopLoop ()
  434. {
  435. loop = false;
  436. // FIXME: send manual stop for reply or input channel.
  437. }
  438. }
  439. #region AsyncResult classes
  440. class CloseAsyncResult : EndpointListenerAsyncResult
  441. {
  442. public CloseAsyncResult (ManualResetEvent asyncEvent,
  443. Guid identifier, TimeSpan timeout,
  444. AsyncCallback callback, object state)
  445. : base (asyncEvent, identifier, timeout,
  446. callback, state)
  447. {
  448. }
  449. }
  450. class OpenAsyncResult : EndpointListenerAsyncResult
  451. {
  452. public OpenAsyncResult (ManualResetEvent asyncEvent,
  453. Guid identifier, TimeSpan timeout,
  454. AsyncCallback callback, object state)
  455. : base (asyncEvent, identifier, timeout,
  456. callback, state)
  457. {
  458. }
  459. }
  460. abstract class EndpointListenerAsyncResult : IAsyncResult
  461. {
  462. ManualResetEvent async_event;
  463. Guid identifier;
  464. TimeSpan timeout;
  465. AsyncCallback callback;
  466. object state;
  467. bool completed, completed_async;
  468. public EndpointListenerAsyncResult (
  469. ManualResetEvent asyncEvent,
  470. Guid identifier, TimeSpan timeout,
  471. AsyncCallback callback, object state)
  472. {
  473. async_event = asyncEvent;
  474. this.identifier = identifier;
  475. this.timeout = timeout;
  476. this.callback = callback;
  477. this.state = state;
  478. }
  479. public WaitHandle AsyncWaitHandle {
  480. get { return async_event; }
  481. }
  482. public bool IsCompleted {
  483. get { return completed; }
  484. }
  485. public TimeSpan Timeout {
  486. get { return timeout; }
  487. }
  488. public void Complete (bool async)
  489. {
  490. completed_async = async;
  491. if (callback != null)
  492. callback (this);
  493. async_event.Set ();
  494. }
  495. public object AsyncState {
  496. get { return state; }
  497. }
  498. public bool CompletedSynchronously {
  499. get { return completed_async; }
  500. }
  501. }
  502. #endregion
  503. }
  504. }