PeerService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Diagnostics;
  9. using System.Net;
  10. using System.Runtime;
  11. using System.ServiceModel;
  12. using System.ServiceModel.Description;
  13. using System.ServiceModel.Diagnostics;
  14. using System.ServiceModel.Dispatcher;
  15. // What the connector interface needs to looks like
  16. interface IPeerConnectorContract
  17. {
  18. void Connect(IPeerNeighbor neighbor, ConnectInfo connectInfo);
  19. void Disconnect(IPeerNeighbor neighbor, DisconnectInfo disconnectInfo);
  20. void Refuse(IPeerNeighbor neighbor, RefuseInfo refuseInfo);
  21. void Welcome(IPeerNeighbor neighbor, WelcomeInfo welcomeInfo);
  22. }
  23. // Implemented by flooder / service uses this to delegate service invocations
  24. interface IPeerFlooderContract<TFloodContract, TLinkContract>
  25. {
  26. //invoked by the peerservice
  27. IAsyncResult OnFloodedMessage(IPeerNeighbor neighbor, TFloodContract floodedInfo, AsyncCallback callback, object state);
  28. void EndFloodMessage(IAsyncResult result);
  29. void ProcessLinkUtility(IPeerNeighbor neighbor, TLinkContract utilityInfo);
  30. }
  31. // Class that implements IPeerService contract for incoming neighbor sessions and messages.
  32. // WARNING: This class is not synchronized. Expects the using class to synchronize access
  33. [ServiceBehavior(
  34. ConcurrencyMode = ConcurrencyMode.Multiple,
  35. InstanceContextMode = InstanceContextMode.Single,
  36. UseSynchronizationContext = false)]
  37. class PeerService : IPeerService, IServiceBehavior, IChannelInitializer
  38. {
  39. public delegate bool ChannelCallback(IClientChannel channel);
  40. public delegate IPeerNeighbor GetNeighborCallback(IPeerProxy channel);
  41. Binding binding;
  42. PeerNodeConfig config;
  43. ChannelCallback newChannelCallback;
  44. GetNeighborCallback getNeighborCallback;
  45. ServiceHost serviceHost; // To listen for incoming neighbor sessions
  46. IPeerConnectorContract connector;
  47. IPeerFlooderContract<Message, UtilityInfo> flooder;
  48. IPeerNodeMessageHandling messageHandler;
  49. public PeerService(PeerNodeConfig config,
  50. ChannelCallback channelCallback,
  51. GetNeighborCallback getNeighborCallback,
  52. Dictionary<Type, object> services)
  53. : this(config, channelCallback, getNeighborCallback, services, null) { }
  54. public PeerService(PeerNodeConfig config,
  55. ChannelCallback channelCallback,
  56. GetNeighborCallback getNeighborCallback,
  57. Dictionary<Type, object> services,
  58. IPeerNodeMessageHandling messageHandler)
  59. {
  60. this.config = config;
  61. this.newChannelCallback = channelCallback;
  62. Fx.Assert(getNeighborCallback != null, "getNeighborCallback must be passed to PeerService constructor");
  63. this.getNeighborCallback = getNeighborCallback;
  64. this.messageHandler = messageHandler;
  65. if (services != null)
  66. {
  67. object reply = null;
  68. services.TryGetValue(typeof(IPeerConnectorContract), out reply);
  69. connector = reply as IPeerConnectorContract;
  70. Fx.Assert(connector != null, "PeerService must be created with a connector implementation");
  71. reply = null;
  72. services.TryGetValue(typeof(IPeerFlooderContract<Message, UtilityInfo>), out reply);
  73. flooder = reply as IPeerFlooderContract<Message, UtilityInfo>;
  74. Fx.Assert(flooder != null, "PeerService must be created with a flooder implementation");
  75. }
  76. this.serviceHost = new ServiceHost(this);
  77. // Add throttling
  78. ServiceThrottlingBehavior throttle = new ServiceThrottlingBehavior();
  79. throttle.MaxConcurrentCalls = this.config.MaxPendingIncomingCalls;
  80. throttle.MaxConcurrentSessions = this.config.MaxConcurrentSessions;
  81. this.serviceHost.Description.Behaviors.Add(throttle);
  82. }
  83. public void Abort()
  84. {
  85. this.serviceHost.Abort();
  86. }
  87. public Binding Binding
  88. {
  89. get { return this.binding; }
  90. }
  91. // Create the binding using user specified config. The stacking is
  92. // BinaryMessageEncoder/TCP
  93. void CreateBinding()
  94. {
  95. Collection<BindingElement> bindingElements = new Collection<BindingElement>();
  96. BindingElement security = this.config.SecurityManager.GetSecurityBindingElement();
  97. if (security != null)
  98. {
  99. bindingElements.Add(security);
  100. }
  101. TcpTransportBindingElement transport = new TcpTransportBindingElement();
  102. transport.MaxReceivedMessageSize = this.config.MaxReceivedMessageSize;
  103. transport.MaxBufferPoolSize = this.config.MaxBufferPoolSize;
  104. transport.TeredoEnabled = true;
  105. MessageEncodingBindingElement encoder = null;
  106. if (messageHandler != null)
  107. encoder = messageHandler.EncodingBindingElement;
  108. if (encoder == null)
  109. {
  110. BinaryMessageEncodingBindingElement bencoder = new BinaryMessageEncodingBindingElement();
  111. this.config.ReaderQuotas.CopyTo(bencoder.ReaderQuotas);
  112. bindingElements.Add(bencoder);
  113. }
  114. else
  115. {
  116. bindingElements.Add(encoder);
  117. }
  118. bindingElements.Add(transport);
  119. this.binding = new CustomBinding(bindingElements);
  120. this.binding.ReceiveTimeout = TimeSpan.MaxValue;
  121. }
  122. // Returns the address that the serviceHost is listening on.
  123. public EndpointAddress GetListenAddress()
  124. {
  125. IChannelListener listener = this.serviceHost.ChannelDispatchers[0].Listener;
  126. return new EndpointAddress(listener.Uri, listener.GetProperty<EndpointIdentity>());
  127. }
  128. IPeerNeighbor GetNeighbor()
  129. {
  130. IPeerNeighbor neighbor = (IPeerNeighbor)getNeighborCallback(OperationContext.Current.GetCallbackChannel<IPeerProxy>());
  131. if (neighbor == null || neighbor.State == PeerNeighborState.Closed)
  132. {
  133. if (DiagnosticUtility.ShouldTraceWarning)
  134. {
  135. TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.PeerNeighborNotFound,
  136. SR.GetString(SR.TraceCodePeerNeighborNotFound),
  137. new PeerNodeTraceRecord(config.NodeId),
  138. OperationContext.Current.IncomingMessage);
  139. }
  140. return null;
  141. }
  142. if (DiagnosticUtility.ShouldTraceVerbose)
  143. {
  144. PeerNeighborState state = neighbor.State;
  145. PeerNodeAddress listenAddr = null;
  146. IPAddress connectIPAddr = null;
  147. if (state >= PeerNeighborState.Opened && state <= PeerNeighborState.Connected)
  148. {
  149. listenAddr = config.GetListenAddress(true);
  150. connectIPAddr = config.ListenIPAddress;
  151. }
  152. PeerNeighborTraceRecord record = new PeerNeighborTraceRecord(neighbor.NodeId,
  153. this.config.NodeId, listenAddr, connectIPAddr, neighbor.GetHashCode(),
  154. neighbor.IsInitiator, state.ToString(), null, null,
  155. OperationContext.Current.IncomingMessage.Headers.Action);
  156. TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerNeighborMessageReceived, SR.GetString(SR.TraceCodePeerNeighborMessageReceived), record, this, null);
  157. }
  158. return neighbor;
  159. }
  160. public void Open(TimeSpan timeout)
  161. {
  162. // Create the neighbor binding
  163. CreateBinding();
  164. this.serviceHost.Description.Endpoints.Clear();
  165. ServiceEndpoint endPoint = this.serviceHost.AddServiceEndpoint(typeof(IPeerService), this.binding, config.GetMeshUri());
  166. endPoint.ListenUri = config.GetSelfUri();
  167. endPoint.ListenUriMode = (this.config.Port > 0) ? ListenUriMode.Explicit : ListenUriMode.Unique;
  168. /*
  169. Uncomment this to allow the retrieval of metadata
  170. using the command:
  171. \binaries.x86chk\svcutil http://localhost /t:metadata
  172. ServiceMetadataBehavior mex = new ServiceMetadataBehavior();
  173. mex.HttpGetEnabled = true;
  174. mex.HttpGetUrl = new Uri("http://localhost");
  175. mex.HttpsGetEnabled = true;
  176. mex.HttpsGetUrl = new Uri("https://localhost");
  177. this.serviceHost.Description.Behaviors.Add(mex);
  178. */
  179. this.config.SecurityManager.ApplyServiceSecurity(this.serviceHost.Description);
  180. this.serviceHost.Open(timeout);
  181. if (DiagnosticUtility.ShouldTraceInformation)
  182. {
  183. TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerServiceOpened,
  184. SR.GetString(SR.TraceCodePeerServiceOpened, this.GetListenAddress()), this);
  185. }
  186. }
  187. //
  188. // IContractBehavior and IChannelInitializer implementation.
  189. // Used to register for incoming channel notification.
  190. //
  191. void IServiceBehavior.Validate(ServiceDescription description, ServiceHostBase serviceHost)
  192. {
  193. }
  194. void IServiceBehavior.AddBindingParameters(ServiceDescription description, ServiceHostBase serviceHost, Collection<ServiceEndpoint> endpoints, BindingParameterCollection parameters)
  195. {
  196. }
  197. void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHost)
  198. {
  199. for (int i = 0; i < serviceHost.ChannelDispatchers.Count; i++)
  200. {
  201. ChannelDispatcher channelDispatcher = serviceHost.ChannelDispatchers[i] as ChannelDispatcher;
  202. if (channelDispatcher != null)
  203. {
  204. bool addedChannelInitializer = false;
  205. foreach (EndpointDispatcher endpointDispatcher in channelDispatcher.Endpoints)
  206. {
  207. if (!endpointDispatcher.IsSystemEndpoint)
  208. {
  209. if (!addedChannelInitializer)
  210. {
  211. channelDispatcher.ChannelInitializers.Add(this);
  212. addedChannelInitializer = true;
  213. }
  214. endpointDispatcher.DispatchRuntime.OperationSelector = new OperationSelector(this.messageHandler);
  215. }
  216. }
  217. }
  218. }
  219. }
  220. void IChannelInitializer.Initialize(IClientChannel channel)
  221. {
  222. newChannelCallback(channel);
  223. }
  224. void IPeerServiceContract.Connect(ConnectInfo connectInfo)
  225. {
  226. IPeerNeighbor neighbor = GetNeighbor();
  227. if (neighbor != null)
  228. {
  229. connector.Connect(neighbor, connectInfo);
  230. }
  231. }
  232. void IPeerServiceContract.Disconnect(DisconnectInfo disconnectInfo)
  233. {
  234. IPeerNeighbor neighbor = GetNeighbor();
  235. if (neighbor != null)
  236. {
  237. connector.Disconnect(neighbor, disconnectInfo);
  238. }
  239. }
  240. void IPeerServiceContract.Refuse(RefuseInfo refuseInfo)
  241. {
  242. IPeerNeighbor neighbor = GetNeighbor();
  243. if (neighbor != null)
  244. {
  245. connector.Refuse(neighbor, refuseInfo);
  246. }
  247. }
  248. void IPeerServiceContract.Welcome(WelcomeInfo welcomeInfo)
  249. {
  250. IPeerNeighbor neighbor = GetNeighbor();
  251. if (neighbor != null)
  252. {
  253. connector.Welcome(neighbor, welcomeInfo);
  254. }
  255. }
  256. IAsyncResult IPeerServiceContract.BeginFloodMessage(Message floodedInfo, AsyncCallback callback, object state)
  257. {
  258. IPeerNeighbor neighbor = GetNeighbor();
  259. if (neighbor != null)
  260. {
  261. return flooder.OnFloodedMessage(neighbor, floodedInfo, callback, state);
  262. }
  263. else
  264. return new CompletedAsyncResult(callback, state);
  265. }
  266. void IPeerServiceContract.EndFloodMessage(IAsyncResult result)
  267. {
  268. flooder.EndFloodMessage(result);
  269. }
  270. void IPeerServiceContract.LinkUtility(UtilityInfo utilityInfo)
  271. {
  272. IPeerNeighbor neighbor = GetNeighbor();
  273. if (neighbor != null)
  274. {
  275. flooder.ProcessLinkUtility(neighbor, utilityInfo);
  276. }
  277. }
  278. Message IPeerServiceContract.ProcessRequestSecurityToken(Message message)
  279. {
  280. IPeerNeighbor neighbor = GetNeighbor();
  281. if (neighbor == null)
  282. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(typeof(IPeerNeighbor).ToString()));
  283. Message reply = this.config.SecurityManager.ProcessRequest(neighbor, message);
  284. if (reply == null)
  285. {
  286. OperationContext current = OperationContext.Current;
  287. current.RequestContext.Close();
  288. current.RequestContext = null;
  289. }
  290. return reply;
  291. }
  292. void IPeerServiceContract.Fault(Message message)
  293. {
  294. IPeerNeighbor neighbor = GetNeighbor();
  295. if (neighbor == null)
  296. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(typeof(IPeerNeighbor).ToString()));
  297. neighbor.Abort(PeerCloseReason.Faulted, PeerCloseInitiator.RemoteNode);
  298. }
  299. void IPeerServiceContract.Ping(Message message)
  300. {
  301. }
  302. }
  303. }