blob: 93a6e6a3d95fee3456c07b0c1c42f4e9ab29ee27 [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 Tattermusch766d72b2015-07-21 20:09:25 -070034using System.Linq;
Jan Tattermusch528fb662016-05-12 08:38:41 -070035using System.Threading;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080036using System.Threading.Tasks;
Jan Tattermusch766d72b2015-07-21 20:09:25 -070037
Jan Tattermusch30868622015-02-19 09:22:33 -080038using Grpc.Core.Internal;
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070039using Grpc.Core.Logging;
40using Grpc.Core.Utils;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080041
Jan Tattermusch30868622015-02-19 09:22:33 -080042namespace Grpc.Core
Jan Tattermuscha7608b02015-02-03 17:54:38 -080043{
Jan Tattermusch286975f2015-03-12 14:04:36 -070044 /// <summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -070045 /// Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers.
46 /// More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking
47 /// 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 -070048 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -070049 public class Channel
Jan Tattermusch15329232015-03-02 15:32:47 -080050 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070051 static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
52
Jan Tattermusch2b357952015-08-20 14:54:33 -070053 readonly object myLock = new object();
54 readonly AtomicCounter activeCallCounter = new AtomicCounter();
Jan Tattermusch528fb662016-05-12 08:38:41 -070055 readonly CancellationTokenSource shutdownTokenSource = new CancellationTokenSource();
Jan Tattermusch2b357952015-08-20 14:54:33 -070056
Jan Tattermusch0c140a82015-08-02 00:54:02 -070057 readonly string target;
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070058 readonly GrpcEnvironment environment;
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 Tattermusch08dea322015-10-26 17:34:10 -070078 using (var nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080079 using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
Jan Tattermusch15329232015-03-02 15:32:47 -080080 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070081 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080082 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070083 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080084 }
85 else
86 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070087 this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080088 }
89 }
Jan Tattermusch15329232015-03-02 15:32:47 -080090 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080091
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070092 /// <summary>
93 /// Creates a channel that connects to a specific host and port.
94 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070095 /// <param name="host">The name or IP address of the host.</param>
96 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070097 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070098 /// <param name="options">Channel options.</param>
Jan Tattermusch5bd70052015-10-06 16:47:49 -070099 public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700100 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800101 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800102 }
103
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700104 /// <summary>
105 /// Gets current connectivity state of this channel.
Jan Tattermusch528fb662016-05-12 08:38:41 -0700106 /// After channel is has been shutdown, <c>ChannelState.FatalFailure</c> will be returned.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700107 /// </summary>
108 public ChannelState State
109 {
110 get
111 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700112 return GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700113 }
114 }
115
116 /// <summary>
117 /// Returned tasks completes once channel state has become different from
118 /// given lastObservedState.
119 /// If deadline is reached or and error occurs, returned task is cancelled.
120 /// </summary>
121 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
122 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800123 GrpcPreconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700124 "FatalFailure is a terminal state. No further state changes can occur.");
125 var tcs = new TaskCompletionSource<object>();
126 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
127 var handler = new BatchCompletionDelegate((success, ctx) =>
128 {
129 if (success)
130 {
131 tcs.SetResult(null);
132 }
133 else
134 {
135 tcs.SetCanceled();
136 }
137 });
138 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
139 return tcs.Task;
140 }
141
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700142 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
143 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700144 {
145 get
146 {
147 return handle.GetTarget();
148 }
149 }
150
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700151 /// <summary>The original target used to create the channel.</summary>
152 public string Target
153 {
154 get
155 {
156 return this.target;
157 }
158 }
159
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700160 /// <summary>
Jan Tattermusch528fb662016-05-12 08:38:41 -0700161 /// Returns a token that gets cancelled once <c>ShutdownAsync</c> is invoked.
162 /// </summary>
163 public CancellationToken ShutdownToken
164 {
165 get
166 {
167 return this.shutdownTokenSource.Token;
168 }
169 }
170
171 /// <summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700172 /// Allows explicitly requesting channel to connect without starting an RPC.
173 /// Returned task completes once state Ready was seen. If the deadline is reached,
174 /// or channel enters the FatalFailure state, the task is cancelled.
175 /// There is no need to call this explicitly unless your use case requires that.
176 /// Starting an RPC on a new channel will request connection implicitly.
177 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700178 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700179 public async Task ConnectAsync(DateTime? deadline = null)
180 {
Jan Tattermusch528fb662016-05-12 08:38:41 -0700181 var currentState = GetConnectivityState(true);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700182 while (currentState != ChannelState.Ready)
183 {
184 if (currentState == ChannelState.FatalFailure)
185 {
186 throw new OperationCanceledException("Channel has reached FatalFailure state.");
187 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800188 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermusch528fb662016-05-12 08:38:41 -0700189 currentState = GetConnectivityState(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700190 }
191 }
192
193 /// <summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700194 /// Waits until there are no more active calls for this channel and then cleans up
195 /// resources used by this channel.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700196 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700197 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800198 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700199 lock (myLock)
200 {
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800201 GrpcPreconditions.CheckState(!shutdownRequested);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700202 shutdownRequested = true;
203 }
204
Jan Tattermusch528fb662016-05-12 08:38:41 -0700205 shutdownTokenSource.Cancel();
206
Jan Tattermusch2b357952015-08-20 14:54:33 -0700207 var activeCallCount = activeCallCounter.Count;
208 if (activeCallCount > 0)
209 {
210 Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
211 }
212
213 handle.Dispose();
214
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800215 await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800216 }
217
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700218 internal ChannelSafeHandle Handle
219 {
220 get
221 {
222 return this.handle;
223 }
224 }
225
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700226 internal GrpcEnvironment Environment
227 {
228 get
229 {
230 return this.environment;
231 }
232 }
233
Jan Tattermusch2b357952015-08-20 14:54:33 -0700234 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800235 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700236 activeCallCounter.Increment();
237
238 bool success = false;
239 handle.DangerousAddRef(ref success);
Jan Tattermusch7a3ee6a2016-02-18 10:36:02 -0800240 GrpcPreconditions.CheckState(success);
Jan Tattermusch2b357952015-08-20 14:54:33 -0700241 }
242
243 internal void RemoveCallReference(object call)
244 {
245 handle.DangerousRelease();
246
247 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800248 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800249
Jan Tattermusch528fb662016-05-12 08:38:41 -0700250 private ChannelState GetConnectivityState(bool tryToConnect)
251 {
252 try
253 {
254 return handle.CheckConnectivityState(tryToConnect);
255 }
256 catch (ObjectDisposedException)
257 {
258 return ChannelState.FatalFailure;
259 }
260 }
261
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800262 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700263 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800264 var key = ChannelOptions.PrimaryUserAgentString;
265 var userAgentString = "";
266
267 ChannelOption option;
268 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700269 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800270 // user-provided userAgentString needs to be at the beginning
271 userAgentString = option.StringValue + " ";
272 };
273
274 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
275 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
276
277 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700278 }
279
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800280 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700281 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800282 var dict = new Dictionary<string, ChannelOption>();
283 if (options == null)
284 {
285 return dict;
286 }
287 foreach (var option in options)
288 {
289 dict.Add(option.Name, option);
290 }
291 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700292 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800293 }
Craig Tiller190d3602015-02-18 09:23:38 -0800294}