Channel.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. // cached handler for watch connectivity state
  117. static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
  118. {
  119. var tcs = (TaskCompletionSource<bool>) state;
  120. tcs.SetResult(success);
  121. };
  122. /// <summary>
  123. /// Returned tasks completes once channel state has become different from
  124. /// given lastObservedState.
  125. /// If deadline is reached or and error occurs, returned task is cancelled.
  126. /// </summary>
  127. public async Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
  128. {
  129. var result = await WaitForStateChangedInternalAsync(lastObservedState, deadline).ConfigureAwait(false);
  130. if (!result)
  131. {
  132. throw new TaskCanceledException("Reached deadline.");
  133. }
  134. }
  135. /// <summary>
  136. /// Returned tasks completes once channel state has become different from
  137. /// given lastObservedState (<c>true</c> is returned) or if the wait has timed out (<c>false</c> is returned).
  138. /// </summary>
  139. internal Task<bool> WaitForStateChangedInternalAsync(ChannelState lastObservedState, DateTime? deadline = null)
  140. {
  141. GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
  142. "Shutdown is a terminal state. No further state changes can occur.");
  143. var tcs = new TaskCompletionSource<bool>();
  144. var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
  145. lock (myLock)
  146. {
  147. // pass "tcs" as "state" for WatchConnectivityStateHandler.
  148. handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
  149. }
  150. return tcs.Task;
  151. }
  152. /// <summary>Resolved address of the remote endpoint in URI format.</summary>
  153. public string ResolvedTarget
  154. {
  155. get
  156. {
  157. return handle.GetTarget();
  158. }
  159. }
  160. /// <summary>The original target used to create the channel.</summary>
  161. public string Target
  162. {
  163. get
  164. {
  165. return this.target;
  166. }
  167. }
  168. /// <summary>
  169. /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
  170. /// </summary>
  171. public CancellationToken ShutdownToken
  172. {
  173. get
  174. {
  175. return this.shutdownTokenSource.Token;
  176. }
  177. }
  178. /// <summary>
  179. /// Allows explicitly requesting channel to connect without starting an RPC.
  180. /// Returned task completes once state Ready was seen. If the deadline is reached,
  181. /// or channel enters the Shutdown state, the task is cancelled.
  182. /// There is no need to call this explicitly unless your use case requires that.
  183. /// Starting an RPC on a new channel will request connection implicitly.
  184. /// </summary>
  185. /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
  186. public async Task ConnectAsync(DateTime? deadline = null)
  187. {
  188. var currentState = GetConnectivityState(true);
  189. while (currentState != ChannelState.Ready)
  190. {
  191. if (currentState == ChannelState.Shutdown)
  192. {
  193. throw new OperationCanceledException("Channel has reached Shutdown state.");
  194. }
  195. await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
  196. currentState = GetConnectivityState(false);
  197. }
  198. }
  199. /// <summary>
  200. /// Shuts down the channel cleanly. It is strongly recommended to shutdown
  201. /// all previously created channels before exiting from the process.
  202. /// </summary>
  203. /// <remarks>
  204. /// This method doesn't wait for all calls on this channel to finish (nor does
  205. /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
  206. /// all the calls on this channel have finished (successfully or with an error)
  207. /// before shutting down the channel to ensure channel shutdown won't impact
  208. /// the outcome of those remote calls.
  209. /// </remarks>
  210. public async Task ShutdownAsync()
  211. {
  212. lock (myLock)
  213. {
  214. GrpcPreconditions.CheckState(!shutdownRequested);
  215. shutdownRequested = true;
  216. }
  217. GrpcEnvironment.UnregisterChannel(this);
  218. shutdownTokenSource.Cancel();
  219. var activeCallCount = activeCallCounter.Count;
  220. if (activeCallCount > 0)
  221. {
  222. Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
  223. }
  224. lock (myLock)
  225. {
  226. handle.Dispose();
  227. }
  228. await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
  229. }
  230. internal ChannelSafeHandle Handle
  231. {
  232. get
  233. {
  234. return this.handle;
  235. }
  236. }
  237. internal GrpcEnvironment Environment
  238. {
  239. get
  240. {
  241. return this.environment;
  242. }
  243. }
  244. internal CompletionQueueSafeHandle CompletionQueue
  245. {
  246. get
  247. {
  248. return this.completionQueue;
  249. }
  250. }
  251. internal void AddCallReference(object call)
  252. {
  253. activeCallCounter.Increment();
  254. bool success = false;
  255. handle.DangerousAddRef(ref success);
  256. GrpcPreconditions.CheckState(success);
  257. }
  258. internal void RemoveCallReference(object call)
  259. {
  260. handle.DangerousRelease();
  261. activeCallCounter.Decrement();
  262. }
  263. private ChannelState GetConnectivityState(bool tryToConnect)
  264. {
  265. try
  266. {
  267. lock (myLock)
  268. {
  269. return handle.CheckConnectivityState(tryToConnect);
  270. }
  271. }
  272. catch (ObjectDisposedException)
  273. {
  274. return ChannelState.Shutdown;
  275. }
  276. }
  277. /// <summary>
  278. /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
  279. /// </summary>
  280. private async Task RunConnectivityWatcherAsync()
  281. {
  282. try
  283. {
  284. var lastState = State;
  285. while (lastState != ChannelState.Shutdown)
  286. {
  287. lock (myLock)
  288. {
  289. if (shutdownRequested)
  290. {
  291. break;
  292. }
  293. }
  294. // ignore the result
  295. await WaitForStateChangedInternalAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
  296. lastState = State;
  297. }
  298. }
  299. catch (ObjectDisposedException) {
  300. // during shutdown, channel is going to be disposed.
  301. }
  302. }
  303. private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
  304. {
  305. var key = ChannelOptions.PrimaryUserAgentString;
  306. var userAgentString = "";
  307. ChannelOption option;
  308. if (options.TryGetValue(key, out option))
  309. {
  310. // user-provided userAgentString needs to be at the beginning
  311. userAgentString = option.StringValue + " ";
  312. };
  313. // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
  314. userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
  315. options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
  316. }
  317. private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
  318. {
  319. var dict = new Dictionary<string, ChannelOption>();
  320. if (options == null)
  321. {
  322. return dict;
  323. }
  324. foreach (var option in options)
  325. {
  326. dict.Add(option.Name, option);
  327. }
  328. return dict;
  329. }
  330. }
  331. }