blob: d8d43c7998d1b84c6cbfcbf394a85662991f5ef5 [file] [log] [blame]
Jan Tattermuscha7fff862015-02-13 11:08:08 -08001#region Copyright notice and license
Jan Tattermuschaf77b3d2015-02-13 11:22:21 -08002// 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 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();
54
Jan Tattermusch0c140a82015-08-02 00:54:02 -070055 readonly string target;
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070056 readonly GrpcEnvironment environment;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080057 readonly ChannelSafeHandle handle;
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080058 readonly Dictionary<string, ChannelOption> options;
Jan Tattermusch2b357952015-08-20 14:54:33 -070059
60 bool shutdownRequested;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080061
Jan Tattermusch15329232015-03-02 15:32:47 -080062 /// <summary>
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070063 /// Creates a channel that connects to a specific host.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070064 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
Jan Tattermusch15329232015-03-02 15:32:47 -080065 /// </summary>
Jan Tattermusch0c140a82015-08-02 00:54:02 -070066 /// <param name="target">Target of the channel.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070067 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070068 /// <param name="options">Channel options.</param>
Jan Tattermusch5bd70052015-10-06 16:47:49 -070069 public Channel(string target, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null)
Jan Tattermusch15329232015-03-02 15:32:47 -080070 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070071 this.target = Preconditions.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 Tattermusch08dea322015-10-26 17:34:10 -070076 using (var nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch7ebbc472015-12-08 22:39:02 -080077 using (var nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options.Values))
Jan Tattermusch15329232015-03-02 15:32:47 -080078 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070079 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080080 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070081 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080082 }
83 else
84 {
Jan Tattermusch0c140a82015-08-02 00:54:02 -070085 this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080086 }
87 }
Jan Tattermusch15329232015-03-02 15:32:47 -080088 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080089
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070090 /// <summary>
91 /// Creates a channel that connects to a specific host and port.
92 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070093 /// <param name="host">The name or IP address of the host.</param>
94 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070095 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070096 /// <param name="options">Channel options.</param>
Jan Tattermusch5bd70052015-10-06 16:47:49 -070097 public Channel(string host, int port, ChannelCredentials credentials, IEnumerable<ChannelOption> options = null) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070098 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -080099 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800100 }
101
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700102 /// <summary>
103 /// Gets current connectivity state of this channel.
104 /// </summary>
105 public ChannelState State
106 {
107 get
108 {
109 return handle.CheckConnectivityState(false);
110 }
111 }
112
113 /// <summary>
114 /// Returned tasks completes once channel state has become different from
115 /// given lastObservedState.
116 /// If deadline is reached or and error occurs, returned task is cancelled.
117 /// </summary>
118 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
119 {
120 Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
121 "FatalFailure is a terminal state. No further state changes can occur.");
122 var tcs = new TaskCompletionSource<object>();
123 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
124 var handler = new BatchCompletionDelegate((success, ctx) =>
125 {
126 if (success)
127 {
128 tcs.SetResult(null);
129 }
130 else
131 {
132 tcs.SetCanceled();
133 }
134 });
135 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
136 return tcs.Task;
137 }
138
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700139 /// <summary>Resolved address of the remote endpoint in URI format.</summary>
140 public string ResolvedTarget
Jan Tattermuschdead9052015-08-01 21:34:31 -0700141 {
142 get
143 {
144 return handle.GetTarget();
145 }
146 }
147
Jan Tattermusch0c140a82015-08-02 00:54:02 -0700148 /// <summary>The original target used to create the channel.</summary>
149 public string Target
150 {
151 get
152 {
153 return this.target;
154 }
155 }
156
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700157 /// <summary>
158 /// Allows explicitly requesting channel to connect without starting an RPC.
159 /// Returned task completes once state Ready was seen. If the deadline is reached,
160 /// or channel enters the FatalFailure state, the task is cancelled.
161 /// There is no need to call this explicitly unless your use case requires that.
162 /// Starting an RPC on a new channel will request connection implicitly.
163 /// </summary>
Jan Tattermusch12855fc2015-08-24 16:43:23 -0700164 /// <param name="deadline">The deadline. <c>null</c> indicates no deadline.</param>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700165 public async Task ConnectAsync(DateTime? deadline = null)
166 {
167 var currentState = handle.CheckConnectivityState(true);
168 while (currentState != ChannelState.Ready)
169 {
170 if (currentState == ChannelState.FatalFailure)
171 {
172 throw new OperationCanceledException("Channel has reached FatalFailure state.");
173 }
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800174 await WaitForStateChangedAsync(currentState, deadline).ConfigureAwait(false);
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700175 currentState = handle.CheckConnectivityState(false);
176 }
177 }
178
179 /// <summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700180 /// Waits until there are no more active calls for this channel and then cleans up
181 /// resources used by this channel.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700182 /// </summary>
Jan Tattermusch2b357952015-08-20 14:54:33 -0700183 public async Task ShutdownAsync()
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800184 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700185 lock (myLock)
186 {
187 Preconditions.CheckState(!shutdownRequested);
188 shutdownRequested = true;
189 }
190
191 var activeCallCount = activeCallCounter.Count;
192 if (activeCallCount > 0)
193 {
194 Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
195 }
196
197 handle.Dispose();
198
Jan Tattermusch723c34b2015-12-07 08:02:01 -0800199 await Task.Run(() => GrpcEnvironment.Release()).ConfigureAwait(false);
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800200 }
201
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700202 internal ChannelSafeHandle Handle
203 {
204 get
205 {
206 return this.handle;
207 }
208 }
209
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700210 internal GrpcEnvironment Environment
211 {
212 get
213 {
214 return this.environment;
215 }
216 }
217
Jan Tattermusch2b357952015-08-20 14:54:33 -0700218 internal void AddCallReference(object call)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800219 {
Jan Tattermusch2b357952015-08-20 14:54:33 -0700220 activeCallCounter.Increment();
221
222 bool success = false;
223 handle.DangerousAddRef(ref success);
224 Preconditions.CheckState(success);
225 }
226
227 internal void RemoveCallReference(object call)
228 {
229 handle.DangerousRelease();
230
231 activeCallCounter.Decrement();
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800232 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800233
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800234 private static void EnsureUserAgentChannelOption(Dictionary<string, ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700235 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800236 var key = ChannelOptions.PrimaryUserAgentString;
237 var userAgentString = "";
238
239 ChannelOption option;
240 if (options.TryGetValue(key, out option))
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700241 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800242 // user-provided userAgentString needs to be at the beginning
243 userAgentString = option.StringValue + " ";
244 };
245
246 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
247 userAgentString += string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
248
249 options[ChannelOptions.PrimaryUserAgentString] = new ChannelOption(key, userAgentString);
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700250 }
251
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800252 private static Dictionary<string, ChannelOption> CreateOptionsDictionary(IEnumerable<ChannelOption> options)
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700253 {
Jan Tattermusch7ebbc472015-12-08 22:39:02 -0800254 var dict = new Dictionary<string, ChannelOption>();
255 if (options == null)
256 {
257 return dict;
258 }
259 foreach (var option in options)
260 {
261 dict.Add(option.Name, option);
262 }
263 return dict;
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700264 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800265 }
Craig Tiller190d3602015-02-18 09:23:38 -0800266}