balancer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. *
  3. * Copyright 2016 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. "fmt"
  21. "net"
  22. "sync"
  23. "golang.org/x/net/context"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/credentials"
  26. "google.golang.org/grpc/grpclog"
  27. "google.golang.org/grpc/naming"
  28. "google.golang.org/grpc/status"
  29. )
  30. // Address represents a server the client connects to.
  31. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  32. type Address struct {
  33. // Addr is the server address on which a connection will be established.
  34. Addr string
  35. // Metadata is the information associated with Addr, which may be used
  36. // to make load balancing decision.
  37. Metadata interface{}
  38. }
  39. // BalancerConfig specifies the configurations for Balancer.
  40. type BalancerConfig struct {
  41. // DialCreds is the transport credential the Balancer implementation can
  42. // use to dial to a remote load balancer server. The Balancer implementations
  43. // can ignore this if it does not need to talk to another party securely.
  44. DialCreds credentials.TransportCredentials
  45. // Dialer is the custom dialer the Balancer implementation can use to dial
  46. // to a remote load balancer server. The Balancer implementations
  47. // can ignore this if it doesn't need to talk to remote balancer.
  48. Dialer func(context.Context, string) (net.Conn, error)
  49. }
  50. // BalancerGetOptions configures a Get call.
  51. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  52. type BalancerGetOptions struct {
  53. // BlockingWait specifies whether Get should block when there is no
  54. // connected address.
  55. BlockingWait bool
  56. }
  57. // Balancer chooses network addresses for RPCs.
  58. // This is the EXPERIMENTAL API and may be changed or extended in the future.
  59. type Balancer interface {
  60. // Start does the initialization work to bootstrap a Balancer. For example,
  61. // this function may start the name resolution and watch the updates. It will
  62. // be called when dialing.
  63. Start(target string, config BalancerConfig) error
  64. // Up informs the Balancer that gRPC has a connection to the server at
  65. // addr. It returns down which is called once the connection to addr gets
  66. // lost or closed.
  67. // TODO: It is not clear how to construct and take advantage of the meaningful error
  68. // parameter for down. Need realistic demands to guide.
  69. Up(addr Address) (down func(error))
  70. // Get gets the address of a server for the RPC corresponding to ctx.
  71. // i) If it returns a connected address, gRPC internals issues the RPC on the
  72. // connection to this address;
  73. // ii) If it returns an address on which the connection is under construction
  74. // (initiated by Notify(...)) but not connected, gRPC internals
  75. // * fails RPC if the RPC is fail-fast and connection is in the TransientFailure or
  76. // Shutdown state;
  77. // or
  78. // * issues RPC on the connection otherwise.
  79. // iii) If it returns an address on which the connection does not exist, gRPC
  80. // internals treats it as an error and will fail the corresponding RPC.
  81. //
  82. // Therefore, the following is the recommended rule when writing a custom Balancer.
  83. // If opts.BlockingWait is true, it should return a connected address or
  84. // block if there is no connected address. It should respect the timeout or
  85. // cancellation of ctx when blocking. If opts.BlockingWait is false (for fail-fast
  86. // RPCs), it should return an address it has notified via Notify(...) immediately
  87. // instead of blocking.
  88. //
  89. // The function returns put which is called once the rpc has completed or failed.
  90. // put can collect and report RPC stats to a remote load balancer.
  91. //
  92. // This function should only return the errors Balancer cannot recover by itself.
  93. // gRPC internals will fail the RPC if an error is returned.
  94. Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error)
  95. // Notify returns a channel that is used by gRPC internals to watch the addresses
  96. // gRPC needs to connect. The addresses might be from a name resolver or remote
  97. // load balancer. gRPC internals will compare it with the existing connected
  98. // addresses. If the address Balancer notified is not in the existing connected
  99. // addresses, gRPC starts to connect the address. If an address in the existing
  100. // connected addresses is not in the notification list, the corresponding connection
  101. // is shutdown gracefully. Otherwise, there are no operations to take. Note that
  102. // the Address slice must be the full list of the Addresses which should be connected.
  103. // It is NOT delta.
  104. Notify() <-chan []Address
  105. // Close shuts down the balancer.
  106. Close() error
  107. }
  108. // downErr implements net.Error. It is constructed by gRPC internals and passed to the down
  109. // call of Balancer.
  110. type downErr struct {
  111. timeout bool
  112. temporary bool
  113. desc string
  114. }
  115. func (e downErr) Error() string { return e.desc }
  116. func (e downErr) Timeout() bool { return e.timeout }
  117. func (e downErr) Temporary() bool { return e.temporary }
  118. func downErrorf(timeout, temporary bool, format string, a ...interface{}) downErr {
  119. return downErr{
  120. timeout: timeout,
  121. temporary: temporary,
  122. desc: fmt.Sprintf(format, a...),
  123. }
  124. }
  125. // RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch
  126. // the name resolution updates and updates the addresses available correspondingly.
  127. func RoundRobin(r naming.Resolver) Balancer {
  128. return &roundRobin{r: r}
  129. }
  130. type addrInfo struct {
  131. addr Address
  132. connected bool
  133. }
  134. type roundRobin struct {
  135. r naming.Resolver
  136. w naming.Watcher
  137. addrs []*addrInfo // all the addresses the client should potentially connect
  138. mu sync.Mutex
  139. addrCh chan []Address // the channel to notify gRPC internals the list of addresses the client should connect to.
  140. next int // index of the next address to return for Get()
  141. waitCh chan struct{} // the channel to block when there is no connected address available
  142. done bool // The Balancer is closed.
  143. }
  144. func (rr *roundRobin) watchAddrUpdates() error {
  145. updates, err := rr.w.Next()
  146. if err != nil {
  147. grpclog.Warningf("grpc: the naming watcher stops working due to %v.", err)
  148. return err
  149. }
  150. rr.mu.Lock()
  151. defer rr.mu.Unlock()
  152. for _, update := range updates {
  153. addr := Address{
  154. Addr: update.Addr,
  155. Metadata: update.Metadata,
  156. }
  157. switch update.Op {
  158. case naming.Add:
  159. var exist bool
  160. for _, v := range rr.addrs {
  161. if addr == v.addr {
  162. exist = true
  163. grpclog.Infoln("grpc: The name resolver wanted to add an existing address: ", addr)
  164. break
  165. }
  166. }
  167. if exist {
  168. continue
  169. }
  170. rr.addrs = append(rr.addrs, &addrInfo{addr: addr})
  171. case naming.Delete:
  172. for i, v := range rr.addrs {
  173. if addr == v.addr {
  174. copy(rr.addrs[i:], rr.addrs[i+1:])
  175. rr.addrs = rr.addrs[:len(rr.addrs)-1]
  176. break
  177. }
  178. }
  179. default:
  180. grpclog.Errorln("Unknown update.Op ", update.Op)
  181. }
  182. }
  183. // Make a copy of rr.addrs and write it onto rr.addrCh so that gRPC internals gets notified.
  184. open := make([]Address, len(rr.addrs))
  185. for i, v := range rr.addrs {
  186. open[i] = v.addr
  187. }
  188. if rr.done {
  189. return ErrClientConnClosing
  190. }
  191. select {
  192. case <-rr.addrCh:
  193. default:
  194. }
  195. rr.addrCh <- open
  196. return nil
  197. }
  198. func (rr *roundRobin) Start(target string, config BalancerConfig) error {
  199. rr.mu.Lock()
  200. defer rr.mu.Unlock()
  201. if rr.done {
  202. return ErrClientConnClosing
  203. }
  204. if rr.r == nil {
  205. // If there is no name resolver installed, it is not needed to
  206. // do name resolution. In this case, target is added into rr.addrs
  207. // as the only address available and rr.addrCh stays nil.
  208. rr.addrs = append(rr.addrs, &addrInfo{addr: Address{Addr: target}})
  209. return nil
  210. }
  211. w, err := rr.r.Resolve(target)
  212. if err != nil {
  213. return err
  214. }
  215. rr.w = w
  216. rr.addrCh = make(chan []Address, 1)
  217. go func() {
  218. for {
  219. if err := rr.watchAddrUpdates(); err != nil {
  220. return
  221. }
  222. }
  223. }()
  224. return nil
  225. }
  226. // Up sets the connected state of addr and sends notification if there are pending
  227. // Get() calls.
  228. func (rr *roundRobin) Up(addr Address) func(error) {
  229. rr.mu.Lock()
  230. defer rr.mu.Unlock()
  231. var cnt int
  232. for _, a := range rr.addrs {
  233. if a.addr == addr {
  234. if a.connected {
  235. return nil
  236. }
  237. a.connected = true
  238. }
  239. if a.connected {
  240. cnt++
  241. }
  242. }
  243. // addr is only one which is connected. Notify the Get() callers who are blocking.
  244. if cnt == 1 && rr.waitCh != nil {
  245. close(rr.waitCh)
  246. rr.waitCh = nil
  247. }
  248. return func(err error) {
  249. rr.down(addr, err)
  250. }
  251. }
  252. // down unsets the connected state of addr.
  253. func (rr *roundRobin) down(addr Address, err error) {
  254. rr.mu.Lock()
  255. defer rr.mu.Unlock()
  256. for _, a := range rr.addrs {
  257. if addr == a.addr {
  258. a.connected = false
  259. break
  260. }
  261. }
  262. }
  263. // Get returns the next addr in the rotation.
  264. func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) {
  265. var ch chan struct{}
  266. rr.mu.Lock()
  267. if rr.done {
  268. rr.mu.Unlock()
  269. err = ErrClientConnClosing
  270. return
  271. }
  272. if len(rr.addrs) > 0 {
  273. if rr.next >= len(rr.addrs) {
  274. rr.next = 0
  275. }
  276. next := rr.next
  277. for {
  278. a := rr.addrs[next]
  279. next = (next + 1) % len(rr.addrs)
  280. if a.connected {
  281. addr = a.addr
  282. rr.next = next
  283. rr.mu.Unlock()
  284. return
  285. }
  286. if next == rr.next {
  287. // Has iterated all the possible address but none is connected.
  288. break
  289. }
  290. }
  291. }
  292. if !opts.BlockingWait {
  293. if len(rr.addrs) == 0 {
  294. rr.mu.Unlock()
  295. err = status.Errorf(codes.Unavailable, "there is no address available")
  296. return
  297. }
  298. // Returns the next addr on rr.addrs for failfast RPCs.
  299. addr = rr.addrs[rr.next].addr
  300. rr.next++
  301. rr.mu.Unlock()
  302. return
  303. }
  304. // Wait on rr.waitCh for non-failfast RPCs.
  305. if rr.waitCh == nil {
  306. ch = make(chan struct{})
  307. rr.waitCh = ch
  308. } else {
  309. ch = rr.waitCh
  310. }
  311. rr.mu.Unlock()
  312. for {
  313. select {
  314. case <-ctx.Done():
  315. err = ctx.Err()
  316. return
  317. case <-ch:
  318. rr.mu.Lock()
  319. if rr.done {
  320. rr.mu.Unlock()
  321. err = ErrClientConnClosing
  322. return
  323. }
  324. if len(rr.addrs) > 0 {
  325. if rr.next >= len(rr.addrs) {
  326. rr.next = 0
  327. }
  328. next := rr.next
  329. for {
  330. a := rr.addrs[next]
  331. next = (next + 1) % len(rr.addrs)
  332. if a.connected {
  333. addr = a.addr
  334. rr.next = next
  335. rr.mu.Unlock()
  336. return
  337. }
  338. if next == rr.next {
  339. // Has iterated all the possible address but none is connected.
  340. break
  341. }
  342. }
  343. }
  344. // The newly added addr got removed by Down() again.
  345. if rr.waitCh == nil {
  346. ch = make(chan struct{})
  347. rr.waitCh = ch
  348. } else {
  349. ch = rr.waitCh
  350. }
  351. rr.mu.Unlock()
  352. }
  353. }
  354. }
  355. func (rr *roundRobin) Notify() <-chan []Address {
  356. return rr.addrCh
  357. }
  358. func (rr *roundRobin) Close() error {
  359. rr.mu.Lock()
  360. defer rr.mu.Unlock()
  361. if rr.done {
  362. return errBalancerClosed
  363. }
  364. rr.done = true
  365. if rr.w != nil {
  366. rr.w.Close()
  367. }
  368. if rr.waitCh != nil {
  369. close(rr.waitCh)
  370. rr.waitCh = nil
  371. }
  372. if rr.addrCh != nil {
  373. close(rr.addrCh)
  374. }
  375. return nil
  376. }
  377. // pickFirst is used to test multi-addresses in one addrConn in which all addresses share the same addrConn.
  378. // It is a wrapper around roundRobin balancer. The logic of all methods works fine because balancer.Get()
  379. // returns the only address Up by resetTransport().
  380. type pickFirst struct {
  381. *roundRobin
  382. }
  383. func pickFirstBalancerV1(r naming.Resolver) Balancer {
  384. return &pickFirst{&roundRobin{r: r}}
  385. }