clientconn.go 66 KB

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