-
Notifications
You must be signed in to change notification settings - Fork 504
/
Copy pathGlobalAddressResolver.cs
327 lines (285 loc) · 14.1 KB
/
GlobalAddressResolver.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Routing
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.ChangeFeed.Exceptions;
using Microsoft.Azure.Cosmos.Common;
using Microsoft.Azure.Cosmos.Core.Trace;
using Microsoft.Azure.Cosmos.Resource.CosmosExceptions;
using Microsoft.Azure.Cosmos.Tracing;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Rntbd;
/// <summary>
/// AddressCache implementation for client SDK. Supports cross region address routing based on
/// avaialbility and preference list.
/// </summary>
internal sealed class GlobalAddressResolver : IAddressResolverExtension, IDisposable
{
private const int MaxBackupReadRegions = 3;
private readonly GlobalEndpointManager endpointManager;
private readonly GlobalPartitionEndpointManager partitionKeyRangeLocationCache;
private readonly Protocol protocol;
private readonly ICosmosAuthorizationTokenProvider tokenProvider;
private readonly CollectionCache collectionCache;
private readonly PartitionKeyRangeCache routingMapProvider;
private readonly int maxEndpoints;
private readonly IServiceConfigurationReader serviceConfigReader;
private readonly CosmosHttpClient httpClient;
private readonly ConcurrentDictionary<Uri, EndpointCache> addressCacheByEndpoint;
private readonly bool enableTcpConnectionEndpointRediscovery;
private readonly bool isReplicaAddressValidationEnabled;
private IOpenConnectionsHandler openConnectionsHandler;
public GlobalAddressResolver(
GlobalEndpointManager endpointManager,
GlobalPartitionEndpointManager partitionKeyRangeLocationCache,
Protocol protocol,
ICosmosAuthorizationTokenProvider tokenProvider,
CollectionCache collectionCache,
PartitionKeyRangeCache routingMapProvider,
IServiceConfigurationReader serviceConfigReader,
ConnectionPolicy connectionPolicy,
CosmosHttpClient httpClient)
{
this.endpointManager = endpointManager;
this.partitionKeyRangeLocationCache = partitionKeyRangeLocationCache;
this.protocol = protocol;
this.tokenProvider = tokenProvider;
this.collectionCache = collectionCache;
this.routingMapProvider = routingMapProvider;
this.serviceConfigReader = serviceConfigReader;
this.httpClient = httpClient;
int maxBackupReadEndpoints =
!connectionPolicy.EnableReadRequestsFallback.HasValue || connectionPolicy.EnableReadRequestsFallback.Value
? GlobalAddressResolver.MaxBackupReadRegions : 0;
this.enableTcpConnectionEndpointRediscovery = connectionPolicy.EnableTcpConnectionEndpointRediscovery;
this.isReplicaAddressValidationEnabled = ConfigurationManager.IsReplicaAddressValidationEnabled();
this.maxEndpoints = maxBackupReadEndpoints + 2; // for write and alternate write endpoint (during failover)
this.addressCacheByEndpoint = new ConcurrentDictionary<Uri, EndpointCache>();
foreach (Uri endpoint in endpointManager.WriteEndpoints)
{
this.GetOrAddEndpoint(endpoint);
}
foreach (Uri endpoint in endpointManager.ReadEndpoints)
{
this.GetOrAddEndpoint(endpoint);
}
}
public async Task OpenAsync(
string databaseName,
ContainerProperties collection,
CancellationToken cancellationToken)
{
CollectionRoutingMap routingMap = await this.routingMapProvider.TryLookupAsync(
collectionRid: collection.ResourceId,
previousValue: null,
request: null,
trace: NoOpTrace.Singleton);
if (routingMap == null)
{
return;
}
List<PartitionKeyRangeIdentity> ranges = routingMap.OrderedPartitionKeyRanges.Select(
range => new PartitionKeyRangeIdentity(collection.ResourceId, range.Id)).ToList();
List<Task> tasks = new List<Task>();
foreach (EndpointCache endpointCache in this.addressCacheByEndpoint.Values)
{
tasks.Add(endpointCache.AddressCache.OpenConnectionsAsync(
databaseName: databaseName,
collection: collection,
partitionKeyRangeIdentities: ranges,
shouldOpenRntbdChannels: false,
cancellationToken: cancellationToken));
}
await Task.WhenAll(tasks);
}
/// <summary>
/// Invokes the gateway address cache to open the rntbd connections to the backend replicas.
/// </summary>
/// <param name="databaseName">A string containing the name of the database.</param>
/// <param name="containerLinkUri">A string containing the container's link uri.</param>
/// <param name="cancellationToken">An Instance of the <see cref="CancellationToken"/>.</param>
public async Task OpenConnectionsToAllReplicasAsync(
string databaseName,
string containerLinkUri,
CancellationToken cancellationToken = default)
{
try
{
ContainerProperties collection = await this.collectionCache.ResolveByNameAsync(
apiVersion: HttpConstants.Versions.CurrentVersion,
resourceAddress: containerLinkUri,
forceRefesh: false,
trace: NoOpTrace.Singleton,
clientSideRequestStatistics: null,
cancellationToken: cancellationToken);
if (collection == null)
{
throw CosmosExceptionFactory.Create(
statusCode: HttpStatusCode.NotFound,
message: $"Could not resolve the collection: {containerLinkUri} for database: {databaseName}.",
stackTrace: default,
headers: new Headers(),
trace: NoOpTrace.Singleton,
error: null,
innerException: default);
}
IReadOnlyList<PartitionKeyRange> partitionKeyRanges = await this.routingMapProvider?.TryGetOverlappingRangesAsync(
collectionRid: collection.ResourceId,
range: FeedRangeEpk.FullRange.Range,
trace: NoOpTrace.Singleton);
IReadOnlyList<PartitionKeyRangeIdentity> partitionKeyRangeIdentities = partitionKeyRanges?.Select(
range => new PartitionKeyRangeIdentity(
collection.ResourceId,
range.Id))
.ToList();
Uri firstPreferredReadRegion = this.endpointManager
.ReadEndpoints
.First();
if (!this.addressCacheByEndpoint.ContainsKey(firstPreferredReadRegion))
{
DefaultTrace.TraceWarning("The Address Cache doesn't contain a value for the first preferred read region: {0} under the database: {1}. '{2}'",
firstPreferredReadRegion,
databaseName,
System.Diagnostics.Trace.CorrelationManager.ActivityId);
return;
}
await this.addressCacheByEndpoint[firstPreferredReadRegion]
.AddressCache
.OpenConnectionsAsync(
databaseName: databaseName,
collection: collection,
partitionKeyRangeIdentities: partitionKeyRangeIdentities,
shouldOpenRntbdChannels: true,
cancellationToken: cancellationToken);
}
catch (Exception ex)
{
throw ex switch
{
DocumentClientException dce => CosmosExceptionFactory.Create(
dce,
NoOpTrace.Singleton),
_ => ex,
};
}
}
/// <inheritdoc/>
public void SetOpenConnectionsHandler(IOpenConnectionsHandler openConnectionsHandler)
{
this.openConnectionsHandler = openConnectionsHandler;
// Sets the openConnectionsHandler for the existing address cache.
// For the new address caches added later, the openConnectionsHandler
// will be set through the constructor.
foreach (EndpointCache endpointCache in this.addressCacheByEndpoint.Values)
{
endpointCache.AddressCache.SetOpenConnectionsHandler(openConnectionsHandler);
}
}
public async Task<PartitionAddressInformation> ResolveAsync(
DocumentServiceRequest request,
bool forceRefresh,
CancellationToken cancellationToken)
{
IAddressResolver resolver = this.GetAddressResolver(request);
PartitionAddressInformation partitionAddressInformation = await resolver.ResolveAsync(request, forceRefresh, cancellationToken);
if (!this.partitionKeyRangeLocationCache.TryAddPartitionLevelLocationOverride(request))
{
return partitionAddressInformation;
}
resolver = this.GetAddressResolver(request);
return await resolver.ResolveAsync(request, forceRefresh, cancellationToken);
}
public async Task UpdateAsync(
ServerKey serverKey,
CancellationToken cancellationToken)
{
foreach (KeyValuePair<Uri, EndpointCache> addressCache in this.addressCacheByEndpoint)
{
// since we don't know which address cache contains the pkRanges mapped to this node,
// we mark all transport uris that has the same server key to unhealthy status in the
// AddressCaches of all regions.
await addressCache.Value.AddressCache.MarkAddressesToUnhealthyAsync(serverKey);
}
}
/// <summary>
/// ReplicatedResourceClient will use this API to get the direct connectivity AddressCache for given request.
/// </summary>
/// <param name="request"></param>
private IAddressResolver GetAddressResolver(DocumentServiceRequest request)
{
Uri endpoint = this.endpointManager.ResolveServiceEndpoint(request);
return this.GetOrAddEndpoint(endpoint).AddressResolver;
}
public void Dispose()
{
foreach (EndpointCache endpointCache in this.addressCacheByEndpoint.Values)
{
endpointCache.AddressCache.Dispose();
}
}
private EndpointCache GetOrAddEndpoint(Uri endpoint)
{
// The GetorAdd is followed by a call to .Count which in a ConcurrentDictionary
// will acquire all locks for all buckets. This is really expensive. Since the check
// there is only to see if we've exceeded the count of endpoints, we can simply
// avoid that check altogether if we are not adding any more endpoints.
if (this.addressCacheByEndpoint.TryGetValue(endpoint, out EndpointCache existingCache))
{
return existingCache;
}
EndpointCache endpointCache = this.addressCacheByEndpoint.GetOrAdd(
endpoint,
(Uri resolvedEndpoint) =>
{
GatewayAddressCache gatewayAddressCache = new GatewayAddressCache(
resolvedEndpoint,
this.protocol,
this.tokenProvider,
this.serviceConfigReader,
this.httpClient,
this.openConnectionsHandler,
enableTcpConnectionEndpointRediscovery: this.enableTcpConnectionEndpointRediscovery,
replicaAddressValidationEnabled: this.isReplicaAddressValidationEnabled);
string location = this.endpointManager.GetLocation(endpoint);
AddressResolver addressResolver = new AddressResolver(null, new NullRequestSigner(), location);
addressResolver.InitializeCaches(this.collectionCache, this.routingMapProvider, gatewayAddressCache);
return new EndpointCache()
{
AddressCache = gatewayAddressCache,
AddressResolver = addressResolver,
};
});
if (this.addressCacheByEndpoint.Count > this.maxEndpoints)
{
IEnumerable<Uri> allEndpoints = this.endpointManager.WriteEndpoints.Union(this.endpointManager.ReadEndpoints);
Queue<Uri> endpoints = new Queue<Uri>(allEndpoints.Reverse());
while (this.addressCacheByEndpoint.Count > this.maxEndpoints)
{
if (endpoints.Count > 0)
{
this.addressCacheByEndpoint.TryRemove(endpoints.Dequeue(), out EndpointCache removedEntry);
}
else
{
break;
}
}
}
return endpointCache;
}
private sealed class EndpointCache
{
public GatewayAddressCache AddressCache { get; set; }
public AddressResolver AddressResolver { get; set; }
}
}
}