blob: 1803920662845c87352ca4a1a3252258429bf492 [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
130 /// <summary>
131 /// Returned tasks completes once channel state has become different from
132 /// given lastObservedState.
133 /// If deadline is reached or and error occurs, returned task is cancelled.
134 /// </summary>
135 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
136 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700137 GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.Shutdown,
138 "Shutdown is a terminal state. No further state changes can occur.");
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700139 var tcs = new TaskCompletionSource<object>();
140 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
141 var handler = new BatchCompletionDelegate((success, ctx) =>
142 {
143 if (success)
144 {
145 tcs.SetResult(null);
146 }
147 else
148 {
149 tcs.SetCanceled();
150 }
151 });
Jan Tattermusche6d1de62016-05-25 19:32:15 -0400152 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, handler);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700153 return tcs.Task;
154 }
155
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700156 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
157 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700158 {
159 get
160 {
161 return handle.GetTarget();
162 }
163 }
164
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700165 /// <summary>The original target used to create the channel.</summary>
166 public string Target
167 {
168 get
169 {
170 return this.target;
171 }
172 }
173
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700174 /// <summary>
Jan Tattermusch528fb662016-05-12 08:38:41 -0700175 /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
176 /// </summary>
177 public CancellationToken ShutdownToken
178 {
179 get
180 {
181 return this.shutdownTokenSource.Token;
182 }
183 }
184
185 /// <summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700186 /// Allows explicitly requesting channel to connect without starting an RPC.
187 /// Returned task completes once state Ready was seen. If the deadline is reached,
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700188 /// or channel enters the Shutdown state, the task is cancelled.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700189 /// There is no need to call this explicitly unless your use case requires that.
190 /// Starting an RPC on a new channel will request connection implicitly.
191 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700192 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700193 public async Task ConnectAsync(DateTime? deadline = null)
194 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700195 var currentState = GetConnectivityState(true);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700196 while (currentState != ChannelState.Ready)
197 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700198 if (currentState == ChannelState.Shutdown)
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700199 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700200 throw new OperationCanceledException("Channel has reached Shutdown state.");
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700201 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800202 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermusch528fb662016-05-12 08:38:41 -0700203 currentState = GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700204 }
205 }
206
207 /// <summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700208 /// Shuts down the channel cleanly. It is strongly recommended to shutdown
209 /// all previously created channels before exiting from the process.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700210 /// </summary>
Jan Tattermuscha134fa72016-06-03 17:24:50 -0700211 /// <remarks>
212 /// This method doesn't wait for all calls on this channel to finish (nor does
213 /// it explicitly cancel all outstanding calls). It is user's responsibility to make sure
214 /// all the calls on this channel have finished (successfully or with an error)
215 /// before shutting down the channel to ensure channel shutdown won't impact
216 /// the outcome of those remote calls.
217 /// </remarks>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700218 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800219 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700220 lock (myLock)
221 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800222 GrpcPreconditions.CheckState(!shutdownRequested);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700223 shutdownRequested = true;
224 }
Jan Tattermusch4aea5282016-06-01 12:42:54 -0700225 GrpcEnvironment.UnregisterChannel(this);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700226
Jan Tattermusch528fb662016-05-12 08:38:41 -0700227 shutdownTokenSource.Cancel();
228
Jan Tattermusch2b357952015-08-20 14:54:33 -0700229 var activeCallCount = activeCallCounter.Count;
230 if (activeCallCount > 0)
231 {
232 Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
233 }
234
235 handle.Dispose();
236
Jan Tattermusch8a507812017-05-08 16:30:12 +0200237 await Task.WhenAll(GrpcEnvironment.ReleaseAsync(), connectivityWatcherTask).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800238 }
239
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700240 internal ChannelSafeHandle Handle
241 {
242 get
243 {
244 return this.handle;
245 }
246 }
247
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700248 internal GrpcEnvironment Environment
249 {
250 get
251 {
252 return this.environment;
253 }
254 }
255
Jan Tattermusch5ee8e772016-05-24 16:17:10 -0400256 internal CompletionQueueSafeHandle CompletionQueue
257 {
258 get
259 {
260 return this.completionQueue;
261 }
262 }
263
Jan Tattermusch2b357952015-08-20 14:54:33 -0700264 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800265 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700266 activeCallCounter.Increment();
267
268 bool success = false;
269 handle.DangerousAddRef(ref success);
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800270 GrpcPreconditions.CheckState(success);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700271 }
272
273 internal void RemoveCallReference(object call)
274 {
275 handle.DangerousRelease();
276
277 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800278 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800279
Jan Tattermusch528fb662016-05-12 08:38:41 -0700280 private ChannelState GetConnectivityState(bool tryToConnect)
281 {
282 try
283 {
284 return handle.CheckConnectivityState(tryToConnect);
285 }
286 catch (ObjectDisposedException)
287 {
Jan Tattermusch49fb84a2016-06-03 16:34:48 -0700288 return ChannelState.Shutdown;
Jan Tattermusch528fb662016-05-12 08:38:41 -0700289 }
290 }
291
Jan Tattermusch8a507812017-05-08 16:30:12 +0200292 /// <summary>
293 /// Constantly Watches channel connectivity status to work around https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/822
294 /// </summary>
295 private async Task RunConnectivityWatcherAsync()
296 {
297 try
298 {
299 var lastState = State;
300 while (lastState != ChannelState.Shutdown)
301 {
302 lock (myLock)
303 {
304 if (shutdownRequested)
305 {
306 break;
307 }
308 }
309
310 try
311 {
312 await WaitForStateChangedAsync(lastState, DateTime.UtcNow.AddSeconds(1)).ConfigureAwait(false);
313 }
314 catch (TaskCanceledException)
315 {
316 // ignore timeout
317 }
318 lastState = State;
319 }
320 }
321 catch (ObjectDisposedException) {
322 // during shutdown, channel is going to be disposed.
323 }
324 }
325
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800326 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700327 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800328 var key = ChannelOptions.PrimaryUserAgentString;
329 var userAgentString = "";
330
331 ChannelOption option;
332 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700333 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800334 // user-provided userAgentString needs to be at the beginning
335 userAgentString = option.StringValue + " ";
336 };
337
338 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
339 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
340
341 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700342 }
343
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800344 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700345 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800346 var dict = new Dictionary<string, ChannelOption>();
347 if (options == null)
348 {
349 return dict;
350 }
351 foreach (var option in options)
352 {
353 dict.Add(option.Name, option);
354 }
355 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700356 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800357 }
Craig Tiller190d3602015-02-18 09:23:38 -0800358}