blob: f2211111f6c0895aadf25aec3f4b68d144bf0d25 [file] [log] [blame]
Jan Tattermuscha7fff862015-02-13 11:08:08 -08001#region Copyright notice and license
Craig Tiller6169d5f2016-03-31 07:46:18 -07002// Copyright 2015, Google Inc.
Jan Tattermuscha7fff862015-02-13 11:08:08 -08003// All rights reserved.
Craig Tiller190d3602015-02-18 09:23:38 -08004//
Jan Tattermuscha7fff862015-02-13 11:08:08 -08005// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
Craig Tiller190d3602015-02-18 09:23:38 -08008//
Jan Tattermuscha7fff862015-02-13 11:08:08 -08009// * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11// * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15// * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
Craig Tiller190d3602015-02-18 09:23:38 -080018//
Jan Tattermuscha7fff862015-02-13 11:08:08 -080019// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Jan Tattermuscha7fff862015-02-13 11:08:08 -080030#endregion
Jan Tattermusch766d72b2015-07-21 20:09:25 -070031
Jan Tattermuscha7608b02015-02-03 17:54:38 -080032using System;
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070033using System.Collections.Generic;
Jan Tattermusch528fb662016-05-12 08:38:41 -070034using System.Threading;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080035using System.Threading.Tasks;
Jan Tattermusch766d72b2015-07-21 20:09:25 -070036
Jan Tattermusch30868622015-02-19 09:22:33 -080037using Grpc.Core.Internal;
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070038using Grpc.Core.Logging;
39using Grpc.Core.Utils;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080040
Jan Tattermusch30868622015-02-19 09:22:33 -080041namespace Grpc.Core
Jan Tattermuscha7608b02015-02-03 17:54:38 -080042{
Jan Tattermusch286975f2015-03-12 14:04:36 -070043 /// <summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -070044 /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
45 /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
46 /// 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 -070047 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -070048 public class Channel
Jan Tattermusch15329232015-03-02 15:32:47 -080049 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070050 static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
51
Jan Tattermusch2b357952015-08-20 14:54:33 -070052 readonly object myLock = new object();
53 readonly AtomicCounter activeCallCounter = new AtomicCounter();
Jan Tattermusch528fb662016-05-12 08:38:41 -070054 readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
Jan Tattermusch2b357952015-08-20 14:54:33 -070055
Jan Tattermusch0c140a82015-08-02 00:54:02 -070056 readonly string target;
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070057 readonly GrpcEnvironment environment;
Jan Tattermusch5ee8e772016-05-24 16:17:10 -040058 readonly CompletionQueueSafeHandle completionQueue;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080059 readonly ChannelSafeHandle handle;
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080060 readonly Dictionary<string, ChannelOption> options;
Jan Tattermusch2b357952015-08-20 14:54:33 -070061
62 bool shutdownRequested;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080063
Jan Tattermusch15329232015-03-02 15:32:47 -080064 /// <summary>
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070065 /// Creates a channel that connects to a specific host.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070066 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
Jan Tattermusch15329232015-03-02 15:32:47 -080067 /// </summary>
Jan Tattermusch0c140a82015-08-02 00:54:02 -070068 /// <param name="target">Target of the channel.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070069 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070070 /// <param name="options">Channel options.</param>
Jan Tattermusch5bd70052015-10-06 16:47:49 -070071 public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null)
Jan Tattermusch15329232015-03-02 15:32:47 -080072 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -080073 this.target = GrpcPreconditions.CheckNotNull(target, "target");
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080074 this.options = CreateOptionsDictionary(options);
Jan Tattermusch766d72b2015-07-21 20:09:25 -070075 EnsureUserAgentChannelOption(this.options);
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080076 this.environment = GrpcEnvironment.AddRef();
77
Jan Tattermusch5ee8e772016-05-24 16:17:10 -040078 this.completionQueue = this.environment.PickCompletionQueue();
Jan Tattermusch08dea322015-10-26 17:34:10 -070079 using (var nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080080 using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
Jan Tattermusch15329232015-03-02 15:32:47 -080081 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070082 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080083 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070084 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080085 }
86 else
87 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070088 this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080089 }
90 }
Jan Tattermusch15329232015-03-02 15:32:47 -080091 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080092
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070093 /// <summary>
94 /// Creates a channel that connects to a specific host and port.
95 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070096 /// <param name="host">The name or IP address of the host.</param>
97 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070098 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070099 /// <param name="options">Channel options.</param>
Jan Tattermusch5bd70052015-10-06 16:47:49 -0700100 public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700101 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800102 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800103 }
104
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700105 /// <summary>
106 /// Gets current connectivity state of this channel.
Jan Tattermusch528fb662016-05-12 08:38:41 -0700107 /// After channel is has been shutdown, <c>ChannelState.FatalFailure</c> will be returned.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700108 /// </summary>
109 public ChannelState State
110 {
111 get
112 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700113 return GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700114 }
115 }
116
117 /// <summary>
118 /// Returned tasks completes once channel state has become different from
119 /// given lastObservedState.
120 /// If deadline is reached or and error occurs, returned task is cancelled.
121 /// </summary>
122 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
123 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800124 GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700125 "FatalFailure is a terminal state. No further state changes can occur.");
126 var tcs = new TaskCompletionSource<object>();
127 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
128 var handler = new BatchCompletionDelegate((success, ctx) =>
129 {
130 if (success)
131 {
132 tcs.SetResult(null);
133 }
134 else
135 {
136 tcs.SetCanceled();
137 }
138 });
Jan Tattermusch5ee8e772016-05-24 16:17:10 -0400139 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, completionQueue, environment.CompletionRegistry, handler);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700140 return tcs.Task;
141 }
142
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700143 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
144 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700145 {
146 get
147 {
148 return handle.GetTarget();
149 }
150 }
151
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700152 /// <summary>The original target used to create the channel.</summary>
153 public string Target
154 {
155 get
156 {
157 return this.target;
158 }
159 }
160
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700161 /// <summary>
Jan Tattermusch528fb662016-05-12 08:38:41 -0700162 /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
163 /// </summary>
164 public CancellationToken ShutdownToken
165 {
166 get
167 {
168 return this.shutdownTokenSource.Token;
169 }
170 }
171
172 /// <summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700173 /// Allows explicitly requesting channel to connect without starting an RPC.
174 /// Returned task completes once state Ready was seen. If the deadline is reached,
175 /// or channel enters the FatalFailure state, the task is cancelled.
176 /// There is no need to call this explicitly unless your use case requires that.
177 /// Starting an RPC on a new channel will request connection implicitly.
178 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700179 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700180 public async Task ConnectAsync(DateTime? deadline = null)
181 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700182 var currentState = GetConnectivityState(true);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700183 while (currentState != ChannelState.Ready)
184 {
185 if (currentState == ChannelState.FatalFailure)
186 {
187 throw new OperationCanceledException("Channel has reached FatalFailure state.");
188 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800189 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermusch528fb662016-05-12 08:38:41 -0700190 currentState = GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700191 }
192 }
193
194 /// <summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700195 /// Waits until there are no more active calls for this channel and then cleans up
196 /// resources used by this channel.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700197 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700198 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800199 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700200 lock (myLock)
201 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800202 GrpcPreconditions.CheckState(!shutdownRequested);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700203 shutdownRequested = true;
204 }
205
Jan Tattermusch528fb662016-05-12 08:38:41 -0700206 shutdownTokenSource.Cancel();
207
Jan Tattermusch2b357952015-08-20 14:54:33 -0700208 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
214 handle.Dispose();
215
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800216 await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800217 }
218
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700219 internal ChannelSafeHandle Handle
220 {
221 get
222 {
223 return this.handle;
224 }
225 }
226
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700227 internal GrpcEnvironment Environment
228 {
229 get
230 {
231 return this.environment;
232 }
233 }
234
Jan Tattermusch5ee8e772016-05-24 16:17:10 -0400235 internal CompletionQueueSafeHandle CompletionQueue
236 {
237 get
238 {
239 return this.completionQueue;
240 }
241 }
242
Jan Tattermusch2b357952015-08-20 14:54:33 -0700243 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800244 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700245 activeCallCounter.Increment();
246
247 bool success = false;
248 handle.DangerousAddRef(ref success);
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800249 GrpcPreconditions.CheckState(success);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700250 }
251
252 internal void RemoveCallReference(object call)
253 {
254 handle.DangerousRelease();
255
256 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800257 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800258
Jan Tattermusch528fb662016-05-12 08:38:41 -0700259 private ChannelState GetConnectivityState(bool tryToConnect)
260 {
261 try
262 {
263 return handle.CheckConnectivityState(tryToConnect);
264 }
265 catch (ObjectDisposedException)
266 {
267 return ChannelState.FatalFailure;
268 }
269 }
270
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800271 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700272 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800273 var key = ChannelOptions.PrimaryUserAgentString;
274 var userAgentString = "";
275
276 ChannelOption option;
277 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700278 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800279 // user-provided userAgentString needs to be at the beginning
280 userAgentString = option.StringValue + " ";
281 };
282
283 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
284 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
285
286 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700287 }
288
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800289 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700290 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800291 var dict = new Dictionary<string, ChannelOption>();
292 if (options == null)
293 {
294 return dict;
295 }
296 foreach (var option in options)
297 {
298 dict.Add(option.Name, option);
299 }
300 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700301 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800302 }
Craig Tiller190d3602015-02-18 09:23:38 -0800303}