-
Notifications
You must be signed in to change notification settings - Fork 16
/
NettyClientUtils.scala
221 lines (193 loc) · 7.94 KB
/
NettyClientUtils.scala
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/
/*
* Copyright (C) 2009-2021 Lightbend Inc. <https://www.lightbend.com>
*/
package org.apache.pekko.grpc.internal
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import org.apache.pekko
import pekko.{ Done, NotUsed }
import pekko.annotation.InternalApi
import pekko.event.LoggingAdapter
import pekko.grpc.{ GrpcClientSettings, GrpcResponseMetadata, GrpcSingleResponse }
import pekko.stream.scaladsl.{ Flow, Keep, Source }
import io.grpc.{ CallOptions, MethodDescriptor }
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts
import io.grpc.netty.shaded.io.grpc.netty.NegotiationType
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder
import io.grpc.netty.shaded.io.netty.handler.ssl.{ SslContext, SslContextBuilder }
import scala.annotation.nowarn
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.{ ExecutionContext, Future, Promise }
import scala.util.{ Failure, Success }
/**
* INTERNAL API
*/
@InternalApi
object NettyClientUtils {
/**
* INTERNAL API
*/
@InternalApi
def createChannel(settings: GrpcClientSettings, log: LoggingAdapter)(
implicit ec: ExecutionContext): InternalChannel = {
@nowarn("cat=deprecation")
var builder =
NettyChannelBuilder
// Not sure why netty wants to be able to shoe-horn the target into a URI... but ok,
// we follow their lead and encode the service name as the 'authority' of the URI.
.forTarget("//" + settings.serviceName)
.flowControlWindow(NettyChannelBuilder.DEFAULT_FLOW_CONTROL_WINDOW)
// TODO avoid nameResolverFactory #1092, then 'nowarn' can be removed above
.nameResolverFactory(
new PekkoDiscoveryNameResolverProvider(
settings.serviceDiscovery,
settings.defaultPort,
settings.serviceName,
settings.servicePortName,
settings.serviceProtocol,
settings.resolveTimeout))
if (!settings.useTls)
builder = builder.usePlaintext()
else {
builder = builder.negotiationType(NegotiationType.TLS)
builder = settings.sslContext match {
case Some(sslContext) =>
builder.sslContext(createNettySslContext(sslContext))
case None =>
(settings.trustManager, settings.sslProvider) match {
case (None, None) =>
builder
case (tm, provider) =>
val context = provider match {
case None =>
GrpcSslContexts.configure(SslContextBuilder.forClient())
case Some(sslProvider) =>
GrpcSslContexts.configure(SslContextBuilder.forClient(), sslProvider)
}
builder.sslContext((tm match {
case None => context
case Some(trustManager) => context.trustManager(trustManager)
}).build())
}
}
}
builder = settings.loadBalancingPolicy.map(builder.defaultLoadBalancingPolicy(_)).getOrElse(builder)
builder = settings.overrideAuthority.map(builder.overrideAuthority(_)).getOrElse(builder)
builder = settings.userAgent.map(builder.userAgent(_)).getOrElse(builder)
builder = settings.channelBuilderOverrides(builder)
val connectionAttempts = settings.loadBalancingPolicy match {
case None | Some("pick_first") => settings.connectionAttempts
case _ =>
// When loadbalancing we cannot count the individual attempts, so
// the only options are '1' ('don't retry') or 'retry indefinitely'
settings.connectionAttempts.flatMap {
case 1 => Some(1)
case _ => None
}
}
val channel = builder.build()
val channelReadyPromise = Promise[Unit]()
val channelClosedPromise = Promise[Done]()
ChannelUtils.monitorChannel(channelReadyPromise, channelClosedPromise, channel, connectionAttempts, log)
channelReadyPromise.future.onComplete {
case Success(()) =>
// OK!
case Failure(e) =>
// shutdown is idempotent in ManagedChannelImpl
channel.shutdown()
channelClosedPromise.tryFailure(e)
}
new InternalChannel {
override def shutdown() = channel.shutdown()
override def done = channelClosedPromise.future
override def invoke[I, O](
request: I,
headers: MetadataImpl,
descriptor: MethodDescriptor[I, O],
options: CallOptions): Future[O] = {
val listener = new UnaryCallAdapter[O]
val call = channel.newCall(descriptor, callOptionsWithDeadline(options, settings))
call.start(listener, headers.toGoogleGrpcMetadata())
call.sendMessage(request)
call.halfClose()
call.request(2)
listener.future
}
override def invokeWithMetadata[I, O](
request: I,
headers: MetadataImpl,
descriptor: MethodDescriptor[I, O],
options: CallOptions): Future[GrpcSingleResponse[O]] = {
val listener = new UnaryCallWithMetadataAdapter[O]
val call = channel.newCall(descriptor, callOptionsWithDeadline(options, settings))
call.start(listener, headers.toGoogleGrpcMetadata())
call.sendMessage(request)
call.halfClose()
call.request(2)
listener.future
}
override def invokeWithMetadata[I, O](
source: Source[I, NotUsed],
headers: MetadataImpl,
descriptor: MethodDescriptor[I, O],
streamingResponse: Boolean,
options: CallOptions) = {
val flow =
createFlow(headers, descriptor, streamingResponse, callOptionsWithDeadline(options, settings))
source.viaMat(flow)(Keep.right)
}
// TODO can't you derive the method name from the descriptor?
private def createFlow[I, O](
headers: MetadataImpl,
descriptor: MethodDescriptor[I, O],
streamingResponse: Boolean,
options: CallOptions): Flow[I, O, Future[GrpcResponseMetadata]] =
Flow.fromGraph(new PekkoNettyGrpcClientGraphStage(descriptor, channel, options, streamingResponse, headers))
}
}
/**
* INTERNAL API
*
* Given a Java [[SSLContext]], create a Netty [[SslContext]] that can be used to build
* a Netty HTTP/2 channel.
*/
@InternalApi
private def createNettySslContext(javaSslContext: SSLContext): SslContext = {
import io.grpc.netty.shaded.io.netty.handler.ssl.{ JdkSslContext, SslProvider }
import java.lang.reflect.Field
// This is a hack for situations where the SSLContext is given.
// This approach forces using SslProvider.JDK, which is known not to work
// on JDK 1.8.0_252
// Create a Netty JdkSslContext object with all the correct ciphers, protocol settings, etc initialized.
val nettySslContext: JdkSslContext =
GrpcSslContexts.configure(GrpcSslContexts.forClient, SslProvider.JDK).build.asInstanceOf[JdkSslContext]
// Patch the SSLContext value inside the JdkSslContext object
val nettySslContextField: Field = classOf[JdkSslContext].getDeclaredField("sslContext")
nettySslContextField.setAccessible(true)
nettySslContextField.set(nettySslContext, javaSslContext)
nettySslContext
}
/**
* INTERNAL API
*/
@InternalApi def callOptions(settings: GrpcClientSettings): CallOptions =
settings.callCredentials.map(CallOptions.DEFAULT.withCallCredentials).getOrElse(CallOptions.DEFAULT)
/**
* INTERNAL API
*/
@InternalApi private[pekko] def callOptionsWithDeadline(
defaultOptions: CallOptions,
settings: GrpcClientSettings): CallOptions =
settings.deadline match {
case d: FiniteDuration => defaultOptions.withDeadlineAfter(d.toMillis, TimeUnit.MILLISECONDS)
case _ => defaultOptions
}
}