-
Notifications
You must be signed in to change notification settings - Fork 58
/
etcdClient.cs
220 lines (179 loc) · 8.23 KB
/
etcdClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using dotnet_etcd.interfaces;
using dotnet_etcd.multiplexer;
using Etcdserverpb;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Grpc.Net.Client;
using Grpc.Net.Client.Balancer;
using Grpc.Net.Client.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace dotnet_etcd
{
/// <summary>
/// Etcd client is the entrypoint for this library.
/// It contains all the functions required to perform operations on etcd.
/// </summary>
public partial class EtcdClient : IDisposable, IEtcdClient
{
#region Variables
private const string InsecurePrefix = "http://";
private const string SecurePrefix = "https://";
private const string StaticHostsPrefix = "static://";
private const string DnsPrefix = "dns://";
private const string AlternateDnsPrefix = "discovery-srv://";
private const string DefaultServerName = "my-etcd-server";
private readonly Connection _connection;
// https://learn.microsoft.com/en-us/aspnet/core/grpc/retries?view=aspnetcore-6.0#configure-a-grpc-retry-policy
private static readonly MethodConfig _defaultGrpcMethodConfig = new()
{
Names = { MethodName.Default },
RetryPolicy = new RetryPolicy
{
MaxAttempts = 5,
InitialBackoff = TimeSpan.FromSeconds(1),
MaxBackoff = TimeSpan.FromSeconds(5),
BackoffMultiplier = 1.5,
RetryableStatusCodes = { StatusCode.Unavailable }
}
};
// https://github.com/grpc/proposal/blob/master/A6-client-retries.md#throttling-retry-attempts-and-hedged-rpcs
private static readonly RetryThrottlingPolicy _defaultRetryThrottlingPolicy = new()
{
MaxTokens = 10,
TokenRatio = 0.1
};
#endregion
#region Initializers
public EtcdClient(string connectionString, int port = 2379, string serverName = DefaultServerName, Action<GrpcChannelOptions> configureChannelOptions = null, Interceptor[] interceptors = null)
{
// Param check
if (string.IsNullOrWhiteSpace(connectionString))
{
throw new ArgumentNullException(nameof(connectionString));
}
// Param sanitization
interceptors ??= Array.Empty<Interceptor>();
if (connectionString.StartsWith(AlternateDnsPrefix, StringComparison.InvariantCultureIgnoreCase))
{
connectionString = connectionString.Substring(AlternateDnsPrefix.Length);
connectionString = DnsPrefix + connectionString;
}
// Connection Configuration
var options = new GrpcChannelOptions
{
ServiceConfig = new ServiceConfig
{
MethodConfigs = { _defaultGrpcMethodConfig },
RetryThrottling = _defaultRetryThrottlingPolicy,
LoadBalancingConfigs = { new RoundRobinConfig() },
}
};
configureChannelOptions.Invoke(options);
// Channel Configuration
GrpcChannel channel = null;
if (connectionString.StartsWith(DnsPrefix, StringComparison.InvariantCultureIgnoreCase))
{
channel = GrpcChannel.ForAddress(connectionString, options);
}
else
{
string[] hosts = Array.Empty<string>();
hosts = connectionString.Split(',');
List<Uri> nodes = new();
for (int i = 0; i < hosts.Length; i++)
{
string host = hosts[i];
if (host.Split(':').Length < 3)
{
host += $":{Convert.ToString(port, CultureInfo.InvariantCulture)}";
}
if (!(host.StartsWith(InsecurePrefix, StringComparison.InvariantCultureIgnoreCase) || host.StartsWith(SecurePrefix, StringComparison.InvariantCultureIgnoreCase)))
{
host = options.Credentials == ChannelCredentials.Insecure ? $"{InsecurePrefix}{host}" : $"{SecurePrefix}{host}";
}
nodes.Add(new Uri(host));
}
var factory = new StaticResolverFactory(addr => nodes.Select(i => new BalancerAddress(i.Host, i.Port)).ToArray());
var services = new ServiceCollection();
services.AddSingleton<ResolverFactory>(factory);
options.ServiceProvider = services.BuildServiceProvider();
channel = GrpcChannel.ForAddress($"{StaticHostsPrefix}{serverName}", options);
}
CallInvoker callInvoker = interceptors != null && interceptors.Length > 0 ? channel.Intercept(interceptors) : channel.CreateCallInvoker();
// Setup Connection
_connection = new Connection
{
_kvClient = new KV.KVClient(callInvoker),
_watchClient = new Watch.WatchClient(callInvoker),
_leaseClient = new Lease.LeaseClient(callInvoker),
_lockClient = new V3Lockpb.Lock.LockClient(callInvoker),
_clusterClient = new Cluster.ClusterClient(callInvoker),
_maintenanceClient = new Maintenance.MaintenanceClient(callInvoker),
_authClient = new Auth.AuthClient(callInvoker)
};
}
[Obsolete("Use constructor accepting Action<GrpcChannelOptions> configureChannelOptions instead.")]
public EtcdClient(string connectionString, int port = 2379, string serverName = DefaultServerName,
HttpClientHandler handler = null, bool ssl = false,
bool useLegacyRpcExceptionForCancellation = false, Interceptor[] interceptors = null,
MethodConfig grpcMethodConfig = null, RetryThrottlingPolicy grpcRetryThrottlingPolicy = null) : this(connectionString, port, serverName, (options) =>
{
grpcMethodConfig ??= _defaultGrpcMethodConfig;
grpcRetryThrottlingPolicy ??= _defaultRetryThrottlingPolicy;
interceptors ??= Array.Empty<Interceptor>();
options.HttpHandler = handler;
options.ThrowOperationCanceledOnCancellation = !useLegacyRpcExceptionForCancellation;
options.ServiceConfig = new ServiceConfig
{
MethodConfigs = { grpcMethodConfig },
RetryThrottling = grpcRetryThrottlingPolicy,
LoadBalancingConfigs = { new RoundRobinConfig() },
};
if (ssl)
{
options.Credentials = new SslCredentials();
}
else
{
#if NETCOREAPP3_1 || NETCOREAPP3_0
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
#endif
options.Credentials = ChannelCredentials.Insecure;
}
}, interceptors)
{
}
#endregion
#region IDisposable Support
private bool _disposed; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
_disposed = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
GC.SuppressFinalize(this);
}
#endregion
}
}