clientconn.go 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888
  1. /*
  2. *
  3. * Copyright 2014 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. "errors"
  22. "fmt"
  23. "math"
  24. "net/url"
  25. "strings"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "google.golang.org/grpc/balancer"
  30. "google.golang.org/grpc/balancer/base"
  31. "google.golang.org/grpc/codes"
  32. "google.golang.org/grpc/connectivity"
  33. "google.golang.org/grpc/internal"
  34. "google.golang.org/grpc/internal/channelz"
  35. "google.golang.org/grpc/internal/grpcsync"
  36. "google.golang.org/grpc/internal/idle"
  37. "google.golang.org/grpc/internal/pretty"
  38. iresolver "google.golang.org/grpc/internal/resolver"
  39. "google.golang.org/grpc/internal/transport"
  40. "google.golang.org/grpc/keepalive"
  41. "google.golang.org/grpc/resolver"
  42. "google.golang.org/grpc/serviceconfig"
  43. "google.golang.org/grpc/status"
  44. _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin.
  45. _ "google.golang.org/grpc/internal/resolver/passthrough" // To register passthrough resolver.
  46. _ "google.golang.org/grpc/internal/resolver/unix" // To register unix resolver.
  47. _ "google.golang.org/grpc/resolver/dns" // To register dns resolver.
  48. )
  49. const (
  50. // minimum time to give a connection to complete
  51. minConnectTimeout = 20 * time.Second
  52. )
  53. var (
  54. // ErrClientConnClosing indicates that the operation is illegal because
  55. // the ClientConn is closing.
  56. //
  57. // Deprecated: this error should not be relied upon by users; use the status
  58. // code of Canceled instead.
  59. ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing")
  60. // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs.
  61. errConnDrain = errors.New("grpc: the connection is drained")
  62. // errConnClosing indicates that the connection is closing.
  63. errConnClosing = errors.New("grpc: the connection is closing")
  64. // errConnIdling indicates the the connection is being closed as the channel
  65. // is moving to an idle mode due to inactivity.
  66. errConnIdling = errors.New("grpc: the connection is closing due to channel idleness")
  67. // invalidDefaultServiceConfigErrPrefix is used to prefix the json parsing error for the default
  68. // service config.
  69. invalidDefaultServiceConfigErrPrefix = "grpc: the provided default service config is invalid"
  70. )
  71. // The following errors are returned from Dial and DialContext
  72. var (
  73. // errNoTransportSecurity indicates that there is no transport security
  74. // being set for ClientConn. Users should either set one or explicitly
  75. // call WithInsecure DialOption to disable security.
  76. errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithTransportCredentials(insecure.NewCredentials()) explicitly or set credentials)")
  77. // errTransportCredsAndBundle indicates that creds bundle is used together
  78. // with other individual Transport Credentials.
  79. errTransportCredsAndBundle = errors.New("grpc: credentials.Bundle may not be used with individual TransportCredentials")
  80. // errNoTransportCredsInBundle indicated that the configured creds bundle
  81. // returned a transport credentials which was nil.
  82. errNoTransportCredsInBundle = errors.New("grpc: credentials.Bundle must return non-nil transport credentials")
  83. // errTransportCredentialsMissing indicates that users want to transmit
  84. // security information (e.g., OAuth2 token) which requires secure
  85. // connection on an insecure connection.
  86. errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)")
  87. )
  88. const (
  89. defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4
  90. defaultClientMaxSendMessageSize = math.MaxInt32
  91. // http2IOBufSize specifies the buffer size for sending frames.
  92. defaultWriteBufSize = 32 * 1024
  93. defaultReadBufSize = 32 * 1024
  94. )
  95. // Dial creates a client connection to the given target.
  96. func Dial(target string, opts ...DialOption) (*ClientConn, error) {
  97. return DialContext(context.Background(), target, opts...)
  98. }
  99. type defaultConfigSelector struct {
  100. sc *ServiceConfig
  101. }
  102. func (dcs *defaultConfigSelector) SelectConfig(rpcInfo iresolver.RPCInfo) (*iresolver.RPCConfig, error) {
  103. return &iresolver.RPCConfig{
  104. Context: rpcInfo.Context,
  105. MethodConfig: getMethodConfig(dcs.sc, rpcInfo.Method),
  106. }, nil
  107. }
  108. // newClient returns a new client in idle mode.
  109. func newClient(target string, opts ...DialOption) (conn *ClientConn, err error) {
  110. cc := &ClientConn{
  111. target: target,
  112. conns: make(map[*addrConn]struct{}),
  113. dopts: defaultDialOptions(),
  114. czData: new(channelzData),
  115. }
  116. cc.retryThrottler.Store((*retryThrottler)(nil))
  117. cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil})
  118. cc.ctx, cc.cancel = context.WithCancel(context.Background())
  119. // Apply dial options.
  120. disableGlobalOpts := false
  121. for _, opt := range opts {
  122. if _, ok := opt.(*disableGlobalDialOptions); ok {
  123. disableGlobalOpts = true
  124. break
  125. }
  126. }
  127. if !disableGlobalOpts {
  128. for _, opt := range globalDialOptions {
  129. opt.apply(&cc.dopts)
  130. }
  131. }
  132. for _, opt := range opts {
  133. opt.apply(&cc.dopts)
  134. }
  135. chainUnaryClientInterceptors(cc)
  136. chainStreamClientInterceptors(cc)
  137. if err := cc.validateTransportCredentials(); err != nil {
  138. return nil, err
  139. }
  140. if cc.dopts.defaultServiceConfigRawJSON != nil {
  141. scpr := parseServiceConfig(*cc.dopts.defaultServiceConfigRawJSON)
  142. if scpr.Err != nil {
  143. return nil, fmt.Errorf("%s: %v", invalidDefaultServiceConfigErrPrefix, scpr.Err)
  144. }
  145. cc.dopts.defaultServiceConfig, _ = scpr.Config.(*ServiceConfig)
  146. }
  147. cc.mkp = cc.dopts.copts.KeepaliveParams
  148. // Register ClientConn with channelz.
  149. cc.channelzRegistration(target)
  150. // TODO: Ideally it should be impossible to error from this function after
  151. // channelz registration. This will require removing some channelz logs
  152. // from the following functions that can error. Errors can be returned to
  153. // the user, and successful logs can be emitted here, after the checks have
  154. // passed and channelz is subsequently registered.
  155. // Determine the resolver to use.
  156. if err := cc.parseTargetAndFindResolver(); err != nil {
  157. channelz.RemoveEntry(cc.channelzID)
  158. return nil, err
  159. }
  160. if err = cc.determineAuthority(); err != nil {
  161. channelz.RemoveEntry(cc.channelzID)
  162. return nil, err
  163. }
  164. cc.csMgr = newConnectivityStateManager(cc.ctx, cc.channelzID)
  165. cc.pickerWrapper = newPickerWrapper(cc.dopts.copts.StatsHandlers)
  166. cc.initIdleStateLocked() // Safe to call without the lock, since nothing else has a reference to cc.
  167. cc.idlenessMgr = idle.NewManager((*idler)(cc), cc.dopts.idleTimeout)
  168. return cc, nil
  169. }
  170. // DialContext creates a client connection to the given target. By default, it's
  171. // a non-blocking dial (the function won't wait for connections to be
  172. // established, and connecting happens in the background). To make it a blocking
  173. // dial, use WithBlock() dial option.
  174. //
  175. // In the non-blocking case, the ctx does not act against the connection. It
  176. // only controls the setup steps.
  177. //
  178. // In the blocking case, ctx can be used to cancel or expire the pending
  179. // connection. Once this function returns, the cancellation and expiration of
  180. // ctx will be noop. Users should call ClientConn.Close to terminate all the
  181. // pending operations after this function returns.
  182. //
  183. // The target name syntax is defined in
  184. // https://github.com/grpc/grpc/blob/master/doc/naming.md.
  185. // e.g. to use dns resolver, a "dns:///" prefix should be applied to the target.
  186. func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) {
  187. cc, err := newClient(target, opts...)
  188. if err != nil {
  189. return nil, err
  190. }
  191. // We start the channel off in idle mode, but kick it out of idle now,
  192. // instead of waiting for the first RPC. Other gRPC implementations do wait
  193. // for the first RPC to kick the channel out of idle. But doing so would be
  194. // a major behavior change for our users who are used to seeing the channel
  195. // active after Dial.
  196. //
  197. // Taking this approach of kicking it out of idle at the end of this method
  198. // allows us to share the code between channel creation and exiting idle
  199. // mode. This will also make it easy for us to switch to starting the
  200. // channel off in idle, i.e. by making newClient exported.
  201. defer func() {
  202. if err != nil {
  203. cc.Close()
  204. }
  205. }()
  206. // This creates the name resolver, load balancer, etc.
  207. if err := cc.idlenessMgr.ExitIdleMode(); err != nil {
  208. return nil, err
  209. }
  210. // Return now for non-blocking dials.
  211. if !cc.dopts.block {
  212. return cc, nil
  213. }
  214. if cc.dopts.timeout > 0 {
  215. var cancel context.CancelFunc
  216. ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout)
  217. defer cancel()
  218. }
  219. defer func() {
  220. select {
  221. case <-ctx.Done():
  222. switch {
  223. case ctx.Err() == err:
  224. conn = nil
  225. case err == nil || !cc.dopts.returnLastError:
  226. conn, err = nil, ctx.Err()
  227. default:
  228. conn, err = nil, fmt.Errorf("%v: %v", ctx.Err(), err)
  229. }
  230. default:
  231. }
  232. }()
  233. // A blocking dial blocks until the clientConn is ready.
  234. for {
  235. s := cc.GetState()
  236. if s == connectivity.Idle {
  237. cc.Connect()
  238. }
  239. if s == connectivity.Ready {
  240. return cc, nil
  241. } else if cc.dopts.copts.FailOnNonTempDialError && s == connectivity.TransientFailure {
  242. if err = cc.connectionError(); err != nil {
  243. terr, ok := err.(interface {
  244. Temporary() bool
  245. })
  246. if ok && !terr.Temporary() {
  247. return nil, err
  248. }
  249. }
  250. }
  251. if !cc.WaitForStateChange(ctx, s) {
  252. // ctx got timeout or canceled.
  253. if err = cc.connectionError(); err != nil && cc.dopts.returnLastError {
  254. return nil, err
  255. }
  256. return nil, ctx.Err()
  257. }
  258. }
  259. }
  260. // addTraceEvent is a helper method to add a trace event on the channel. If the
  261. // channel is a nested one, the same event is also added on the parent channel.
  262. func (cc *ClientConn) addTraceEvent(msg string) {
  263. ted := &channelz.TraceEventDesc{
  264. Desc: fmt.Sprintf("Channel %s", msg),
  265. Severity: channelz.CtInfo,
  266. }
  267. if cc.dopts.channelzParentID != nil {
  268. ted.Parent = &channelz.TraceEventDesc{
  269. Desc: fmt.Sprintf("Nested channel(id:%d) %s", cc.channelzID.Int(), msg),
  270. Severity: channelz.CtInfo,
  271. }
  272. }
  273. channelz.AddTraceEvent(logger, cc.channelzID, 0, ted)
  274. }
  275. type idler ClientConn
  276. func (i *idler) EnterIdleMode() {
  277. (*ClientConn)(i).enterIdleMode()
  278. }
  279. func (i *idler) ExitIdleMode() error {
  280. return (*ClientConn)(i).exitIdleMode()
  281. }
  282. // exitIdleMode moves the channel out of idle mode by recreating the name
  283. // resolver and load balancer. This should never be called directly; use
  284. // cc.idlenessMgr.ExitIdleMode instead.
  285. func (cc *ClientConn) exitIdleMode() (err error) {
  286. cc.mu.Lock()
  287. if cc.conns == nil {
  288. cc.mu.Unlock()
  289. return errConnClosing
  290. }
  291. cc.mu.Unlock()
  292. // This needs to be called without cc.mu because this builds a new resolver
  293. // which might update state or report error inline, which would then need to
  294. // acquire cc.mu.
  295. if err := cc.resolverWrapper.start(); err != nil {
  296. return err
  297. }
  298. cc.addTraceEvent("exiting idle mode")
  299. return nil
  300. }
  301. // initIdleStateLocked initializes common state to how it should be while idle.
  302. func (cc *ClientConn) initIdleStateLocked() {
  303. cc.resolverWrapper = newCCResolverWrapper(cc)
  304. cc.balancerWrapper = newCCBalancerWrapper(cc)
  305. cc.firstResolveEvent = grpcsync.NewEvent()
  306. // cc.conns == nil is a proxy for the ClientConn being closed. So, instead
  307. // of setting it to nil here, we recreate the map. This also means that we
  308. // don't have to do this when exiting idle mode.
  309. cc.conns = make(map[*addrConn]struct{})
  310. }
  311. // enterIdleMode puts the channel in idle mode, and as part of it shuts down the
  312. // name resolver, load balancer, and any subchannels. This should never be
  313. // called directly; use cc.idlenessMgr.EnterIdleMode instead.
  314. func (cc *ClientConn) enterIdleMode() {
  315. cc.mu.Lock()
  316. if cc.conns == nil {
  317. cc.mu.Unlock()
  318. return
  319. }
  320. conns := cc.conns
  321. rWrapper := cc.resolverWrapper
  322. rWrapper.close()
  323. cc.pickerWrapper.reset()
  324. bWrapper := cc.balancerWrapper
  325. bWrapper.close()
  326. cc.csMgr.updateState(connectivity.Idle)
  327. cc.addTraceEvent("entering idle mode")
  328. cc.initIdleStateLocked()
  329. cc.mu.Unlock()
  330. // Block until the name resolver and LB policy are closed.
  331. <-rWrapper.serializer.Done()
  332. <-bWrapper.serializer.Done()
  333. // Close all subchannels after the LB policy is closed.
  334. for ac := range conns {
  335. ac.tearDown(errConnIdling)
  336. }
  337. }
  338. // validateTransportCredentials performs a series of checks on the configured
  339. // transport credentials. It returns a non-nil error if any of these conditions
  340. // are met:
  341. // - no transport creds and no creds bundle is configured
  342. // - both transport creds and creds bundle are configured
  343. // - creds bundle is configured, but it lacks a transport credentials
  344. // - insecure transport creds configured alongside call creds that require
  345. // transport level security
  346. //
  347. // If none of the above conditions are met, the configured credentials are
  348. // deemed valid and a nil error is returned.
  349. func (cc *ClientConn) validateTransportCredentials() error {
  350. if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil {
  351. return errNoTransportSecurity
  352. }
  353. if cc.dopts.copts.TransportCredentials != nil && cc.dopts.copts.CredsBundle != nil {
  354. return errTransportCredsAndBundle
  355. }
  356. if cc.dopts.copts.CredsBundle != nil && cc.dopts.copts.CredsBundle.TransportCredentials() == nil {
  357. return errNoTransportCredsInBundle
  358. }
  359. transportCreds := cc.dopts.copts.TransportCredentials
  360. if transportCreds == nil {
  361. transportCreds = cc.dopts.copts.CredsBundle.TransportCredentials()
  362. }
  363. if transportCreds.Info().SecurityProtocol == "insecure" {
  364. for _, cd := range cc.dopts.copts.PerRPCCredentials {
  365. if cd.RequireTransportSecurity() {
  366. return errTransportCredentialsMissing
  367. }
  368. }
  369. }
  370. return nil
  371. }
  372. // channelzRegistration registers the newly created ClientConn with channelz and
  373. // stores the returned identifier in `cc.channelzID` and `cc.csMgr.channelzID`.
  374. // A channelz trace event is emitted for ClientConn creation. If the newly
  375. // created ClientConn is a nested one, i.e a valid parent ClientConn ID is
  376. // specified via a dial option, the trace event is also added to the parent.
  377. //
  378. // Doesn't grab cc.mu as this method is expected to be called only at Dial time.
  379. func (cc *ClientConn) channelzRegistration(target string) {
  380. cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target)
  381. cc.addTraceEvent("created")
  382. }
  383. // chainUnaryClientInterceptors chains all unary client interceptors into one.
  384. func chainUnaryClientInterceptors(cc *ClientConn) {
  385. interceptors := cc.dopts.chainUnaryInts
  386. // Prepend dopts.unaryInt to the chaining interceptors if it exists, since unaryInt will
  387. // be executed before any other chained interceptors.
  388. if cc.dopts.unaryInt != nil {
  389. interceptors = append([]UnaryClientInterceptor{cc.dopts.unaryInt}, interceptors...)
  390. }
  391. var chainedInt UnaryClientInterceptor
  392. if len(interceptors) == 0 {
  393. chainedInt = nil
  394. } else if len(interceptors) == 1 {
  395. chainedInt = interceptors[0]
  396. } else {
  397. chainedInt = func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error {
  398. return interceptors[0](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, 0, invoker), opts...)
  399. }
  400. }
  401. cc.dopts.unaryInt = chainedInt
  402. }
  403. // getChainUnaryInvoker recursively generate the chained unary invoker.
  404. func getChainUnaryInvoker(interceptors []UnaryClientInterceptor, curr int, finalInvoker UnaryInvoker) UnaryInvoker {
  405. if curr == len(interceptors)-1 {
  406. return finalInvoker
  407. }
  408. return func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error {
  409. return interceptors[curr+1](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, curr+1, finalInvoker), opts...)
  410. }
  411. }
  412. // chainStreamClientInterceptors chains all stream client interceptors into one.
  413. func chainStreamClientInterceptors(cc *ClientConn) {
  414. interceptors := cc.dopts.chainStreamInts
  415. // Prepend dopts.streamInt to the chaining interceptors if it exists, since streamInt will
  416. // be executed before any other chained interceptors.
  417. if cc.dopts.streamInt != nil {
  418. interceptors = append([]StreamClientInterceptor{cc.dopts.streamInt}, interceptors...)
  419. }
  420. var chainedInt StreamClientInterceptor
  421. if len(interceptors) == 0 {
  422. chainedInt = nil
  423. } else if len(interceptors) == 1 {
  424. chainedInt = interceptors[0]
  425. } else {
  426. chainedInt = func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) {
  427. return interceptors[0](ctx, desc, cc, method, getChainStreamer(interceptors, 0, streamer), opts...)
  428. }
  429. }
  430. cc.dopts.streamInt = chainedInt
  431. }
  432. // getChainStreamer recursively generate the chained client stream constructor.
  433. func getChainStreamer(interceptors []StreamClientInterceptor, curr int, finalStreamer Streamer) Streamer {
  434. if curr == len(interceptors)-1 {
  435. return finalStreamer
  436. }
  437. return func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) {
  438. return interceptors[curr+1](ctx, desc, cc, method, getChainStreamer(interceptors, curr+1, finalStreamer), opts...)
  439. }
  440. }
  441. // newConnectivityStateManager creates an connectivityStateManager with
  442. // the specified id.
  443. func newConnectivityStateManager(ctx context.Context, id *channelz.Identifier) *connectivityStateManager {
  444. return &connectivityStateManager{
  445. channelzID: id,
  446. pubSub: grpcsync.NewPubSub(ctx),
  447. }
  448. }
  449. // connectivityStateManager keeps the connectivity.State of ClientConn.
  450. // This struct will eventually be exported so the balancers can access it.
  451. //
  452. // TODO: If possible, get rid of the `connectivityStateManager` type, and
  453. // provide this functionality using the `PubSub`, to avoid keeping track of
  454. // the connectivity state at two places.
  455. type connectivityStateManager struct {
  456. mu sync.Mutex
  457. state connectivity.State
  458. notifyChan chan struct{}
  459. channelzID *channelz.Identifier
  460. pubSub *grpcsync.PubSub
  461. }
  462. // updateState updates the connectivity.State of ClientConn.
  463. // If there's a change it notifies goroutines waiting on state change to
  464. // happen.
  465. func (csm *connectivityStateManager) updateState(state connectivity.State) {
  466. csm.mu.Lock()
  467. defer csm.mu.Unlock()
  468. if csm.state == connectivity.Shutdown {
  469. return
  470. }
  471. if csm.state == state {
  472. return
  473. }
  474. csm.state = state
  475. csm.pubSub.Publish(state)
  476. channelz.Infof(logger, csm.channelzID, "Channel Connectivity change to %v", state)
  477. if csm.notifyChan != nil {
  478. // There are other goroutines waiting on this channel.
  479. close(csm.notifyChan)
  480. csm.notifyChan = nil
  481. }
  482. }
  483. func (csm *connectivityStateManager) getState() connectivity.State {
  484. csm.mu.Lock()
  485. defer csm.mu.Unlock()
  486. return csm.state
  487. }
  488. func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} {
  489. csm.mu.Lock()
  490. defer csm.mu.Unlock()
  491. if csm.notifyChan == nil {
  492. csm.notifyChan = make(chan struct{})
  493. }
  494. return csm.notifyChan
  495. }
  496. // ClientConnInterface defines the functions clients need to perform unary and
  497. // streaming RPCs. It is implemented by *ClientConn, and is only intended to
  498. // be referenced by generated code.
  499. type ClientConnInterface interface {
  500. // Invoke performs a unary RPC and returns after the response is received
  501. // into reply.
  502. Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error
  503. // NewStream begins a streaming RPC.
  504. NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
  505. }
  506. // Assert *ClientConn implements ClientConnInterface.
  507. var _ ClientConnInterface = (*ClientConn)(nil)
  508. // ClientConn represents a virtual connection to a conceptual endpoint, to
  509. // perform RPCs.
  510. //
  511. // A ClientConn is free to have zero or more actual connections to the endpoint
  512. // based on configuration, load, etc. It is also free to determine which actual
  513. // endpoints to use and may change it every RPC, permitting client-side load
  514. // balancing.
  515. //
  516. // A ClientConn encapsulates a range of functionality including name
  517. // resolution, TCP connection establishment (with retries and backoff) and TLS
  518. // handshakes. It also handles errors on established connections by
  519. // re-resolving the name and reconnecting.
  520. type ClientConn struct {
  521. ctx context.Context // Initialized using the background context at dial time.
  522. cancel context.CancelFunc // Cancelled on close.
  523. // The following are initialized at dial time, and are read-only after that.
  524. target string // User's dial target.
  525. parsedTarget resolver.Target // See parseTargetAndFindResolver().
  526. authority string // See determineAuthority().
  527. dopts dialOptions // Default and user specified dial options.
  528. channelzID *channelz.Identifier // Channelz identifier for the channel.
  529. resolverBuilder resolver.Builder // See parseTargetAndFindResolver().
  530. idlenessMgr *idle.Manager
  531. // The following provide their own synchronization, and therefore don't
  532. // require cc.mu to be held to access them.
  533. csMgr *connectivityStateManager
  534. pickerWrapper *pickerWrapper
  535. safeConfigSelector iresolver.SafeConfigSelector
  536. czData *channelzData
  537. retryThrottler atomic.Value // Updated from service config.
  538. // mu protects the following fields.
  539. // TODO: split mu so the same mutex isn't used for everything.
  540. mu sync.RWMutex
  541. resolverWrapper *ccResolverWrapper // Always recreated whenever entering idle to simplify Close.
  542. balancerWrapper *ccBalancerWrapper // Always recreated whenever entering idle to simplify Close.
  543. sc *ServiceConfig // Latest service config received from the resolver.
  544. conns map[*addrConn]struct{} // Set to nil on close.
  545. mkp keepalive.ClientParameters // May be updated upon receipt of a GoAway.
  546. // firstResolveEvent is used to track whether the name resolver sent us at
  547. // least one update. RPCs block on this event. May be accessed without mu
  548. // if we know we cannot be asked to enter idle mode while accessing it (e.g.
  549. // when the idle manager has already been closed, or if we are already
  550. // entering idle mode).
  551. firstResolveEvent *grpcsync.Event
  552. lceMu sync.Mutex // protects lastConnectionError
  553. lastConnectionError error
  554. }
  555. // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or
  556. // ctx expires. A true value is returned in former case and false in latter.
  557. //
  558. // # Experimental
  559. //
  560. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  561. // later release.
  562. func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool {
  563. ch := cc.csMgr.getNotifyChan()
  564. if cc.csMgr.getState() != sourceState {
  565. return true
  566. }
  567. select {
  568. case <-ctx.Done():
  569. return false
  570. case <-ch:
  571. return true
  572. }
  573. }
  574. // GetState returns the connectivity.State of ClientConn.
  575. //
  576. // # Experimental
  577. //
  578. // Notice: This API is EXPERIMENTAL and may be changed or removed in a later
  579. // release.
  580. func (cc *ClientConn) GetState() connectivity.State {
  581. return cc.csMgr.getState()
  582. }
  583. // Connect causes all subchannels in the ClientConn to attempt to connect if
  584. // the channel is idle. Does not wait for the connection attempts to begin
  585. // before returning.
  586. //
  587. // # Experimental
  588. //
  589. // Notice: This API is EXPERIMENTAL and may be changed or removed in a later
  590. // release.
  591. func (cc *ClientConn) Connect() {
  592. if err := cc.idlenessMgr.ExitIdleMode(); err != nil {
  593. cc.addTraceEvent(err.Error())
  594. return
  595. }
  596. // If the ClientConn was not in idle mode, we need to call ExitIdle on the
  597. // LB policy so that connections can be created.
  598. cc.mu.Lock()
  599. cc.balancerWrapper.exitIdle()
  600. cc.mu.Unlock()
  601. }
  602. // waitForResolvedAddrs blocks until the resolver has provided addresses or the
  603. // context expires. Returns nil unless the context expires first; otherwise
  604. // returns a status error based on the context.
  605. func (cc *ClientConn) waitForResolvedAddrs(ctx context.Context) error {
  606. // This is on the RPC path, so we use a fast path to avoid the
  607. // more-expensive "select" below after the resolver has returned once.
  608. if cc.firstResolveEvent.HasFired() {
  609. return nil
  610. }
  611. select {
  612. case <-cc.firstResolveEvent.Done():
  613. return nil
  614. case <-ctx.Done():
  615. return status.FromContextError(ctx.Err()).Err()
  616. case <-cc.ctx.Done():
  617. return ErrClientConnClosing
  618. }
  619. }
  620. var emptyServiceConfig *ServiceConfig
  621. func init() {
  622. cfg := parseServiceConfig("{}")
  623. if cfg.Err != nil {
  624. panic(fmt.Sprintf("impossible error parsing empty service config: %v", cfg.Err))
  625. }
  626. emptyServiceConfig = cfg.Config.(*ServiceConfig)
  627. internal.SubscribeToConnectivityStateChanges = func(cc *ClientConn, s grpcsync.Subscriber) func() {
  628. return cc.csMgr.pubSub.Subscribe(s)
  629. }
  630. internal.EnterIdleModeForTesting = func(cc *ClientConn) {
  631. cc.idlenessMgr.EnterIdleModeForTesting()
  632. }
  633. internal.ExitIdleModeForTesting = func(cc *ClientConn) error {
  634. return cc.idlenessMgr.ExitIdleMode()
  635. }
  636. }
  637. func (cc *ClientConn) maybeApplyDefaultServiceConfig(addrs []resolver.Address) {
  638. if cc.sc != nil {
  639. cc.applyServiceConfigAndBalancer(cc.sc, nil, addrs)
  640. return
  641. }
  642. if cc.dopts.defaultServiceConfig != nil {
  643. cc.applyServiceConfigAndBalancer(cc.dopts.defaultServiceConfig, &defaultConfigSelector{cc.dopts.defaultServiceConfig}, addrs)
  644. } else {
  645. cc.applyServiceConfigAndBalancer(emptyServiceConfig, &defaultConfigSelector{emptyServiceConfig}, addrs)
  646. }
  647. }
  648. func (cc *ClientConn) updateResolverStateAndUnlock(s resolver.State, err error) error {
  649. defer cc.firstResolveEvent.Fire()
  650. // Check if the ClientConn is already closed. Some fields (e.g.
  651. // balancerWrapper) are set to nil when closing the ClientConn, and could
  652. // cause nil pointer panic if we don't have this check.
  653. if cc.conns == nil {
  654. cc.mu.Unlock()
  655. return nil
  656. }
  657. if err != nil {
  658. // May need to apply the initial service config in case the resolver
  659. // doesn't support service configs, or doesn't provide a service config
  660. // with the new addresses.
  661. cc.maybeApplyDefaultServiceConfig(nil)
  662. cc.balancerWrapper.resolverError(err)
  663. // No addresses are valid with err set; return early.
  664. cc.mu.Unlock()
  665. return balancer.ErrBadResolverState
  666. }
  667. var ret error
  668. if cc.dopts.disableServiceConfig {
  669. channelz.Infof(logger, cc.channelzID, "ignoring service config from resolver (%v) and applying the default because service config is disabled", s.ServiceConfig)
  670. cc.maybeApplyDefaultServiceConfig(s.Addresses)
  671. } else if s.ServiceConfig == nil {
  672. cc.maybeApplyDefaultServiceConfig(s.Addresses)
  673. // TODO: do we need to apply a failing LB policy if there is no
  674. // default, per the error handling design?
  675. } else {
  676. if sc, ok := s.ServiceConfig.Config.(*ServiceConfig); s.ServiceConfig.Err == nil && ok {
  677. configSelector := iresolver.GetConfigSelector(s)
  678. if configSelector != nil {
  679. if len(s.ServiceConfig.Config.(*ServiceConfig).Methods) != 0 {
  680. channelz.Infof(logger, cc.channelzID, "method configs in service config will be ignored due to presence of config selector")
  681. }
  682. } else {
  683. configSelector = &defaultConfigSelector{sc}
  684. }
  685. cc.applyServiceConfigAndBalancer(sc, configSelector, s.Addresses)
  686. } else {
  687. ret = balancer.ErrBadResolverState
  688. if cc.sc == nil {
  689. // Apply the failing LB only if we haven't received valid service config
  690. // from the name resolver in the past.
  691. cc.applyFailingLBLocked(s.ServiceConfig)
  692. cc.mu.Unlock()
  693. return ret
  694. }
  695. }
  696. }
  697. var balCfg serviceconfig.LoadBalancingConfig
  698. if cc.sc != nil && cc.sc.lbConfig != nil {
  699. balCfg = cc.sc.lbConfig.cfg
  700. }
  701. bw := cc.balancerWrapper
  702. cc.mu.Unlock()
  703. uccsErr := bw.updateClientConnState(&balancer.ClientConnState{ResolverState: s, BalancerConfig: balCfg})
  704. if ret == nil {
  705. ret = uccsErr // prefer ErrBadResolver state since any other error is
  706. // currently meaningless to the caller.
  707. }
  708. return ret
  709. }
  710. // applyFailingLBLocked is akin to configuring an LB policy on the channel which
  711. // always fails RPCs. Here, an actual LB policy is not configured, but an always
  712. // erroring picker is configured, which returns errors with information about
  713. // what was invalid in the received service config. A config selector with no
  714. // service config is configured, and the connectivity state of the channel is
  715. // set to TransientFailure.
  716. func (cc *ClientConn) applyFailingLBLocked(sc *serviceconfig.ParseResult) {
  717. var err error
  718. if sc.Err != nil {
  719. err = status.Errorf(codes.Unavailable, "error parsing service config: %v", sc.Err)
  720. } else {
  721. err = status.Errorf(codes.Unavailable, "illegal service config type: %T", sc.Config)
  722. }
  723. cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil})
  724. cc.pickerWrapper.updatePicker(base.NewErrPicker(err))
  725. cc.csMgr.updateState(connectivity.TransientFailure)
  726. }
  727. // Makes a copy of the input addresses slice and clears out the balancer
  728. // attributes field. Addresses are passed during subconn creation and address
  729. // update operations. In both cases, we will clear the balancer attributes by
  730. // calling this function, and therefore we will be able to use the Equal method
  731. // provided by the resolver.Address type for comparison.
  732. func copyAddressesWithoutBalancerAttributes(in []resolver.Address) []resolver.Address {
  733. out := make([]resolver.Address, len(in))
  734. for i := range in {
  735. out[i] = in[i]
  736. out[i].BalancerAttributes = nil
  737. }
  738. return out
  739. }
  740. // newAddrConnLocked creates an addrConn for addrs and adds it to cc.conns.
  741. //
  742. // Caller needs to make sure len(addrs) > 0.
  743. func (cc *ClientConn) newAddrConnLocked(addrs []resolver.Address, opts balancer.NewSubConnOptions) (*addrConn, error) {
  744. if cc.conns == nil {
  745. return nil, ErrClientConnClosing
  746. }
  747. ac := &addrConn{
  748. state: connectivity.Idle,
  749. cc: cc,
  750. addrs: copyAddressesWithoutBalancerAttributes(addrs),
  751. scopts: opts,
  752. dopts: cc.dopts,
  753. czData: new(channelzData),
  754. resetBackoff: make(chan struct{}),
  755. stateChan: make(chan struct{}),
  756. }
  757. ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
  758. var err error
  759. ac.channelzID, err = channelz.RegisterSubChannel(ac, cc.channelzID, "")
  760. if err != nil {
  761. return nil, err
  762. }
  763. channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{
  764. Desc: "Subchannel created",
  765. Severity: channelz.CtInfo,
  766. Parent: &channelz.TraceEventDesc{
  767. Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelzID.Int()),
  768. Severity: channelz.CtInfo,
  769. },
  770. })
  771. // Track ac in cc. This needs to be done before any getTransport(...) is called.
  772. cc.conns[ac] = struct{}{}
  773. return ac, nil
  774. }
  775. // removeAddrConn removes the addrConn in the subConn from clientConn.
  776. // It also tears down the ac with the given error.
  777. func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) {
  778. cc.mu.Lock()
  779. if cc.conns == nil {
  780. cc.mu.Unlock()
  781. return
  782. }
  783. delete(cc.conns, ac)
  784. cc.mu.Unlock()
  785. ac.tearDown(err)
  786. }
  787. func (cc *ClientConn) channelzMetric() *channelz.ChannelInternalMetric {
  788. return &channelz.ChannelInternalMetric{
  789. State: cc.GetState(),
  790. Target: cc.target,
  791. CallsStarted: atomic.LoadInt64(&cc.czData.callsStarted),
  792. CallsSucceeded: atomic.LoadInt64(&cc.czData.callsSucceeded),
  793. CallsFailed: atomic.LoadInt64(&cc.czData.callsFailed),
  794. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&cc.czData.lastCallStartedTime)),
  795. }
  796. }
  797. // Target returns the target string of the ClientConn.
  798. //
  799. // # Experimental
  800. //
  801. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  802. // later release.
  803. func (cc *ClientConn) Target() string {
  804. return cc.target
  805. }
  806. func (cc *ClientConn) incrCallsStarted() {
  807. atomic.AddInt64(&cc.czData.callsStarted, 1)
  808. atomic.StoreInt64(&cc.czData.lastCallStartedTime, time.Now().UnixNano())
  809. }
  810. func (cc *ClientConn) incrCallsSucceeded() {
  811. atomic.AddInt64(&cc.czData.callsSucceeded, 1)
  812. }
  813. func (cc *ClientConn) incrCallsFailed() {
  814. atomic.AddInt64(&cc.czData.callsFailed, 1)
  815. }
  816. // connect starts creating a transport.
  817. // It does nothing if the ac is not IDLE.
  818. // TODO(bar) Move this to the addrConn section.
  819. func (ac *addrConn) connect() error {
  820. ac.mu.Lock()
  821. if ac.state == connectivity.Shutdown {
  822. if logger.V(2) {
  823. logger.Infof("connect called on shutdown addrConn; ignoring.")
  824. }
  825. ac.mu.Unlock()
  826. return errConnClosing
  827. }
  828. if ac.state != connectivity.Idle {
  829. if logger.V(2) {
  830. logger.Infof("connect called on addrConn in non-idle state (%v); ignoring.", ac.state)
  831. }
  832. ac.mu.Unlock()
  833. return nil
  834. }
  835. ac.mu.Unlock()
  836. ac.resetTransport()
  837. return nil
  838. }
  839. func equalAddresses(a, b []resolver.Address) bool {
  840. if len(a) != len(b) {
  841. return false
  842. }
  843. for i, v := range a {
  844. if !v.Equal(b[i]) {
  845. return false
  846. }
  847. }
  848. return true
  849. }
  850. // updateAddrs updates ac.addrs with the new addresses list and handles active
  851. // connections or connection attempts.
  852. func (ac *addrConn) updateAddrs(addrs []resolver.Address) {
  853. ac.mu.Lock()
  854. channelz.Infof(logger, ac.channelzID, "addrConn: updateAddrs curAddr: %v, addrs: %v", pretty.ToJSON(ac.curAddr), pretty.ToJSON(addrs))
  855. addrs = copyAddressesWithoutBalancerAttributes(addrs)
  856. if equalAddresses(ac.addrs, addrs) {
  857. ac.mu.Unlock()
  858. return
  859. }
  860. ac.addrs = addrs
  861. if ac.state == connectivity.Shutdown ||
  862. ac.state == connectivity.TransientFailure ||
  863. ac.state == connectivity.Idle {
  864. // We were not connecting, so do nothing but update the addresses.
  865. ac.mu.Unlock()
  866. return
  867. }
  868. if ac.state == connectivity.Ready {
  869. // Try to find the connected address.
  870. for _, a := range addrs {
  871. a.ServerName = ac.cc.getServerName(a)
  872. if a.Equal(ac.curAddr) {
  873. // We are connected to a valid address, so do nothing but
  874. // update the addresses.
  875. ac.mu.Unlock()
  876. return
  877. }
  878. }
  879. }
  880. // We are either connected to the wrong address or currently connecting.
  881. // Stop the current iteration and restart.
  882. ac.cancel()
  883. ac.ctx, ac.cancel = context.WithCancel(ac.cc.ctx)
  884. // We have to defer here because GracefulClose => onClose, which requires
  885. // locking ac.mu.
  886. if ac.transport != nil {
  887. defer ac.transport.GracefulClose()
  888. ac.transport = nil
  889. }
  890. if len(addrs) == 0 {
  891. ac.updateConnectivityState(connectivity.Idle, nil)
  892. }
  893. ac.mu.Unlock()
  894. // Since we were connecting/connected, we should start a new connection
  895. // attempt.
  896. go ac.resetTransport()
  897. }
  898. // getServerName determines the serverName to be used in the connection
  899. // handshake. The default value for the serverName is the authority on the
  900. // ClientConn, which either comes from the user's dial target or through an
  901. // authority override specified using the WithAuthority dial option. Name
  902. // resolvers can specify a per-address override for the serverName through the
  903. // resolver.Address.ServerName field which is used only if the WithAuthority
  904. // dial option was not used. The rationale is that per-address authority
  905. // overrides specified by the name resolver can represent a security risk, while
  906. // an override specified by the user is more dependable since they probably know
  907. // what they are doing.
  908. func (cc *ClientConn) getServerName(addr resolver.Address) string {
  909. if cc.dopts.authority != "" {
  910. return cc.dopts.authority
  911. }
  912. if addr.ServerName != "" {
  913. return addr.ServerName
  914. }
  915. return cc.authority
  916. }
  917. func getMethodConfig(sc *ServiceConfig, method string) MethodConfig {
  918. if sc == nil {
  919. return MethodConfig{}
  920. }
  921. if m, ok := sc.Methods[method]; ok {
  922. return m
  923. }
  924. i := strings.LastIndex(method, "/")
  925. if m, ok := sc.Methods[method[:i+1]]; ok {
  926. return m
  927. }
  928. return sc.Methods[""]
  929. }
  930. // GetMethodConfig gets the method config of the input method.
  931. // If there's an exact match for input method (i.e. /service/method), we return
  932. // the corresponding MethodConfig.
  933. // If there isn't an exact match for the input method, we look for the service's default
  934. // config under the service (i.e /service/) and then for the default for all services (empty string).
  935. //
  936. // If there is a default MethodConfig for the service, we return it.
  937. // Otherwise, we return an empty MethodConfig.
  938. func (cc *ClientConn) GetMethodConfig(method string) MethodConfig {
  939. // TODO: Avoid the locking here.
  940. cc.mu.RLock()
  941. defer cc.mu.RUnlock()
  942. return getMethodConfig(cc.sc, method)
  943. }
  944. func (cc *ClientConn) healthCheckConfig() *healthCheckConfig {
  945. cc.mu.RLock()
  946. defer cc.mu.RUnlock()
  947. if cc.sc == nil {
  948. return nil
  949. }
  950. return cc.sc.healthCheckConfig
  951. }
  952. func (cc *ClientConn) getTransport(ctx context.Context, failfast bool, method string) (transport.ClientTransport, balancer.PickResult, error) {
  953. return cc.pickerWrapper.pick(ctx, failfast, balancer.PickInfo{
  954. Ctx: ctx,
  955. FullMethodName: method,
  956. })
  957. }
  958. func (cc *ClientConn) applyServiceConfigAndBalancer(sc *ServiceConfig, configSelector iresolver.ConfigSelector, addrs []resolver.Address) {
  959. if sc == nil {
  960. // should never reach here.
  961. return
  962. }
  963. cc.sc = sc
  964. if configSelector != nil {
  965. cc.safeConfigSelector.UpdateConfigSelector(configSelector)
  966. }
  967. if cc.sc.retryThrottling != nil {
  968. newThrottler := &retryThrottler{
  969. tokens: cc.sc.retryThrottling.MaxTokens,
  970. max: cc.sc.retryThrottling.MaxTokens,
  971. thresh: cc.sc.retryThrottling.MaxTokens / 2,
  972. ratio: cc.sc.retryThrottling.TokenRatio,
  973. }
  974. cc.retryThrottler.Store(newThrottler)
  975. } else {
  976. cc.retryThrottler.Store((*retryThrottler)(nil))
  977. }
  978. var newBalancerName string
  979. if cc.sc == nil || (cc.sc.lbConfig == nil && cc.sc.LB == nil) {
  980. // No service config or no LB policy specified in config.
  981. newBalancerName = PickFirstBalancerName
  982. } else if cc.sc.lbConfig != nil {
  983. newBalancerName = cc.sc.lbConfig.name
  984. } else { // cc.sc.LB != nil
  985. newBalancerName = *cc.sc.LB
  986. }
  987. cc.balancerWrapper.switchTo(newBalancerName)
  988. }
  989. func (cc *ClientConn) resolveNow(o resolver.ResolveNowOptions) {
  990. cc.mu.RLock()
  991. cc.resolverWrapper.resolveNow(o)
  992. cc.mu.RUnlock()
  993. }
  994. func (cc *ClientConn) resolveNowLocked(o resolver.ResolveNowOptions) {
  995. cc.resolverWrapper.resolveNow(o)
  996. }
  997. // ResetConnectBackoff wakes up all subchannels in transient failure and causes
  998. // them to attempt another connection immediately. It also resets the backoff
  999. // times used for subsequent attempts regardless of the current state.
  1000. //
  1001. // In general, this function should not be used. Typical service or network
  1002. // outages result in a reasonable client reconnection strategy by default.
  1003. // However, if a previously unavailable network becomes available, this may be
  1004. // used to trigger an immediate reconnect.
  1005. //
  1006. // # Experimental
  1007. //
  1008. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1009. // later release.
  1010. func (cc *ClientConn) ResetConnectBackoff() {
  1011. cc.mu.Lock()
  1012. conns := cc.conns
  1013. cc.mu.Unlock()
  1014. for ac := range conns {
  1015. ac.resetConnectBackoff()
  1016. }
  1017. }
  1018. // Close tears down the ClientConn and all underlying connections.
  1019. func (cc *ClientConn) Close() error {
  1020. defer func() {
  1021. cc.cancel()
  1022. <-cc.csMgr.pubSub.Done()
  1023. }()
  1024. // Prevent calls to enter/exit idle immediately, and ensure we are not
  1025. // currently entering/exiting idle mode.
  1026. cc.idlenessMgr.Close()
  1027. cc.mu.Lock()
  1028. if cc.conns == nil {
  1029. cc.mu.Unlock()
  1030. return ErrClientConnClosing
  1031. }
  1032. conns := cc.conns
  1033. cc.conns = nil
  1034. cc.csMgr.updateState(connectivity.Shutdown)
  1035. // We can safely unlock and continue to access all fields now as
  1036. // cc.conns==nil, preventing any further operations on cc.
  1037. cc.mu.Unlock()
  1038. cc.resolverWrapper.close()
  1039. // The order of closing matters here since the balancer wrapper assumes the
  1040. // picker is closed before it is closed.
  1041. cc.pickerWrapper.close()
  1042. cc.balancerWrapper.close()
  1043. <-cc.resolverWrapper.serializer.Done()
  1044. <-cc.balancerWrapper.serializer.Done()
  1045. for ac := range conns {
  1046. ac.tearDown(ErrClientConnClosing)
  1047. }
  1048. cc.addTraceEvent("deleted")
  1049. // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add
  1050. // trace reference to the entity being deleted, and thus prevent it from being
  1051. // deleted right away.
  1052. channelz.RemoveEntry(cc.channelzID)
  1053. return nil
  1054. }
  1055. // addrConn is a network connection to a given address.
  1056. type addrConn struct {
  1057. ctx context.Context
  1058. cancel context.CancelFunc
  1059. cc *ClientConn
  1060. dopts dialOptions
  1061. acbw *acBalancerWrapper
  1062. scopts balancer.NewSubConnOptions
  1063. // transport is set when there's a viable transport (note: ac state may not be READY as LB channel
  1064. // health checking may require server to report healthy to set ac to READY), and is reset
  1065. // to nil when the current transport should no longer be used to create a stream (e.g. after GoAway
  1066. // is received, transport is closed, ac has been torn down).
  1067. transport transport.ClientTransport // The current transport.
  1068. mu sync.Mutex
  1069. curAddr resolver.Address // The current address.
  1070. addrs []resolver.Address // All addresses that the resolver resolved to.
  1071. // Use updateConnectivityState for updating addrConn's connectivity state.
  1072. state connectivity.State
  1073. stateChan chan struct{} // closed and recreated on every state change.
  1074. backoffIdx int // Needs to be stateful for resetConnectBackoff.
  1075. resetBackoff chan struct{}
  1076. channelzID *channelz.Identifier
  1077. czData *channelzData
  1078. }
  1079. // Note: this requires a lock on ac.mu.
  1080. func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error) {
  1081. if ac.state == s {
  1082. return
  1083. }
  1084. // When changing states, reset the state change channel.
  1085. close(ac.stateChan)
  1086. ac.stateChan = make(chan struct{})
  1087. ac.state = s
  1088. if lastErr == nil {
  1089. channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v", s)
  1090. } else {
  1091. channelz.Infof(logger, ac.channelzID, "Subchannel Connectivity change to %v, last error: %s", s, lastErr)
  1092. }
  1093. ac.acbw.updateState(s, lastErr)
  1094. }
  1095. // adjustParams updates parameters used to create transports upon
  1096. // receiving a GoAway.
  1097. func (ac *addrConn) adjustParams(r transport.GoAwayReason) {
  1098. switch r {
  1099. case transport.GoAwayTooManyPings:
  1100. v := 2 * ac.dopts.copts.KeepaliveParams.Time
  1101. ac.cc.mu.Lock()
  1102. if v > ac.cc.mkp.Time {
  1103. ac.cc.mkp.Time = v
  1104. }
  1105. ac.cc.mu.Unlock()
  1106. }
  1107. }
  1108. func (ac *addrConn) resetTransport() {
  1109. ac.mu.Lock()
  1110. acCtx := ac.ctx
  1111. if acCtx.Err() != nil {
  1112. ac.mu.Unlock()
  1113. return
  1114. }
  1115. addrs := ac.addrs
  1116. backoffFor := ac.dopts.bs.Backoff(ac.backoffIdx)
  1117. // This will be the duration that dial gets to finish.
  1118. dialDuration := minConnectTimeout
  1119. if ac.dopts.minConnectTimeout != nil {
  1120. dialDuration = ac.dopts.minConnectTimeout()
  1121. }
  1122. if dialDuration < backoffFor {
  1123. // Give dial more time as we keep failing to connect.
  1124. dialDuration = backoffFor
  1125. }
  1126. // We can potentially spend all the time trying the first address, and
  1127. // if the server accepts the connection and then hangs, the following
  1128. // addresses will never be tried.
  1129. //
  1130. // The spec doesn't mention what should be done for multiple addresses.
  1131. // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md#proposed-backoff-algorithm
  1132. connectDeadline := time.Now().Add(dialDuration)
  1133. ac.updateConnectivityState(connectivity.Connecting, nil)
  1134. ac.mu.Unlock()
  1135. if err := ac.tryAllAddrs(acCtx, addrs, connectDeadline); err != nil {
  1136. ac.cc.resolveNow(resolver.ResolveNowOptions{})
  1137. ac.mu.Lock()
  1138. if acCtx.Err() != nil {
  1139. // addrConn was torn down.
  1140. ac.mu.Unlock()
  1141. return
  1142. }
  1143. // After exhausting all addresses, the addrConn enters
  1144. // TRANSIENT_FAILURE.
  1145. ac.updateConnectivityState(connectivity.TransientFailure, err)
  1146. // Backoff.
  1147. b := ac.resetBackoff
  1148. ac.mu.Unlock()
  1149. timer := time.NewTimer(backoffFor)
  1150. select {
  1151. case <-timer.C:
  1152. ac.mu.Lock()
  1153. ac.backoffIdx++
  1154. ac.mu.Unlock()
  1155. case <-b:
  1156. timer.Stop()
  1157. case <-acCtx.Done():
  1158. timer.Stop()
  1159. return
  1160. }
  1161. ac.mu.Lock()
  1162. if acCtx.Err() == nil {
  1163. ac.updateConnectivityState(connectivity.Idle, err)
  1164. }
  1165. ac.mu.Unlock()
  1166. return
  1167. }
  1168. // Success; reset backoff.
  1169. ac.mu.Lock()
  1170. ac.backoffIdx = 0
  1171. ac.mu.Unlock()
  1172. }
  1173. // tryAllAddrs tries to creates a connection to the addresses, and stop when at
  1174. // the first successful one. It returns an error if no address was successfully
  1175. // connected, or updates ac appropriately with the new transport.
  1176. func (ac *addrConn) tryAllAddrs(ctx context.Context, addrs []resolver.Address, connectDeadline time.Time) error {
  1177. var firstConnErr error
  1178. for _, addr := range addrs {
  1179. if ctx.Err() != nil {
  1180. return errConnClosing
  1181. }
  1182. ac.mu.Lock()
  1183. ac.cc.mu.RLock()
  1184. ac.dopts.copts.KeepaliveParams = ac.cc.mkp
  1185. ac.cc.mu.RUnlock()
  1186. copts := ac.dopts.copts
  1187. if ac.scopts.CredsBundle != nil {
  1188. copts.CredsBundle = ac.scopts.CredsBundle
  1189. }
  1190. ac.mu.Unlock()
  1191. channelz.Infof(logger, ac.channelzID, "Subchannel picks a new address %q to connect", addr.Addr)
  1192. err := ac.createTransport(ctx, addr, copts, connectDeadline)
  1193. if err == nil {
  1194. return nil
  1195. }
  1196. if firstConnErr == nil {
  1197. firstConnErr = err
  1198. }
  1199. ac.cc.updateConnectionError(err)
  1200. }
  1201. // Couldn't connect to any address.
  1202. return firstConnErr
  1203. }
  1204. // createTransport creates a connection to addr. It returns an error if the
  1205. // address was not successfully connected, or updates ac appropriately with the
  1206. // new transport.
  1207. func (ac *addrConn) createTransport(ctx context.Context, addr resolver.Address, copts transport.ConnectOptions, connectDeadline time.Time) error {
  1208. addr.ServerName = ac.cc.getServerName(addr)
  1209. hctx, hcancel := context.WithCancel(ctx)
  1210. onClose := func(r transport.GoAwayReason) {
  1211. ac.mu.Lock()
  1212. defer ac.mu.Unlock()
  1213. // adjust params based on GoAwayReason
  1214. ac.adjustParams(r)
  1215. if ctx.Err() != nil {
  1216. // Already shut down or connection attempt canceled. tearDown() or
  1217. // updateAddrs() already cleared the transport and canceled hctx
  1218. // via ac.ctx, and we expected this connection to be closed, so do
  1219. // nothing here.
  1220. return
  1221. }
  1222. hcancel()
  1223. if ac.transport == nil {
  1224. // We're still connecting to this address, which could error. Do
  1225. // not update the connectivity state or resolve; these will happen
  1226. // at the end of the tryAllAddrs connection loop in the event of an
  1227. // error.
  1228. return
  1229. }
  1230. ac.transport = nil
  1231. // Refresh the name resolver on any connection loss.
  1232. ac.cc.resolveNow(resolver.ResolveNowOptions{})
  1233. // Always go idle and wait for the LB policy to initiate a new
  1234. // connection attempt.
  1235. ac.updateConnectivityState(connectivity.Idle, nil)
  1236. }
  1237. connectCtx, cancel := context.WithDeadline(ctx, connectDeadline)
  1238. defer cancel()
  1239. copts.ChannelzParentID = ac.channelzID
  1240. newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, addr, copts, onClose)
  1241. if err != nil {
  1242. if logger.V(2) {
  1243. logger.Infof("Creating new client transport to %q: %v", addr, err)
  1244. }
  1245. // newTr is either nil, or closed.
  1246. hcancel()
  1247. channelz.Warningf(logger, ac.channelzID, "grpc: addrConn.createTransport failed to connect to %s. Err: %v", addr, err)
  1248. return err
  1249. }
  1250. ac.mu.Lock()
  1251. defer ac.mu.Unlock()
  1252. if ctx.Err() != nil {
  1253. // This can happen if the subConn was removed while in `Connecting`
  1254. // state. tearDown() would have set the state to `Shutdown`, but
  1255. // would not have closed the transport since ac.transport would not
  1256. // have been set at that point.
  1257. //
  1258. // We run this in a goroutine because newTr.Close() calls onClose()
  1259. // inline, which requires locking ac.mu.
  1260. //
  1261. // The error we pass to Close() is immaterial since there are no open
  1262. // streams at this point, so no trailers with error details will be sent
  1263. // out. We just need to pass a non-nil error.
  1264. //
  1265. // This can also happen when updateAddrs is called during a connection
  1266. // attempt.
  1267. go newTr.Close(transport.ErrConnClosing)
  1268. return nil
  1269. }
  1270. if hctx.Err() != nil {
  1271. // onClose was already called for this connection, but the connection
  1272. // was successfully established first. Consider it a success and set
  1273. // the new state to Idle.
  1274. ac.updateConnectivityState(connectivity.Idle, nil)
  1275. return nil
  1276. }
  1277. ac.curAddr = addr
  1278. ac.transport = newTr
  1279. ac.startHealthCheck(hctx) // Will set state to READY if appropriate.
  1280. return nil
  1281. }
  1282. // startHealthCheck starts the health checking stream (RPC) to watch the health
  1283. // stats of this connection if health checking is requested and configured.
  1284. //
  1285. // LB channel health checking is enabled when all requirements below are met:
  1286. // 1. it is not disabled by the user with the WithDisableHealthCheck DialOption
  1287. // 2. internal.HealthCheckFunc is set by importing the grpc/health package
  1288. // 3. a service config with non-empty healthCheckConfig field is provided
  1289. // 4. the load balancer requests it
  1290. //
  1291. // It sets addrConn to READY if the health checking stream is not started.
  1292. //
  1293. // Caller must hold ac.mu.
  1294. func (ac *addrConn) startHealthCheck(ctx context.Context) {
  1295. var healthcheckManagingState bool
  1296. defer func() {
  1297. if !healthcheckManagingState {
  1298. ac.updateConnectivityState(connectivity.Ready, nil)
  1299. }
  1300. }()
  1301. if ac.cc.dopts.disableHealthCheck {
  1302. return
  1303. }
  1304. healthCheckConfig := ac.cc.healthCheckConfig()
  1305. if healthCheckConfig == nil {
  1306. return
  1307. }
  1308. if !ac.scopts.HealthCheckEnabled {
  1309. return
  1310. }
  1311. healthCheckFunc := ac.cc.dopts.healthCheckFunc
  1312. if healthCheckFunc == nil {
  1313. // The health package is not imported to set health check function.
  1314. //
  1315. // TODO: add a link to the health check doc in the error message.
  1316. channelz.Error(logger, ac.channelzID, "Health check is requested but health check function is not set.")
  1317. return
  1318. }
  1319. healthcheckManagingState = true
  1320. // Set up the health check helper functions.
  1321. currentTr := ac.transport
  1322. newStream := func(method string) (any, error) {
  1323. ac.mu.Lock()
  1324. if ac.transport != currentTr {
  1325. ac.mu.Unlock()
  1326. return nil, status.Error(codes.Canceled, "the provided transport is no longer valid to use")
  1327. }
  1328. ac.mu.Unlock()
  1329. return newNonRetryClientStream(ctx, &StreamDesc{ServerStreams: true}, method, currentTr, ac)
  1330. }
  1331. setConnectivityState := func(s connectivity.State, lastErr error) {
  1332. ac.mu.Lock()
  1333. defer ac.mu.Unlock()
  1334. if ac.transport != currentTr {
  1335. return
  1336. }
  1337. ac.updateConnectivityState(s, lastErr)
  1338. }
  1339. // Start the health checking stream.
  1340. go func() {
  1341. err := ac.cc.dopts.healthCheckFunc(ctx, newStream, setConnectivityState, healthCheckConfig.ServiceName)
  1342. if err != nil {
  1343. if status.Code(err) == codes.Unimplemented {
  1344. channelz.Error(logger, ac.channelzID, "Subchannel health check is unimplemented at server side, thus health check is disabled")
  1345. } else {
  1346. channelz.Errorf(logger, ac.channelzID, "Health checking failed: %v", err)
  1347. }
  1348. }
  1349. }()
  1350. }
  1351. func (ac *addrConn) resetConnectBackoff() {
  1352. ac.mu.Lock()
  1353. close(ac.resetBackoff)
  1354. ac.backoffIdx = 0
  1355. ac.resetBackoff = make(chan struct{})
  1356. ac.mu.Unlock()
  1357. }
  1358. // getReadyTransport returns the transport if ac's state is READY or nil if not.
  1359. func (ac *addrConn) getReadyTransport() transport.ClientTransport {
  1360. ac.mu.Lock()
  1361. defer ac.mu.Unlock()
  1362. if ac.state == connectivity.Ready {
  1363. return ac.transport
  1364. }
  1365. return nil
  1366. }
  1367. // getTransport waits until the addrconn is ready and returns the transport.
  1368. // If the context expires first, returns an appropriate status. If the
  1369. // addrConn is stopped first, returns an Unavailable status error.
  1370. func (ac *addrConn) getTransport(ctx context.Context) (transport.ClientTransport, error) {
  1371. for ctx.Err() == nil {
  1372. ac.mu.Lock()
  1373. t, state, sc := ac.transport, ac.state, ac.stateChan
  1374. ac.mu.Unlock()
  1375. if state == connectivity.Ready {
  1376. return t, nil
  1377. }
  1378. if state == connectivity.Shutdown {
  1379. return nil, status.Errorf(codes.Unavailable, "SubConn shutting down")
  1380. }
  1381. select {
  1382. case <-ctx.Done():
  1383. case <-sc:
  1384. }
  1385. }
  1386. return nil, status.FromContextError(ctx.Err()).Err()
  1387. }
  1388. // tearDown starts to tear down the addrConn.
  1389. //
  1390. // Note that tearDown doesn't remove ac from ac.cc.conns, so the addrConn struct
  1391. // will leak. In most cases, call cc.removeAddrConn() instead.
  1392. func (ac *addrConn) tearDown(err error) {
  1393. ac.mu.Lock()
  1394. if ac.state == connectivity.Shutdown {
  1395. ac.mu.Unlock()
  1396. return
  1397. }
  1398. curTr := ac.transport
  1399. ac.transport = nil
  1400. // We have to set the state to Shutdown before anything else to prevent races
  1401. // between setting the state and logic that waits on context cancellation / etc.
  1402. ac.updateConnectivityState(connectivity.Shutdown, nil)
  1403. ac.cancel()
  1404. ac.curAddr = resolver.Address{}
  1405. channelz.AddTraceEvent(logger, ac.channelzID, 0, &channelz.TraceEventDesc{
  1406. Desc: "Subchannel deleted",
  1407. Severity: channelz.CtInfo,
  1408. Parent: &channelz.TraceEventDesc{
  1409. Desc: fmt.Sprintf("Subchannel(id:%d) deleted", ac.channelzID.Int()),
  1410. Severity: channelz.CtInfo,
  1411. },
  1412. })
  1413. // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add
  1414. // trace reference to the entity being deleted, and thus prevent it from
  1415. // being deleted right away.
  1416. channelz.RemoveEntry(ac.channelzID)
  1417. ac.mu.Unlock()
  1418. // We have to release the lock before the call to GracefulClose/Close here
  1419. // because both of them call onClose(), which requires locking ac.mu.
  1420. if curTr != nil {
  1421. if err == errConnDrain {
  1422. // Close the transport gracefully when the subConn is being shutdown.
  1423. //
  1424. // GracefulClose() may be executed multiple times if:
  1425. // - multiple GoAway frames are received from the server
  1426. // - there are concurrent name resolver or balancer triggered
  1427. // address removal and GoAway
  1428. curTr.GracefulClose()
  1429. } else {
  1430. // Hard close the transport when the channel is entering idle or is
  1431. // being shutdown. In the case where the channel is being shutdown,
  1432. // closing of transports is also taken care of by cancelation of cc.ctx.
  1433. // But in the case where the channel is entering idle, we need to
  1434. // explicitly close the transports here. Instead of distinguishing
  1435. // between these two cases, it is simpler to close the transport
  1436. // unconditionally here.
  1437. curTr.Close(err)
  1438. }
  1439. }
  1440. }
  1441. func (ac *addrConn) getState() connectivity.State {
  1442. ac.mu.Lock()
  1443. defer ac.mu.Unlock()
  1444. return ac.state
  1445. }
  1446. func (ac *addrConn) ChannelzMetric() *channelz.ChannelInternalMetric {
  1447. ac.mu.Lock()
  1448. addr := ac.curAddr.Addr
  1449. ac.mu.Unlock()
  1450. return &channelz.ChannelInternalMetric{
  1451. State: ac.getState(),
  1452. Target: addr,
  1453. CallsStarted: atomic.LoadInt64(&ac.czData.callsStarted),
  1454. CallsSucceeded: atomic.LoadInt64(&ac.czData.callsSucceeded),
  1455. CallsFailed: atomic.LoadInt64(&ac.czData.callsFailed),
  1456. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&ac.czData.lastCallStartedTime)),
  1457. }
  1458. }
  1459. func (ac *addrConn) incrCallsStarted() {
  1460. atomic.AddInt64(&ac.czData.callsStarted, 1)
  1461. atomic.StoreInt64(&ac.czData.lastCallStartedTime, time.Now().UnixNano())
  1462. }
  1463. func (ac *addrConn) incrCallsSucceeded() {
  1464. atomic.AddInt64(&ac.czData.callsSucceeded, 1)
  1465. }
  1466. func (ac *addrConn) incrCallsFailed() {
  1467. atomic.AddInt64(&ac.czData.callsFailed, 1)
  1468. }
  1469. type retryThrottler struct {
  1470. max float64
  1471. thresh float64
  1472. ratio float64
  1473. mu sync.Mutex
  1474. tokens float64 // TODO(dfawley): replace with atomic and remove lock.
  1475. }
  1476. // throttle subtracts a retry token from the pool and returns whether a retry
  1477. // should be throttled (disallowed) based upon the retry throttling policy in
  1478. // the service config.
  1479. func (rt *retryThrottler) throttle() bool {
  1480. if rt == nil {
  1481. return false
  1482. }
  1483. rt.mu.Lock()
  1484. defer rt.mu.Unlock()
  1485. rt.tokens--
  1486. if rt.tokens < 0 {
  1487. rt.tokens = 0
  1488. }
  1489. return rt.tokens <= rt.thresh
  1490. }
  1491. func (rt *retryThrottler) successfulRPC() {
  1492. if rt == nil {
  1493. return
  1494. }
  1495. rt.mu.Lock()
  1496. defer rt.mu.Unlock()
  1497. rt.tokens += rt.ratio
  1498. if rt.tokens > rt.max {
  1499. rt.tokens = rt.max
  1500. }
  1501. }
  1502. type channelzChannel struct {
  1503. cc *ClientConn
  1504. }
  1505. func (c *channelzChannel) ChannelzMetric() *channelz.ChannelInternalMetric {
  1506. return c.cc.channelzMetric()
  1507. }
  1508. // ErrClientConnTimeout indicates that the ClientConn cannot establish the
  1509. // underlying connections within the specified timeout.
  1510. //
  1511. // Deprecated: This error is never returned by grpc and should not be
  1512. // referenced by users.
  1513. var ErrClientConnTimeout = errors.New("grpc: timed out when dialing")
  1514. // getResolver finds the scheme in the cc's resolvers or the global registry.
  1515. // scheme should always be lowercase (typically by virtue of url.Parse()
  1516. // performing proper RFC3986 behavior).
  1517. func (cc *ClientConn) getResolver(scheme string) resolver.Builder {
  1518. for _, rb := range cc.dopts.resolvers {
  1519. if scheme == rb.Scheme() {
  1520. return rb
  1521. }
  1522. }
  1523. return resolver.Get(scheme)
  1524. }
  1525. func (cc *ClientConn) updateConnectionError(err error) {
  1526. cc.lceMu.Lock()
  1527. cc.lastConnectionError = err
  1528. cc.lceMu.Unlock()
  1529. }
  1530. func (cc *ClientConn) connectionError() error {
  1531. cc.lceMu.Lock()
  1532. defer cc.lceMu.Unlock()
  1533. return cc.lastConnectionError
  1534. }
  1535. // parseTargetAndFindResolver parses the user's dial target and stores the
  1536. // parsed target in `cc.parsedTarget`.
  1537. //
  1538. // The resolver to use is determined based on the scheme in the parsed target
  1539. // and the same is stored in `cc.resolverBuilder`.
  1540. //
  1541. // Doesn't grab cc.mu as this method is expected to be called only at Dial time.
  1542. func (cc *ClientConn) parseTargetAndFindResolver() error {
  1543. channelz.Infof(logger, cc.channelzID, "original dial target is: %q", cc.target)
  1544. var rb resolver.Builder
  1545. parsedTarget, err := parseTarget(cc.target)
  1546. if err != nil {
  1547. channelz.Infof(logger, cc.channelzID, "dial target %q parse failed: %v", cc.target, err)
  1548. } else {
  1549. channelz.Infof(logger, cc.channelzID, "parsed dial target is: %#v", parsedTarget)
  1550. rb = cc.getResolver(parsedTarget.URL.Scheme)
  1551. if rb != nil {
  1552. cc.parsedTarget = parsedTarget
  1553. cc.resolverBuilder = rb
  1554. return nil
  1555. }
  1556. }
  1557. // We are here because the user's dial target did not contain a scheme or
  1558. // specified an unregistered scheme. We should fallback to the default
  1559. // scheme, except when a custom dialer is specified in which case, we should
  1560. // always use passthrough scheme.
  1561. defScheme := resolver.GetDefaultScheme()
  1562. channelz.Infof(logger, cc.channelzID, "fallback to scheme %q", defScheme)
  1563. canonicalTarget := defScheme + ":///" + cc.target
  1564. parsedTarget, err = parseTarget(canonicalTarget)
  1565. if err != nil {
  1566. channelz.Infof(logger, cc.channelzID, "dial target %q parse failed: %v", canonicalTarget, err)
  1567. return err
  1568. }
  1569. channelz.Infof(logger, cc.channelzID, "parsed dial target is: %+v", parsedTarget)
  1570. rb = cc.getResolver(parsedTarget.URL.Scheme)
  1571. if rb == nil {
  1572. return fmt.Errorf("could not get resolver for default scheme: %q", parsedTarget.URL.Scheme)
  1573. }
  1574. cc.parsedTarget = parsedTarget
  1575. cc.resolverBuilder = rb
  1576. return nil
  1577. }
  1578. // parseTarget uses RFC 3986 semantics to parse the given target into a
  1579. // resolver.Target struct containing url. Query params are stripped from the
  1580. // endpoint.
  1581. func parseTarget(target string) (resolver.Target, error) {
  1582. u, err := url.Parse(target)
  1583. if err != nil {
  1584. return resolver.Target{}, err
  1585. }
  1586. return resolver.Target{URL: *u}, nil
  1587. }
  1588. func encodeAuthority(authority string) string {
  1589. const upperhex = "0123456789ABCDEF"
  1590. // Return for characters that must be escaped as per
  1591. // Valid chars are mentioned here:
  1592. // https://datatracker.ietf.org/doc/html/rfc3986#section-3.2
  1593. shouldEscape := func(c byte) bool {
  1594. // Alphanum are always allowed.
  1595. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' {
  1596. return false
  1597. }
  1598. switch c {
  1599. case '-', '_', '.', '~': // Unreserved characters
  1600. return false
  1601. case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // Subdelim characters
  1602. return false
  1603. case ':', '[', ']', '@': // Authority related delimeters
  1604. return false
  1605. }
  1606. // Everything else must be escaped.
  1607. return true
  1608. }
  1609. hexCount := 0
  1610. for i := 0; i < len(authority); i++ {
  1611. c := authority[i]
  1612. if shouldEscape(c) {
  1613. hexCount++
  1614. }
  1615. }
  1616. if hexCount == 0 {
  1617. return authority
  1618. }
  1619. required := len(authority) + 2*hexCount
  1620. t := make([]byte, required)
  1621. j := 0
  1622. // This logic is a barebones version of escape in the go net/url library.
  1623. for i := 0; i < len(authority); i++ {
  1624. switch c := authority[i]; {
  1625. case shouldEscape(c):
  1626. t[j] = '%'
  1627. t[j+1] = upperhex[c>>4]
  1628. t[j+2] = upperhex[c&15]
  1629. j += 3
  1630. default:
  1631. t[j] = authority[i]
  1632. j++
  1633. }
  1634. }
  1635. return string(t)
  1636. }
  1637. // Determine channel authority. The order of precedence is as follows:
  1638. // - user specified authority override using `WithAuthority` dial option
  1639. // - creds' notion of server name for the authentication handshake
  1640. // - endpoint from dial target of the form "scheme://[authority]/endpoint"
  1641. //
  1642. // Stores the determined authority in `cc.authority`.
  1643. //
  1644. // Returns a non-nil error if the authority returned by the transport
  1645. // credentials do not match the authority configured through the dial option.
  1646. //
  1647. // Doesn't grab cc.mu as this method is expected to be called only at Dial time.
  1648. func (cc *ClientConn) determineAuthority() error {
  1649. dopts := cc.dopts
  1650. // Historically, we had two options for users to specify the serverName or
  1651. // authority for a channel. One was through the transport credentials
  1652. // (either in its constructor, or through the OverrideServerName() method).
  1653. // The other option (for cases where WithInsecure() dial option was used)
  1654. // was to use the WithAuthority() dial option.
  1655. //
  1656. // A few things have changed since:
  1657. // - `insecure` package with an implementation of the `TransportCredentials`
  1658. // interface for the insecure case
  1659. // - WithAuthority() dial option support for secure credentials
  1660. authorityFromCreds := ""
  1661. if creds := dopts.copts.TransportCredentials; creds != nil && creds.Info().ServerName != "" {
  1662. authorityFromCreds = creds.Info().ServerName
  1663. }
  1664. authorityFromDialOption := dopts.authority
  1665. if (authorityFromCreds != "" && authorityFromDialOption != "") && authorityFromCreds != authorityFromDialOption {
  1666. return fmt.Errorf("ClientConn's authority from transport creds %q and dial option %q don't match", authorityFromCreds, authorityFromDialOption)
  1667. }
  1668. endpoint := cc.parsedTarget.Endpoint()
  1669. target := cc.target
  1670. switch {
  1671. case authorityFromDialOption != "":
  1672. cc.authority = authorityFromDialOption
  1673. case authorityFromCreds != "":
  1674. cc.authority = authorityFromCreds
  1675. case strings.HasPrefix(target, "unix:") || strings.HasPrefix(target, "unix-abstract:"):
  1676. // TODO: remove when the unix resolver implements optional interface to
  1677. // return channel authority.
  1678. cc.authority = "localhost"
  1679. case strings.HasPrefix(endpoint, ":"):
  1680. cc.authority = "localhost" + endpoint
  1681. default:
  1682. // TODO: Define an optional interface on the resolver builder to return
  1683. // the channel authority given the user's dial target. For resolvers
  1684. // which don't implement this interface, we will use the endpoint from
  1685. // "scheme://authority/endpoint" as the default authority.
  1686. // Escape the endpoint to handle use cases where the endpoint
  1687. // might not be a valid authority by default.
  1688. // For example an endpoint which has multiple paths like
  1689. // 'a/b/c', which is not a valid authority by default.
  1690. cc.authority = encodeAuthority(endpoint)
  1691. }
  1692. channelz.Infof(logger, cc.channelzID, "Channel authority set to %q", cc.authority)
  1693. return nil
  1694. }