blob: abe19a6fc69351e4a57858521d58a874b423c3b7 [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 {
Jan Tattermusch9b9807a2018-03-21 09:54:39 +0100163 if (handle.IsClosed)
164 {
165 // If channel has been already shutdown and handle was disposed, we would end up with
Jan Tattermuschf6909b22018-03-21 12:08:17 +0100166 // an abandoned completion added to the completion registry. Instead, we make sure we fail early.
167 throw new ObjectDisposedException(nameof(handle), "Channel handle has already been disposed.");
Jan Tattermusch9b9807a2018-03-21 09:54:39 +0100168 }
169 else
170 {
171 // pass "tcs" as "state" for WatchConnectivityStateHandler.
172 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, WatchConnectivityStateHandler, tcs);
173 }
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100174 }
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700175 return tcs.Task;
176 }
177
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700178 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
179 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700180 {
181 get
182 {
183 return handle.GetTarget();
184 }
185 }
186
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700187 /// <summary>The original target used to create the channel.</summary>
188 public string Target
189 {
190 get
191 {
192 return this.target;
193 }
194 }
195
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700196 /// <summary>
Jan Tattermusch528fb662016-05-12 08:38:41 -0700197 /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
198 /// </summary>
199 public CancellationToken ShutdownToken
200 {
201 get
202 {
203 return this.shutdownTokenSource.Token;
204 }
205 }
206
207 /// <summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700208 /// Allows explicitly requesting channel to connect without starting an RPC.
209 /// Returned task completes once state Ready was seen. If the deadline is reached,
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700210 /// or channel enters the Shutdown state, the task is cancelled.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700211 /// There is no need to call this explicitly unless your use case requires that.
212 /// Starting an RPC on a new channel will request connection implicitly.
213 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700214 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700215 public async Task ConnectAsync(DateTime? deadline = null)
216 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700217 var currentState = GetConnectivityState(true);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700218 while (currentState != ChannelState.Ready)
219 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700220 if (currentState == ChannelState.Shutdown)
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700221 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700222 throw new OperationCanceledException("Channel has reached Shutdown state.");
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700223 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800224 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermusch528fb662016-05-12 08:38:41 -0700225 currentState = GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700226 }
227 }
228
229 /// <summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700230 /// Shuts down the channel cleanly. It is strongly recommended to shutdown
231 /// all previously created channels before exiting from the process.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700232 /// </summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700233 /// <remarks>
234 /// This method doesn't wait for all calls on this channel to finish (nor does
235 /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
236 /// all the calls on this channel have finished (successfully or with an error)
237 /// before shutting down the channel to ensure channel shutdown won't impact
238 /// the outcome of those remote calls.
239 /// </remarks>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700240 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800241 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700242 lock (myLock)
243 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800244 GrpcPreconditions.CheckState(!shutdownRequested);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700245 shutdownRequested = true;
246 }
Jan Tattermusch4aea5282016-06-01 12:42:54 -0700247 GrpcEnvironment.UnregisterChannel(this);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700248
Jan Tattermusch528fb662016-05-12 08:38:41 -0700249 shutdownTokenSource.Cancel();
250
Jan Tattermusch2b357952015-08-20 14:54:33 -0700251 var activeCallCount = activeCallCounter.Count;
252 if (activeCallCount > 0)
253 {
254 Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
255 }
256
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100257 lock (myLock)
258 {
259 handle.Dispose();
260 }
Jan Tattermusch2b357952015-08-20 14:54:33 -0700261
Jan Tattermusch8a507812017-05-08 16:30:12 +0200262 await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800263 }
264
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700265 internal ChannelSafeHandle Handle
266 {
267 get
268 {
269 return this.handle;
270 }
271 }
272
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700273 internal GrpcEnvironment Environment
274 {
275 get
276 {
277 return this.environment;
278 }
279 }
280
Jan Tattermusch5ee8e772016-05-24 16:17:10 -0400281 internal CompletionQueueSafeHandle CompletionQueue
282 {
283 get
284 {
285 return this.completionQueue;
286 }
287 }
288
Jan Tattermusch2b357952015-08-20 14:54:33 -0700289 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800290 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700291 activeCallCounter.Increment();
292
293 bool success = false;
294 handle.DangerousAddRef(ref success);
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800295 GrpcPreconditions.CheckState(success);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700296 }
297
298 internal void RemoveCallReference(object call)
299 {
300 handle.DangerousRelease();
301
302 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800303 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800304
Jan Tattermusch528fb662016-05-12 08:38:41 -0700305 private ChannelState GetConnectivityState(bool tryToConnect)
306 {
307 try
308 {
Jan Tattermusch737f6e72017-12-07 18:07:35 +0100309 lock (myLock)
310 {
311 return handle.CheckConnectivityState(tryToConnect);
312 }
Jan Tattermusch528fb662016-05-12 08:38:41 -0700313 }
314 catch (ObjectDisposedException)
315 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700316 return ChannelState.Shutdown;
Jan Tattermusch528fb662016-05-12 08:38:41 -0700317 }
318 }
319
Jan Tattermusch8a507812017-05-08 16:30:12 +0200320 /// <summary>
321 /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
322 /// </summary>
323 private async Task RunConnectivityWatcherAsync()
324 {
325 try
326 {
327 var lastState = State;
328 while (lastState != ChannelState.Shutdown)
329 {
330 lock (myLock)
331 {
332 if (shutdownRequested)
333 {
334 break;
335 }
336 }
337
Jan Tattermusch7b0bca22018-01-09 12:13:57 +0100338 // ignore the result
339 await WaitForStateChangedInternalAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
Jan Tattermusch8a507812017-05-08 16:30:12 +0200340 lastState = State;
341 }
342 }
343 catch (ObjectDisposedException) {
344 // during shutdown, channel is going to be disposed.
345 }
346 }
347
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800348 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700349 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800350 var key = ChannelOptions.PrimaryUserAgentString;
351 var userAgentString = "";
352
353 ChannelOption option;
354 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700355 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800356 // user-provided userAgentString needs to be at the beginning
357 userAgentString = option.StringValue + " ";
358 };
359
360 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
361 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
362
363 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700364 }
365
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800366 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700367 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800368 var dict = new Dictionary<string, ChannelOption>();
369 if (options == null)
370 {
371 return dict;
372 }
373 foreach (var option in options)
374 {
375 dict.Add(option.Name, option);
376 }
377 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700378 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800379 }
Craig Tiller190d3602015-02-18 09:23:38 -0800380}