Channel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using Grpc.Core.Internal;
  21. using Grpc.Core.Logging;
  22. using Grpc.Core.Utils;
  23. namespace Grpc.Core
  24. {
  25. /// <summary>
  26. /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
  27. /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
  28. /// a remote call so in general you should reuse a single channel for as many calls as possible.
  29. /// </summary>
  30. public class Channel : ChannelBase
  31. {
  32. static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
  33. readonly object myLock = new object();
  34. readonly AtomicCounter activeCallCounter = new AtomicCounter();
  35. readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
  36. readonly GrpcEnvironment environment;
  37. readonly CompletionQueueSafeHandle completionQueue;
  38. readonly ChannelSafeHandle handle;
  39. readonly Dictionary<string, ChannelOption> options;
  40. bool shutdownRequested;
  41. /// <summary>
  42. /// Creates a channel that connects to a specific host.
  43. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
  44. /// </summary>
  45. /// <param name="target">Target of the channel.</param>
  46. /// <param name="credentials">Credentials to secure the channel.</param>
  47. public Channel(string target, ChannelCredentials credentials) :
  48. this(target, credentials, null)
  49. {
  50. }
  51. /// <summary>
  52. /// Creates a channel that connects to a specific host.
  53. /// Port will default to 80 for an unsecure channel or to 443 for a secure channel.
  54. /// </summary>
  55. /// <param name="target">Target of the channel.</param>
  56. /// <param name="credentials">Credentials to secure the channel.</param>
  57. /// <param name="options">Channel options.</param>
  58. public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options) : base(target)
  59. {
  60. this.options = CreateOptionsDictionary(options);
  61. EnsureUserAgentChannelOption(this.options);
  62. this.environment = GrpcEnvironment.AddRef();
  63. this.completionQueue = this.environment.PickCompletionQueue();
  64. using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
  65. {
  66. var nativeCredentials = credentials.ToNativeCredentials();
  67. if (nativeCredentials != null)
  68. {
  69. this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
  70. }
  71. else
  72. {
  73. this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
  74. }
  75. }
  76. GrpcEnvironment.RegisterChannel(this);
  77. }
  78. /// <summary>
  79. /// Creates a channel that connects to a specific host and port.
  80. /// </summary>
  81. /// <param name="host">The name or IP address of the host.</param>
  82. /// <param name="port">The port.</param>
  83. /// <param name="credentials">Credentials to secure the channel.</param>
  84. public Channel(string host, int port, ChannelCredentials credentials) :
  85. this(host, port, credentials, null)
  86. {
  87. }
  88. /// <summary>
  89. /// Creates a channel that connects to a specific host and port.
  90. /// </summary>
  91. /// <param name="host">The name or IP address of the host.</param>
  92. /// <param name="port">The port.</param>
  93. /// <param name="credentials">Credentials to secure the channel.</param>
  94. /// <param name="options">Channel options.</param>
  95. public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
  96. this(string.Format("{0}:{1}", host, port), credentials, options)
  97. {
  98. }
  99. /// <summary>
  100. /// Gets current connectivity state of this channel.
  101. /// After channel has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
  102. /// </summary>
  103. public ChannelState State
  104. {
  105. get
  106. {
  107. return GetConnectivityState(false);
  108. }
  109. }
  110. // cached handler for watch connectivity state
  111. static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
  112. {
  113. var tcs = (TaskCompletionSource<bool>) state;
  114. tcs.SetResult(success);
  115. };
  116. /// <summary>
  117. /// Returned tasks completes once channel state has become different from
  118. /// given lastObservedState.
  119. /// If deadline is reached or an error occurs, returned task is cancelled.
  120. /// </summary>
  121. public async Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
  122. {
  123. var result = await TryWaitForStateChangedAsync(lastObservedState, deadline).ConfigureAwait(false);
  124. if (!result)
  125. {
  126. throw new TaskCanceledException("Reached deadline.");
  127. }
  128. }
  129. /// <summary>
  130. /// Returned tasks completes once channel state has become different from
  131. /// given lastObservedState (<c>true</c> is returned) or if the wait has timed out (<c>false</c> is returned).
  132. /// </summary>
  133. public Task<bool> TryWaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
  134. {
  135. GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
  136. "Shutdown is a terminal state. No further state changes can occur.");
  137. var tcs = new TaskCompletionSource<bool>();
  138. var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
  139. lock (myLock)
  140. {
  141. if (handle.IsClosed)
  142. {
  143. // If channel has been already shutdown and handle was disposed, we would end up with
  144. // an abandoned completion added to the completion registry. Instead, we make sure we fail early.
  145. throw new ObjectDisposedException(nameof(handle), "Channel handle has already been disposed.");
  146. }
  147. else
  148. {
  149. // pass "tcs" as "state" for WatchConnectivityStateHandler.
  150. handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
  151. }
  152. }
  153. return tcs.Task;
  154. }
  155. /// <summary>Resolved address of the remote endpoint in URI format.</summary>
  156. public string ResolvedTarget
  157. {
  158. get
  159. {
  160. return handle.GetTarget();
  161. }
  162. }
  163. /// <summary>
  164. /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
  165. /// </summary>
  166. public CancellationToken ShutdownToken
  167. {
  168. get
  169. {
  170. return this.shutdownTokenSource.Token;
  171. }
  172. }
  173. /// <summary>
  174. /// Allows explicitly requesting channel to connect without starting an RPC.
  175. /// Returned task completes once state Ready was seen. If the deadline is reached,
  176. /// or channel enters the Shutdown state, the task is cancelled.
  177. /// There is no need to call this explicitly unless your use case requires that.
  178. /// Starting an RPC on a new channel will request connection implicitly.
  179. /// </summary>
  180. /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
  181. public async Task ConnectAsync(DateTime? deadline = null)
  182. {
  183. var currentState = GetConnectivityState(true);
  184. while (currentState != ChannelState.Ready)
  185. {
  186. if (currentState == ChannelState.Shutdown)
  187. {
  188. throw new OperationCanceledException("Channel has reached Shutdown state.");
  189. }
  190. await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
  191. currentState = GetConnectivityState(false);
  192. }
  193. }
  194. /// <summary>Provides implementation of a non-virtual public member.</summary>
  195. protected override async Task ShutdownAsyncCore()
  196. {
  197. lock (myLock)
  198. {
  199. GrpcPreconditions.CheckState(!shutdownRequested);
  200. shutdownRequested = true;
  201. }
  202. GrpcEnvironment.UnregisterChannel(this);
  203. shutdownTokenSource.Cancel();
  204. var activeCallCount = activeCallCounter.Count;
  205. if (activeCallCount > 0)
  206. {
  207. Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
  208. }
  209. lock (myLock)
  210. {
  211. handle.Dispose();
  212. }
  213. await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false);
  214. }
  215. /// <summary>
  216. /// Create a new <see cref="CallInvoker"/> for the channel.
  217. /// </summary>
  218. /// <returns>A new <see cref="CallInvoker"/>.</returns>
  219. public override CallInvoker CreateCallInvoker()
  220. {
  221. return new DefaultCallInvoker(this);
  222. }
  223. internal ChannelSafeHandle Handle
  224. {
  225. get
  226. {
  227. return this.handle;
  228. }
  229. }
  230. internal GrpcEnvironment Environment
  231. {
  232. get
  233. {
  234. return this.environment;
  235. }
  236. }
  237. internal CompletionQueueSafeHandle CompletionQueue
  238. {
  239. get
  240. {
  241. return this.completionQueue;
  242. }
  243. }
  244. internal void AddCallReference(object call)
  245. {
  246. activeCallCounter.Increment();
  247. bool success = false;
  248. handle.DangerousAddRef(ref success);
  249. GrpcPreconditions.CheckState(success);
  250. }
  251. internal void RemoveCallReference(object call)
  252. {
  253. handle.DangerousRelease();
  254. activeCallCounter.Decrement();
  255. }
  256. // for testing only
  257. internal long GetCallReferenceCount()
  258. {
  259. return activeCallCounter.Count;
  260. }
  261. private ChannelState GetConnectivityState(bool tryToConnect)
  262. {
  263. try
  264. {
  265. lock (myLock)
  266. {
  267. return handle.CheckConnectivityState(tryToConnect);
  268. }
  269. }
  270. catch (ObjectDisposedException)
  271. {
  272. return ChannelState.Shutdown;
  273. }
  274. }
  275. private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
  276. {
  277. var key = ChannelOptions.PrimaryUserAgentString;
  278. var userAgentString = "";
  279. ChannelOption option;
  280. if (options.TryGetValue(key, out option))
  281. {
  282. // user-provided userAgentString needs to be at the beginning
  283. userAgentString = option.StringValue + " ";
  284. };
  285. // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
  286. userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
  287. options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
  288. }
  289. private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
  290. {
  291. var dict = new Dictionary<string, ChannelOption>();
  292. if (options == null)
  293. {
  294. return dict;
  295. }
  296. foreach (var option in options)
  297. {
  298. dict.Add(option.Name, option);
  299. }
  300. return dict;
  301. }
  302. }
  303. }