2 // ChannelDispatcher.cs
5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2005,2009 Novell, Inc. http://www.novell.com
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
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;
38 namespace System.ServiceModel.Dispatcher
40 public class ChannelDispatcher : ChannelDispatcherBase
45 Collection<IErrorHandler> error_handlers
46 = new Collection<IErrorHandler> ();
47 IChannelListener listener;
48 internal IDefaultCommunicationTimeouts timeouts; // FIXME: remove internal
49 MessageVersion message_version;
50 bool receive_sync, include_exception_detail_in_faults,
51 manual_addressing, is_tx_receive;
52 int max_tx_batch_size;
53 SynchronizedCollection<IChannelInitializer> initializers
54 = new SynchronizedCollection<IChannelInitializer> ();
55 IsolationLevel tx_isolation_level;
57 ServiceThrottle throttle;
59 Guid identifier = Guid.NewGuid ();
60 ManualResetEvent async_event = new ManualResetEvent (false);
62 ListenerLoopManager loop_manager;
63 SynchronizedCollection<EndpointDispatcher> endpoints;
65 [MonoTODO ("get binding info from config")]
66 public ChannelDispatcher (IChannelListener listener)
67 : this (listener, null)
71 public ChannelDispatcher (
72 IChannelListener listener, string bindingName)
73 : this (listener, bindingName, null)
77 public ChannelDispatcher (
78 IChannelListener listener, string bindingName,
79 IDefaultCommunicationTimeouts timeouts)
82 throw new ArgumentNullException ("listener");
83 Init (listener, bindingName, timeouts);
86 private void Init (IChannelListener listener, string bindingName,
87 IDefaultCommunicationTimeouts timeouts)
89 this.listener = listener;
90 this.binding_name = bindingName;
91 // IChannelListener is often a ChannelListenerBase
92 // which implements IDefaultCommunicationTimeouts.
93 this.timeouts = timeouts ?? listener as IDefaultCommunicationTimeouts ?? DefaultCommunicationTimeouts.Instance;
94 endpoints = new SynchronizedCollection<EndpointDispatcher> ();
97 internal void InitializeServiceEndpoint (Type serviceType, ServiceEndpoint se)
99 this.MessageVersion = se.Binding.MessageVersion;
100 if (this.MessageVersion == null)
101 this.MessageVersion = MessageVersion.Default;
103 //Attach one EndpointDispacher to the ChannelDispatcher
104 EndpointDispatcher ed = new EndpointDispatcher (se.Address, se.Contract.Name, se.Contract.Namespace);
105 ed.InitializeServiceEndpoint (false, this, serviceType, se);
106 this.Endpoints.Add (ed);
109 public string BindingName {
110 get { return binding_name; }
113 public SynchronizedCollection<IChannelInitializer> ChannelInitializers {
114 get { return initializers; }
117 protected internal override TimeSpan DefaultCloseTimeout {
118 get { return timeouts.CloseTimeout; }
121 protected internal override TimeSpan DefaultOpenTimeout {
122 get { return timeouts.OpenTimeout; }
125 public Collection<IErrorHandler> ErrorHandlers {
126 get { return error_handlers; }
129 public SynchronizedCollection<EndpointDispatcher> Endpoints {
130 get { return endpoints; }
134 public bool IsTransactedAccept {
135 get { throw new NotImplementedException (); }
138 public bool IsTransactedReceive {
139 get { return is_tx_receive; }
140 set { is_tx_receive = value; }
143 public bool ManualAddressing {
144 get { return manual_addressing; }
145 set { manual_addressing = value; }
148 public int MaxTransactedBatchSize {
149 get { return max_tx_batch_size; }
150 set { max_tx_batch_size = value; }
153 public override ServiceHostBase Host {
157 public override IChannelListener Listener {
158 get { return listener; }
161 public MessageVersion MessageVersion {
162 get { return message_version; }
163 set { message_version = value; }
166 public bool ReceiveSynchronously {
167 get { return receive_sync; }
169 ThrowIfDisposedOrImmutable ();
170 receive_sync = value;
174 public bool IncludeExceptionDetailInFaults {
175 get { return include_exception_detail_in_faults; }
176 set { include_exception_detail_in_faults = value; }
179 public ServiceThrottle ServiceThrottle {
180 get { return throttle; }
181 set { throttle = value; }
184 public IsolationLevel TransactionIsolationLevel {
185 get { return tx_isolation_level; }
186 set { tx_isolation_level = value; }
189 public TimeSpan TransactionTimeout {
190 get { return tx_timeout; }
191 set { tx_timeout = value; }
194 protected internal override void Attach (ServiceHostBase host)
199 public override void CloseInput ()
201 if (loop_manager != null)
202 loop_manager.CloseInput ();
205 protected internal override void Detach (ServiceHostBase host)
210 protected override void OnAbort ()
212 if (loop_manager != null)
213 loop_manager.Stop (TimeSpan.FromTicks (1));
216 Action<TimeSpan> open_delegate;
217 Action<TimeSpan> close_delegate;
219 protected override IAsyncResult OnBeginClose (TimeSpan timeout,
220 AsyncCallback callback, object state)
222 if (close_delegate == null)
223 close_delegate = new Action<TimeSpan> (OnClose);
224 return close_delegate.BeginInvoke (timeout, callback, state);
227 protected override IAsyncResult OnBeginOpen (TimeSpan timeout,
228 AsyncCallback callback, object state)
230 if (open_delegate == null)
231 open_delegate = new Action<TimeSpan> (OnClose);
232 return open_delegate.BeginInvoke (timeout, callback, state);
235 protected override void OnClose (TimeSpan timeout)
237 if (loop_manager != null)
238 loop_manager.Stop (timeout);
241 protected override void OnClosed ()
244 host.ChannelDispatchers.Remove (this);
248 protected override void OnEndClose (IAsyncResult result)
250 close_delegate.EndInvoke (result);
253 protected override void OnEndOpen (IAsyncResult result)
255 open_delegate.EndInvoke (result);
258 protected override void OnOpen (TimeSpan timeout)
260 if (Host == null || MessageVersion == null)
261 throw new InvalidOperationException ("Service host is not attached to this ChannelDispatcher.");
263 loop_manager = new ListenerLoopManager (this, timeout);
266 [MonoTODO ("what to do here?")]
267 protected override void OnOpening ()
271 protected override void OnOpened ()
273 loop_manager.Setup ();
276 internal void StartLoop ()
278 // FIXME: not sure if it should be filled here.
279 if (ServiceThrottle == null)
280 ServiceThrottle = new ServiceThrottle ();
282 loop_manager.Start ();
285 void HandleError (Exception ex)
287 foreach (IErrorHandler handler in ErrorHandlers)
288 if (handler.HandleError (ex))
293 // isolated from ChannelDispatcher
294 class ListenerLoopManager
296 ChannelDispatcher owner;
297 AutoResetEvent handle = new AutoResetEvent (false);
298 AutoResetEvent creator_handle = new AutoResetEvent (false);
299 ManualResetEvent stop_handle = new ManualResetEvent (false);
302 TimeSpan open_timeout;
303 Func<IAsyncResult> channel_acceptor;
304 List<IChannel> channels = new List<IChannel> ();
306 public ListenerLoopManager (ChannelDispatcher owner, TimeSpan openTimeout)
309 open_timeout = openTimeout;
314 if (owner.Listener.State != CommunicationState.Opened)
315 owner.Listener.Open (open_timeout);
317 // It is tested at Open(), but strangely it is not instantiated at this point.
318 foreach (var ed in owner.Endpoints)
319 if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
320 throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
321 SetupChannelAcceptor ();
326 foreach (var ed in owner.Endpoints)
327 if (ed.DispatchRuntime.InstanceContextProvider == null)
328 ed.DispatchRuntime.InstanceContextProvider = new DefaultInstanceContextProvider ();
330 if (loop_thread == null)
331 loop_thread = new Thread (new ThreadStart (Loop));
332 loop_thread.Start ();
335 Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
337 IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
340 AsyncCallback callback = delegate (IAsyncResult result) {
342 ChannelAccepted (r.EndAcceptChannel (result));
343 } catch (Exception ex) {
344 Console.WriteLine ("Exception during finishing channel acceptance.");
345 Console.WriteLine (ex);
350 return r.BeginAcceptChannel (callback, null);
351 } catch (Exception ex) {
352 Console.WriteLine ("Exception during accepting channel.");
353 Console.WriteLine (ex);
359 void SetupChannelAcceptor ()
361 var l = owner.Listener;
363 CreateAcceptor<IReplyChannel> (l) ??
364 CreateAcceptor<IReplySessionChannel> (l) ??
365 CreateAcceptor<IInputChannel> (l) ??
366 CreateAcceptor<IInputSessionChannel> (l) ??
367 CreateAcceptor<IDuplexChannel> (l) ??
368 CreateAcceptor<IDuplexSessionChannel> (l);
369 if (channel_acceptor == null)
370 throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
373 public void Stop (TimeSpan timeout)
376 creator_handle.Set ();
378 if (stop_handle != null) {
379 stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
380 stop_handle.Close ();
383 if (owner.Listener.State != CommunicationState.Closed)
384 owner.Listener.Abort ();
385 if (loop_thread != null && loop_thread.IsAlive)
386 loop_thread.Abort ();
390 public void CloseInput ()
392 foreach (var ch in channels.ToArray ()) {
393 if (ch.State == CommunicationState.Closed)
394 channels.Remove (ch); // zonbie, if exists
404 } catch (Exception ex) {
406 Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
407 Console.WriteLine (ex);
409 if (stop_handle != null)
418 // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
419 // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
421 //FIXME: The logic here should be somewhat different as follows:
423 //2. Get the appropriate EndPointDispatcher that can handle the message
424 // which is done using the filters (AddressFilter, ContractFilter).
425 //3. Let the appropriate endpoint handle the request.
428 while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
430 creator_handle.WaitOne (); // released by ChannelAccepted()
431 creator_handle.Reset ();
435 handle.WaitOne (); // released by IChannel.Close()
438 owner.Listener.Close ();
442 void ChannelAccepted (IChannel ch)
445 if (ch == null) // could happen when it was aborted
448 var dis = ch as IDisposable;
455 ch.Opened += delegate {
456 ch.Faulted += delegate {
457 if (channels.Contains (ch))
458 channels.Remove (ch);
459 handle.Set (); // release loop wait lock.
461 ch.Closed += delegate {
462 if (channels.Contains (ch))
463 channels.Remove (ch);
464 handle.Set (); // release loop wait lock.
469 creator_handle.Set ();
472 ProcessRequestOrInput (ch);
475 void ProcessRequestOrInput (IChannel ch)
477 var reply = ch as IReplyChannel;
478 var input = ch as IInputChannel;
481 if (owner.ReceiveSynchronously) {
483 if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
484 ProcessRequest (reply, rc);
486 reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
488 } else if (input != null) {
489 if (owner.ReceiveSynchronously) {
491 if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
492 ProcessInput (input, msg);
494 input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
499 void TryReceiveRequestDone (IAsyncResult result)
502 var reply = (IReplyChannel) result.AsyncState;
503 if (reply.EndTryReceiveRequest (result, out rc))
504 ProcessRequest (reply, rc);
507 void TryReceiveDone (IAsyncResult result)
510 var input = (IInputChannel) result.AsyncState;
511 if (input.EndTryReceive (result, out msg))
512 ProcessInput (input, msg);
515 void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
519 MessageVersion version = rc.RequestMessage.Version;
520 FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
521 Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
524 catch (Exception e) { }
527 void ProcessRequest (IReplyChannel reply, RequestContext rc)
530 EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
531 new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
533 } catch (EndpointNotFoundException ex) {
534 SendEndpointNotFound (rc, ex);
535 } catch (Exception ex) {
537 Console.WriteLine (ex);
539 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
540 if (reply.State != CommunicationState.Closed)
541 ProcessRequestOrInput (reply);
545 void ProcessInput (IInputChannel input, Message message)
548 EndpointDispatcher candidate = null;
549 candidate = FindEndpointDispatcher (message);
550 new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
551 ProcessInput (message);
553 catch (Exception ex) {
555 Console.WriteLine (ex);
557 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
558 if (input.State != CommunicationState.Closed)
559 ProcessRequestOrInput (input);
563 EndpointDispatcher FindEndpointDispatcher (Message message) {
564 EndpointDispatcher candidate = null;
565 for (int i = 0; i < owner.Endpoints.Count; i++) {
566 if (MessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
567 var newdis = owner.Endpoints [i];
568 if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
570 else if (candidate.FilterPriority == newdis.FilterPriority)
571 throw new MultipleFilterMatchesException ();
574 if (candidate == null && owner.Host != null)
575 owner.Host.OnUnknownMessageReceived (message);
579 bool MessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
581 Uri to = req.Headers.To;
584 if (to.AbsoluteUri == Constants.WsaAnonymousUri)
586 return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);