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 (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 bool IsMessageMatchesEndpointDispatcher (Message req, EndpointDispatcher endpoint)
287 Uri to = req.Headers.To;
290 if (to.AbsoluteUri == Constants.WsaAnonymousUri)
292 return endpoint.AddressFilter.Match (req) && endpoint.ContractFilter.Match (req);
295 void HandleError (Exception ex)
297 foreach (IErrorHandler handler in ErrorHandlers)
298 if (handler.HandleError (ex))
302 class ListenerLoopManager
304 ChannelDispatcher owner;
305 AutoResetEvent handle = new AutoResetEvent (false);
306 AutoResetEvent creator_handle = new AutoResetEvent (false);
307 ManualResetEvent stop_handle = new ManualResetEvent (false);
310 TimeSpan open_timeout;
311 Func<IAsyncResult> channel_acceptor;
312 List<IChannel> channels = new List<IChannel> ();
314 public ListenerLoopManager (ChannelDispatcher owner, TimeSpan openTimeout)
317 open_timeout = openTimeout;
322 if (owner.Listener.State != CommunicationState.Opened)
323 owner.Listener.Open (open_timeout);
325 // It is tested at Open(), but strangely it is not instantiated at this point.
326 foreach (var ed in owner.Endpoints)
327 if (ed.DispatchRuntime.InstanceContextProvider == null && (ed.DispatchRuntime.Type == null || ed.DispatchRuntime.Type.GetConstructor (Type.EmptyTypes) == null))
328 throw new InvalidOperationException ("There is no default constructor for the service Type in the DispatchRuntime");
329 SetupChannelAcceptor ();
334 foreach (var ed in owner.Endpoints)
335 if (ed.DispatchRuntime.InstanceContextProvider == null)
336 ed.DispatchRuntime.InstanceContextProvider = new DefaultInstanceContextProvider ();
338 if (loop_thread == null)
339 loop_thread = new Thread (new ThreadStart (Loop));
340 loop_thread.Start ();
343 Func<IAsyncResult> CreateAcceptor<TChannel> (IChannelListener l) where TChannel : class, IChannel
345 IChannelListener<TChannel> r = l as IChannelListener<TChannel>;
348 AsyncCallback callback = delegate (IAsyncResult result) {
350 ChannelAccepted (r.EndAcceptChannel (result));
351 } catch (Exception ex) {
352 Console.WriteLine ("Exception during finishing channel acceptance.");
353 Console.WriteLine (ex);
358 return r.BeginAcceptChannel (callback, null);
359 } catch (Exception ex) {
360 Console.WriteLine ("Exception during accepting channel.");
361 Console.WriteLine (ex);
367 void SetupChannelAcceptor ()
369 var l = owner.Listener;
371 CreateAcceptor<IReplyChannel> (l) ??
372 CreateAcceptor<IReplySessionChannel> (l) ??
373 CreateAcceptor<IInputChannel> (l) ??
374 CreateAcceptor<IInputSessionChannel> (l) ??
375 CreateAcceptor<IDuplexChannel> (l) ??
376 CreateAcceptor<IDuplexSessionChannel> (l);
377 if (channel_acceptor == null)
378 throw new InvalidOperationException (String.Format ("Unrecognized channel listener type: {0}", l.GetType ()));
381 public void Stop (TimeSpan timeout)
384 creator_handle.Set ();
386 if (stop_handle != null) {
387 stop_handle.WaitOne (timeout > TimeSpan.Zero ? timeout : TimeSpan.FromTicks (1));
388 stop_handle.Close ();
391 if (owner.Listener.State != CommunicationState.Closed)
392 owner.Listener.Abort ();
393 if (loop_thread != null && loop_thread.IsAlive)
394 loop_thread.Abort ();
398 public void CloseInput ()
400 foreach (var ch in channels.ToArray ()) {
401 if (ch.State == CommunicationState.Closed)
402 channels.Remove (ch); // zonbie, if exists
412 } catch (Exception ex) {
414 Console.WriteLine ("ChannelDispatcher caught an exception inside dispatcher loop, which is likely thrown by the channel listener {0}", owner.Listener);
415 Console.WriteLine (ex);
417 if (stop_handle != null)
426 // FIXME: use WaitForChannel() for (*only* for) transacted channel listeners.
427 // http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3faa4a5e-8602-4dbe-a181-73b3f581835e
429 //FIXME: The logic here should be somewhat different as follows:
431 //2. Get the appropriate EndPointDispatcher that can handle the message
432 // which is done using the filters (AddressFilter, ContractFilter).
433 //3. Let the appropriate endpoint handle the request.
436 while (loop && channels.Count < owner.ServiceThrottle.MaxConcurrentSessions) {
438 creator_handle.WaitOne (); // released by ChannelAccepted()
439 creator_handle.Reset ();
443 handle.WaitOne (); // released by IChannel.Close()
446 owner.Listener.Close ();
450 void ChannelAccepted (IChannel ch)
453 if (ch == null) // could happen when it was aborted
456 var dis = ch as IDisposable;
463 ch.Opened += delegate {
464 ch.Faulted += delegate {
465 if (channels.Contains (ch))
466 channels.Remove (ch);
467 handle.Set (); // release loop wait lock.
469 ch.Closed += delegate {
470 if (channels.Contains (ch))
471 channels.Remove (ch);
472 handle.Set (); // release loop wait lock.
477 creator_handle.Set ();
480 ProcessRequestOrInput (ch);
483 void ProcessRequestOrInput (IChannel ch)
485 var reply = ch as IReplyChannel;
486 var input = ch as IInputChannel;
489 if (owner.ReceiveSynchronously) {
491 if (reply.TryReceiveRequest (owner.timeouts.ReceiveTimeout, out rc))
492 ProcessRequest (reply, rc);
494 reply.BeginTryReceiveRequest (owner.timeouts.ReceiveTimeout, TryReceiveRequestDone, reply);
496 } else if (input != null) {
497 if (owner.ReceiveSynchronously) {
499 if (input.TryReceive (owner.timeouts.ReceiveTimeout, out msg))
500 ProcessInput (input, msg);
502 input.BeginTryReceive (owner.timeouts.ReceiveTimeout, TryReceiveDone, input);
507 void TryReceiveRequestDone (IAsyncResult result)
510 var reply = (IReplyChannel) result.AsyncState;
511 if (reply.EndTryReceiveRequest (result, out rc))
512 ProcessRequest (reply, rc);
515 void TryReceiveDone (IAsyncResult result)
518 var input = (IInputChannel) result.AsyncState;
519 if (input.EndTryReceive (result, out msg))
520 ProcessInput (input, msg);
523 void SendEndpointNotFound (RequestContext rc, EndpointNotFoundException ex)
527 MessageVersion version = rc.RequestMessage.Version;
528 FaultCode fc = new FaultCode ("DestinationUnreachable", version.Addressing.Namespace);
529 Message res = Message.CreateMessage (version, fc, "error occured", rc.RequestMessage.Headers.Action);
532 catch (Exception e) { }
535 void ProcessRequest (IReplyChannel reply, RequestContext rc)
538 EndpointDispatcher candidate = FindEndpointDispatcher (rc.RequestMessage);
539 new InputOrReplyRequestProcessor (candidate.DispatchRuntime, reply).
541 } catch (EndpointNotFoundException ex) {
542 SendEndpointNotFound (rc, ex);
543 } catch (Exception ex) {
545 Console.WriteLine (ex);
547 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
548 if (reply.State != CommunicationState.Closed)
549 ProcessRequestOrInput (reply);
553 void ProcessInput (IInputChannel input, Message message)
556 EndpointDispatcher candidate = null;
557 candidate = FindEndpointDispatcher (message);
558 new InputOrReplyRequestProcessor (candidate.DispatchRuntime, input).
559 ProcessInput (message);
561 catch (Exception ex) {
563 Console.WriteLine (ex);
565 // unless it is closed by session/call manager, move it back to the loop to receive the next message.
566 if (input.State != CommunicationState.Closed)
567 ProcessRequestOrInput (input);
571 EndpointDispatcher FindEndpointDispatcher (Message message) {
572 EndpointDispatcher candidate = null;
573 for (int i = 0; i < owner.Endpoints.Count; i++) {
574 if (owner.IsMessageMatchesEndpointDispatcher (message, owner.Endpoints [i])) {
575 var newdis = owner.Endpoints [i];
576 if (candidate == null || candidate.FilterPriority < newdis.FilterPriority)
578 else if (candidate.FilterPriority == newdis.FilterPriority)
579 throw new MultipleFilterMatchesException ();
582 if (candidate == null)
583 owner.Host.OnUnknownMessageReceived (message);