blob: 0b696104438978eff78e35f3f9d98414355b573b [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 Tattermusch04eb89c2015-06-12 13:03:05 -070055 bool disposed;
Jan Tattermuscha7608b02015-02-03 17:54:38 -080056
Jan Tattermusch15329232015-03-02 15:32:47 -080057 /// <summary>
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070058 /// Creates a channel that connects to a specific host.
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070059 /// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
Jan Tattermusch15329232015-03-02 15:32:47 -080060 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070061 /// <param name="host">The name or IP address of the host.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070062 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070063 /// <param name="options">Channel options.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070064 public Channel(string host, Credentials credentials, IEnumerable<ChannelOption> options = null)
Jan Tattermusch15329232015-03-02 15:32:47 -080065 {
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070066 Preconditions.CheckNotNull(host);
Jan Tattermusch04eb89c2015-06-12 13:03:05 -070067 this.environment = GrpcEnvironment.GetInstance();
Jan Tattermusch766d72b2015-07-21 20:09:25 -070068 this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
69
70 EnsureUserAgentChannelOption(this.options);
Jan Tattermuscha96ac052015-07-24 14:49:30 -070071 using (CredentialsSafeHandle nativeCredentials = credentials.ToNativeCredentials())
Jan Tattermusch766d72b2015-07-21 20:09:25 -070072 using (ChannelArgsSafeHandle nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options))
Jan Tattermusch15329232015-03-02 15:32:47 -080073 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070074 if (nativeCredentials != null)
Jan Tattermusch15329232015-03-02 15:32:47 -080075 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070076 this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, host, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080077 }
78 else
79 {
Jan Tattermuscha96ac052015-07-24 14:49:30 -070080 this.handle = ChannelSafeHandle.CreateInsecure(host, nativeChannelArgs);
Jan Tattermusch15329232015-03-02 15:32:47 -080081 }
82 }
Jan Tattermusch15329232015-03-02 15:32:47 -080083 }
Jan Tattermuscha7608b02015-02-03 17:54:38 -080084
Jan Tattermuschda71a4d2015-06-08 15:36:53 -070085 /// <summary>
86 /// Creates a channel that connects to a specific host and port.
87 /// </summary>
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070088 /// <param name="host">The name or IP address of the host.</param>
89 /// <param name="port">The port.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070090 /// <param name="credentials">Credentials to secure the channel.</param>
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070091 /// <param name="options">Channel options.</param>
Jan Tattermuscha96ac052015-07-24 14:49:30 -070092 public Channel(string host, int port, Credentials credentials, IEnumerable<ChannelOption> options = null) :
Jan Tattermusch2ddb5a62015-06-08 17:51:36 -070093 this(string.Format("{0}:{1}", host, port), credentials, options)
Jan Tattermuscha7608b02015-02-03 17:54:38 -080094 {
Jan Tattermuscha7608b02015-02-03 17:54:38 -080095 }
96
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -070097 /// <summary>
98 /// Gets current connectivity state of this channel.
99 /// </summary>
100 public ChannelState State
101 {
102 get
103 {
104 return handle.CheckConnectivityState(false);
105 }
106 }
107
108 /// <summary>
109 /// Returned tasks completes once channel state has become different from
110 /// given lastObservedState.
111 /// If deadline is reached or and error occurs, returned task is cancelled.
112 /// </summary>
113 public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
114 {
115 Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
116 "FatalFailure is a terminal state. No further state changes can occur.");
117 var tcs = new TaskCompletionSource<object>();
118 var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
119 var handler = new BatchCompletionDelegate((success, ctx) =>
120 {
121 if (success)
122 {
123 tcs.SetResult(null);
124 }
125 else
126 {
127 tcs.SetCanceled();
128 }
129 });
130 handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
131 return tcs.Task;
132 }
133
Jan Tattermuschdead9052015-08-01 21:34:31 -0700134 /// <summary> Address of the remote endpoint in URI format.</summary>
135 public string Target
136 {
137 get
138 {
139 return handle.GetTarget();
140 }
141 }
142
Jan Tattermuschd8bbdea2015-07-22 12:51:06 -0700143 /// <summary>
144 /// Allows explicitly requesting channel to connect without starting an RPC.
145 /// Returned task completes once state Ready was seen. If the deadline is reached,
146 /// or channel enters the FatalFailure state, the task is cancelled.
147 /// There is no need to call this explicitly unless your use case requires that.
148 /// Starting an RPC on a new channel will request connection implicitly.
149 /// </summary>
150 public async Task ConnectAsync(DateTime? deadline = null)
151 {
152 var currentState = handle.CheckConnectivityState(true);
153 while (currentState != ChannelState.Ready)
154 {
155 if (currentState == ChannelState.FatalFailure)
156 {
157 throw new OperationCanceledException("Channel has reached FatalFailure state.");
158 }
159 await WaitForStateChangedAsync(currentState, deadline);
160 currentState = handle.CheckConnectivityState(false);
161 }
162 }
163
164 /// <summary>
165 /// Destroys the underlying channel.
166 /// </summary>
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800167 public void Dispose()
168 {
169 Dispose(true);
170 GC.SuppressFinalize(this);
171 }
172
Jan Tattermuscha5272b62015-04-30 11:56:46 -0700173 internal ChannelSafeHandle Handle
174 {
175 get
176 {
177 return this.handle;
178 }
179 }
180
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700181 internal CompletionQueueSafeHandle CompletionQueue
182 {
183 get
184 {
185 return this.environment.CompletionQueue;
186 }
187 }
188
189 internal CompletionRegistry CompletionRegistry
190 {
191 get
192 {
193 return this.environment.CompletionRegistry;
194 }
195 }
196
197 internal GrpcEnvironment Environment
198 {
199 get
200 {
201 return this.environment;
202 }
203 }
204
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800205 protected virtual void Dispose(bool disposing)
206 {
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700207 if (disposing && handle != null && !disposed)
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800208 {
Jan Tattermusch04eb89c2015-06-12 13:03:05 -0700209 disposed = true;
Jan Tattermuscha7608b02015-02-03 17:54:38 -0800210 handle.Dispose();
211 }
212 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800213
Jan Tattermusch766d72b2015-07-21 20:09:25 -0700214 private static void EnsureUserAgentChannelOption(List<ChannelOption> options)
215 {
216 if (!options.Any((option) => option.Name == ChannelOptions.PrimaryUserAgentString))
217 {
218 options.Add(new ChannelOption(ChannelOptions.PrimaryUserAgentString, GetUserAgentString()));
219 }
220 }
221
222 private static string GetUserAgentString()
223 {
224 // TODO(jtattermusch): it would be useful to also provide .NET/mono version.
225 return string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
226 }
Jan Tattermusch15329232015-03-02 15:32:47 -0800227 }
Craig Tiller190d3602015-02-18 09:23:38 -0800228}