-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
RequestPipeline.cs
597 lines (505 loc) · 19.7 KB
/
RequestPipeline.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Elasticsearch.Net.Diagnostics;
using Elasticsearch.Net.Extensions;
using Elasticsearch.Net.Specification.NodesApi;
using static Elasticsearch.Net.AuditEvent;
namespace Elasticsearch.Net
{
public class RequestPipeline : IRequestPipeline
{
private static readonly string NoNodesAttemptedMessage =
"No nodes were attempted, this can happen when a node predicate does not match any nodes";
private readonly IConnection _connection;
private readonly IConnectionPool _connectionPool;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IMemoryStreamFactory _memoryStreamFactory;
private readonly IConnectionConfigurationValues _settings;
private static DiagnosticSource DiagnosticSource { get; } = new DiagnosticListener(DiagnosticSources.RequestPipeline.SourceName);
public RequestPipeline(
IConnectionConfigurationValues configurationValues,
IDateTimeProvider dateTimeProvider,
IMemoryStreamFactory memoryStreamFactory,
IRequestParameters requestParameters
)
{
_settings = configurationValues;
_connectionPool = _settings.ConnectionPool;
_connection = _settings.Connection;
_dateTimeProvider = dateTimeProvider;
_memoryStreamFactory = memoryStreamFactory;
RequestConfiguration = requestParameters?.RequestConfiguration;
StartedOn = dateTimeProvider.Now();
}
public List<Audit> AuditTrail { get; } = new List<Audit>();
public bool DepletedRetries => Retried >= MaxRetries + 1 || IsTakingTooLong;
public bool FirstPoolUsageNeedsSniffing =>
!RequestDisabledSniff
&& _connectionPool.SupportsReseeding && _settings.SniffsOnStartup && !_connectionPool.SniffedOnStartup;
public bool IsTakingTooLong
{
get
{
var timeout = _settings.MaxRetryTimeout.GetValueOrDefault(RequestTimeout);
var now = _dateTimeProvider.Now();
//we apply a soft margin so that if a request timesout at 59 seconds when the maximum is 60 we also abort.
var margin = timeout.TotalMilliseconds / 100.0 * 98;
var marginTimeSpan = TimeSpan.FromMilliseconds(margin);
var timespanCall = now - StartedOn;
var tookToLong = timespanCall >= marginTimeSpan;
return tookToLong;
}
}
public int MaxRetries =>
RequestConfiguration?.ForceNode != null
? 0
: Math.Min(RequestConfiguration?.MaxRetries ?? _settings.MaxRetries.GetValueOrDefault(int.MaxValue), _connectionPool.MaxRetries);
public bool Refresh { get; private set; }
public int Retried { get; private set; }
public IEnumerable<Node> SniffNodes => _connectionPool
.CreateView(LazyAuditable)
.ToList()
.OrderBy(n => n.MasterEligible ? n.Uri.Port : int.MaxValue);
public static string SniffPath => "_nodes/http,settings";
public bool SniffsOnConnectionFailure =>
!RequestDisabledSniff
&& _connectionPool.SupportsReseeding && _settings.SniffsOnConnectionFault;
public bool SniffsOnStaleCluster =>
!RequestDisabledSniff
&& _connectionPool.SupportsReseeding && _settings.SniffInformationLifeSpan.HasValue;
public bool StaleClusterState
{
get
{
if (!SniffsOnStaleCluster) return false;
// ReSharper disable once PossibleInvalidOperationException
// already checked by SniffsOnStaleCluster
var sniffLifeSpan = _settings.SniffInformationLifeSpan.Value;
var now = _dateTimeProvider.Now();
var lastSniff = _connectionPool.LastUpdate;
return sniffLifeSpan < now - lastSniff;
}
}
public DateTime StartedOn { get; }
private TimeSpan PingTimeout =>
RequestConfiguration?.PingTimeout
?? _settings.PingTimeout
?? (_connectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);
private IRequestConfiguration RequestConfiguration { get; }
private bool RequestDisabledSniff => RequestConfiguration != null && (RequestConfiguration.DisableSniff ?? false);
private TimeSpan RequestTimeout => RequestConfiguration?.RequestTimeout ?? _settings.RequestTimeout;
private NodesInfoRequestParameters SniffParameters => new NodesInfoRequestParameters
{
Timeout = PingTimeout,
FlatSettings = true
};
void IDisposable.Dispose() => Dispose();
public void AuditCancellationRequested() => Audit(CancellationRequested).Dispose();
public void BadResponse<TResponse>(ref TResponse response, IApiCallDetails callDetails, RequestData data,
ElasticsearchClientException exception
)
where TResponse : class, IElasticsearchResponse, new()
{
if (response == null)
{
//make sure we copy over the error body in case we disabled direct streaming.
var s = callDetails?.ResponseBodyInBytes == null ? Stream.Null : _memoryStreamFactory.Create(callDetails.ResponseBodyInBytes);
var m = callDetails?.ResponseMimeType ?? RequestData.MimeType;
response = ResponseBuilder.ToResponse<TResponse>(data, exception, callDetails?.HttpStatusCode, null, s, m);
}
response.ApiCall.AuditTrail = AuditTrail;
}
public TResponse CallElasticsearch<TResponse>(RequestData requestData)
where TResponse : class, IElasticsearchResponse, new()
{
using (var audit = Audit(HealthyResponse, requestData.Node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.CallElasticsearch, requestData))
{
audit.Path = requestData.PathAndQuery;
try
{
var response = _connection.Request<TResponse>(requestData);
d.EndState = response.ApiCall;
response.ApiCall.AuditTrail = AuditTrail;
ThrowBadAuthPipelineExceptionWhenNeeded(response.ApiCall, response);
if (!response.ApiCall.Success) audit.Event = requestData.OnFailureAuditEvent;
return response;
}
catch (Exception e)
{
audit.Event = requestData.OnFailureAuditEvent;
audit.Exception = e;
throw;
}
}
}
public async Task<TResponse> CallElasticsearchAsync<TResponse>(RequestData requestData, CancellationToken cancellationToken)
where TResponse : class, IElasticsearchResponse, new()
{
using (var audit = Audit(HealthyResponse, requestData.Node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.CallElasticsearch, requestData))
{
audit.Path = requestData.PathAndQuery;
try
{
var response = await _connection.RequestAsync<TResponse>(requestData, cancellationToken).ConfigureAwait(false);
d.EndState = response.ApiCall;
response.ApiCall.AuditTrail = AuditTrail;
ThrowBadAuthPipelineExceptionWhenNeeded(response.ApiCall, response);
if (!response.ApiCall.Success) audit.Event = requestData.OnFailureAuditEvent;
return response;
}
catch (Exception e)
{
audit.Event = requestData.OnFailureAuditEvent;
audit.Exception = e;
throw;
}
}
}
public ElasticsearchClientException CreateClientException<TResponse>(
TResponse response, IApiCallDetails callDetails, RequestData data, List<PipelineException> pipelineExceptions
)
where TResponse : class, IElasticsearchResponse, new()
{
if (callDetails?.Success ?? false) return null;
var innerException = pipelineExceptions.HasAny() ? pipelineExceptions.AsAggregateOrFirst() : callDetails?.OriginalException;
var statusCode = callDetails?.HttpStatusCode != null ? callDetails.HttpStatusCode.Value.ToString() : "unknown";
var resource = callDetails == null
? "unknown resource"
: $"Status code {statusCode} from: {callDetails.HttpMethod} {callDetails.Uri.PathAndQuery}";
var exceptionMessage = innerException?.Message ?? "Request failed to execute";
var pipelineFailure = data.OnFailurePipelineFailure;
if (pipelineExceptions.HasAny())
pipelineFailure = pipelineExceptions.Last().FailureReason;
if (IsTakingTooLong)
{
pipelineFailure = PipelineFailure.MaxTimeoutReached;
Audit(MaxTimeoutReached);
exceptionMessage = "Maximum timeout reached while retrying request";
}
else if (Retried >= MaxRetries && MaxRetries > 0)
{
pipelineFailure = PipelineFailure.MaxRetriesReached;
Audit(MaxRetriesReached);
exceptionMessage = "Maximum number of retries reached";
var now = _dateTimeProvider.Now();
var activeNodes = _connectionPool.Nodes.Count(n => n.IsAlive || n.DeadUntil <= now);
if (Retried >= activeNodes)
{
Audit(FailedOverAllNodes);
exceptionMessage += ", failed over to all the known alive nodes before failing";
}
}
exceptionMessage += $". Call: {resource}";
if (response != null && response.TryGetServerErrorReason(out var reason))
exceptionMessage += $". ServerError: {reason}";
var clientException = new ElasticsearchClientException(pipelineFailure, exceptionMessage, innerException)
{
Request = data,
Response = callDetails,
AuditTrail = AuditTrail
};
return clientException;
}
public void FirstPoolUsage(SemaphoreSlim semaphore)
{
if (!FirstPoolUsageNeedsSniffing) return;
if (!semaphore.Wait(_settings.RequestTimeout))
{
if (FirstPoolUsageNeedsSniffing)
throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, null);
return;
}
if (!FirstPoolUsageNeedsSniffing)
{
semaphore.Release();
return;
}
try
{
using (Audit(SniffOnStartup))
{
Sniff();
_connectionPool.SniffedOnStartup = true;
}
}
finally
{
semaphore.Release();
}
}
public async Task FirstPoolUsageAsync(SemaphoreSlim semaphore, CancellationToken cancellationToken)
{
if (!FirstPoolUsageNeedsSniffing) return;
// TODO cancellationToken could throw here and will bubble out as OperationCancelledException
// everywhere else it would bubble out wrapped in a `UnexpectedElasticsearchClientException`
var success = await semaphore.WaitAsync(_settings.RequestTimeout, cancellationToken).ConfigureAwait(false);
if (!success)
{
if (FirstPoolUsageNeedsSniffing)
throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, null);
return;
}
if (!FirstPoolUsageNeedsSniffing)
{
semaphore.Release();
return;
}
try
{
using (Audit(SniffOnStartup))
{
await SniffAsync(cancellationToken).ConfigureAwait(false);
_connectionPool.SniffedOnStartup = true;
}
}
finally
{
semaphore.Release();
}
}
public void MarkAlive(Node node) => node.MarkAlive();
public void MarkDead(Node node)
{
var deadUntil = _dateTimeProvider.DeadTime(node.FailedAttempts, _settings.DeadTimeout, _settings.MaxDeadTimeout);
node.MarkDead(deadUntil);
Retried++;
}
public IEnumerable<Node> NextNode()
{
if (RequestConfiguration?.ForceNode != null)
{
yield return new Node(RequestConfiguration.ForceNode);
yield break;
}
//This for loop allows to break out of the view state machine if we need to
//force a refresh (after reseeding connectionpool). We have a hardcoded limit of only
//allowing 100 of these refreshes per call
var refreshed = false;
for (var i = 0; i < 100; i++)
{
if (DepletedRetries) yield break;
foreach (var node in _connectionPool
.CreateView(LazyAuditable)
.TakeWhile(node => !DepletedRetries))
{
if (!_settings.NodePredicate(node)) continue;
yield return node;
if (!Refresh) continue;
Refresh = false;
refreshed = true;
break;
}
//unless a refresh was requested we will not iterate over more then a single view.
//keep in mind refreshes are also still bound to overall maxretry count/timeout.
if (!refreshed) break;
}
}
public void Ping(Node node)
{
if (PingDisabled(node)) return;
var pingData = CreatePingRequestData(node);
using (var audit = Audit(PingSuccess, node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.Ping, pingData))
{
audit.Path = pingData.PathAndQuery;
try
{
var response = _connection.Request<VoidResponse>(pingData);
d.EndState = response;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//ping should not silently accept bad but valid http responses
if (!response.Success)
throw new PipelineException(pingData.OnFailurePipelineFailure, response.OriginalException) { ApiCall = response };
}
catch (Exception e)
{
var response = (e as PipelineException)?.ApiCall;
audit.Event = PingFailure;
audit.Exception = e;
throw new PipelineException(PipelineFailure.PingFailure, e) { ApiCall = response };
}
}
}
public async Task PingAsync(Node node, CancellationToken cancellationToken)
{
if (PingDisabled(node)) return;
var pingData = CreatePingRequestData(node);
using (var audit = Audit(PingSuccess, node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.Ping, pingData))
{
audit.Path = pingData.PathAndQuery;
try
{
var response = await _connection.RequestAsync<VoidResponse>(pingData, cancellationToken).ConfigureAwait(false);
d.EndState = response;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//ping should not silently accept bad but valid http responses
if (!response.Success)
throw new PipelineException(pingData.OnFailurePipelineFailure, response.OriginalException) { ApiCall = response };
}
catch (Exception e)
{
var response = (e as PipelineException)?.ApiCall;
audit.Event = PingFailure;
audit.Exception = e;
throw new PipelineException(PipelineFailure.PingFailure, e) { ApiCall = response };
}
}
}
public void Sniff()
{
var exceptions = new List<Exception>();
foreach (var node in SniffNodes)
{
var requestData = CreateSniffRequestData(node);
using (var audit = Audit(SniffSuccess, node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.Sniff, requestData))
using(DiagnosticSource.Diagnose(DiagnosticSources.RequestPipeline.Sniff, requestData))
{
try
{
audit.Path = requestData.PathAndQuery;
var response = _connection.Request<SniffResponse>(requestData);
d.EndState = response;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//sniff should not silently accept bad but valid http responses
if (!response.Success)
throw new PipelineException(requestData.OnFailurePipelineFailure, response.OriginalException) { ApiCall = response };
var nodes = response.ToNodes(_connectionPool.UsingSsl);
_connectionPool.Reseed(nodes);
Refresh = true;
return;
}
catch (Exception e)
{
audit.Event = SniffFailure;
audit.Exception = e;
exceptions.Add(e);
}
}
}
throw new PipelineException(PipelineFailure.SniffFailure, exceptions.AsAggregateOrFirst());
}
public async Task SniffAsync(CancellationToken cancellationToken)
{
var exceptions = new List<Exception>();
foreach (var node in SniffNodes)
{
var requestData = CreateSniffRequestData(node);
using (var audit = Audit(SniffSuccess, node))
using (var d = DiagnosticSource.Diagnose<RequestData, IApiCallDetails>(DiagnosticSources.RequestPipeline.Sniff, requestData))
{
try
{
audit.Path = requestData.PathAndQuery;
var response = await _connection.RequestAsync<SniffResponse>(requestData, cancellationToken).ConfigureAwait(false);
d.EndState = response;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//sniff should not silently accept bad but valid http responses
if (!response.Success)
throw new PipelineException(requestData.OnFailurePipelineFailure, response.OriginalException) { ApiCall = response };
_connectionPool.Reseed(response.ToNodes(_connectionPool.UsingSsl));
Refresh = true;
return;
}
catch (Exception e)
{
audit.Event = SniffFailure;
audit.Exception = e;
exceptions.Add(e);
}
}
}
throw new PipelineException(PipelineFailure.SniffFailure, exceptions.AsAggregateOrFirst());
}
public void SniffOnConnectionFailure()
{
if (!SniffsOnConnectionFailure) return;
using (Audit(SniffOnFail))
Sniff();
}
public async Task SniffOnConnectionFailureAsync(CancellationToken cancellationToken)
{
if (!SniffsOnConnectionFailure) return;
using (Audit(SniffOnFail))
await SniffAsync(cancellationToken).ConfigureAwait(false);
}
public void SniffOnStaleCluster()
{
if (!StaleClusterState) return;
using (Audit(AuditEvent.SniffOnStaleCluster))
{
Sniff();
_connectionPool.SniffedOnStartup = true;
}
}
public async Task SniffOnStaleClusterAsync(CancellationToken cancellationToken)
{
if (!StaleClusterState) return;
using (Audit(AuditEvent.SniffOnStaleCluster))
{
await SniffAsync(cancellationToken).ConfigureAwait(false);
_connectionPool.SniffedOnStartup = true;
}
}
public void ThrowNoNodesAttempted(RequestData requestData, List<PipelineException> seenExceptions)
{
var clientException = new ElasticsearchClientException(PipelineFailure.NoNodesAttempted, NoNodesAttemptedMessage, (Exception)null);
using (Audit(NoNodesAttempted))
throw new UnexpectedElasticsearchClientException(clientException, seenExceptions)
{
Request = requestData,
AuditTrail = AuditTrail
};
}
private bool PingDisabled(Node node) =>
(RequestConfiguration?.DisablePing).GetValueOrDefault(false)
|| _settings.DisablePings || !_connectionPool.SupportsPinging || !node.IsResurrected;
private Auditable Audit(AuditEvent type, Node node = null) => new Auditable(type, AuditTrail, _dateTimeProvider, node);
private RequestData CreatePingRequestData(Node node)
{
var requestOverrides = new RequestConfiguration
{
PingTimeout = PingTimeout,
RequestTimeout = PingTimeout,
BasicAuthenticationCredentials = _settings.BasicAuthenticationCredentials,
ApiKeyAuthenticationCredentials = _settings.ApiKeyAuthenticationCredentials,
EnableHttpPipelining = RequestConfiguration?.EnableHttpPipelining ?? _settings.HttpPipeliningEnabled,
ForceNode = RequestConfiguration?.ForceNode
};
IRequestParameters requestParameters = new RootNodeInfoRequestParameters();
requestParameters.RequestConfiguration = requestOverrides;
var data = new RequestData(HttpMethod.HEAD, string.Empty, null, _settings, requestParameters, _memoryStreamFactory) { Node = node };
return data;
}
private static void ThrowBadAuthPipelineExceptionWhenNeeded(IApiCallDetails details, IElasticsearchResponse response = null)
{
if (details?.HttpStatusCode == 401)
throw new PipelineException(PipelineFailure.BadAuthentication, details.OriginalException)
{
Response = response,
ApiCall = details
};
}
private void LazyAuditable(AuditEvent e, Node n)
{
using (new Auditable(e, AuditTrail, _dateTimeProvider, n)) { }
}
private RequestData CreateSniffRequestData(Node node) =>
new RequestData(HttpMethod.GET, SniffPath, null, _settings, SniffParameters, _memoryStreamFactory)
{
Node = node
};
protected virtual void Dispose() { }
}
}