Channel.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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
  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 string target;
  37. readonly GrpcEnvironment environment;
  38. readonly CompletionQueueSafeHandle completionQueue;
  39. readonly ChannelSafeHandle handle;
  40. readonly Dictionary<string, ChannelOption> options;
  41. readonly Task connectivityWatcherTask;
  42. bool shutdownRequested;
  43. /// <summary>
  44. /// Creates a channel that connects to a specific host.
  45. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
  46. /// </summary>
  47. /// <param name="target">Target of the channel.</param>
  48. /// <param name="credentials">Credentials to secure the channel.</param>
  49. public Channel(string target, ChannelCredentials credentials) :
  50. this(target, credentials, null)
  51. {
  52. }
  53. /// <summary>
  54. /// Creates a channel that connects to a specific host.
  55. /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
  56. /// </summary>
  57. /// <param name="target">Target of the channel.</param>
  58. /// <param name="credentials">Credentials to secure the channel.</param>
  59. /// <param name="options">Channel options.</param>
  60. public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
  61. {
  62. this.target = GrpcPreconditions.CheckNotNull(target, "target");
  63. this.options = CreateOptionsDictionary(options);
  64. EnsureUserAgentChannelOption(this.options);
  65. this.environment = GrpcEnvironment.AddRef();
  66. this.completionQueue = this.environment.PickCompletionQueue();
  67. using (var nativeCredentials = credentials.ToNativeCredentials())
  68. using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
  69. {
  70. if (nativeCredentials != null)
  71. {
  72. this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
  73. }
  74. else
  75. {
  76. this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
  77. }
  78. }
  79. // TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822.
  80. // Remove once retries are supported in C core
  81. this.connectivityWatcherTask = RunConnectivityWatcherAsync();
  82. GrpcEnvironment.RegisterChannel(this);
  83. }
  84. /// <summary>
  85. /// Creates a channel that connects to a specific host and port.
  86. /// </summary>
  87. /// <param name="host">The name or IP address of the host.</param>
  88. /// <param name="port">The port.</param>
  89. /// <param name="credentials">Credentials to secure the channel.</param>
  90. public Channel(string host, int port, ChannelCredentials credentials) :
  91. this(host, port, credentials, null)
  92. {
  93. }
  94. /// <summary>
  95. /// Creates a channel that connects to a specific host and port.
  96. /// </summary>
  97. /// <param name="host">The name or IP address of the host.</param>
  98. /// <param name="port">The port.</param>
  99. /// <param name="credentials">Credentials to secure the channel.</param>
  100. /// <param name="options">Channel options.</param>
  101. public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
  102. this(string.Format("{0}:{1}", host, port), credentials, options)
  103. {
  104. }
  105. /// <summary>
  106. /// Gets current connectivity state of this channel.
  107. /// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
  108. /// </summary>
  109. public ChannelState State
  110. {
  111. get
  112. {
  113. return GetConnectivityState(false);
  114. }
  115. }
  116. /// <summary>
  117. /// Returned tasks completes once channel state has become different from
  118. /// given lastObservedState.
  119. /// If deadline is reached or and error occurs, returned task is cancelled.
  120. /// </summary>
  121. public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
  122. {
  123. GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
  124. "Shutdown is a terminal state. No further state changes can occur.");
  125. var tcs = new TaskCompletionSource<object>();
  126. var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
  127. var handler = new BatchCompletionDelegate((success, ctx) =>
  128. {
  129. if (success)
  130. {
  131. tcs.SetResult(null);
  132. }
  133. else
  134. {
  135. tcs.SetCanceled();
  136. }
  137. });
  138. handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, handler);
  139. return tcs.Task;
  140. }
  141. /// <summary>Resolved address of the remote endpoint in URI format.</summary>
  142. public string ResolvedTarget
  143. {
  144. get
  145. {
  146. return handle.GetTarget();
  147. }
  148. }
  149. /// <summary>The original target used to create the channel.</summary>
  150. public string Target
  151. {
  152. get
  153. {
  154. return this.target;
  155. }
  156. }
  157. /// <summary>
  158. /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
  159. /// </summary>
  160. public CancellationToken ShutdownToken
  161. {
  162. get
  163. {
  164. return this.shutdownTokenSource.Token;
  165. }
  166. }
  167. /// <summary>
  168. /// Allows explicitly requesting channel to connect without starting an RPC.
  169. /// Returned task completes once state Ready was seen. If the deadline is reached,
  170. /// or channel enters the Shutdown state, the task is cancelled.
  171. /// There is no need to call this explicitly unless your use case requires that.
  172. /// Starting an RPC on a new channel will request connection implicitly.
  173. /// </summary>
  174. /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
  175. public async Task ConnectAsync(DateTime? deadline = null)
  176. {
  177. var currentState = GetConnectivityState(true);
  178. while (currentState != ChannelState.Ready)
  179. {
  180. if (currentState == ChannelState.Shutdown)
  181. {
  182. throw new OperationCanceledException("Channel has reached Shutdown state.");
  183. }
  184. await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
  185. currentState = GetConnectivityState(false);
  186. }
  187. }
  188. /// <summary>
  189. /// Shuts down the channel cleanly. It is strongly recommended to shutdown
  190. /// all previously created channels before exiting from the process.
  191. /// </summary>
  192. /// <remarks>
  193. /// This method doesn't wait for all calls on this channel to finish (nor does
  194. /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
  195. /// all the calls on this channel have finished (successfully or with an error)
  196. /// before shutting down the channel to ensure channel shutdown won't impact
  197. /// the outcome of those remote calls.
  198. /// </remarks>
  199. public async Task ShutdownAsync()
  200. {
  201. lock (myLock)
  202. {
  203. GrpcPreconditions.CheckState(!shutdownRequested);
  204. shutdownRequested = true;
  205. }
  206. GrpcEnvironment.UnregisterChannel(this);
  207. shutdownTokenSource.Cancel();
  208. var activeCallCount = activeCallCounter.Count;
  209. if (activeCallCount > 0)
  210. {
  211. Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
  212. }
  213. handle.Dispose();
  214. await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
  215. }
  216. internal ChannelSafeHandle Handle
  217. {
  218. get
  219. {
  220. return this.handle;
  221. }
  222. }
  223. internal GrpcEnvironment Environment
  224. {
  225. get
  226. {
  227. return this.environment;
  228. }
  229. }
  230. internal CompletionQueueSafeHandle CompletionQueue
  231. {
  232. get
  233. {
  234. return this.completionQueue;
  235. }
  236. }
  237. internal void AddCallReference(object call)
  238. {
  239. activeCallCounter.Increment();
  240. bool success = false;
  241. handle.DangerousAddRef(ref success);
  242. GrpcPreconditions.CheckState(success);
  243. }
  244. internal void RemoveCallReference(object call)
  245. {
  246. handle.DangerousRelease();
  247. activeCallCounter.Decrement();
  248. }
  249. private ChannelState GetConnectivityState(bool tryToConnect)
  250. {
  251. try
  252. {
  253. return handle.CheckConnectivityState(tryToConnect);
  254. }
  255. catch (ObjectDisposedException)
  256. {
  257. return ChannelState.Shutdown;
  258. }
  259. }
  260. /// <summary>
  261. /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
  262. /// </summary>
  263. private async Task RunConnectivityWatcherAsync()
  264. {
  265. try
  266. {
  267. var lastState = State;
  268. while (lastState != ChannelState.Shutdown)
  269. {
  270. lock (myLock)
  271. {
  272. if (shutdownRequested)
  273. {
  274. break;
  275. }
  276. }
  277. try
  278. {
  279. await WaitForStateChangedAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
  280. }
  281. catch (TaskCanceledException)
  282. {
  283. // ignore timeout
  284. }
  285. lastState = State;
  286. }
  287. }
  288. catch (ObjectDisposedException) {
  289. // during shutdown, channel is going to be disposed.
  290. }
  291. }
  292. private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
  293. {
  294. var key = ChannelOptions.PrimaryUserAgentString;
  295. var userAgentString = "";
  296. ChannelOption option;
  297. if (options.TryGetValue(key, out option))
  298. {
  299. // user-provided userAgentString needs to be at the beginning
  300. userAgentString = option.StringValue + " ";
  301. };
  302. // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
  303. userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
  304. options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
  305. }
  306. private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
  307. {
  308. var dict = new Dictionary<string, ChannelOption>();
  309. if (options == null)
  310. {
  311. return dict;
  312. }
  313. foreach (var option in options)
  314. {
  315. dict.Add(option.Name, option);
  316. }
  317. return dict;
  318. }
  319. }
  320. }