dialoptions.go 18 KB

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