forked from grpc/grpc-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OkHttpClientTransport.java
1416 lines (1317 loc) · 50.5 KB
/
OkHttpClientTransport.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
/*
* Copyright 2014 The gRPC Authors
*
* Licensed 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 io.grpc.okhttp;
import static com.google.common.base.Preconditions.checkState;
import static io.grpc.okhttp.Utils.DEFAULT_WINDOW_SIZE;
import static io.grpc.okhttp.Utils.DEFAULT_WINDOW_UPDATE_RATIO;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Supplier;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.Attributes;
import io.grpc.CallOptions;
import io.grpc.ClientStreamTracer;
import io.grpc.Grpc;
import io.grpc.HttpConnectProxiedSocketAddress;
import io.grpc.InternalChannelz;
import io.grpc.InternalChannelz.SocketStats;
import io.grpc.InternalLogId;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.SecurityLevel;
import io.grpc.Status;
import io.grpc.Status.Code;
import io.grpc.StatusException;
import io.grpc.internal.ClientStreamListener.RpcProgress;
import io.grpc.internal.ConnectionClientTransport;
import io.grpc.internal.GrpcAttributes;
import io.grpc.internal.GrpcUtil;
import io.grpc.internal.Http2Ping;
import io.grpc.internal.InUseStateAggregator;
import io.grpc.internal.KeepAliveManager;
import io.grpc.internal.KeepAliveManager.ClientKeepAlivePinger;
import io.grpc.internal.SerializingExecutor;
import io.grpc.internal.StatsTraceContext;
import io.grpc.internal.TransportTracer;
import io.grpc.okhttp.ExceptionHandlingFrameWriter.TransportExceptionHandler;
import io.grpc.okhttp.internal.ConnectionSpec;
import io.grpc.okhttp.internal.Credentials;
import io.grpc.okhttp.internal.StatusLine;
import io.grpc.okhttp.internal.framed.ErrorCode;
import io.grpc.okhttp.internal.framed.FrameReader;
import io.grpc.okhttp.internal.framed.FrameWriter;
import io.grpc.okhttp.internal.framed.Header;
import io.grpc.okhttp.internal.framed.HeadersMode;
import io.grpc.okhttp.internal.framed.Http2;
import io.grpc.okhttp.internal.framed.Settings;
import io.grpc.okhttp.internal.framed.Variant;
import io.grpc.okhttp.internal.proxy.HttpUrl;
import io.grpc.okhttp.internal.proxy.Request;
import io.perfmark.PerfMark;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.util.Collections;
import java.util.Deque;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.ByteString;
import okio.Okio;
import okio.Source;
import okio.Timeout;
/**
* A okhttp-based {@link ConnectionClientTransport} implementation.
*/
class OkHttpClientTransport implements ConnectionClientTransport, TransportExceptionHandler,
OutboundFlowController.Transport {
private static final Map<ErrorCode, Status> ERROR_CODE_TO_STATUS = buildErrorCodeToStatusMap();
private static final Logger log = Logger.getLogger(OkHttpClientTransport.class.getName());
private static Map<ErrorCode, Status> buildErrorCodeToStatusMap() {
Map<ErrorCode, Status> errorToStatus = new EnumMap<>(ErrorCode.class);
errorToStatus.put(ErrorCode.NO_ERROR,
Status.INTERNAL.withDescription("No error: A GRPC status of OK should have been sent"));
errorToStatus.put(ErrorCode.PROTOCOL_ERROR,
Status.INTERNAL.withDescription("Protocol error"));
errorToStatus.put(ErrorCode.INTERNAL_ERROR,
Status.INTERNAL.withDescription("Internal error"));
errorToStatus.put(ErrorCode.FLOW_CONTROL_ERROR,
Status.INTERNAL.withDescription("Flow control error"));
errorToStatus.put(ErrorCode.STREAM_CLOSED,
Status.INTERNAL.withDescription("Stream closed"));
errorToStatus.put(ErrorCode.FRAME_TOO_LARGE,
Status.INTERNAL.withDescription("Frame too large"));
errorToStatus.put(ErrorCode.REFUSED_STREAM,
Status.UNAVAILABLE.withDescription("Refused stream"));
errorToStatus.put(ErrorCode.CANCEL,
Status.CANCELLED.withDescription("Cancelled"));
errorToStatus.put(ErrorCode.COMPRESSION_ERROR,
Status.INTERNAL.withDescription("Compression error"));
errorToStatus.put(ErrorCode.CONNECT_ERROR,
Status.INTERNAL.withDescription("Connect error"));
errorToStatus.put(ErrorCode.ENHANCE_YOUR_CALM,
Status.RESOURCE_EXHAUSTED.withDescription("Enhance your calm"));
errorToStatus.put(ErrorCode.INADEQUATE_SECURITY,
Status.PERMISSION_DENIED.withDescription("Inadequate security"));
return Collections.unmodifiableMap(errorToStatus);
}
private final InetSocketAddress address;
private final String defaultAuthority;
private final String userAgent;
private final Random random = new Random();
// Returns new unstarted stopwatches
private final Supplier<Stopwatch> stopwatchFactory;
private final int initialWindowSize;
private final Variant variant;
private Listener listener;
@GuardedBy("lock")
private ExceptionHandlingFrameWriter frameWriter;
private OutboundFlowController outboundFlow;
private final Object lock = new Object();
private final InternalLogId logId;
@GuardedBy("lock")
private int nextStreamId;
@GuardedBy("lock")
private final Map<Integer, OkHttpClientStream> streams = new HashMap<>();
private final Executor executor;
// Wrap on executor, to guarantee some operations be executed serially.
private final SerializingExecutor serializingExecutor;
private final ScheduledExecutorService scheduler;
private final int maxMessageSize;
private int connectionUnacknowledgedBytesRead;
private ClientFrameHandler clientFrameHandler;
// Caution: Not synchronized, new value can only be safely read after the connection is complete.
private Attributes attributes;
/**
* Indicates the transport is in go-away state: no new streams will be processed, but existing
* streams may continue.
*/
@GuardedBy("lock")
private Status goAwayStatus;
@GuardedBy("lock")
private boolean goAwaySent;
@GuardedBy("lock")
private Http2Ping ping;
@GuardedBy("lock")
private boolean stopped;
@GuardedBy("lock")
private boolean hasStream;
private final SocketFactory socketFactory;
private SSLSocketFactory sslSocketFactory;
private HostnameVerifier hostnameVerifier;
private Socket socket;
@GuardedBy("lock")
private int maxConcurrentStreams = 0;
@SuppressWarnings("JdkObsolete") // Usage is bursty; want low memory usage when empty
@GuardedBy("lock")
private final Deque<OkHttpClientStream> pendingStreams = new LinkedList<>();
private final ConnectionSpec connectionSpec;
private KeepAliveManager keepAliveManager;
private boolean enableKeepAlive;
private long keepAliveTimeNanos;
private long keepAliveTimeoutNanos;
private boolean keepAliveWithoutCalls;
private final Runnable tooManyPingsRunnable;
private final int maxInboundMetadataSize;
private final boolean useGetForSafeMethods;
@GuardedBy("lock")
private final TransportTracer transportTracer;
@GuardedBy("lock")
private final InUseStateAggregator<OkHttpClientStream> inUseState =
new InUseStateAggregator<OkHttpClientStream>() {
@Override
protected void handleInUse() {
listener.transportInUse(true);
}
@Override
protected void handleNotInUse() {
listener.transportInUse(false);
}
};
@GuardedBy("lock")
private InternalChannelz.Security securityInfo;
@VisibleForTesting
@Nullable
final HttpConnectProxiedSocketAddress proxiedAddr;
@VisibleForTesting
int proxySocketTimeout = 30000;
// The following fields should only be used for test.
Runnable connectingCallback;
SettableFuture<Void> connectedFuture;
public OkHttpClientTransport(
OkHttpChannelBuilder.OkHttpTransportFactory transportFactory,
InetSocketAddress address,
String authority,
@Nullable String userAgent,
Attributes eagAttrs,
@Nullable HttpConnectProxiedSocketAddress proxiedAddr,
Runnable tooManyPingsRunnable) {
this(
transportFactory,
address,
authority,
userAgent,
eagAttrs,
GrpcUtil.STOPWATCH_SUPPLIER,
new Http2(),
proxiedAddr,
tooManyPingsRunnable);
}
private OkHttpClientTransport(
OkHttpChannelBuilder.OkHttpTransportFactory transportFactory,
InetSocketAddress address,
String authority,
@Nullable String userAgent,
Attributes eagAttrs,
Supplier<Stopwatch> stopwatchFactory,
Variant variant,
@Nullable HttpConnectProxiedSocketAddress proxiedAddr,
Runnable tooManyPingsRunnable) {
this.address = Preconditions.checkNotNull(address, "address");
this.defaultAuthority = authority;
this.maxMessageSize = transportFactory.maxMessageSize;
this.initialWindowSize = transportFactory.flowControlWindow;
this.executor = Preconditions.checkNotNull(transportFactory.executor, "executor");
serializingExecutor = new SerializingExecutor(transportFactory.executor);
this.scheduler = Preconditions.checkNotNull(
transportFactory.scheduledExecutorService, "scheduledExecutorService");
// Client initiated streams are odd, server initiated ones are even. Server should not need to
// use it. We start clients at 3 to avoid conflicting with HTTP negotiation.
nextStreamId = 3;
this.socketFactory = transportFactory.socketFactory == null
? SocketFactory.getDefault() : transportFactory.socketFactory;
this.sslSocketFactory = transportFactory.sslSocketFactory;
this.hostnameVerifier = transportFactory.hostnameVerifier;
this.connectionSpec = Preconditions.checkNotNull(
transportFactory.connectionSpec, "connectionSpec");
this.stopwatchFactory = Preconditions.checkNotNull(stopwatchFactory, "stopwatchFactory");
this.variant = Preconditions.checkNotNull(variant, "variant");
this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent);
this.proxiedAddr = proxiedAddr;
this.tooManyPingsRunnable =
Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable");
this.maxInboundMetadataSize = transportFactory.maxInboundMetadataSize;
this.transportTracer = transportFactory.transportTracerFactory.create();
this.logId = InternalLogId.allocate(getClass(), address.toString());
this.attributes = Attributes.newBuilder()
.set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs).build();
this.useGetForSafeMethods = transportFactory.useGetForSafeMethods;
initTransportTracer();
}
/**
* Create a transport connected to a fake peer for test.
*/
@VisibleForTesting
OkHttpClientTransport(
OkHttpChannelBuilder.OkHttpTransportFactory transportFactory,
String userAgent,
Supplier<Stopwatch> stopwatchFactory,
Variant variant,
@Nullable Runnable connectingCallback,
SettableFuture<Void> connectedFuture,
Runnable tooManyPingsRunnable) {
this(
transportFactory,
new InetSocketAddress("127.0.0.1", 80),
"notarealauthority:80",
userAgent,
Attributes.EMPTY,
stopwatchFactory,
variant,
null,
tooManyPingsRunnable);
this.connectingCallback = connectingCallback;
this.connectedFuture = Preconditions.checkNotNull(connectedFuture, "connectedFuture");
}
// sslSocketFactory is set to null when use plaintext.
boolean isUsingPlaintext() {
return sslSocketFactory == null;
}
private void initTransportTracer() {
synchronized (lock) { // to make @GuardedBy linter happy
transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() {
@Override
public TransportTracer.FlowControlWindows read() {
synchronized (lock) {
long local = outboundFlow == null ? -1 : outboundFlow.windowUpdate(null, 0);
// connectionUnacknowledgedBytesRead is only readable by ClientFrameHandler, so we
// provide a lower bound.
long remote = (long) (initialWindowSize * DEFAULT_WINDOW_UPDATE_RATIO);
return new TransportTracer.FlowControlWindows(local, remote);
}
}
});
}
}
/**
* Enable keepalive with custom delay and timeout.
*/
void enableKeepAlive(boolean enable, long keepAliveTimeNanos,
long keepAliveTimeoutNanos, boolean keepAliveWithoutCalls) {
enableKeepAlive = enable;
this.keepAliveTimeNanos = keepAliveTimeNanos;
this.keepAliveTimeoutNanos = keepAliveTimeoutNanos;
this.keepAliveWithoutCalls = keepAliveWithoutCalls;
}
@Override
public void ping(final PingCallback callback, Executor executor) {
long data = 0;
Http2Ping p;
boolean writePing;
synchronized (lock) {
checkState(frameWriter != null);
if (stopped) {
Http2Ping.notifyFailed(callback, executor, getPingFailure());
return;
}
if (ping != null) {
// we only allow one outstanding ping at a time, so just add the callback to
// any outstanding operation
p = ping;
writePing = false;
} else {
// set outstanding operation and then write the ping after releasing lock
data = random.nextLong();
Stopwatch stopwatch = stopwatchFactory.get();
stopwatch.start();
p = ping = new Http2Ping(data, stopwatch);
writePing = true;
transportTracer.reportKeepAliveSent();
}
if (writePing) {
frameWriter.ping(false, (int) (data >>> 32), (int) data);
}
}
// If transport concurrently failed/stopped since we released the lock above, this could
// immediately invoke callback (which we shouldn't do while holding a lock)
p.addCallback(callback, executor);
}
@Override
public OkHttpClientStream newStream(
MethodDescriptor<?, ?> method, Metadata headers, CallOptions callOptions,
ClientStreamTracer[] tracers) {
Preconditions.checkNotNull(method, "method");
Preconditions.checkNotNull(headers, "headers");
StatsTraceContext statsTraceContext =
StatsTraceContext.newClientContext(tracers, getAttributes(), headers);
// FIXME: it is likely wrong to pass the transportTracer here as it'll exit the lock's scope
synchronized (lock) { // to make @GuardedBy linter happy
return new OkHttpClientStream(
method,
headers,
frameWriter,
OkHttpClientTransport.this,
outboundFlow,
lock,
maxMessageSize,
initialWindowSize,
defaultAuthority,
userAgent,
statsTraceContext,
transportTracer,
callOptions,
useGetForSafeMethods);
}
}
@GuardedBy("lock")
void streamReadyToStart(OkHttpClientStream clientStream) {
if (goAwayStatus != null) {
clientStream.transportState().transportReportStatus(
goAwayStatus, RpcProgress.MISCARRIED, true, new Metadata());
} else if (streams.size() >= maxConcurrentStreams) {
pendingStreams.add(clientStream);
setInUse(clientStream);
} else {
startStream(clientStream);
}
}
@SuppressWarnings("GuardedBy")
@GuardedBy("lock")
private void startStream(OkHttpClientStream stream) {
Preconditions.checkState(
stream.transportState().id() == OkHttpClientStream.ABSENT_ID, "StreamId already assigned");
streams.put(nextStreamId, stream);
setInUse(stream);
// TODO(b/145386688): This access should be guarded by 'stream.transportState().lock'; instead
// found: 'this.lock'
stream.transportState().start(nextStreamId);
// For unary and server streaming, there will be a data frame soon, no need to flush the header.
if ((stream.getType() != MethodType.UNARY && stream.getType() != MethodType.SERVER_STREAMING)
|| stream.useGet()) {
frameWriter.flush();
}
if (nextStreamId >= Integer.MAX_VALUE - 2) {
// Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs
// correctly.
nextStreamId = Integer.MAX_VALUE;
startGoAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR,
Status.UNAVAILABLE.withDescription("Stream ids exhausted"));
} else {
nextStreamId += 2;
}
}
/**
* Starts pending streams, returns true if at least one pending stream is started.
*/
@GuardedBy("lock")
private boolean startPendingStreams() {
boolean hasStreamStarted = false;
while (!pendingStreams.isEmpty() && streams.size() < maxConcurrentStreams) {
OkHttpClientStream stream = pendingStreams.poll();
startStream(stream);
hasStreamStarted = true;
}
return hasStreamStarted;
}
/**
* Removes given pending stream, used when a pending stream is cancelled.
*/
@GuardedBy("lock")
void removePendingStream(OkHttpClientStream pendingStream) {
pendingStreams.remove(pendingStream);
maybeClearInUse(pendingStream);
}
@Override
public Runnable start(Listener listener) {
this.listener = Preconditions.checkNotNull(listener, "listener");
if (enableKeepAlive) {
keepAliveManager = new KeepAliveManager(
new ClientKeepAlivePinger(this), scheduler, keepAliveTimeNanos, keepAliveTimeoutNanos,
keepAliveWithoutCalls);
keepAliveManager.onTransportStarted();
}
int maxQueuedControlFrames = 10000;
final AsyncSink asyncSink = AsyncSink.sink(serializingExecutor, this, maxQueuedControlFrames);
FrameWriter rawFrameWriter = asyncSink.limitControlFramesWriter(
variant.newWriter(Okio.buffer(asyncSink), true));
synchronized (lock) {
// Handle FrameWriter exceptions centrally, since there are many callers. Note that errors
// coming from rawFrameWriter are generally broken invariants/bugs, as AsyncSink does not
// propagate syscall errors through the FrameWriter. But we handle the AsyncSink failures with
// the same TransportExceptionHandler instance so it is all mixed back together.
frameWriter = new ExceptionHandlingFrameWriter(this, rawFrameWriter);
outboundFlow = new OutboundFlowController(this, frameWriter);
}
final CountDownLatch latch = new CountDownLatch(1);
// Connecting in the serializingExecutor, so that some stream operations like synStream
// will be executed after connected.
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
// This is a hack to make sure the connection preface and initial settings to be sent out
// without blocking the start. By doing this essentially prevents potential deadlock when
// network is not available during startup while another thread holding lock to send the
// initial preface.
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// Use closed source on failure so that the reader immediately shuts down.
BufferedSource source = Okio.buffer(new Source() {
@Override
public long read(Buffer sink, long byteCount) {
return -1;
}
@Override
public Timeout timeout() {
return Timeout.NONE;
}
@Override
public void close() {
}
});
Socket sock;
SSLSession sslSession = null;
try {
if (proxiedAddr == null) {
sock = socketFactory.createSocket(address.getAddress(), address.getPort());
} else {
if (proxiedAddr.getProxyAddress() instanceof InetSocketAddress) {
sock = createHttpProxySocket(
proxiedAddr.getTargetAddress(),
(InetSocketAddress) proxiedAddr.getProxyAddress(),
proxiedAddr.getUsername(),
proxiedAddr.getPassword()
);
} else {
throw Status.INTERNAL.withDescription(
"Unsupported SocketAddress implementation "
+ proxiedAddr.getProxyAddress().getClass()).asException();
}
}
if (sslSocketFactory != null) {
SSLSocket sslSocket = OkHttpTlsUpgrader.upgrade(
sslSocketFactory, hostnameVerifier, sock, getOverridenHost(), getOverridenPort(),
connectionSpec);
sslSession = sslSocket.getSession();
sock = sslSocket;
}
sock.setTcpNoDelay(true);
source = Okio.buffer(Okio.source(sock));
asyncSink.becomeConnected(Okio.sink(sock), sock);
// The return value of OkHttpTlsUpgrader.upgrade is an SSLSocket that has this info
attributes = attributes.toBuilder()
.set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, sock.getRemoteSocketAddress())
.set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, sock.getLocalSocketAddress())
.set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession)
.set(GrpcAttributes.ATTR_SECURITY_LEVEL,
sslSession == null ? SecurityLevel.NONE : SecurityLevel.PRIVACY_AND_INTEGRITY)
.build();
} catch (StatusException e) {
startGoAway(0, ErrorCode.INTERNAL_ERROR, e.getStatus());
return;
} catch (Exception e) {
onException(e);
return;
} finally {
clientFrameHandler = new ClientFrameHandler(variant.newReader(source, true));
}
synchronized (lock) {
socket = Preconditions.checkNotNull(sock, "socket");
if (sslSession != null) {
securityInfo = new InternalChannelz.Security(new InternalChannelz.Tls(sslSession));
}
}
}
});
// Schedule to send connection preface & settings before any other write.
try {
sendConnectionPrefaceAndSettings();
} finally {
latch.countDown();
}
serializingExecutor.execute(new Runnable() {
@Override
public void run() {
if (connectingCallback != null) {
connectingCallback.run();
}
// ClientFrameHandler need to be started after connectionPreface / settings, otherwise it
// may send goAway immediately.
executor.execute(clientFrameHandler);
synchronized (lock) {
maxConcurrentStreams = Integer.MAX_VALUE;
startPendingStreams();
}
if (connectedFuture != null) {
connectedFuture.set(null);
}
}
});
return null;
}
/**
* Should only be called once when the transport is first established.
*/
private void sendConnectionPrefaceAndSettings() {
synchronized (lock) {
frameWriter.connectionPreface();
Settings settings = new Settings();
OkHttpSettingsUtil.set(settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE, initialWindowSize);
frameWriter.settings(settings);
if (initialWindowSize > DEFAULT_WINDOW_SIZE) {
frameWriter.windowUpdate(
Utils.CONNECTION_STREAM_ID, initialWindowSize - DEFAULT_WINDOW_SIZE);
}
}
}
private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress,
String proxyUsername, String proxyPassword) throws StatusException {
Socket sock = null;
try {
// The proxy address may not be resolved
if (proxyAddress.getAddress() != null) {
sock = socketFactory.createSocket(proxyAddress.getAddress(), proxyAddress.getPort());
} else {
sock =
socketFactory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
}
sock.setTcpNoDelay(true);
// A socket timeout is needed because lost network connectivity while reading from the proxy,
// can cause reading from the socket to hang.
sock.setSoTimeout(proxySocketTimeout);
Source source = Okio.source(sock);
BufferedSink sink = Okio.buffer(Okio.sink(sock));
// Prepare headers and request method line
Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword);
HttpUrl url = proxyRequest.httpUrl();
String requestLine =
String.format(Locale.US, "CONNECT %s:%d HTTP/1.1", url.host(), url.port());
// Write request to socket
sink.writeUtf8(requestLine).writeUtf8("\r\n");
for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) {
sink.writeUtf8(proxyRequest.headers().name(i))
.writeUtf8(": ")
.writeUtf8(proxyRequest.headers().value(i))
.writeUtf8("\r\n");
}
sink.writeUtf8("\r\n");
// Flush buffer (flushes socket and sends request)
sink.flush();
// Read status line, check if 2xx was returned
StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source));
// Drain rest of headers
while (!readUtf8LineStrictUnbuffered(source).equals("")) {}
if (statusLine.code < 200 || statusLine.code >= 300) {
Buffer body = new Buffer();
try {
sock.shutdownOutput();
source.read(body, 1024);
} catch (IOException ex) {
body.writeUtf8("Unable to read body: " + ex.toString());
}
try {
sock.close();
} catch (IOException ignored) {
// ignored
}
String message = String.format(
Locale.US,
"Response returned from proxy was not successful (expected 2xx, got %d %s). "
+ "Response body:\n%s",
statusLine.code, statusLine.message, body.readUtf8());
throw Status.UNAVAILABLE.withDescription(message).asException();
}
// As the socket will be used for RPCs from here on, we want the socket timeout back to zero.
sock.setSoTimeout(0);
return sock;
} catch (IOException e) {
if (sock != null) {
GrpcUtil.closeQuietly(sock);
}
throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e)
.asException();
}
}
private Request createHttpProxyRequest(InetSocketAddress address, String proxyUsername,
String proxyPassword) {
HttpUrl tunnelUrl = new HttpUrl.Builder()
.scheme("https")
.host(address.getHostName())
.port(address.getPort())
.build();
Request.Builder request = new Request.Builder()
.url(tunnelUrl)
.header("Host", tunnelUrl.host() + ":" + tunnelUrl.port())
.header("User-Agent", userAgent);
// If we have proxy credentials, set them right away
if (proxyUsername != null && proxyPassword != null) {
request.header("Proxy-Authorization", Credentials.basic(proxyUsername, proxyPassword));
}
return request.build();
}
private static String readUtf8LineStrictUnbuffered(Source source) throws IOException {
Buffer buffer = new Buffer();
while (true) {
if (source.read(buffer, 1) == -1) {
throw new EOFException("\\n not found: " + buffer.readByteString().hex());
}
if (buffer.getByte(buffer.size() - 1) == '\n') {
return buffer.readUtf8LineStrict();
}
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("logId", logId.getId())
.add("address", address)
.toString();
}
@Override
public InternalLogId getLogId() {
return logId;
}
/**
* Gets the overridden authority hostname. If the authority is overridden to be an invalid
* authority, uri.getHost() will (rightly) return null, since the authority is no longer
* an actual service. This method overrides the behavior for practical reasons. For example,
* if an authority is in the form "invalid_authority" (note the "_"), rather than return null,
* we return the input. This is because the return value, in conjunction with getOverridenPort,
* are used by the SSL library to reconstruct the actual authority. It /already/ has a
* connection to the port, independent of this function.
*
* <p>Note: if the defaultAuthority has a port number in it and is also bad, this code will do
* the wrong thing. An example wrong behavior would be "invalid_host:443". Registry based
* authorities do not have ports, so this is even more wrong than before. Sorry.
*/
@VisibleForTesting
String getOverridenHost() {
URI uri = GrpcUtil.authorityToUri(defaultAuthority);
if (uri.getHost() != null) {
return uri.getHost();
}
return defaultAuthority;
}
@VisibleForTesting
int getOverridenPort() {
URI uri = GrpcUtil.authorityToUri(defaultAuthority);
if (uri.getPort() != -1) {
return uri.getPort();
}
return address.getPort();
}
@Override
public void shutdown(Status reason) {
synchronized (lock) {
if (goAwayStatus != null) {
return;
}
goAwayStatus = reason;
listener.transportShutdown(goAwayStatus);
stopIfNecessary();
}
}
@Override
public void shutdownNow(Status reason) {
shutdown(reason);
synchronized (lock) {
Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, OkHttpClientStream> entry = it.next();
it.remove();
entry.getValue().transportState().transportReportStatus(reason, false, new Metadata());
maybeClearInUse(entry.getValue());
}
for (OkHttpClientStream stream : pendingStreams) {
// in cases such as the connection fails to ACK keep-alive, pending streams should have a
// chance to retry and be routed to another connection.
stream.transportState().transportReportStatus(
reason, RpcProgress.MISCARRIED, true, new Metadata());
maybeClearInUse(stream);
}
pendingStreams.clear();
stopIfNecessary();
}
}
@Override
public Attributes getAttributes() {
return attributes;
}
/**
* Gets all active streams as an array.
*/
@Override
public OutboundFlowController.StreamState[] getActiveStreams() {
synchronized (lock) {
OutboundFlowController.StreamState[] flowStreams =
new OutboundFlowController.StreamState[streams.size()];
int i = 0;
for (OkHttpClientStream stream : streams.values()) {
flowStreams[i++] = stream.transportState().getOutboundFlowState();
}
return flowStreams;
}
}
@VisibleForTesting
ClientFrameHandler getHandler() {
return clientFrameHandler;
}
@VisibleForTesting
SocketFactory getSocketFactory() {
return socketFactory;
}
@VisibleForTesting
int getPendingStreamSize() {
synchronized (lock) {
return pendingStreams.size();
}
}
@VisibleForTesting
void setNextStreamId(int nextStreamId) {
synchronized (lock) {
this.nextStreamId = nextStreamId;
}
}
/**
* Finish all active streams due to an IOException, then close the transport.
*/
@Override
public void onException(Throwable failureCause) {
Preconditions.checkNotNull(failureCause, "failureCause");
Status status = Status.UNAVAILABLE.withCause(failureCause);
startGoAway(0, ErrorCode.INTERNAL_ERROR, status);
}
/**
* Send GOAWAY to the server, then finish all active streams and close the transport.
*/
private void onError(ErrorCode errorCode, String moreDetail) {
startGoAway(0, errorCode, toGrpcStatus(errorCode).augmentDescription(moreDetail));
}
private void startGoAway(int lastKnownStreamId, ErrorCode errorCode, Status status) {
synchronized (lock) {
if (goAwayStatus == null) {
goAwayStatus = status;
listener.transportShutdown(status);
}
if (errorCode != null && !goAwaySent) {
// Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated
// streams. The GOAWAY is part of graceful shutdown.
goAwaySent = true;
frameWriter.goAway(0, errorCode, new byte[0]);
}
Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, OkHttpClientStream> entry = it.next();
if (entry.getKey() > lastKnownStreamId) {
it.remove();
entry.getValue().transportState().transportReportStatus(
status, RpcProgress.REFUSED, false, new Metadata());
maybeClearInUse(entry.getValue());
}
}
for (OkHttpClientStream stream : pendingStreams) {
stream.transportState().transportReportStatus(
status, RpcProgress.MISCARRIED, true, new Metadata());
maybeClearInUse(stream);
}
pendingStreams.clear();
stopIfNecessary();
}
}
/**
* Called when a stream is closed, we do things like:
* <ul>
* <li>Removing the stream from the map.
* <li>Optionally reporting the status.
* <li>Starting pending streams if we can.
* <li>Stopping the transport if this is the last live stream under a go-away status.
* </ul>
*
* @param streamId the Id of the stream.
* @param status the final status of this stream, null means no need to report.
* @param stopDelivery interrupt queued messages in the deframer
* @param errorCode reset the stream with this ErrorCode if not null.
* @param trailers the trailers received if not null
*/
void finishStream(
int streamId,
@Nullable Status status,
RpcProgress rpcProgress,
boolean stopDelivery,
@Nullable ErrorCode errorCode,
@Nullable Metadata trailers) {
synchronized (lock) {
OkHttpClientStream stream = streams.remove(streamId);
if (stream != null) {
if (errorCode != null) {
frameWriter.rstStream(streamId, ErrorCode.CANCEL);
}
if (status != null) {
stream
.transportState()
.transportReportStatus(
status,
rpcProgress,
stopDelivery,
trailers != null ? trailers : new Metadata());
}
if (!startPendingStreams()) {
stopIfNecessary();
maybeClearInUse(stream);
}
}
}
}
/**
* When the transport is in goAway state, we should stop it once all active streams finish.
*/
@GuardedBy("lock")
private void stopIfNecessary() {
if (!(goAwayStatus != null && streams.isEmpty() && pendingStreams.isEmpty())) {
return;
}
if (stopped) {
return;
}
stopped = true;
if (keepAliveManager != null) {
keepAliveManager.onTransportTermination();
}
if (ping != null) {
ping.failed(getPingFailure());
ping = null;
}
if (!goAwaySent) {
// Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated
// streams. The GOAWAY is part of graceful shutdown.
goAwaySent = true;
frameWriter.goAway(0, ErrorCode.NO_ERROR, new byte[0]);
}
// We will close the underlying socket in the writing thread to break out the reader
// thread, which will close the frameReader and notify the listener.
frameWriter.close();
}
@GuardedBy("lock")
private void maybeClearInUse(OkHttpClientStream stream) {
if (hasStream) {
if (pendingStreams.isEmpty() && streams.isEmpty()) {
hasStream = false;
if (keepAliveManager != null) {