You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

dialoptions.go 19 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. *
  3. * Copyright 2018 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package grpc
  19. import (
  20. "context"
  21. "fmt"
  22. "net"
  23. "time"
  24. "google.golang.org/grpc/balancer"
  25. "google.golang.org/grpc/credentials"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/internal"
  28. "google.golang.org/grpc/internal/backoff"
  29. "google.golang.org/grpc/internal/envconfig"
  30. "google.golang.org/grpc/internal/transport"
  31. "google.golang.org/grpc/keepalive"
  32. "google.golang.org/grpc/resolver"
  33. "google.golang.org/grpc/stats"
  34. )
  35. // dialOptions configure a Dial call. dialOptions are set by the DialOption
  36. // values passed to Dial.
  37. type dialOptions struct {
  38. unaryInt UnaryClientInterceptor
  39. streamInt StreamClientInterceptor
  40. chainUnaryInts []UnaryClientInterceptor
  41. chainStreamInts []StreamClientInterceptor
  42. cp Compressor
  43. dc Decompressor
  44. bs backoff.Strategy
  45. block bool
  46. insecure bool
  47. timeout time.Duration
  48. scChan <-chan ServiceConfig
  49. authority string
  50. copts transport.ConnectOptions
  51. callOptions []CallOption
  52. // This is used by v1 balancer dial option WithBalancer to support v1
  53. // balancer, and also by WithBalancerName dial option.
  54. balancerBuilder balancer.Builder
  55. // This is to support grpclb.
  56. resolverBuilder resolver.Builder
  57. reqHandshake envconfig.RequireHandshakeSetting
  58. channelzParentID int64
  59. disableServiceConfig bool
  60. disableRetry bool
  61. disableHealthCheck bool
  62. healthCheckFunc internal.HealthChecker
  63. minConnectTimeout func() time.Duration
  64. defaultServiceConfig *ServiceConfig // defaultServiceConfig is parsed from defaultServiceConfigRawJSON.
  65. defaultServiceConfigRawJSON *string
  66. }
  67. // DialOption configures how we set up the connection.
  68. type DialOption interface {
  69. apply(*dialOptions)
  70. }
  71. // EmptyDialOption does not alter the dial configuration. It can be embedded in
  72. // another structure to build custom dial options.
  73. //
  74. // This API is EXPERIMENTAL.
  75. type EmptyDialOption struct{}
  76. func (EmptyDialOption) apply(*dialOptions) {}
  77. // funcDialOption wraps a function that modifies dialOptions into an
  78. // implementation of the DialOption interface.
  79. type funcDialOption struct {
  80. f func(*dialOptions)
  81. }
  82. func (fdo *funcDialOption) apply(do *dialOptions) {
  83. fdo.f(do)
  84. }
  85. func newFuncDialOption(f func(*dialOptions)) *funcDialOption {
  86. return &funcDialOption{
  87. f: f,
  88. }
  89. }
  90. // WithWaitForHandshake blocks until the initial settings frame is received from
  91. // the server before assigning RPCs to the connection.
  92. //
  93. // Deprecated: this is the default behavior, and this option will be removed
  94. // after the 1.18 release.
  95. func WithWaitForHandshake() DialOption {
  96. return newFuncDialOption(func(o *dialOptions) {
  97. o.reqHandshake = envconfig.RequireHandshakeOn
  98. })
  99. }
  100. // WithWriteBufferSize determines how much data can be batched before doing a
  101. // write on the wire. The corresponding memory allocation for this buffer will
  102. // be twice the size to keep syscalls low. The default value for this buffer is
  103. // 32KB.
  104. //
  105. // Zero will disable the write buffer such that each write will be on underlying
  106. // connection. Note: A Send call may not directly translate to a write.
  107. func WithWriteBufferSize(s int) DialOption {
  108. return newFuncDialOption(func(o *dialOptions) {
  109. o.copts.WriteBufferSize = s
  110. })
  111. }
  112. // WithReadBufferSize lets you set the size of read buffer, this determines how
  113. // much data can be read at most for each read syscall.
  114. //
  115. // The default value for this buffer is 32KB. Zero will disable read buffer for
  116. // a connection so data framer can access the underlying conn directly.
  117. func WithReadBufferSize(s int) DialOption {
  118. return newFuncDialOption(func(o *dialOptions) {
  119. o.copts.ReadBufferSize = s
  120. })
  121. }
  122. // WithInitialWindowSize returns a DialOption which sets the value for initial
  123. // window size on a stream. The lower bound for window size is 64K and any value
  124. // smaller than that will be ignored.
  125. func WithInitialWindowSize(s int32) DialOption {
  126. return newFuncDialOption(func(o *dialOptions) {
  127. o.copts.InitialWindowSize = s
  128. })
  129. }
  130. // WithInitialConnWindowSize returns a DialOption which sets the value for
  131. // initial window size on a connection. The lower bound for window size is 64K
  132. // and any value smaller than that will be ignored.
  133. func WithInitialConnWindowSize(s int32) DialOption {
  134. return newFuncDialOption(func(o *dialOptions) {
  135. o.copts.InitialConnWindowSize = s
  136. })
  137. }
  138. // WithMaxMsgSize returns a DialOption which sets the maximum message size the
  139. // client can receive.
  140. //
  141. // Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead.
  142. func WithMaxMsgSize(s int) DialOption {
  143. return WithDefaultCallOptions(MaxCallRecvMsgSize(s))
  144. }
  145. // WithDefaultCallOptions returns a DialOption which sets the default
  146. // CallOptions for calls over the connection.
  147. func WithDefaultCallOptions(cos ...CallOption) DialOption {
  148. return newFuncDialOption(func(o *dialOptions) {
  149. o.callOptions = append(o.callOptions, cos...)
  150. })
  151. }
  152. // WithCodec returns a DialOption which sets a codec for message marshaling and
  153. // unmarshaling.
  154. //
  155. // Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead.
  156. func WithCodec(c Codec) DialOption {
  157. return WithDefaultCallOptions(CallCustomCodec(c))
  158. }
  159. // WithCompressor returns a DialOption which sets a Compressor to use for
  160. // message compression. It has lower priority than the compressor set by the
  161. // UseCompressor CallOption.
  162. //
  163. // Deprecated: use UseCompressor instead.
  164. func WithCompressor(cp Compressor) DialOption {
  165. return newFuncDialOption(func(o *dialOptions) {
  166. o.cp = cp
  167. })
  168. }
  169. // WithDecompressor returns a DialOption which sets a Decompressor to use for
  170. // incoming message decompression. If incoming response messages are encoded
  171. // using the decompressor's Type(), it will be used. Otherwise, the message
  172. // encoding will be used to look up the compressor registered via
  173. // encoding.RegisterCompressor, which will then be used to decompress the
  174. // message. If no compressor is registered for the encoding, an Unimplemented
  175. // status error will be returned.
  176. //
  177. // Deprecated: use encoding.RegisterCompressor instead.
  178. func WithDecompressor(dc Decompressor) DialOption {
  179. return newFuncDialOption(func(o *dialOptions) {
  180. o.dc = dc
  181. })
  182. }
  183. // WithBalancer returns a DialOption which sets a load balancer with the v1 API.
  184. // Name resolver will be ignored if this DialOption is specified.
  185. //
  186. // Deprecated: use the new balancer APIs in balancer package and
  187. // WithBalancerName.
  188. func WithBalancer(b Balancer) DialOption {
  189. return newFuncDialOption(func(o *dialOptions) {
  190. o.balancerBuilder = &balancerWrapperBuilder{
  191. b: b,
  192. }
  193. })
  194. }
  195. // WithBalancerName sets the balancer that the ClientConn will be initialized
  196. // with. Balancer registered with balancerName will be used. This function
  197. // panics if no balancer was registered by balancerName.
  198. //
  199. // The balancer cannot be overridden by balancer option specified by service
  200. // config.
  201. //
  202. // This is an EXPERIMENTAL API.
  203. func WithBalancerName(balancerName string) DialOption {
  204. builder := balancer.Get(balancerName)
  205. if builder == nil {
  206. panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName))
  207. }
  208. return newFuncDialOption(func(o *dialOptions) {
  209. o.balancerBuilder = builder
  210. })
  211. }
  212. // withResolverBuilder is only for grpclb.
  213. func withResolverBuilder(b resolver.Builder) DialOption {
  214. return newFuncDialOption(func(o *dialOptions) {
  215. o.resolverBuilder = b
  216. })
  217. }
  218. // WithServiceConfig returns a DialOption which has a channel to read the
  219. // service configuration.
  220. //
  221. // Deprecated: service config should be received through name resolver, as
  222. // specified here.
  223. // https://github.com/grpc/grpc/blob/master/doc/service_config.md
  224. func WithServiceConfig(c <-chan ServiceConfig) DialOption {
  225. return newFuncDialOption(func(o *dialOptions) {
  226. o.scChan = c
  227. })
  228. }
  229. // WithBackoffMaxDelay configures the dialer to use the provided maximum delay
  230. // when backing off after failed connection attempts.
  231. func WithBackoffMaxDelay(md time.Duration) DialOption {
  232. return WithBackoffConfig(BackoffConfig{MaxDelay: md})
  233. }
  234. // WithBackoffConfig configures the dialer to use the provided backoff
  235. // parameters after connection failures.
  236. //
  237. // Use WithBackoffMaxDelay until more parameters on BackoffConfig are opened up
  238. // for use.
  239. func WithBackoffConfig(b BackoffConfig) DialOption {
  240. return withBackoff(backoff.Exponential{
  241. MaxDelay: b.MaxDelay,
  242. })
  243. }
  244. // withBackoff sets the backoff strategy used for connectRetryNum after a failed
  245. // connection attempt.
  246. //
  247. // This can be exported if arbitrary backoff strategies are allowed by gRPC.
  248. func withBackoff(bs backoff.Strategy) DialOption {
  249. return newFuncDialOption(func(o *dialOptions) {
  250. o.bs = bs
  251. })
  252. }
  253. // WithBlock returns a DialOption which makes caller of Dial blocks until the
  254. // underlying connection is up. Without this, Dial returns immediately and
  255. // connecting the server happens in background.
  256. func WithBlock() DialOption {
  257. return newFuncDialOption(func(o *dialOptions) {
  258. o.block = true
  259. })
  260. }
  261. // WithInsecure returns a DialOption which disables transport security for this
  262. // ClientConn. Note that transport security is required unless WithInsecure is
  263. // set.
  264. func WithInsecure() DialOption {
  265. return newFuncDialOption(func(o *dialOptions) {
  266. o.insecure = true
  267. })
  268. }
  269. // WithTransportCredentials returns a DialOption which configures a connection
  270. // level security credentials (e.g., TLS/SSL). This should not be used together
  271. // with WithCredentialsBundle.
  272. func WithTransportCredentials(creds credentials.TransportCredentials) DialOption {
  273. return newFuncDialOption(func(o *dialOptions) {
  274. o.copts.TransportCredentials = creds
  275. })
  276. }
  277. // WithPerRPCCredentials returns a DialOption which sets credentials and places
  278. // auth state on each outbound RPC.
  279. func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption {
  280. return newFuncDialOption(func(o *dialOptions) {
  281. o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds)
  282. })
  283. }
  284. // WithCredentialsBundle returns a DialOption to set a credentials bundle for
  285. // the ClientConn.WithCreds. This should not be used together with
  286. // WithTransportCredentials.
  287. //
  288. // This API is experimental.
  289. func WithCredentialsBundle(b credentials.Bundle) DialOption {
  290. return newFuncDialOption(func(o *dialOptions) {
  291. o.copts.CredsBundle = b
  292. })
  293. }
  294. // WithTimeout returns a DialOption that configures a timeout for dialing a
  295. // ClientConn initially. This is valid if and only if WithBlock() is present.
  296. //
  297. // Deprecated: use DialContext and context.WithTimeout instead.
  298. func WithTimeout(d time.Duration) DialOption {
  299. return newFuncDialOption(func(o *dialOptions) {
  300. o.timeout = d
  301. })
  302. }
  303. // WithContextDialer returns a DialOption that sets a dialer to create
  304. // connections. If FailOnNonTempDialError() is set to true, and an error is
  305. // returned by f, gRPC checks the error's Temporary() method to decide if it
  306. // should try to reconnect to the network address.
  307. func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption {
  308. return newFuncDialOption(func(o *dialOptions) {
  309. o.copts.Dialer = f
  310. })
  311. }
  312. func init() {
  313. internal.WithResolverBuilder = withResolverBuilder
  314. internal.WithHealthCheckFunc = withHealthCheckFunc
  315. }
  316. // WithDialer returns a DialOption that specifies a function to use for dialing
  317. // network addresses. If FailOnNonTempDialError() is set to true, and an error
  318. // is returned by f, gRPC checks the error's Temporary() method to decide if it
  319. // should try to reconnect to the network address.
  320. //
  321. // Deprecated: use WithContextDialer instead
  322. func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption {
  323. return WithContextDialer(
  324. func(ctx context.Context, addr string) (net.Conn, error) {
  325. if deadline, ok := ctx.Deadline(); ok {
  326. return f(addr, time.Until(deadline))
  327. }
  328. return f(addr, 0)
  329. })
  330. }
  331. // WithStatsHandler returns a DialOption that specifies the stats handler for
  332. // all the RPCs and underlying network connections in this ClientConn.
  333. func WithStatsHandler(h stats.Handler) DialOption {
  334. return newFuncDialOption(func(o *dialOptions) {
  335. o.copts.StatsHandler = h
  336. })
  337. }
  338. // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on
  339. // non-temporary dial errors. If f is true, and dialer returns a non-temporary
  340. // error, gRPC will fail the connection to the network address and won't try to
  341. // reconnect. The default value of FailOnNonTempDialError is false.
  342. //
  343. // FailOnNonTempDialError only affects the initial dial, and does not do
  344. // anything useful unless you are also using WithBlock().
  345. //
  346. // This is an EXPERIMENTAL API.
  347. func FailOnNonTempDialError(f bool) DialOption {
  348. return newFuncDialOption(func(o *dialOptions) {
  349. o.copts.FailOnNonTempDialError = f
  350. })
  351. }
  352. // WithUserAgent returns a DialOption that specifies a user agent string for all
  353. // the RPCs.
  354. func WithUserAgent(s string) DialOption {
  355. return newFuncDialOption(func(o *dialOptions) {
  356. o.copts.UserAgent = s
  357. })
  358. }
  359. // WithKeepaliveParams returns a DialOption that specifies keepalive parameters
  360. // for the client transport.
  361. func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption {
  362. if kp.Time < internal.KeepaliveMinPingTime {
  363. grpclog.Warningf("Adjusting keepalive ping interval to minimum period of %v", internal.KeepaliveMinPingTime)
  364. kp.Time = internal.KeepaliveMinPingTime
  365. }
  366. return newFuncDialOption(func(o *dialOptions) {
  367. o.copts.KeepaliveParams = kp
  368. })
  369. }
  370. // WithUnaryInterceptor returns a DialOption that specifies the interceptor for
  371. // unary RPCs.
  372. func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption {
  373. return newFuncDialOption(func(o *dialOptions) {
  374. o.unaryInt = f
  375. })
  376. }
  377. // WithChainUnaryInterceptor returns a DialOption that specifies the chained
  378. // interceptor for unary RPCs. The first interceptor will be the outer most,
  379. // while the last interceptor will be the inner most wrapper around the real call.
  380. // All interceptors added by this method will be chained, and the interceptor
  381. // defined by WithUnaryInterceptor will always be prepended to the chain.
  382. func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption {
  383. return newFuncDialOption(func(o *dialOptions) {
  384. o.chainUnaryInts = append(o.chainUnaryInts, interceptors...)
  385. })
  386. }
  387. // WithStreamInterceptor returns a DialOption that specifies the interceptor for
  388. // streaming RPCs.
  389. func WithStreamInterceptor(f StreamClientInterceptor) DialOption {
  390. return newFuncDialOption(func(o *dialOptions) {
  391. o.streamInt = f
  392. })
  393. }
  394. // WithChainStreamInterceptor returns a DialOption that specifies the chained
  395. // interceptor for unary RPCs. The first interceptor will be the outer most,
  396. // while the last interceptor will be the inner most wrapper around the real call.
  397. // All interceptors added by this method will be chained, and the interceptor
  398. // defined by WithStreamInterceptor will always be prepended to the chain.
  399. func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption {
  400. return newFuncDialOption(func(o *dialOptions) {
  401. o.chainStreamInts = append(o.chainStreamInts, interceptors...)
  402. })
  403. }
  404. // WithAuthority returns a DialOption that specifies the value to be used as the
  405. // :authority pseudo-header. This value only works with WithInsecure and has no
  406. // effect if TransportCredentials are present.
  407. func WithAuthority(a string) DialOption {
  408. return newFuncDialOption(func(o *dialOptions) {
  409. o.authority = a
  410. })
  411. }
  412. // WithChannelzParentID returns a DialOption that specifies the channelz ID of
  413. // current ClientConn's parent. This function is used in nested channel creation
  414. // (e.g. grpclb dial).
  415. func WithChannelzParentID(id int64) DialOption {
  416. return newFuncDialOption(func(o *dialOptions) {
  417. o.channelzParentID = id
  418. })
  419. }
  420. // WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any
  421. // service config provided by the resolver and provides a hint to the resolver
  422. // to not fetch service configs.
  423. //
  424. // Note that this dial option only disables service config from resolver. If
  425. // default service config is provided, gRPC will use the default service config.
  426. func WithDisableServiceConfig() DialOption {
  427. return newFuncDialOption(func(o *dialOptions) {
  428. o.disableServiceConfig = true
  429. })
  430. }
  431. // WithDefaultServiceConfig returns a DialOption that configures the default
  432. // service config, which will be used in cases where:
  433. // 1. WithDisableServiceConfig is called.
  434. // 2. Resolver does not return service config or if the resolver gets and invalid config.
  435. //
  436. // This API is EXPERIMENTAL.
  437. func WithDefaultServiceConfig(s string) DialOption {
  438. return newFuncDialOption(func(o *dialOptions) {
  439. o.defaultServiceConfigRawJSON = &s
  440. })
  441. }
  442. // WithDisableRetry returns a DialOption that disables retries, even if the
  443. // service config enables them. This does not impact transparent retries, which
  444. // will happen automatically if no data is written to the wire or if the RPC is
  445. // unprocessed by the remote server.
  446. //
  447. // Retry support is currently disabled by default, but will be enabled by
  448. // default in the future. Until then, it may be enabled by setting the
  449. // environment variable "GRPC_GO_RETRY" to "on".
  450. //
  451. // This API is EXPERIMENTAL.
  452. func WithDisableRetry() DialOption {
  453. return newFuncDialOption(func(o *dialOptions) {
  454. o.disableRetry = true
  455. })
  456. }
  457. // WithMaxHeaderListSize returns a DialOption that specifies the maximum
  458. // (uncompressed) size of header list that the client is prepared to accept.
  459. func WithMaxHeaderListSize(s uint32) DialOption {
  460. return newFuncDialOption(func(o *dialOptions) {
  461. o.copts.MaxHeaderListSize = &s
  462. })
  463. }
  464. // WithDisableHealthCheck disables the LB channel health checking for all
  465. // SubConns of this ClientConn.
  466. //
  467. // This API is EXPERIMENTAL.
  468. func WithDisableHealthCheck() DialOption {
  469. return newFuncDialOption(func(o *dialOptions) {
  470. o.disableHealthCheck = true
  471. })
  472. }
  473. // withHealthCheckFunc replaces the default health check function with the
  474. // provided one. It makes tests easier to change the health check function.
  475. //
  476. // For testing purpose only.
  477. func withHealthCheckFunc(f internal.HealthChecker) DialOption {
  478. return newFuncDialOption(func(o *dialOptions) {
  479. o.healthCheckFunc = f
  480. })
  481. }
  482. func defaultDialOptions() dialOptions {
  483. return dialOptions{
  484. disableRetry: !envconfig.Retry,
  485. reqHandshake: envconfig.RequireHandshake,
  486. healthCheckFunc: internal.HealthCheckFunc,
  487. copts: transport.ConnectOptions{
  488. WriteBufferSize: defaultWriteBufSize,
  489. ReadBufferSize: defaultReadBufSize,
  490. },
  491. }
  492. }
  493. // withGetMinConnectDeadline specifies the function that clientconn uses to
  494. // get minConnectDeadline. This can be used to make connection attempts happen
  495. // faster/slower.
  496. //
  497. // For testing purpose only.
  498. func withMinConnectDeadline(f func() time.Duration) DialOption {
  499. return newFuncDialOption(func(o *dialOptions) {
  500. o.minConnectTimeout = f
  501. })
  502. }