blob: 8a71afa01a34e16c2ef01286acad7edeab1a8278 [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.Runtime.InteropServices;
36using System.Threading;
37using System.Threading.Tasks;
Jan Tattermusch766d72b2015-07-21 20:09:25 -070038
Jan Tattermusch30868622015-02-19 09:22:33 -080039using Grpc.Core.Internal;
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070040using Grpc.Core.Logging;
41using Grpc.Core.Utils;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080042
Jan Tattermusch30868622015-02-19 09:22:33 -080043namespace Grpc.Core
Jan Tattermuscha7608b02015-02-03 17:54:38 -080044{
Jan Tattermusch286975f2015-03-12 14:04:36 -070045 /// <summary>
46 /// gRPC Channel
47 /// </summary>
Jan Tattermusch15329232015-03-02 15:32:47 -080048 public class Channel : IDisposable
49 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070050 static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
51
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070052 readonly GrpcEnvironment environment;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080053 readonly ChannelSafeHandle handle;
Jan Tattermusch766d72b2015-07-21 20:09:25 -070054 readonly List<ChannelOption> options;
Jan Tattermusch075dde42015-03-11 18:21:00 -070055 readonly string target;
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070056 bool disposed;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080057
Jan Tattermusch15329232015-03-02 15:32:47 -080058 /// <summary>
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070059 /// Creates a channel that connects to a specific host.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070060 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
Jan Tattermusch15329232015-03-02 15:32:47 -080061 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070062 /// <param name="host">The name or IP address of the host.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070063 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070064 /// <param name="options">Channel options.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070065 public Channel(string host, Credentials credentials, IEnumerable<ChannelOption> options = null)
Jan Tattermusch15329232015-03-02 15:32:47 -080066 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070067 Preconditions.CheckNotNull(host);
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070068 this.environment = GrpcEnvironment.GetInstance();
Jan Tattermusch766d72b2015-07-21 20:09:25 -070069 this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
70
71 EnsureUserAgentChannelOption(this.options);
Jan Tattermuscha96ac052015-07-24 14:49:30 -070072 using (CredentialsSafeHandle nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch766d72b2015-07-21 20:09:25 -070073 using (ChannelArgsSafeHandle nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options))
Jan Tattermusch15329232015-03-02 15:32:47 -080074 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070075 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080076 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070077 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, host, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080078 }
79 else
80 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070081 this.handle = ChannelSafeHandle.CreateInsecure(host, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080082 }
83 }
Jan Tattermusch766d72b2015-07-21 20:09:25 -070084 this.target = GetOverridenTarget(host, this.options);
Jan Tattermusch15329232015-03-02 15:32:47 -080085 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080086
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070087 /// <summary>
88 /// Creates a channel that connects to a specific host and port.
89 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070090 /// <param name="host">The name or IP address of the host.</param>
91 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070092 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070093 /// <param name="options">Channel options.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070094 public Channel(string host, int port, Credentials credentials, IEnumerable<ChannelOption> options = null) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070095 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -080096 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -080097 }
98
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070099 /// <summary>
100 /// Gets current connectivity state of this channel.
101 /// </summary>
102 public ChannelState State
103 {
104 get
105 {
106 return handle.CheckConnectivityState(false);
107 }
108 }
109
110 /// <summary>
111 /// Returned tasks completes once channel state has become different from
112 /// given lastObservedState.
113 /// If deadline is reached or and error occurs, returned task is cancelled.
114 /// </summary>
115 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
116 {
117 Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
118 "FatalFailure is a terminal state. No further state changes can occur.");
119 var tcs = new TaskCompletionSource<object>();
120 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
121 var handler = new BatchCompletionDelegate((success, ctx) =>
122 {
123 if (success)
124 {
125 tcs.SetResult(null);
126 }
127 else
128 {
129 tcs.SetCanceled();
130 }
131 });
132 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
133 return tcs.Task;
134 }
135
136 /// <summary>
137 /// Allows explicitly requesting channel to connect without starting an RPC.
138 /// Returned task completes once state Ready was seen. If the deadline is reached,
139 /// or channel enters the FatalFailure state, the task is cancelled.
140 /// There is no need to call this explicitly unless your use case requires that.
141 /// Starting an RPC on a new channel will request connection implicitly.
142 /// </summary>
143 public async Task ConnectAsync(DateTime? deadline = null)
144 {
145 var currentState = handle.CheckConnectivityState(true);
146 while (currentState != ChannelState.Ready)
147 {
148 if (currentState == ChannelState.FatalFailure)
149 {
150 throw new OperationCanceledException("Channel has reached FatalFailure state.");
151 }
152 await WaitForStateChangedAsync(currentState, deadline);
153 currentState = handle.CheckConnectivityState(false);
154 }
155 }
156
157 /// <summary>
158 /// Destroys the underlying channel.
159 /// </summary>
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800160 public void Dispose()
161 {
162 Dispose(true);
163 GC.SuppressFinalize(this);
164 }
165
Jan Tattermuschda71a4d2015-06-08 15:36:53 -0700166 internal string Target
167 {
168 get
169 {
170 return target;
171 }
172 }
173
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700174 internal ChannelSafeHandle Handle
175 {
176 get
177 {
178 return this.handle;
179 }
180 }
181
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700182 internal CompletionQueueSafeHandle CompletionQueue
183 {
184 get
185 {
186 return this.environment.CompletionQueue;
187 }
188 }
189
190 internal CompletionRegistry CompletionRegistry
191 {
192 get
193 {
194 return this.environment.CompletionRegistry;
195 }
196 }
197
198 internal GrpcEnvironment Environment
199 {
200 get
201 {
202 return this.environment;
203 }
204 }
205
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800206 protected virtual void Dispose(bool disposing)
207 {
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700208 if (disposing && handle != null && !disposed)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800209 {
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700210 disposed = true;
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800211 handle.Dispose();
212 }
213 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800214
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700215 private static void EnsureUserAgentChannelOption(List<ChannelOption> options)
216 {
217 if (!options.Any((option) => option.Name == ChannelOptions.PrimaryUserAgentString))
218 {
219 options.Add(new ChannelOption(ChannelOptions.PrimaryUserAgentString, GetUserAgentString()));
220 }
221 }
222
223 private static string GetUserAgentString()
224 {
225 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
226 return string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
227 }
228
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700229 /// <summary>
230 /// Look for SslTargetNameOverride option and return its value instead of originalTarget
231 /// if found.
232 /// </summary>
233 private static string GetOverridenTarget(string originalTarget, IEnumerable<ChannelOption> options)
Jan Tattermusch15329232015-03-02 15:32:47 -0800234 {
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700235 if (options == null)
Jan Tattermusch15329232015-03-02 15:32:47 -0800236 {
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700237 return originalTarget;
Jan Tattermusch15329232015-03-02 15:32:47 -0800238 }
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700239 foreach (var option in options)
Jan Tattermusch15329232015-03-02 15:32:47 -0800240 {
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700241 if (option.Type == ChannelOption.OptionType.String
242 && option.Name == ChannelOptions.SslTargetNameOverride)
243 {
244 return option.StringValue;
245 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800246 }
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -0700247 return originalTarget;
Jan Tattermusch15329232015-03-02 15:32:47 -0800248 }
249 }
Craig Tiller190d3602015-02-18 09:23:38 -0800250}