clientconn.go 66 KB

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