blob: e7b30cd1e94c503ad4e5f239adc49d2e6f0d3365 [file] [log] [blame]
Jan Tattermuscha7fff862015-02-13 11:08:08 -08001#region Copyright notice and license
Jan Tattermusch7897ae92017-06-07 22:57:36 +02002// Copyright 2015 gRPC authors.
Craig Tiller190d3602015-02-18 09:23:38 -08003//
Jan Tattermusch7897ae92017-06-07 22:57:36 +02004// 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
Craig Tiller190d3602015-02-18 09:23:38 -08007//
Jan Tattermusch7897ae92017-06-07 22:57:36 +02008// http://www.apache.org/licenses/LICENSE-2.0
Craig Tiller190d3602015-02-18 09:23:38 -08009//
Jan Tattermusch7897ae92017-06-07 22:57:36 +020010// 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.
Jan Tattermuscha7fff862015-02-13 11:08:08 -080015#endregion
Jan Tattermusch766d72b2015-07-21 20:09:25 -070016
Jan Tattermuscha7608b02015-02-03 17:54:38 -080017using System;
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070018using System.Collections.Generic;
Jan Tattermusch528fb662016-05-12 08:38:41 -070019using System.Threading;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080020using System.Threading.Tasks;
Jan Tattermusch766d72b2015-07-21 20:09:25 -070021
Jan Tattermusch30868622015-02-19 09:22:33 -080022using Grpc.Core.Internal;
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070023using Grpc.Core.Logging;
24using Grpc.Core.Utils;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080025
Jan Tattermusch30868622015-02-19 09:22:33 -080026namespace Grpc.Core
Jan Tattermuscha7608b02015-02-03 17:54:38 -080027{
Jan Tattermusch286975f2015-03-12 14:04:36 -070028 /// <summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -070029 /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
30 /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
31 /// a remote call so in general you should reuse a single channel for as many calls as possible.
Jan Tattermusch286975f2015-03-12 14:04:36 -070032 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -070033 public class Channel
Jan Tattermusch15329232015-03-02 15:32:47 -080034 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070035 static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
36
Jan Tattermusch2b357952015-08-20 14:54:33 -070037 readonly object myLock = new object();
38 readonly AtomicCounter activeCallCounter = new AtomicCounter();
Jan Tattermusch528fb662016-05-12 08:38:41 -070039 readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
Jan Tattermusch2b357952015-08-20 14:54:33 -070040
Jan Tattermusch0c140a82015-08-02 00:54:02 -070041 readonly string target;
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070042 readonly GrpcEnvironment environment;
Jan Tattermusch5ee8e772016-05-24 16:17:10 -040043 readonly CompletionQueueSafeHandle completionQueue;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080044 readonly ChannelSafeHandle handle;
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080045 readonly Dictionary<string, ChannelOption> options;
Jan Tattermusch2b357952015-08-20 14:54:33 -070046
Jan Tattermusch8a507812017-05-08 16:30:12 +020047 readonly Task connectivityWatcherTask;
48
Jan Tattermusch2b357952015-08-20 14:54:33 -070049 bool shutdownRequested;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080050
Jan Tattermusch15329232015-03-02 15:32:47 -080051 /// <summary>
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070052 /// Creates a channel that connects to a specific host.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070053 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
Jan Tattermusch15329232015-03-02 15:32:47 -080054 /// </summary>
Jan Tattermusch0c140a82015-08-02 00:54:02 -070055 /// <param name="target">Target of the channel.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070056 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch8d829d02016-06-06 16:43:54 -070057 public Channel(string target, ChannelCredentials credentials) :
58 this(target, credentials, null)
59 {
60 }
61
62 /// <summary>
63 /// Creates a channel that connects to a specific host.
64 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
65 /// </summary>
66 /// <param name="target">Target of the channel.</param>
67 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070068 /// <param name="options">Channel options.</param>
Jan Tattermusch8d829d02016-06-06 16:43:54 -070069 public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options)
Jan Tattermusch15329232015-03-02 15:32:47 -080070 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -080071 this.target = GrpcPreconditions.CheckNotNull(target, "target");
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080072 this.options = CreateOptionsDictionary(options);
Jan Tattermusch766d72b2015-07-21 20:09:25 -070073 EnsureUserAgentChannelOption(this.options);
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080074 this.environment = GrpcEnvironment.AddRef();
75
Jan Tattermusch5ee8e772016-05-24 16:17:10 -040076 this.completionQueue = this.environment.PickCompletionQueue();
Jan Tattermusch08dea322015-10-26 17:34:10 -070077 using (var nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080078 using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
Jan Tattermusch15329232015-03-02 15:32:47 -080079 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070080 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080081 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070082 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080083 }
84 else
85 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070086 this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080087 }
88 }
Jan Tattermusch8a507812017-05-08 16:30:12 +020089 // TODO(jtattermusch): Workaround for https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822.
90 // Remove once retries are supported in C core
91 this.connectivityWatcherTask = RunConnectivityWatcherAsync();
Jan Tattermusch4aea5282016-06-01 12:42:54 -070092 GrpcEnvironment.RegisterChannel(this);
Jan Tattermusch15329232015-03-02 15:32:47 -080093 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080094
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070095 /// <summary>
96 /// Creates a channel that connects to a specific host and port.
97 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070098 /// <param name="host">The name or IP address of the host.</param>
99 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -0700100 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch8d829d02016-06-06 16:43:54 -0700101 public Channel(string host, int port, ChannelCredentials credentials) :
102 this(host, port, credentials, null)
103 {
104 }
105
106 /// <summary>
107 /// Creates a channel that connects to a specific host and port.
108 /// </summary>
109 /// <param name="host">The name or IP address of the host.</param>
110 /// <param name="port">The port.</param>
111 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700112 /// <param name="options">Channel options.</param>
Jan Tattermusch8d829d02016-06-06 16:43:54 -0700113 public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700114 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800115 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800116 }
117
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700118 /// <summary>
119 /// Gets current connectivity state of this channel.
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700120 /// After channel is has been shutdown, <c>ChannelState.Shutdown</c> will be returned.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700121 /// </summary>
122 public ChannelState State
123 {
124 get
125 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700126 return GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700127 }
128 }
129
Jan Tattermusch8b451ed2017-11-20 11:46:48 +0100130 // cached handler for watch connectivity state
131 static readonly BatchCompletionDelegate WatchConnectivityStateHandler = (success, ctx, state) =>
132 {
Jan Tattermusch7b0bca22018-01-09 12:13:57 +0100133 var tcs = (TaskCompletionSource<bool>) state;
134 tcs.SetResult(success);
Jan Tattermusch8b451ed2017-11-20 11:46:48 +0100135 };
136
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700137 /// <summary>
138 /// Returned tasks completes once channel state has become different from
139 /// given lastObservedState.
140 /// If deadline is reached or and error occurs, returned task is cancelled.
141 /// </summary>
Jan Tattermusch7b0bca22018-01-09 12:13:57 +0100142 public async Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
143 {
144 var result = await WaitForStateChangedInternalAsync(lastObservedState, deadline).ConfigureAwait(false);
145 if (!result)
146 {
147 throw new TaskCanceledException("Reached deadline.");
148 }
149 }
150
151 /// <summary>
152 /// Returned tasks completes once channel state has become different from
153 /// given lastObservedState (<c>true</c> is returned) or if the wait has timed out (<c>false</c> is returned).
154 /// </summary>
155 internal Task<bool> WaitForStateChangedInternalAsync(ChannelState lastObservedState, DateTime? deadline = null)
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700156 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700157 GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
158 "Shutdown is a terminal state. No further state changes can occur.");
Jan Tattermusch7b0bca22018-01-09 12:13:57 +0100159 var tcs = new TaskCompletionSource<bool>();
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700160 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100161 lock (myLock)
162 {
163 // pass "tcs" as "state" for WatchConnectivityStateHandler.
164 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
165 }
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700166 return tcs.Task;
167 }
168
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700169 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
170 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700171 {
172 get
173 {
174 return handle.GetTarget();
175 }
176 }
177
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700178 /// <summary>The original target used to create the channel.</summary>
179 public string Target
180 {
181 get
182 {
183 return this.target;
184 }
185 }
186
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700187 /// <summary>
Jan Tattermusch528fb662016-05-12 08:38:41 -0700188 /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
189 /// </summary>
190 public CancellationToken ShutdownToken
191 {
192 get
193 {
194 return this.shutdownTokenSource.Token;
195 }
196 }
197
198 /// <summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700199 /// Allows explicitly requesting channel to connect without starting an RPC.
200 /// Returned task completes once state Ready was seen. If the deadline is reached,
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700201 /// or channel enters the Shutdown state, the task is cancelled.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700202 /// There is no need to call this explicitly unless your use case requires that.
203 /// Starting an RPC on a new channel will request connection implicitly.
204 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700205 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700206 public async Task ConnectAsync(DateTime? deadline = null)
207 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700208 var currentState = GetConnectivityState(true);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700209 while (currentState != ChannelState.Ready)
210 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700211 if (currentState == ChannelState.Shutdown)
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700212 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700213 throw new OperationCanceledException("Channel has reached Shutdown state.");
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700214 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800215 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermusch528fb662016-05-12 08:38:41 -0700216 currentState = GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700217 }
218 }
219
220 /// <summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700221 /// Shuts down the channel cleanly. It is strongly recommended to shutdown
222 /// all previously created channels before exiting from the process.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700223 /// </summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700224 /// <remarks>
225 /// This method doesn't wait for all calls on this channel to finish (nor does
226 /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
227 /// all the calls on this channel have finished (successfully or with an error)
228 /// before shutting down the channel to ensure channel shutdown won't impact
229 /// the outcome of those remote calls.
230 /// </remarks>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700231 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800232 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700233 lock (myLock)
234 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800235 GrpcPreconditions.CheckState(!shutdownRequested);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700236 shutdownRequested = true;
237 }
Jan Tattermusch4aea5282016-06-01 12:42:54 -0700238 GrpcEnvironment.UnregisterChannel(this);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700239
Jan Tattermusch528fb662016-05-12 08:38:41 -0700240 shutdownTokenSource.Cancel();
241
Jan Tattermusch2b357952015-08-20 14:54:33 -0700242 var activeCallCount = activeCallCounter.Count;
243 if (activeCallCount > 0)
244 {
245 Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
246 }
247
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100248 lock (myLock)
249 {
250 handle.Dispose();
251 }
Jan Tattermusch2b357952015-08-20 14:54:33 -0700252
Jan Tattermusch8a507812017-05-08 16:30:12 +0200253 await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800254 }
255
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700256 internal ChannelSafeHandle Handle
257 {
258 get
259 {
260 return this.handle;
261 }
262 }
263
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700264 internal GrpcEnvironment Environment
265 {
266 get
267 {
268 return this.environment;
269 }
270 }
271
Jan Tattermusch5ee8e772016-05-24 16:17:10 -0400272 internal CompletionQueueSafeHandle CompletionQueue
273 {
274 get
275 {
276 return this.completionQueue;
277 }
278 }
279
Jan Tattermusch2b357952015-08-20 14:54:33 -0700280 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800281 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700282 activeCallCounter.Increment();
283
284 bool success = false;
285 handle.DangerousAddRef(ref success);
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800286 GrpcPreconditions.CheckState(success);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700287 }
288
289 internal void RemoveCallReference(object call)
290 {
291 handle.DangerousRelease();
292
293 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800294 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800295
Jan Tattermusch528fb662016-05-12 08:38:41 -0700296 private ChannelState GetConnectivityState(bool tryToConnect)
297 {
298 try
299 {
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100300 lock (myLock)
301 {
302 return handle.CheckConnectivityState(tryToConnect);
303 }
Jan Tattermusch528fb662016-05-12 08:38:41 -0700304 }
305 catch (ObjectDisposedException)
306 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700307 return ChannelState.Shutdown;
Jan Tattermusch528fb662016-05-12 08:38:41 -0700308 }
309 }
310
Jan Tattermusch8a507812017-05-08 16:30:12 +0200311 /// <summary>
312 /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
313 /// </summary>
314 private async Task RunConnectivityWatcherAsync()
315 {
316 try
317 {
318 var lastState = State;
319 while (lastState != ChannelState.Shutdown)
320 {
321 lock (myLock)
322 {
323 if (shutdownRequested)
324 {
325 break;
326 }
327 }
328
Jan Tattermusch7b0bca22018-01-09 12:13:57 +0100329 // ignore the result
330 await WaitForStateChangedInternalAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
Jan Tattermusch8a507812017-05-08 16:30:12 +0200331 lastState = State;
332 }
333 }
334 catch (ObjectDisposedException) {
335 // during shutdown, channel is going to be disposed.
336 }
337 }
338
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800339 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700340 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800341 var key = ChannelOptions.PrimaryUserAgentString;
342 var userAgentString = "";
343
344 ChannelOption option;
345 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700346 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800347 // user-provided userAgentString needs to be at the beginning
348 userAgentString = option.StringValue + " ";
349 };
350
351 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
352 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
353
354 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700355 }
356
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800357 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700358 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800359 var dict = new Dictionary<string, ChannelOption>();
360 if (options == null)
361 {
362 return dict;
363 }
364 foreach (var option in options)
365 {
366 dict.Add(option.Name, option);
367 }
368 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700369 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800370 }
Craig Tiller190d3602015-02-18 09:23:38 -0800371}