forked from ravendb/ravendb-jvm-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestExecutor.java
1891 lines (1507 loc) · 78.4 KB
/
RequestExecutor.java
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package net.ravendb.client.http;
import net.ravendb.client.Constants;
import net.ravendb.client.documents.conventions.DocumentConventions;
import net.ravendb.client.documents.operations.DatabaseHealthCheckOperation;
import net.ravendb.client.documents.operations.GetStatisticsOperation;
import net.ravendb.client.documents.operations.configuration.GetClientConfigurationOperation;
import net.ravendb.client.documents.session.*;
import net.ravendb.client.exceptions.*;
import net.ravendb.client.exceptions.database.DatabaseDoesNotExistException;
import net.ravendb.client.exceptions.security.AuthorizationException;
import net.ravendb.client.extensions.HttpExtensions;
import net.ravendb.client.extensions.JsonExtensions;
import net.ravendb.client.primitives.*;
import net.ravendb.client.primitives.Timer;
import net.ravendb.client.serverwide.commands.GetDatabaseTopologyCommand;
import net.ravendb.client.util.CertificateUtils;
import net.ravendb.client.util.TimeUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@SuppressWarnings("SameParameterValue")
public class RequestExecutor implements CleanCloseable {
private static UUID GLOBAL_APPLICATION_IDENTIFIER = UUID.randomUUID();
private static final int INITIAL_TOPOLOGY_ETAG = -2;
public static Consumer<HttpClientBuilder> configureHttpClient = null;
private static final GetStatisticsOperation backwardCompatibilityFailureCheckOperation = new GetStatisticsOperation("failure=check");
private static final DatabaseHealthCheckOperation failureCheckOperation = new DatabaseHealthCheckOperation();
private static Set<String> _useOldFailureCheckOperation = ConcurrentHashMap.newKeySet();
/**
* Extension point to plug - in request post processing like adding proxy etc.
*/
public static Consumer<HttpRequestBase> requestPostProcessor = null;
public static final String CLIENT_VERSION = "5.4.0";
private static final ConcurrentMap<String, CloseableHttpClient> globalHttpClientWithCompression = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, CloseableHttpClient> globalHttpClientWithoutCompression = new ConcurrentHashMap<>();
private final Semaphore _updateDatabaseTopologySemaphore = new Semaphore(1);
private final Semaphore _updateClientConfigurationSemaphore = new Semaphore(1);
private final ConcurrentMap<ServerNode, NodeStatus> _failedNodesTimers = new ConcurrentHashMap<>();
private final KeyStore certificate;
private final char[] keyPassword;
private final KeyStore trustStore;
private final String _databaseName;
private static final Log logger = LogFactory.getLog(RequestExecutor.class);
private Date _lastReturnedResponse;
protected final ExecutorService _executorService;
private final HttpCache cache;
private ServerNode _topologyTakenFromNode;
public HttpCache getCache() {
return cache;
}
public final ThreadLocal<AggressiveCacheOptions> aggressiveCaching = new ThreadLocal<>();
public Topology getTopology() {
return _nodeSelector != null ? _nodeSelector.getTopology() : null;
}
private CloseableHttpClient _httpClient;
public CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = _httpClient;
if (httpClient != null) {
return httpClient;
}
return _httpClient = createHttpClient();
}
public List<ServerNode> getTopologyNodes() {
return Optional.ofNullable(getTopology())
.map(Topology::getNodes)
.map(Collections::unmodifiableList)
.orElse(null);
}
private volatile Timer _updateTopologyTimer;
protected NodeSelector _nodeSelector;
private Duration _defaultTimeout;
public final AtomicLong numberOfServerRequests = new AtomicLong(0);
public String getUrl() {
if (_nodeSelector == null) {
return null;
}
CurrentIndexAndNode preferredNode = _nodeSelector.getPreferredNode();
return preferredNode != null ? preferredNode.currentNode.getUrl() : null;
}
protected long topologyEtag;
public long getTopologyEtag() {
return topologyEtag;
}
protected long clientConfigurationEtag;
public long getClientConfigurationEtag() {
return clientConfigurationEtag;
}
private final DocumentConventions conventions;
protected boolean _disableTopologyUpdates;
protected boolean _disableClientConfigurationUpdates;
protected String lastServerVersion;
public String getLastServerVersion() {
return lastServerVersion;
}
public Duration getDefaultTimeout() {
return _defaultTimeout;
}
public void setDefaultTimeout(Duration timeout) {
_defaultTimeout = timeout;
}
private Duration _secondBroadcastAttemptTimeout;
public Duration getSecondBroadcastAttemptTimeout() {
return _secondBroadcastAttemptTimeout;
}
public void setSecondBroadcastAttemptTimeout(Duration secondBroadcastAttemptTimeout) {
_secondBroadcastAttemptTimeout = secondBroadcastAttemptTimeout;
}
private Duration _firstBroadcastAttemptTimeout;
public Duration getFirstBroadcastAttemptTimeout() {
return _firstBroadcastAttemptTimeout;
}
public void setFirstBroadcastAttemptTimeout(Duration firstBroadcastAttemptTimeout) {
_firstBroadcastAttemptTimeout = firstBroadcastAttemptTimeout;
}
private final List<EventHandler<FailedRequestEventArgs>> _onFailedRequest = new ArrayList<>();
public void addOnFailedRequestListener(EventHandler<FailedRequestEventArgs> handler) {
this._onFailedRequest.add(handler);
}
public void removeOnFailedRequestListener(EventHandler<FailedRequestEventArgs> handler) {
this._onFailedRequest.remove(handler);
}
private final List<EventHandler<BeforeRequestEventArgs>> _onBeforeRequest = new ArrayList<>();
public void addOnBeforeRequestListener(EventHandler<BeforeRequestEventArgs> handler) {
this._onBeforeRequest.add(handler);
}
public void removeOnBeforeRequestListener(EventHandler<BeforeRequestEventArgs> handler) {
this._onBeforeRequest.remove(handler);
}
private final List<EventHandler<SucceedRequestEventArgs>> _onSucceedRequest = new ArrayList<>();
public void addOnSucceedRequestListener(EventHandler<SucceedRequestEventArgs> handler) {
this._onSucceedRequest.add(handler);
}
public void removeOnSucceedRequestListener(EventHandler<SucceedRequestEventArgs> handler) {
this._onSucceedRequest.remove(handler);
}
private final List<EventHandler<TopologyUpdatedEventArgs>> _onTopologyUpdated = new ArrayList<>();
public void addOnTopologyUpdatedListener(EventHandler<TopologyUpdatedEventArgs> handler) {
_onTopologyUpdated.add(handler);
}
public void removeOnTopologyUpdatedListener(EventHandler<TopologyUpdatedEventArgs> handler) {
_onTopologyUpdated.remove(handler);
}
private void onFailedRequestInvoke(String url, Exception e) {
onFailedRequestInvoke(url, e, null, null);
}
private void onFailedRequestInvoke(String url, Exception e, HttpRequest request, HttpResponse response) {
EventHelper.invoke(_onFailedRequest, this, new FailedRequestEventArgs(_databaseName, url, e, request, response));
}
private CloseableHttpClient createHttpClient() {
ConcurrentMap<String, CloseableHttpClient> httpClientCache = getHttpClientCache();
String name = getHttpClientName();
return httpClientCache.computeIfAbsent(name, n -> createClient());
}
private String getHttpClientName() {
if (certificate != null) {
return CertificateUtils.extractThumbprintFromCertificate(certificate);
}
return "";
}
private ConcurrentMap<String, CloseableHttpClient> getHttpClientCache() {
return conventions.isUseCompression() ? globalHttpClientWithCompression : globalHttpClientWithoutCompression;
}
public DocumentConventions getConventions() {
return conventions;
}
public KeyStore getCertificate() {
return certificate;
}
public char[] getKeyPassword() {
return keyPassword;
}
public KeyStore getTrustStore() {
return trustStore;
}
/**
* Constructs a new {@link RequestExecutor} associated with a specific database.
*
* This method is protected and can't be directly called from outside the library.
* It is used internally by the {@link #create create} method.
*
* @param databaseName A {@link String} containing the name of the database on which to execute requests
* @param certificate A {@link KeyStore} containing the client certificate to be used when connecting to a node
* @param keyPassword An array of char containing the password for the authentication certificate
* @param trustStore A {@link KeyStore} containing the public certificate chain of the node being connected to
* @param conventions A {@link DocumentConventions} object containing any conventions to be used for requests by this {@link RequestExecutor}
* @param executorService An {@link ExecutorService} to be used for executing tasks
* @param initialUrls An array of {@link String} containing the initial set of one or more URLs pointing to nodes within a single cluster
*/
protected RequestExecutor(String databaseName, KeyStore certificate, char[] keyPassword, KeyStore trustStore, DocumentConventions conventions, ExecutorService executorService, String[] initialUrls) {
cache = new HttpCache(conventions.getMaxHttpCacheSize());
_executorService = executorService;
_databaseName = databaseName;
this.certificate = certificate;
this.keyPassword = keyPassword;
this.trustStore = trustStore;
_lastReturnedResponse = new Date();
this.conventions = conventions.clone();
this._defaultTimeout = conventions.getRequestTimeout();
this._secondBroadcastAttemptTimeout = conventions.getSecondBroadcastAttemptTimeout();
this._firstBroadcastAttemptTimeout = conventions.getFirstBroadcastAttemptTimeout();
}
/**
* Creates a new {@link RequestExecutor} and triggers an initial topology update for the database topology.
*
* @param databaseName A {@link String} containing the name of the database on which to execute requests
* @param certificate A {@link KeyStore} containing the client certificate to be used when connecting to a node
* @param keyPassword An array of char containing the password for the authentication certificate
* @param trustStore A {@link KeyStore} containing the public certificate chain of the node being connected to
* @param conventions A {@link DocumentConventions} object containing any conventions to be used for requests by this {@link RequestExecutor}
* @param executorService An {@link ExecutorService} to be used for executing tasks
* @param initialUrls An array of {@link String} containing the initial set of one or more URLs pointing to nodes within a single cluster
*/
public static RequestExecutor create(String[] initialUrls, String databaseName, KeyStore certificate, char[] keyPassword, KeyStore trustStore, ExecutorService executorService, DocumentConventions conventions) {
RequestExecutor executor = new RequestExecutor(databaseName, certificate, keyPassword, trustStore, conventions, executorService, initialUrls);
executor._firstTopologyUpdate = executor.firstTopologyUpdate(initialUrls, GLOBAL_APPLICATION_IDENTIFIER);
return executor;
}
/**
* Creates a new {@link RequestExecutor} for a single node, allowing for configuration updates, and triggers an
* initial topology update for the database topology.
*
* It does this by calling {@link #createForSingleNodeWithoutConfigurationUpdates}, then re-enabling client configuration updates.
*
* @param databaseName A {@link String} containing the name of the database on which to execute requests
* @param certificate A {@link KeyStore} containing the client certificate to be used when connecting to a node
* @param keyPassword An array of char containing the password for the authentication certificate
* @param trustStore A {@link KeyStore} containing the public certificate chain of the node being connected to
* @param conventions A {@link DocumentConventions} object containing any conventions to be used for requests by this {@link RequestExecutor}
* @param executorService An {@link ExecutorService} to be used for executing tasks
* @param initialUrls An array of {@link String} containing the initial set of one or more URLs pointing to nodes within a single cluster
*/
public static RequestExecutor createForSingleNodeWithConfigurationUpdates(String url, String databaseName, KeyStore certificate, char[] keyPassword, KeyStore trustStore, ExecutorService executorService, DocumentConventions conventions) {
RequestExecutor executor = createForSingleNodeWithoutConfigurationUpdates(url, databaseName, certificate, keyPassword, trustStore, executorService, conventions);
executor._disableClientConfigurationUpdates = false;
return executor;
}
/**
* Creates a new {@link RequestExecutor} for a single node and disables configuration updates, and triggers an
* initial topology update for the database topology.
*
* It does this by initially creating a regular, cluster-based {@link RequestExecutor}, then replaces the topology with
* an empty {@link Topology}, disables topology and client configuration updates, and manually adds a single server node
* to the {@link NodeSelector}.
*
* @param databaseName A {@link String} containing the name of the database on which to execute requests
* @param certificate A {@link KeyStore} containing the client certificate to be used when connecting to a node
* @param keyPassword An array of char containing the password for the authentication certificate
* @param trustStore A {@link KeyStore} containing the public certificate chain of the node being connected to
* @param conventions A {@link DocumentConventions} object containing any conventions to be used for requests by this {@link RequestExecutor}
* @param executorService An {@link ExecutorService} to be used for executing tasks
* @param initialUrls An array of {@link String} containing the initial set of one or more URLs pointing to nodes within a single cluster
*/
public static RequestExecutor createForSingleNodeWithoutConfigurationUpdates(String url, String databaseName, KeyStore certificate, char[] keyPassword, KeyStore trustStore, ExecutorService executorService, DocumentConventions conventions) {
final String[] initialUrls = validateUrls(new String[]{url}, certificate);
RequestExecutor executor = new RequestExecutor(databaseName, certificate, keyPassword, trustStore, conventions, executorService, initialUrls);
Topology topology = new Topology();
topology.setEtag(-1L);
ServerNode serverNode = new ServerNode();
serverNode.setDatabase(databaseName);
serverNode.setUrl(initialUrls[0]);
topology.setNodes(Collections.singletonList(serverNode));
executor._nodeSelector = new NodeSelector(topology, executorService);
executor.topologyEtag = INITIAL_TOPOLOGY_ETAG;
executor._disableTopologyUpdates = true;
executor._disableClientConfigurationUpdates = true;
return executor;
}
protected CompletableFuture<Void> updateClientConfigurationAsync(ServerNode serverNode) {
if (_disposed) {
return CompletableFuture.completedFuture(null);
}
return CompletableFuture.runAsync(() -> {
try {
_updateClientConfigurationSemaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
boolean oldDisableClientConfigurationUpdates = _disableClientConfigurationUpdates;
_disableClientConfigurationUpdates = true;
try {
if (_disposed) {
return;
}
GetClientConfigurationOperation.GetClientConfigurationCommand command = new GetClientConfigurationOperation.GetClientConfigurationCommand();
execute(serverNode, null, command, false, null);
GetClientConfigurationOperation.Result result = command.getResult();
if (result == null) {
return;
}
conventions.updateFrom(result.getConfiguration());
clientConfigurationEtag = result.getEtag();
} finally {
_disableClientConfigurationUpdates = oldDisableClientConfigurationUpdates;
_updateClientConfigurationSemaphore.release();
}
}, _executorService);
}
public CompletableFuture<Boolean> updateTopologyAsync(UpdateTopologyParameters parameters) {
if (parameters == null) {
throw new IllegalArgumentException("Parameters cannot be null");
}
if (_disableTopologyUpdates) {
return CompletableFuture.completedFuture(false);
}
if (_disposed) {
return CompletableFuture.completedFuture(false);
}
return CompletableFuture.supplyAsync(() -> {
//prevent double topology updates if execution takes too much time
// --> in cases with transient issues
try {
boolean lockTaken = _updateDatabaseTopologySemaphore.tryAcquire(parameters.getTimeoutInMs(), TimeUnit.MILLISECONDS);
if (!lockTaken) {
return false;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
if (_disposed) {
return false;
}
GetDatabaseTopologyCommand command = new GetDatabaseTopologyCommand(parameters.getDebugTag(),
getConventions().isSendApplicationIdentifier() ? parameters.getApplicationIdentifier() : null);
execute(parameters.getNode(), null, command, false, null);
Topology topology = command.getResult();
if (_nodeSelector == null) {
_nodeSelector = new NodeSelector(topology, _executorService);
if (conventions.getReadBalanceBehavior() == ReadBalanceBehavior.FASTEST_NODE) {
_nodeSelector.scheduleSpeedTest();
}
} else if (_nodeSelector.onUpdateTopology(topology, parameters.isForceUpdate())) {
disposeAllFailedNodesTimers();
if (conventions.getReadBalanceBehavior() == ReadBalanceBehavior.FASTEST_NODE) {
_nodeSelector.scheduleSpeedTest();
}
}
topologyEtag = _nodeSelector.getTopology().getEtag();
onTopologyUpdatedInvoke(topology);
} catch (Exception e) {
if (!_disposed) {
throw e;
}
} finally {
_updateDatabaseTopologySemaphore.release();
}
return true;
}, _executorService);
}
protected void disposeAllFailedNodesTimers() {
_failedNodesTimers.forEach((node, status) -> status.close());
_failedNodesTimers.clear();
}
public <TResult> void execute(RavenCommand<TResult> command) {
execute(command, null);
}
public <TResult> void execute(RavenCommand<TResult> command, SessionInfo sessionInfo) {
CompletableFuture<Void> topologyUpdate = _firstTopologyUpdate;
if (topologyUpdate != null &&
(topologyUpdate.isDone() && !topologyUpdate.isCompletedExceptionally() && !topologyUpdate.isCancelled())
|| _disableTopologyUpdates) {
CurrentIndexAndNode currentIndexAndNode = chooseNodeForRequest(command, sessionInfo);
execute(currentIndexAndNode.currentNode, currentIndexAndNode.currentIndex, command, true, sessionInfo);
} else {
unlikelyExecute(command, topologyUpdate, sessionInfo);
}
}
public <TResult> CurrentIndexAndNode chooseNodeForRequest(RavenCommand<TResult> cmd, SessionInfo sessionInfo) {
if (!_disableTopologyUpdates) {
// when we disable topology updates we cannot rely on the node tag,
// because the initial topology will not have them
if (StringUtils.isNotBlank(cmd.getSelectedNodeTag())) {
return _nodeSelector.getRequestedNode(cmd.getSelectedNodeTag());
}
}
if (conventions.getLoadBalanceBehavior() == LoadBalanceBehavior.USE_SESSION_CONTEXT) {
if (sessionInfo != null && sessionInfo.canUseLoadBalanceBehavior()) {
return _nodeSelector.getNodeBySessionId(sessionInfo.getSessionId());
}
}
if (!cmd.isReadRequest()) {
return _nodeSelector.getPreferredNode();
}
switch (conventions.getReadBalanceBehavior()) {
case NONE:
return _nodeSelector.getPreferredNode();
case ROUND_ROBIN:
return _nodeSelector.getNodeBySessionId(sessionInfo != null ? sessionInfo.getSessionId() : 0);
case FASTEST_NODE:
return _nodeSelector.getFastestNode();
default:
throw new IllegalArgumentException();
}
}
private <TResult> void unlikelyExecute(RavenCommand<TResult> command, CompletableFuture<Void> topologyUpdate, SessionInfo sessionInfo) {
waitForTopologyUpdate(topologyUpdate);
CurrentIndexAndNode currentIndexAndNode = chooseNodeForRequest(command, sessionInfo);
execute(currentIndexAndNode.currentNode, currentIndexAndNode.currentIndex, command, true, sessionInfo);
}
private void waitForTopologyUpdate(CompletableFuture<Void> topologyUpdate) {
try {
if (topologyUpdate == null || topologyUpdate.isCompletedExceptionally()) {
synchronized (this) {
if (_firstTopologyUpdate == null || topologyUpdate == _firstTopologyUpdate) {
if (_lastKnownUrls == null) {
// shouldn't happen
throw new IllegalStateException("No known topology and no previously known one, cannot proceed, likely a bug");
}
_firstTopologyUpdate = firstTopologyUpdate(_lastKnownUrls, null);
}
topologyUpdate = _firstTopologyUpdate;
}
}
topologyUpdate.get();
} catch (InterruptedException | ExecutionException e) {
synchronized (this) {
if (_firstTopologyUpdate == topologyUpdate) {
_firstTopologyUpdate = null; // next request will raise it
}
}
throw ExceptionsUtils.unwrapException(e);
}
}
private void updateTopologyCallback() {
Date time = new Date();
if (time.getTime() - _lastReturnedResponse.getTime() <= Duration.ofMinutes(5).toMillis()) {
return;
}
ServerNode serverNode;
try {
NodeSelector selector = _nodeSelector;
if (selector == null) {
return;
}
CurrentIndexAndNode preferredNode = selector.getPreferredNode();
serverNode = preferredNode.currentNode;
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Couldn't get preferred node Topology from _updateTopologyTimer", e);
}
return;
}
UpdateTopologyParameters updateParameters = new UpdateTopologyParameters(serverNode);
updateParameters.setTimeoutInMs(0);
updateParameters.setDebugTag("timer-callback");
updateTopologyAsync(updateParameters)
.exceptionally(ex -> {
if (logger.isInfoEnabled()) {
logger.info("Couldn't update topology from _updateTopologyTimer", ex);
}
return null;
});
}
protected CompletableFuture<Void> firstTopologyUpdate(String[] inputUrls) {
return firstTopologyUpdate(inputUrls, null);
}
@SuppressWarnings({"ConstantConditions"})
protected CompletableFuture<Void> firstTopologyUpdate(String[] inputUrls, UUID applicationIdentifier) {
final String[] initialUrls = validateUrls(inputUrls, certificate);
ArrayList<Tuple<String, Exception>> list = new ArrayList<>();
return CompletableFuture.runAsync(() -> {
for (String url : initialUrls) {
try {
ServerNode serverNode = new ServerNode();
serverNode.setUrl(url);
serverNode.setDatabase(_databaseName);
UpdateTopologyParameters updateParameters = new UpdateTopologyParameters(serverNode);
updateParameters.setTimeoutInMs(Integer.MAX_VALUE);
updateParameters.setDebugTag("first-topology-update");
updateParameters.setApplicationIdentifier(applicationIdentifier);
updateTopologyAsync(updateParameters).get();
initializeUpdateTopologyTimer();
_topologyTakenFromNode = serverNode;
return;
} catch (Exception e) {
if (e instanceof ExecutionException && e.getCause() instanceof AuthorizationException) {
// auth exceptions will always happen, on all nodes
// so errors immediately
_lastKnownUrls = initialUrls;
throw (AuthorizationException) e.getCause();
}
if (e instanceof ExecutionException && e.getCause() instanceof DatabaseDoesNotExistException) {
// Will happen on all node in the cluster,
// so errors immediately
_lastKnownUrls = initialUrls;
throw (DatabaseDoesNotExistException) e.getCause();
}
list.add(Tuple.create(url, e));
}
}
Topology topology = new Topology();
topology.setEtag(topologyEtag);
List<ServerNode> topologyNodes = getTopologyNodes();
if (topologyNodes == null) {
topologyNodes = Arrays.stream(initialUrls)
.map(url -> {
ServerNode serverNode = new ServerNode();
serverNode.setUrl(url);
serverNode.setDatabase(_databaseName);
serverNode.setClusterTag("!");
return serverNode;
}).collect(Collectors.toList());
}
topology.setNodes(topologyNodes);
_nodeSelector = new NodeSelector(topology, _executorService);
if (initialUrls != null && initialUrls.length > 0) {
initializeUpdateTopologyTimer();
return;
}
_lastKnownUrls = initialUrls;
String details = list.stream().map(x -> x.first + " -> " + Optional.ofNullable(x.second).map(Throwable::getMessage).orElse("")).collect(Collectors.joining(", "));
throwExceptions(details);
}, _executorService);
}
protected void throwExceptions(String details) {
throw new IllegalStateException("Failed to retrieve database topology from all known nodes" + System.lineSeparator() + details);
}
public static String[] validateUrls(String[] initialUrls, KeyStore certificate) {
String[] cleanUrls = new String[initialUrls.length];
boolean requireHttps = certificate != null;
for (int index = 0; index < initialUrls.length; index++) {
String url = initialUrls[index];
try {
new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("'" + url + "' is not a valid url");
}
cleanUrls[index] = StringUtils.stripEnd(url, "/");
requireHttps |= url.startsWith("https://");
}
if (!requireHttps) {
return cleanUrls;
}
for (String url : initialUrls) {
if (!url.startsWith("http://")) {
continue;
}
if (certificate != null) {
throw new IllegalStateException("The url " + url + " is using HTTP, but a certificate is specified, which require us to use HTTPS");
}
throw new IllegalStateException("The url " + url + " is using HTTP, but other urls are using HTTPS, and mixing of HTTP and HTTPS is not allowed.");
}
return cleanUrls;
}
private void initializeUpdateTopologyTimer() {
if (_updateTopologyTimer != null) {
return;
}
synchronized (this) {
if (_updateTopologyTimer != null) {
return;
}
_updateTopologyTimer = new Timer(this::updateTopologyCallback, Duration.ofMinutes(1), Duration.ofMinutes(1), _executorService);
}
}
public <TResult> void execute(ServerNode chosenNode, Integer nodeIndex, RavenCommand<TResult> command, boolean shouldRetry, SessionInfo sessionInfo) {
execute(chosenNode, nodeIndex, command, shouldRetry, sessionInfo, null);
}
/**
* Executes the command via an http request to the chosen node.
*
* @param <TResult> TResult - The type of the result
* @param chosenNode A ServerNode representing the node this request should be executed on
* @param nodeIndex An integer representing the index of the chosen server node
* @param command The RavenCommand to be executed
* @param shouldRetry A boolean indicating hether or not the command should be retried on failure
* @param sessionInfo A SessionInfo object...
* @param requestRef A reference to an HttpBaseRequest on which to operate
*/
@SuppressWarnings({"ConstantConditions"})
public <TResult> void execute(ServerNode chosenNode, Integer nodeIndex, RavenCommand<TResult> command, boolean shouldRetry, SessionInfo sessionInfo, Reference<HttpRequestBase> requestRef) {
if (command.failoverTopologyEtag == INITIAL_TOPOLOGY_ETAG) {
command.failoverTopologyEtag = INITIAL_TOPOLOGY_ETAG;
if (_nodeSelector != null && _nodeSelector.getTopology() != null) {
Topology topology = _nodeSelector.getTopology();
if (topology.getEtag() != null) {
command.failoverTopologyEtag = topology.getEtag();
}
}
}
Reference<String> urlRef = new Reference<>();
HttpRequestBase request = createRequest(chosenNode, command, urlRef);
if (request == null) {
return;
}
if (requestRef != null) {
requestRef.value = request;
}
if (request == null) {
return;
}
//noinspection SimplifiableConditionalExpression
boolean noCaching = sessionInfo != null ? sessionInfo.isNoCaching() : false;
Reference<String> cachedChangeVectorRef = new Reference<>();
Reference<String> cachedValue = new Reference<>();
try (HttpCache.ReleaseCacheItem cachedItem = getFromCache(command, !noCaching, urlRef.value, cachedChangeVectorRef, cachedValue)) {
if (cachedChangeVectorRef.value != null) {
if (tryGetFromCache(command, cachedItem, cachedValue.value)) {
return;
}
}
setRequestHeaders(sessionInfo, cachedChangeVectorRef.value, request);
command.numberOfAttempts = command.numberOfAttempts + 1;
int attemptNum = command.numberOfAttempts;
EventHelper.invoke(_onBeforeRequest, this, new BeforeRequestEventArgs(_databaseName, urlRef.value, request, attemptNum));
CloseableHttpResponse response = sendRequestToServer(chosenNode, nodeIndex, command, shouldRetry, sessionInfo, request, urlRef.value);
if (response == null) {
return;
}
CompletableFuture<Void> refreshTask = refreshIfNeeded(chosenNode, response);
command.statusCode = response.getStatusLine().getStatusCode();
ResponseDisposeHandling responseDispose = ResponseDisposeHandling.AUTOMATIC;
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
EventHelper.invoke(_onSucceedRequest, this, new SucceedRequestEventArgs(_databaseName, urlRef.value, response, request, attemptNum));
cachedItem.notModified();
try {
if (command.getResponseType() == RavenCommandResponseType.OBJECT) {
command.setResponse(cachedValue.value, true);
}
} catch (IOException e) {
throw ExceptionsUtils.unwrapException(e);
}
return;
}
if (response.getStatusLine().getStatusCode() >= 400) {
if (!handleUnsuccessfulResponse(chosenNode, nodeIndex, command, request, response, urlRef.value, sessionInfo, shouldRetry)) {
Header dbMissingHeader = response.getFirstHeader("Database-Missing");
if (dbMissingHeader != null && dbMissingHeader.getValue() != null) {
throw new DatabaseDoesNotExistException(dbMissingHeader.getValue());
}
throwFailedToContactAllNodes(command, request);
}
return; // we either handled this already in the unsuccessful response or we are throwing
}
EventHelper.invoke(_onSucceedRequest, this, new SucceedRequestEventArgs(_databaseName, urlRef.value, response, request, attemptNum));
responseDispose = command.processResponse(cache, response, urlRef.value);
_lastReturnedResponse = new Date();
} finally {
if (responseDispose == ResponseDisposeHandling.AUTOMATIC) {
IOUtils.closeQuietly(response, null);
}
try {
refreshTask.get();
} catch (Exception e) {
//noinspection ThrowFromFinallyBlock
throw ExceptionsUtils.unwrapException(e);
}
}
}
}
private CompletableFuture<Void> refreshIfNeeded(ServerNode chosenNode, CloseableHttpResponse response) {
Boolean refreshTopology = Optional.ofNullable(HttpExtensions.getBooleanHeader(response, Constants.Headers.REFRESH_TOPOLOGY)).orElse(false);
Boolean refreshClientConfiguration = Optional.ofNullable(HttpExtensions.getBooleanHeader(response, Constants.Headers.REFRESH_CLIENT_CONFIGURATION)).orElse(false);
CompletableFuture<Boolean> refreshTask = CompletableFuture.completedFuture(false);
CompletableFuture<Void> refreshClientConfigurationTask = CompletableFuture.completedFuture(null);
if (refreshTopology) {
UpdateTopologyParameters updateParameters = new UpdateTopologyParameters(chosenNode);
updateParameters.setTimeoutInMs(0);
updateParameters.setDebugTag("refresh-topology-header");
refreshTask = updateTopologyAsync(updateParameters);
}
if (refreshClientConfiguration) {
refreshClientConfigurationTask = updateClientConfigurationAsync(chosenNode);
}
return CompletableFuture.allOf(refreshTask, refreshClientConfigurationTask);
}
private <TResult> CloseableHttpResponse sendRequestToServer(ServerNode chosenNode, Integer nodeIndex, RavenCommand<TResult> command,
boolean shouldRetry, SessionInfo sessionInfo, HttpRequestBase request, String url) {
try {
numberOfServerRequests.incrementAndGet();
Duration timeout = ObjectUtils.firstNonNull(command.getTimeout(), _defaultTimeout);
if (timeout != null) {
AggressiveCacheOptions callingTheadAggressiveCaching = aggressiveCaching.get();
CompletableFuture<CloseableHttpResponse> sendTask = CompletableFuture.supplyAsync(() -> {
AggressiveCacheOptions aggressiveCacheOptionsToRestore = aggressiveCaching.get();
try {
aggressiveCaching.set(callingTheadAggressiveCaching);
return send(chosenNode, command, sessionInfo, request);
} catch (IOException e) {
throw ExceptionsUtils.unwrapException(e);
} finally {
aggressiveCaching.set(aggressiveCacheOptionsToRestore);
}
}, _executorService);
try {
return sendTask.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw ExceptionsUtils.unwrapException(e);
} catch (TimeoutException e) {
request.abort();
net.ravendb.client.exceptions.TimeoutException timeoutException = new net.ravendb.client.exceptions.TimeoutException("The request for " + request.getURI() + " failed with timeout after " + TimeUtils.durationToTimeSpan(timeout), e);
if (!shouldRetry) {
if (command.getFailedNodes() == null) {
command.setFailedNodes(new HashMap<>());
}
command.getFailedNodes().put(chosenNode, timeoutException);
throw timeoutException;
}
if (!handleServerDown(url, chosenNode, nodeIndex, command, request, null, timeoutException, sessionInfo, shouldRetry)) {
throwFailedToContactAllNodes(command, request);
}
return null;
} catch (ExecutionException e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause instanceof IOException) {
throw (IOException) rootCause;
}
throw ExceptionsUtils.unwrapException(e);
}
} else {
return send(chosenNode, command, sessionInfo, request);
}
} catch (IOException e) {
if (!shouldRetry) {
throw ExceptionsUtils.unwrapException(e);
}
if (!handleServerDown(url, chosenNode, nodeIndex, command, request, null, e, sessionInfo, shouldRetry)) {
throwFailedToContactAllNodes(command, request);
}
return null;
}
}
private <TResult> CloseableHttpResponse send(ServerNode chosenNode, RavenCommand<TResult> command, SessionInfo sessionInfo, HttpRequestBase request) throws IOException {
CloseableHttpResponse response = null;
if (shouldExecuteOnAll(chosenNode, command)) {
response = executeOnAllToFigureOutTheFastest(chosenNode, command);
} else {
response = command.send(getHttpClient(), request);
}
// PERF: The reason to avoid rechecking every time is that servers wont change so rapidly
// and therefore we dimish its cost by orders of magnitude just doing it
// once in a while. We dont care also about the potential race conditions that may happen
// here mainly because the idea is to have a lax mechanism to recheck that is at least
// orders of magnitude faster than currently.
if (chosenNode.shouldUpdateServerVersion()) {
String serverVersion = tryGetServerVersion(response);
if (serverVersion != null) {
chosenNode.updateServerVersion(serverVersion);
}
}
lastServerVersion = chosenNode.getLastServerVersion();
if (sessionInfo != null && sessionInfo.getLastClusterTransactionIndex() != null) {
// if we reach here it means that sometime a cluster transaction has occurred against this database.
// Since the current executed command can be dependent on that, we have to wait for the cluster transaction.
// But we can't do that if the server is an old one.
if (lastServerVersion == null || lastServerVersion.compareToIgnoreCase("4.1") < 0) {
throw new ClientVersionMismatchException("The server on " + chosenNode.getUrl() + " has an old version and can't perform " +
"the command since this command dependent on a cluster transaction which this node doesn't support.");
}
}
return response;
}
private void setRequestHeaders(SessionInfo sessionInfo, String cachedChangeVector, HttpRequest request) {
if (cachedChangeVector != null) {
request.addHeader(Constants.Headers.IF_NONE_MATCH, "\"" + cachedChangeVector + "\"");
}
if (!_disableClientConfigurationUpdates) {
request.addHeader(Constants.Headers.CLIENT_CONFIGURATION_ETAG, "\"" + clientConfigurationEtag + "\"");
}
if (sessionInfo != null && sessionInfo.getLastClusterTransactionIndex() != null) {
request.addHeader(Constants.Headers.LAST_KNOWN_CLUSTER_TRANSACTION_INDEX, sessionInfo.getLastClusterTransactionIndex().toString());
}