/
Http2SolrClient.java
1283 lines (1151 loc) · 46.3 KB
/
Http2SolrClient.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.impl;
import static org.apache.solr.client.solrj.impl.BaseHttpSolrClient.RemoteExecutionException;
import static org.apache.solr.client.solrj.impl.BaseHttpSolrClient.RemoteSolrException;
import static org.apache.solr.common.util.Utils.getObjectByPath;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Phaser;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import org.apache.http.entity.ContentType;
import org.apache.solr.client.solrj.ResponseParser;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.V2RequestSupport;
import org.apache.solr.client.solrj.embedded.SSLConfig;
import org.apache.solr.client.solrj.request.RequestWriter;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.request.V2Request;
import org.apache.solr.client.solrj.util.AsyncListener;
import org.apache.solr.client.solrj.util.Cancellable;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.StringUtils;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.UpdateParams;
import org.apache.solr.common.util.ContentStream;
import org.apache.solr.common.util.ExecutorUtil;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.ObjectReleaseTracker;
import org.apache.solr.common.util.SolrNamedThreadFactory;
import org.apache.solr.common.util.Utils;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.ProtocolHandlers;
import org.eclipse.jetty.client.api.AuthenticationStore;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.http.HttpClientTransportOverHTTP;
import org.eclipse.jetty.client.util.ByteBufferContentProvider;
import org.eclipse.jetty.client.util.FormContentProvider;
import org.eclipse.jetty.client.util.InputStreamContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.client.util.MultiPartContentProvider;
import org.eclipse.jetty.client.util.OutputStreamContentProvider;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.io.ClientConnector;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.Fields;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Difference between this {@link Http2SolrClient} and {@link HttpSolrClient}:
*
* <ul>
* <li>{@link Http2SolrClient} sends requests in HTTP/2
* <li>{@link Http2SolrClient} can point to multiple urls
* <li>{@link Http2SolrClient} does not expose its internal httpClient like {@link
* HttpSolrClient#getHttpClient()}, sharing connection pools should be done by {@link
* Http2SolrClient.Builder#withHttpClient(Http2SolrClient)}
* </ul>
*
* @lucene.experimental
*/
public class Http2SolrClient extends SolrClient {
public static final String REQ_PRINCIPAL_KEY = "solr-req-principal";
private static volatile SSLConfig defaultSSLConfig;
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String AGENT = "Solr[" + Http2SolrClient.class.getName() + "] 2.0";
private static final Charset FALLBACK_CHARSET = StandardCharsets.UTF_8;
private static final String DEFAULT_PATH = "/select";
private static final List<String> errPath = Arrays.asList("metadata", "error-class");
private HttpClient httpClient;
private volatile Set<String> urlParamNames = Set.of();
private long idleTimeoutMillis;
private long requestTimeoutMillis;
protected ResponseParser parser = new BinaryResponseParser();
protected RequestWriter requestWriter = new BinaryRequestWriter();
private List<HttpListenerFactory> listenerFactory = new ArrayList<>();
private AsyncTracker asyncTracker = new AsyncTracker();
/** The URL of the Solr server. */
private String serverBaseUrl;
private boolean closeClient;
private ExecutorService executor;
private boolean shutdownExecutor;
private final String basicAuthAuthorizationStr;
private AuthenticationStoreHolder authenticationStore;
protected Http2SolrClient(String serverBaseUrl, Builder builder) {
if (serverBaseUrl != null) {
if (!serverBaseUrl.equals("/") && serverBaseUrl.endsWith("/")) {
serverBaseUrl = serverBaseUrl.substring(0, serverBaseUrl.length() - 1);
}
if (serverBaseUrl.startsWith("//")) {
serverBaseUrl = serverBaseUrl.substring(1, serverBaseUrl.length());
}
this.serverBaseUrl = serverBaseUrl;
}
if (builder.idleTimeoutMillis != null && builder.idleTimeoutMillis > 0) {
idleTimeoutMillis = builder.idleTimeoutMillis;
} else {
idleTimeoutMillis = HttpClientUtil.DEFAULT_SO_TIMEOUT;
}
if (builder.http2SolrClient == null) {
httpClient = createHttpClient(builder);
closeClient = true;
} else {
httpClient = builder.http2SolrClient.httpClient;
}
if (builder.basicAuthUser != null && builder.basicAuthPassword != null) {
basicAuthAuthorizationStr =
basicAuthCredentialsToAuthorizationString(
builder.basicAuthUser, builder.basicAuthPassword);
} else {
basicAuthAuthorizationStr = null;
}
if (builder.requestWriter != null) {
requestWriter = builder.requestWriter;
}
if (builder.responseParser != null) {
parser = builder.responseParser;
}
if (builder.requestTimeoutMillis == null) {
requestTimeoutMillis = -1;
} else {
requestTimeoutMillis = builder.requestTimeoutMillis;
}
httpClient.setFollowRedirects(builder.followRedirects);
this.urlParamNames = builder.urlParamNames;
assert ObjectReleaseTracker.track(this);
}
public void addListenerFactory(HttpListenerFactory factory) {
this.listenerFactory.add(factory);
}
// internal usage only
HttpClient getHttpClient() {
return httpClient;
}
// internal usage only
ProtocolHandlers getProtocolHandlers() {
return httpClient.getProtocolHandlers();
}
private HttpClient createHttpClient(Builder builder) {
HttpClient httpClient;
executor = builder.executor;
if (executor == null) {
BlockingArrayQueue<Runnable> queue = new BlockingArrayQueue<>(256, 256);
this.executor =
new ExecutorUtil.MDCAwareThreadPoolExecutor(
32, 256, 60, TimeUnit.SECONDS, queue, new SolrNamedThreadFactory("h2sc"));
shutdownExecutor = true;
} else {
shutdownExecutor = false;
}
SslContextFactory.Client sslContextFactory;
boolean sslEnabled;
if (builder.sslConfig == null) {
sslEnabled =
System.getProperty("javax.net.ssl.keyStore") != null
|| System.getProperty("javax.net.ssl.trustStore") != null;
sslContextFactory = sslEnabled ? getDefaultSslContextFactory() : null;
} else {
sslContextFactory = builder.sslConfig.createClientContextFactory();
sslEnabled = true;
}
HttpClientTransport transport;
if (builder.useHttp1_1) {
if (log.isDebugEnabled()) {
log.debug("Create Http2SolrClient with HTTP/1.1 transport");
}
ClientConnector clientConnector = new ClientConnector();
clientConnector.setReuseAddress(true);
clientConnector.setSslContextFactory(sslContextFactory);
clientConnector.setSelectors(2);
transport = new HttpClientTransportOverHTTP(clientConnector);
httpClient = new HttpClient(transport);
if (builder.maxConnectionsPerHost != null)
httpClient.setMaxConnectionsPerDestination(builder.maxConnectionsPerHost);
} else {
log.debug("Create Http2SolrClient with HTTP/2 transport");
ClientConnector clientConnector = new ClientConnector();
clientConnector.setReuseAddress(true);
clientConnector.setSslContextFactory(sslContextFactory);
clientConnector.setSelectors(2);
HTTP2Client http2client = new HTTP2Client(clientConnector);
transport = new HttpClientTransportOverHTTP2(http2client);
httpClient = new HttpClient(transport);
httpClient.setMaxConnectionsPerDestination(4);
}
httpClient.setExecutor(this.executor);
httpClient.setStrictEventOrdering(false);
httpClient.setConnectBlocking(true);
httpClient.setFollowRedirects(false);
httpClient.setMaxRequestsQueuedPerDestination(
asyncTracker.getMaxRequestsQueuedPerDestination());
httpClient.setUserAgentField(new HttpField(HttpHeader.USER_AGENT, AGENT));
httpClient.setIdleTimeout(idleTimeoutMillis);
this.authenticationStore = new AuthenticationStoreHolder();
httpClient.setAuthenticationStore(this.authenticationStore);
if (builder.connectionTimeoutMillis != null)
httpClient.setConnectTimeout(builder.connectionTimeoutMillis);
try {
httpClient.start();
} catch (Exception e) {
close(); // make sure we clean up
throw new RuntimeException(e);
}
return httpClient;
}
@Override
public void close() {
// we wait for async requests, so far devs don't want to give sugar for this
asyncTracker.waitForComplete();
try {
if (closeClient) {
httpClient.stop();
httpClient.destroy();
}
} catch (Exception e) {
throw new RuntimeException("Exception on closing client", e);
} finally {
if (shutdownExecutor) {
ExecutorUtil.shutdownAndAwaitTermination(executor);
}
}
assert ObjectReleaseTracker.release(this);
}
public void setAuthenticationStore(AuthenticationStore authenticationStore) {
this.authenticationStore.updateAuthenticationStore(authenticationStore);
}
public boolean isV2ApiRequest(final SolrRequest<?> request) {
return request instanceof V2Request || request.getPath().contains("/____v2");
}
public long getIdleTimeout() {
return idleTimeoutMillis;
}
public static class OutStream implements Closeable {
private final String origCollection;
private final ModifiableSolrParams origParams;
private final OutputStreamContentProvider outProvider;
private final InputStreamResponseListener responseListener;
private final boolean isXml;
public OutStream(
String origCollection,
ModifiableSolrParams origParams,
OutputStreamContentProvider outProvider,
InputStreamResponseListener responseListener,
boolean isXml) {
this.origCollection = origCollection;
this.origParams = origParams;
this.outProvider = outProvider;
this.responseListener = responseListener;
this.isXml = isXml;
}
boolean belongToThisStream(SolrRequest<?> solrRequest, String collection) {
ModifiableSolrParams solrParams = new ModifiableSolrParams(solrRequest.getParams());
if (!origParams.toNamedList().equals(solrParams.toNamedList())
|| !StringUtils.equals(origCollection, collection)) {
return false;
}
return true;
}
public void write(byte b[]) throws IOException {
this.outProvider.getOutputStream().write(b);
}
public void flush() throws IOException {
this.outProvider.getOutputStream().flush();
}
@Override
public void close() throws IOException {
if (isXml) {
write("</stream>".getBytes(FALLBACK_CHARSET));
}
this.outProvider.getOutputStream().close();
}
// TODO this class should be hidden
public InputStreamResponseListener getResponseListener() {
return responseListener;
}
}
public OutStream initOutStream(String baseUrl, UpdateRequest updateRequest, String collection)
throws IOException {
String contentType = requestWriter.getUpdateContentType();
final ModifiableSolrParams origParams = new ModifiableSolrParams(updateRequest.getParams());
// The parser 'wt=' and 'version=' params are used instead of the
// original params
ModifiableSolrParams requestParams = new ModifiableSolrParams(origParams);
requestParams.set(CommonParams.WT, parser.getWriterType());
requestParams.set(CommonParams.VERSION, parser.getVersion());
String basePath = baseUrl;
if (collection != null) basePath += "/" + collection;
if (!basePath.endsWith("/")) basePath += "/";
OutputStreamContentProvider provider = new OutputStreamContentProvider();
Request postRequest =
httpClient
.newRequest(basePath + "update" + requestParams.toQueryString())
.method(HttpMethod.POST)
.header(HttpHeader.CONTENT_TYPE, contentType)
.content(provider);
decorateRequest(postRequest, updateRequest);
InputStreamResponseListener responseListener = new InputStreamResponseListener();
postRequest.send(responseListener);
boolean isXml = ClientUtils.TEXT_XML.equals(requestWriter.getUpdateContentType());
OutStream outStream = new OutStream(collection, origParams, provider, responseListener, isXml);
if (isXml) {
outStream.write("<stream>".getBytes(FALLBACK_CHARSET));
}
return outStream;
}
public void send(OutStream outStream, SolrRequest<?> req, String collection) throws IOException {
assert outStream.belongToThisStream(req, collection);
this.requestWriter.write(req, outStream.outProvider.getOutputStream());
if (outStream.isXml) {
// check for commit or optimize
SolrParams params = req.getParams();
if (params != null) {
String fmt = null;
if (params.getBool(UpdateParams.OPTIMIZE, false)) {
fmt = "<optimize waitSearcher=\"%s\" />";
} else if (params.getBool(UpdateParams.COMMIT, false)) {
fmt = "<commit waitSearcher=\"%s\" />";
}
if (fmt != null) {
byte[] content =
String.format(
Locale.ROOT, fmt, params.getBool(UpdateParams.WAIT_SEARCHER, false) + "")
.getBytes(FALLBACK_CHARSET);
outStream.write(content);
}
}
}
outStream.flush();
}
@SuppressWarnings("StaticAssignmentOfThrowable")
private static final Exception CANCELLED_EXCEPTION = new Exception();
private static final Cancellable FAILED_MAKING_REQUEST_CANCELLABLE = () -> {};
public Cancellable asyncRequest(
SolrRequest<?> solrRequest,
String collection,
AsyncListener<NamedList<Object>> asyncListener) {
Request req;
try {
req = makeRequest(solrRequest, collection);
} catch (SolrServerException | IOException e) {
asyncListener.onFailure(e);
return FAILED_MAKING_REQUEST_CANCELLABLE;
}
final ResponseParser parser =
solrRequest.getResponseParser() == null ? this.parser : solrRequest.getResponseParser();
req.onRequestQueued(asyncTracker.queuedListener)
.onComplete(asyncTracker.completeListener)
.send(
new InputStreamResponseListener() {
@Override
public void onHeaders(Response response) {
super.onHeaders(response);
InputStreamResponseListener listener = this;
executor.execute(
() -> {
InputStream is = listener.getInputStream();
assert ObjectReleaseTracker.track(is);
try {
NamedList<Object> body =
processErrorsAndResponse(solrRequest, parser, response, is);
asyncListener.onSuccess(body);
} catch (RemoteSolrException e) {
if (SolrException.getRootCause(e) != CANCELLED_EXCEPTION) {
asyncListener.onFailure(e);
}
} catch (SolrServerException e) {
asyncListener.onFailure(e);
}
});
}
@Override
public void onFailure(Response response, Throwable failure) {
super.onFailure(response, failure);
if (failure != CANCELLED_EXCEPTION) {
asyncListener.onFailure(new SolrServerException(failure.getMessage(), failure));
}
}
});
return () -> req.abort(CANCELLED_EXCEPTION);
}
@Override
public NamedList<Object> request(SolrRequest<?> solrRequest, String collection)
throws SolrServerException, IOException {
Request req = makeRequest(solrRequest, collection);
final ResponseParser parser =
solrRequest.getResponseParser() == null ? this.parser : solrRequest.getResponseParser();
Throwable abortCause = null;
try {
InputStreamResponseListener listener = new InputStreamResponseListener();
req.send(listener);
Response response = listener.get(idleTimeoutMillis, TimeUnit.MILLISECONDS);
InputStream is = listener.getInputStream();
assert ObjectReleaseTracker.track(is);
return processErrorsAndResponse(solrRequest, parser, response, is);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
abortCause = e;
throw new RuntimeException(e);
} catch (TimeoutException e) {
throw new SolrServerException(
"Timeout occurred while waiting response from server at: " + req.getURI(), e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
abortCause = cause;
if (cause instanceof ConnectException) {
throw new SolrServerException("Server refused connection at: " + req.getURI(), cause);
}
if (cause instanceof SolrServerException) {
throw (SolrServerException) cause;
} else if (cause instanceof IOException) {
throw new SolrServerException(
"IOException occurred when talking to server at: " + getBaseURL(), cause);
}
throw new SolrServerException(cause.getMessage(), cause);
} catch (SolrServerException | RuntimeException sse) {
abortCause = sse;
throw sse;
} finally {
if (abortCause != null) {
req.abort(abortCause);
}
}
}
private NamedList<Object> processErrorsAndResponse(
SolrRequest<?> solrRequest, ResponseParser parser, Response response, InputStream is)
throws SolrServerException {
String contentType = response.getHeaders().get(HttpHeader.CONTENT_TYPE);
String mimeType = null;
String encoding = null;
if (contentType != null) {
mimeType = MimeTypes.getContentTypeWithoutCharset(contentType);
encoding = MimeTypes.getCharsetFromContentType(contentType);
}
return processErrorsAndResponse(
response, parser, is, mimeType, encoding, isV2ApiRequest(solrRequest));
}
private void setBasicAuthHeader(SolrRequest<?> solrRequest, Request req) {
if (solrRequest.getBasicAuthUser() != null && solrRequest.getBasicAuthPassword() != null) {
String encoded =
basicAuthCredentialsToAuthorizationString(
solrRequest.getBasicAuthUser(), solrRequest.getBasicAuthPassword());
req.header("Authorization", encoded);
} else if (basicAuthAuthorizationStr != null) {
req.header("Authorization", basicAuthAuthorizationStr);
}
}
private String basicAuthCredentialsToAuthorizationString(String user, String pass) {
String userPass = user + ":" + pass;
return "Basic " + Base64.getEncoder().encodeToString(userPass.getBytes(FALLBACK_CHARSET));
}
private Request makeRequest(SolrRequest<?> solrRequest, String collection)
throws SolrServerException, IOException {
Request req = createRequest(solrRequest, collection);
decorateRequest(req, solrRequest);
return req;
}
private void decorateRequest(Request req, SolrRequest<?> solrRequest) {
req.header(HttpHeader.ACCEPT_ENCODING, null);
if (requestTimeoutMillis > 0) {
req.timeout(requestTimeoutMillis, TimeUnit.MILLISECONDS);
} else {
req.timeout(idleTimeoutMillis, TimeUnit.MILLISECONDS);
}
if (solrRequest.getUserPrincipal() != null) {
req.attribute(REQ_PRINCIPAL_KEY, solrRequest.getUserPrincipal());
}
setBasicAuthHeader(solrRequest, req);
for (HttpListenerFactory factory : listenerFactory) {
HttpListenerFactory.RequestResponseListener listener = factory.get();
listener.onQueued(req);
req.onRequestBegin(listener);
req.onComplete(listener);
}
Map<String, String> headers = solrRequest.getHeaders();
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
req.header(entry.getKey(), entry.getValue());
}
}
}
private String changeV2RequestEndpoint(String basePath) throws MalformedURLException {
URL oldURL = new URL(basePath);
String newPath = oldURL.getPath().replaceFirst("/solr", "/api");
return new URL(oldURL.getProtocol(), oldURL.getHost(), oldURL.getPort(), newPath).toString();
}
private Request createRequest(SolrRequest<?> solrRequest, String collection)
throws IOException, SolrServerException {
if (solrRequest.getBasePath() == null && serverBaseUrl == null)
throw new IllegalArgumentException("Destination node is not provided!");
if (solrRequest instanceof V2RequestSupport) {
solrRequest = ((V2RequestSupport) solrRequest).getV2Request();
}
SolrParams params = solrRequest.getParams();
RequestWriter.ContentWriter contentWriter = requestWriter.getContentWriter(solrRequest);
Collection<ContentStream> streams =
contentWriter == null ? requestWriter.getContentStreams(solrRequest) : null;
String path = requestWriter.getPath(solrRequest);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = solrRequest.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
if (parser != null) {
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
}
// TODO add invariantParams support
String basePath = solrRequest.getBasePath() == null ? serverBaseUrl : solrRequest.getBasePath();
if (collection != null) basePath += "/" + collection;
if (solrRequest instanceof V2Request) {
if (System.getProperty("solr.v2RealPath") == null) {
basePath = changeV2RequestEndpoint(basePath);
} else {
basePath = serverBaseUrl + "/____v2";
}
}
if (SolrRequest.METHOD.GET == solrRequest.getMethod()) {
if (streams != null || contentWriter != null) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
}
return httpClient
.newRequest(basePath + path + wparams.toQueryString())
.method(HttpMethod.GET);
}
if (SolrRequest.METHOD.DELETE == solrRequest.getMethod()) {
return httpClient
.newRequest(basePath + path + wparams.toQueryString())
.method(HttpMethod.DELETE);
}
if (SolrRequest.METHOD.POST == solrRequest.getMethod()
|| SolrRequest.METHOD.PUT == solrRequest.getMethod()) {
String url = basePath + path;
boolean hasNullStreamName = false;
if (streams != null) {
hasNullStreamName = streams.stream().anyMatch(cs -> cs.getName() == null);
}
boolean isMultipart = streams != null && streams.size() > 1 && !hasNullStreamName;
HttpMethod method =
SolrRequest.METHOD.POST == solrRequest.getMethod() ? HttpMethod.POST : HttpMethod.PUT;
if (contentWriter != null) {
Request req = httpClient.newRequest(url + wparams.toQueryString()).method(method);
BinaryRequestWriter.BAOS baos = new BinaryRequestWriter.BAOS();
contentWriter.write(baos);
// SOLR-16265: TODO reduce memory usage
return req.content(
// We're throwing this BAOS away, so no need to copy the byte[], just use the raw buf
new ByteBufferContentProvider(
contentWriter.getContentType(), ByteBuffer.wrap(baos.getbuf(), 0, baos.size())));
} else if (streams == null || isMultipart) {
// send server list and request list as query string params
ModifiableSolrParams queryParams = calculateQueryParams(this.urlParamNames, wparams);
queryParams.add(calculateQueryParams(solrRequest.getQueryParams(), wparams));
Request req = httpClient.newRequest(url + queryParams.toQueryString()).method(method);
return fillContentStream(req, streams, wparams, isMultipart);
} else {
// It is has one stream, it is the post body, put the params in the URL
ContentStream contentStream = streams.iterator().next();
return httpClient
.newRequest(url + wparams.toQueryString())
.method(method)
.content(
new InputStreamContentProvider(contentStream.getStream()),
contentStream.getContentType());
}
}
throw new SolrServerException("Unsupported method: " + solrRequest.getMethod());
}
private Request fillContentStream(
Request req,
Collection<ContentStream> streams,
ModifiableSolrParams wparams,
boolean isMultipart)
throws IOException {
if (isMultipart) {
// multipart/form-data
MultiPartContentProvider content = new MultiPartContentProvider();
Iterator<String> iter = wparams.getParameterNamesIterator();
while (iter.hasNext()) {
String key = iter.next();
String[] vals = wparams.getParams(key);
if (vals != null) {
for (String val : vals) {
content.addFieldPart(key, new StringContentProvider(val), null);
}
}
}
if (streams != null) {
for (ContentStream contentStream : streams) {
String contentType = contentStream.getContentType();
if (contentType == null) {
contentType = "multipart/form-data"; // default
}
String name = contentStream.getName();
if (name == null) {
name = "";
}
HttpFields.Mutable fields = HttpFields.build(1);
fields.add(HttpHeader.CONTENT_TYPE, contentType);
content.addFilePart(
name,
contentStream.getName(),
new InputStreamContentProvider(contentStream.getStream()),
fields);
}
}
req.content(content);
} else {
// application/x-www-form-urlencoded
Fields fields = new Fields();
Iterator<String> iter = wparams.getParameterNamesIterator();
while (iter.hasNext()) {
String key = iter.next();
String[] vals = wparams.getParams(key);
if (vals != null) {
for (String val : vals) {
fields.add(key, val);
}
}
}
req.content(new FormContentProvider(fields, FALLBACK_CHARSET));
}
return req;
}
private boolean wantStream(final ResponseParser processor) {
return processor == null || processor instanceof InputStreamResponseParser;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private NamedList<Object> processErrorsAndResponse(
Response response,
final ResponseParser processor,
InputStream is,
String mimeType,
String encoding,
final boolean isV2Api)
throws SolrServerException {
boolean shouldClose = true;
try {
// handle some http level checks before trying to parse the response
int httpStatus = response.getStatus();
switch (httpStatus) {
case HttpStatus.OK_200:
case HttpStatus.BAD_REQUEST_400:
case HttpStatus.CONFLICT_409:
break;
case HttpStatus.MOVED_PERMANENTLY_301:
case HttpStatus.MOVED_TEMPORARILY_302:
if (!httpClient.isFollowRedirects()) {
throw new SolrServerException(
"Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ").");
}
break;
default:
if (processor == null || mimeType == null) {
throw new RemoteSolrException(
serverBaseUrl,
httpStatus,
"non ok status: " + httpStatus + ", message:" + response.getReason(),
null);
}
}
if (wantStream(parser)) {
// no processor specified, return raw stream
NamedList<Object> rsp = new NamedList<>();
rsp.add("stream", is);
// Only case where stream should not be closed
shouldClose = false;
return rsp;
}
final Collection<String> processorSupportedContentTypes = processor.getContentTypes();
if (processorSupportedContentTypes != null && !processorSupportedContentTypes.isEmpty()) {
final Collection<String> processorMimeTypes =
processorSupportedContentTypes.stream()
.map(ct -> ContentType.parse(ct).getMimeType().trim().toLowerCase(Locale.ROOT))
.collect(Collectors.toSet());
if (!processorMimeTypes.contains(mimeType)) {
// unexpected mime type
final String allSupportedTypes = String.join(", ", processorMimeTypes);
String prefix =
"Expected mime type in [" + allSupportedTypes + "] but got " + mimeType + ". ";
String exceptionEncoding = encoding != null ? encoding : FALLBACK_CHARSET.name();
try {
ByteArrayOutputStream body = new ByteArrayOutputStream();
is.transferTo(body);
throw new RemoteSolrException(
serverBaseUrl, httpStatus, prefix + body.toString(exceptionEncoding), null);
} catch (IOException e) {
throw new RemoteSolrException(
serverBaseUrl,
httpStatus,
"Could not parse response with encoding " + exceptionEncoding,
e);
}
}
}
NamedList<Object> rsp;
try {
rsp = processor.processResponse(is, encoding);
} catch (Exception e) {
throw new RemoteSolrException(serverBaseUrl, httpStatus, e.getMessage(), e);
}
Object error = rsp == null ? null : rsp.get("error");
if (error != null
&& (String.valueOf(getObjectByPath(error, true, errPath))
.endsWith("ExceptionWithErrObject"))) {
throw RemoteExecutionException.create(serverBaseUrl, rsp);
}
if (httpStatus != HttpStatus.OK_200 && !isV2Api) {
NamedList<String> metadata = null;
String reason = null;
try {
if (error != null) {
reason = (String) Utils.getObjectByPath(error, false, Collections.singletonList("msg"));
if (reason == null) {
reason =
(String) Utils.getObjectByPath(error, false, Collections.singletonList("trace"));
}
Object metadataObj =
Utils.getObjectByPath(error, false, Collections.singletonList("metadata"));
if (metadataObj instanceof NamedList) {
metadata = (NamedList<String>) metadataObj;
} else if (metadataObj instanceof List) {
// NamedList parsed as List convert to NamedList again
List<Object> list = (List<Object>) metadataObj;
metadata = new NamedList<>(list.size() / 2);
for (int i = 0; i < list.size(); i += 2) {
metadata.add((String) list.get(i), (String) list.get(i + 1));
}
} else if (metadataObj instanceof Map) {
metadata = new NamedList((Map) metadataObj);
}
}
} catch (Exception ex) {
/* Ignored */
}
if (reason == null) {
StringBuilder msg = new StringBuilder();
msg.append(response.getReason())
.append("\n\n")
.append("request: ")
.append(response.getRequest().getMethod());
reason = java.net.URLDecoder.decode(msg.toString(), FALLBACK_CHARSET);
}
RemoteSolrException rss = new RemoteSolrException(serverBaseUrl, httpStatus, reason, null);
if (metadata != null) rss.setMetadata(metadata);
throw rss;
}
return rsp;
} finally {
if (shouldClose) {
try {
is.close();
assert ObjectReleaseTracker.release(is);
} catch (IOException e) {
// quitely
}
}
}
}
/**
* Choose the {@link RequestWriter} to use.
*
* <p>By default, {@link BinaryRequestWriter} is used.
*
* <p>Note: This setter method is <b>not thread-safe</b>.
*
* @deprecated use {@link Http2SolrClient.Builder#withRequestWriter(RequestWriter)} instead
*/
@Deprecated
public void setRequestWriter(RequestWriter requestWriter) {
this.requestWriter = requestWriter;
}
protected RequestWriter getRequestWriter() {
return requestWriter;
}
/**
* Configure whether the client should follow redirects or not.
*
* <p>This defaults to false under the assumption that if you are following a redirect to get to a
* Solr installation, something is configured wrong somewhere.
*
* @deprecated use {@link Http2SolrClient.Builder#withFollowRedirects(boolean)}
* Redirects(boolean)} instead
*/
@Deprecated
public void setFollowRedirects(boolean follow) {
httpClient.setFollowRedirects(follow);
}
public String getBaseURL() {
return serverBaseUrl;
}
private static class AsyncTracker {
private static final int MAX_OUTSTANDING_REQUESTS = 1000;
// wait for async requests
private final Phaser phaser;
// maximum outstanding requests left
private final Semaphore available;
private final Request.QueuedListener queuedListener;
private final Response.CompleteListener completeListener;
AsyncTracker() {
// TODO: what about shared instances?
phaser = new Phaser(1);
available = new Semaphore(MAX_OUTSTANDING_REQUESTS, false);
queuedListener =
request -> {
phaser.register();
try {
available.acquire();
} catch (InterruptedException ignored) {
}
};
completeListener =
result -> {
phaser.arriveAndDeregister();
available.release();
};
}
int getMaxRequestsQueuedPerDestination() {
// comfortably above max outstanding requests
return MAX_OUTSTANDING_REQUESTS * 3;
}
public void waitForComplete() {
phaser.arriveAndAwaitAdvance();
phaser.arriveAndDeregister();
}
}
public static class Builder {
private Http2SolrClient http2SolrClient;
private SSLConfig sslConfig = defaultSSLConfig;
private Long idleTimeoutMillis;
private Long connectionTimeoutMillis;
private Long requestTimeoutMillis;
private Integer maxConnectionsPerHost;
private String basicAuthUser;
private String basicAuthPassword;
private boolean useHttp1_1 = Boolean.getBoolean("solr.http1");
private boolean followRedirects = false;
protected String baseSolrUrl;
private ExecutorService executor;
protected RequestWriter requestWriter;
protected ResponseParser responseParser;
private Set<String> urlParamNames = Set.of();